query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Remove the specified user from the given domain's block list | function removeUser( domain, user, callback ) {
getBlockList( domain, function( list ) {
var index = list.indexOf( user );
if( index != -1 ) {
list.splice( index, 1 );
setBlockList( domain, list, callback );
}
} );
} | [
"function removeUserFromList(listName, userName) {\r\n\tvar curList\t= getValue(listName,'');\r\n\r\n\t// We add a leading and trailing ;, so that when searching for ;username; to replace will find even the ones at the beginning or end of the string\r\n\tcurList\t\t= ';' + curList\r\n\r\n\t// escape the userName and then search for it; the string we have is an escaped version of the string\r\n\tuserName\t= ';' + urlencode( userName );\r\n\r\n\t// Remove the user from the list\r\n\tvar iUser\t= curList.search( userName );\r\n\tif ( iUser > -1 ) {\r\n\t\tcurList\t\t= getValue( listName, '');\r\n\t\tcurList\t\t= curList.replace( userName, \"\");\r\n\t\tsetValue( listName, curList );\r\n\t } else {\r\n\t}\r\n\r\n }",
"async unblockUser(user, userToUnblock) {\n const userId = extractUserId(user);\n const userIdToUnblock = extractUserId(userToUnblock);\n await this._client.callApi({\n url: `users/${userId}/blocks/${userIdToUnblock}`,\n method: 'DELETE',\n scope: 'user_blocks_edit'\n });\n }",
"function removeVoter(user) {\n var pokerCard = document.getElementById(user);\n votingContainer.removeChild(pokerCard);\n var rosterEntry = document.getElementById(user);\n messageContainer.removeChild(rosterEntry);\n}",
"function addUser( domain, user, callback ) {\n\tgetBlockList( domain, function( list ) {\n\t\tvar index = list.indexOf( user );\n\n\t\tif( index == -1 ) {\n\t\t\tlist.push( user );\n\t\t\tsetBlockList( domain, list, function(){} );\n\t\t}\n\n\t\tcallback( list );\n\t} );\n}",
"function unbanUser(ip, name)\n {\n if (ip)\n {\n var user = objectWithKeyAndValue(banList, 'ip', ip);\n if (user)\n {\n var index = banList.indexOf(user);\n banList.splice(index, 1);\n sendServerMsgUser(\"You unbanned \" + ip);\n io.sockets.socket(socket.id).emit('banSync', banList);\n saveBanList();\n console.log('[' + ip + '] was unbanned');\n return;\n }\n }\n else if (name)\n {\n var user = objectWithKeyAndValue(banList, 'lastName', name);\n if (user)\n {\n var index = banList.indexOf(user);\n banList.splice(index, 1);\n sendServerMsgUser(\"You unbanned \" + name);\n io.sockets.socket(socket.id).emit('banSync', banList);\n saveBanList();\n console.log('[' + name + '] was unbanned');\n return;\n }\n }\n \n sendServerMsgUser(\"Unable to unban that user\");\n console.log(\"Couldn't unban user: user with that ip or name not found\");\n }",
"function removeLast(params){\r\n if(!params[1]){\r\n unsafeWindow.addMessage('','No user specified: \\'removeLast [user]','','hashtext');\r\n return;\r\n }\r\n\tvar user = params[1],\r\n\t\tremoveIndex = -1,\r\n \ti;\r\n\r\n\t// Look for the user last added video\r\n for (i = unsafeWindow.playlist.length - 1; i >= 0; i--) {\r\n if(unsafeWindow.playlist[i].addedby.toLowerCase() === user.toLowerCase()){\r\n removeIndex = i;\r\n break;\r\n }\r\n }\r\n\t\r\n\tif (removeIndex === -1){\r\n\t\tunsafeWindow.addMessage('',\"The user didn't add any video\",'','hashtext');\r\n\t}else{\r\n\t\tunsafeWindow.sendcmd('remove', {info: unsafeWindow.playlist[removeIndex].info});\r\n\t}\r\n\t\t\r\n}",
"function muut_remove_online_user(user) {\n if(user.path.substr(0,1) == '@') {\n var username = user.path.substr(1);\n }\n var username_for_selector = tidy_muut_username(username);\n widget_online_users_wrapper.find('.m-user-online_' + username_for_selector).fadeOut(500, function() { $(this).remove() });\n muut_update_online_users_widget();\n }",
"function deleteFromList(user_id){\n return db('saved_list')\n .where({ user_id })\n // .andWhere({ book_id })\n .delete()\n}",
"removeUser(userId) {\n for (let user of this.getUsers()) {\n if (user._id === userId) {\n this.users.splice(this.users.indexOf(user), 1);\n }\n }\n }",
"function removeMemberFromCommunity(domainName, data, done) {\n /* const arr = [];\n const query = (`DELETE FROM ${MEMBERSHIP_TABLE} WHERE username =? AND domain = ? `);\n // console.log(data.length);\n // console.log(typeof (data));\n console.log(data);\n data.forEach((val) => {\n arr.push({ query, params: [val.username.toLowerCase(), domainName.toLowerCase()] });\n });\n return client.batch(arr, { prepare: true }, (err, res) => {\n if (err) {\n return done(err);\n }\n return done(undefined, res);\n });*/\n}",
"function unmodUser(trip)\n {\n var mod = modList.indexOf(trip);\n if (mod > -1)\n {\n modList.splice(mod, 1);\n sendServerMsgUser(\"You unmodded \" + trip);\n io.sockets.socket(socket.id).emit('modSync', modList);\n console.log('[' + trip + '] was unmodded');\n saveModList();\n updateUserType(trip);\n }\n else\n {\n sendServerMsgUser(\"Unable to unmod \" + trip);\n console.log('[' + trip + '] could not be found in mod list');\n }\n }",
"function delUserForMeeting( data, callback ) {\n\t\t\tvar url = '/meetingdelusers';\n\n\t\t\tnew IO({\n\t\t\t\turl: url,\n\t\t\t\ttype: 'post',\n\t\t\t\tdata: data,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\t\tcallback(data);\n\t\t\t\t}\n\t\t\t});\n\n\t\t}",
"unhideFromUser(user1,user2){\n let changed=false;\n for(var i=0;i<this.users[user1].friendsDontShow.length;i++){\n if(this.users[user1].friendsDontShow[i].id == user2){\n this.users[user1].friendsDontShow.splice(i,1);\n changed=true;\n break;\n }\n }\n return changed;\n }",
"function unlinkDocument( user, document, res ) {\n var docIndex = arrayIdIndex( document._id, user.docList );\n if( docIndex === -1 ) return handleError( res, \"Document Unlink Error: Document not in User's Document List\" );\n user.docList.splice( docIndex, 1 );\n user.save()\n .catch( updateUserError => handleError( res, \"Update User Error: \" + updateUserError ) )\n .then( updatedUser => {\n var userIndex = arrayIdIndex( user._id, document.collaboratorList );\n if( userIndex === -1 ) return handleError( res, \"User Unlink Error: User not in Document's Collaborator List\" );\n document.collaboratorList.splice( userIndex, 1 );\n return document.save();\n })\n .catch( documentUpdateError => handleError( res, \"Document Update Error: \" + documentUpdateError ) )\n .then( updatedDocument => {\n res.json({ success: true, action: \"unlink\" });\n });\n}",
"removeUserFromChannel(username, channel){\n var index = -1;\n var ch = this.getChannelByName(channel);\n if(ch != null){\n for (var i = 0; i < ch.users.length; i++) {\n var u = ch.users[i];\n if(u.name == username){\n index = i;\n }\n }\n }\n if(index > -1 && ch != null){\n ch.users.splice(index, 1);\n }\n io.emit('refreshchannels', [this.name, username]);\n dbDelete({groupname: this.name, channelname: channel, username: username}, \"channel_users\");\n }",
"function removeDeadUsers() {\n users = users.filter(function(user) {\n return Math.round((Date.now()-user.time)) < 20000;});\n console.log(\"Removed dead users\");\n}",
"function deleteUser(req, res) {\n User.remove({_id : req.params.id}, (err, result) => {\n res.json({ message: \"Bucket successfully deleted!\", result });\n });\n}",
"function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }",
"function removeEventUser(user, data, callback) {\n $.ajax({\n url: '/events/user/remove/' + user,\n data: JSON.stringify(data),\n headers: {\n 'Authorization': 'Bearer ' + token\n },\n type: 'PUT',\n dataType: 'json',\n contentType: 'application/json',\n success: callback\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the specified domain type's regular expression for matching sample values. | function getSampleDataRegExp(domainType) {
if (angular.isUndefined(domainType.$regexp)) {
domainType.$regexp = getRegExp(domainType.regexPattern, domainType.regexFlags);
}
return domainType.$regexp;
} | [
"function getFieldNameRegExp(domainType) {\n if (angular.isUndefined(domainType.$fieldNameRegexp)) {\n domainType.$fieldNameRegexp = getRegExp(domainType.fieldNamePattern, domainType.fieldNameFlags);\n }\n return domainType.$fieldNameRegexp;\n }",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\tfor (type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\t// Get all the replaceable keywords from corpus, stick them into an array\n\tfor(type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\t// Construct regular expression in the form of '@(keyword1,keyword2,keyword3,...)'\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function match(type, value) {\n}",
"function parseRegExp(node) {\n const evaluated = (0, util_1.getStaticValue)(node, globalScope);\n if (evaluated == null || !(evaluated.value instanceof RegExp)) {\n return null;\n }\n const { source, flags } = evaluated.value;\n const isStartsWith = source.startsWith('^');\n const isEndsWith = source.endsWith('$');\n if (isStartsWith === isEndsWith ||\n flags.includes('i') ||\n flags.includes('m')) {\n return null;\n }\n const text = parseRegExpText(source, flags.includes('u'));\n if (text == null) {\n return null;\n }\n return { isEndsWith, isStartsWith, text };\n }",
"function getRegExp(pattern, flags) {\n var safeFlags = angular.isString(flags) ? flags : \"\";\n return (angular.isString(pattern) && pattern.length > 0) ? new RegExp(pattern, safeFlags) : null;\n }",
"function regenerateRegExp(){\r\n\t\tpseudoRE = new RegExp('::?(' + Object.keys(pseudos).join('|') + ')(\\\\\\\\[0-9]+)?');\r\n\t}",
"function regexpFrom(string, flags) {\n return new RegExp(core.escapeRegExp(string), flags);\n }",
"function _globalize($regexp) {\n return new RegExp(String($regexp).slice(1, -1), \"g\");\n }",
"function getRegExpForCurrentEnv() {\n if (MY_DEBUG) {\n return MY_DEBUG_REGEXP;\n }\n\n let url = location.href;\n if (url.match(DEV_URL_REGEXP)) {\n return DEV_URL_REGEXP;\n } else if (url.match(STG_URL_REGEXP)) {\n return STG_URL_REGEXP;\n } else {\n return PRO_URL_REGEXP;\n }\n}",
"function getAttributePattern(attribute){\n\tvar pattern = new RegExp(attribute + '\\=\"(.*?)\"');\n\treturn pattern;\n}",
"function Simplification() {\r\n var regEx = document.getElementsByClassName(\"simpli\")[0].value;\r\n var text = document.getElementsByClassName(\"simpli\")[1].value;\r\n\r\n var re = new RegExp(regEx);\r\n\r\n var reponse = re.exec(text);\r\n document.getElementById(\"testSimpli\").value = reponse;\r\n\r\n}",
"function compileRegExp(lexer, str) {\n if (typeof (str) !== 'string') {\n return null;\n }\n var n = 0;\n while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions\n n++;\n str = str.replace(/@(\\w+)/g, function (s, attr) {\n var sub = '';\n if (typeof (lexer[attr]) === 'string') {\n sub = lexer[attr];\n }\n else if (lexer[attr] && lexer[attr] instanceof RegExp) {\n sub = lexer[attr].source;\n }\n else {\n if (lexer[attr] === undefined) {\n _monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"throwError\"](lexer, 'language definition does not contain attribute \\'' + attr + '\\', used at: ' + str);\n }\n else {\n _monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"throwError\"](lexer, 'attribute reference \\'' + attr + '\\' must be a string, used at: ' + str);\n }\n }\n return (_monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"empty\"](sub) ? '' : '(?:' + sub + ')');\n });\n }\n return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n}",
"function AttrRegex(attr) {\r\n return new RegExp(attr + \"=\" + bracketsRegexText);\r\n}",
"function buildRuleRegExp( languageNode, contextNode )\n{\n\tvar sRegExp, ruleNode, regExpExprNode, rootNode;\n\tvar keywordListNode, keywordListNameNode, keywordListRegExpNode,xp;\n\t\n\trootNode = languageNode.selectSingleNode(\"/*\");\n\tsRegExp=\"(\";\n\n\tvar ruleList=contextNode.childNodes;\n\t// building regular expression\t\n\tfor (ruleNode=ruleList.nextNode(); ruleNode != null; ruleNode=ruleList.nextNode() )\n\t{\n\t\tif (ruleNode.nodeName == \"#comment\")\n\t\t\tcontinue;\n\t\t\t\n\t\t// apply rule...\n\t\tif (ruleNode.nodeName == \"detect2chars\")\n\t\t{\n\t\t\tvar char0=ruleNode.attributes.getNamedItem(\"char\").value;\n\t\t\tvar char1=ruleNode.attributes.getNamedItem(\"char1\").value;\n\t\t\tsRegExp= sRegExp + stringToRegExp( char0 + char1 ) + \"|\";\n\t\t}\n\t\telse if (ruleNode.nodeName == \"detectchar\")\n\t\t{\n\t\t\tvar char0=ruleNode.attributes.getNamedItem(\"char\").value;\n\t\t\tsRegExp=sRegExp + stringToRegExp( char0 ) + \"|\";\n\t\t}\n\t\telse if (ruleNode.nodeName == \"linecontinue\")\n\t\t{\n\t\t\tsRegExp=sRegExp + \"\\n|\"\n\t\t}\n\t\telse if (ruleNode.nodeName == \"regexp\" )\n\t\t{\n\t\t\tregExpExprNode = ruleNode.attributes.getNamedItem(\"expression\");\n\t\t\tif ( regExpExprNode == null )\n\t\t\t\tthrow \"Regular expression rule missing expression attribute\";\n\t\t\t\t\n\t\t\tsRegExp=sRegExp + regExpExprNode.nodeTypedValue + \"|\";\n\t\t}\n\t\telse if (ruleNode.nodeName == \"keyword\")\n\t\t{\n\t\t\t// finding keywordlist\n\t\t\tkeywordListNameNode = ruleNode.attributes.getNamedItem(\"family\");\n\t\t\tif (keywordListNameNode == null)\n\t\t\t\tthrow \"Keyword rule missing family\";\n\t\t\txp=\"keywordlists/keywordlist[@id=\\\"\"\n\t\t\t\t\t+ keywordListNameNode.nodeTypedValue \n\t\t\t\t\t+ \"\\\"]\";\n\t\t\tkeywordListNode = rootNode.selectSingleNode(xp);\n\t\t\tif (keywordListNode == null)\n\t\t\t\tthrow \"Could not find keywordlist (xp: \"+ xp + \")\";\n\t\t\t\t\n\t\t\tkeywordListRegExpNode = keywordListNode.attributes.getNamedItem(\"regexp\");\n\t\t\tif (keywordListRegExpNode == null)\n\t\t\t\tthrow \"Could not find keywordlist regular expression\";\n\t\t\t\t\n\t\t\t// adding regexp\n\t\t\tsRegExp=sRegExp+keywordListRegExpNode.nodeTypedValue+\"|\";\n\t\t}\n\t}\n\n\tif (sRegExp.length > 1)\n\t\tsRegExp=sRegExp.substring(0,sRegExp.length-1)+\")\";\n\telse\n\t\tsRegExp=\"\";\n\t\n\treturn sRegExp;\t\n}",
"injectRegexEntity(lang, entity) {\n return new Promise((resolve) => {\n this.ner.addRegexRule(lang, entity.name, new RegExp(entity.regex, 'g'))\n\n resolve()\n })\n }",
"function create_extension_pattern(purpose) {\n // One-character symbols that can be used to indicate an extension.\n var single_extension_characters = \"x\\uFF58#\\uFF03~\\uFF5E\";\n\n switch (purpose) {\n // For parsing, we are slightly more lenient in our interpretation than for matching. Here we\n // allow \"comma\" and \"semicolon\" as possible extension indicators. When matching, these are\n case 'parsing':\n single_extension_characters = ',;' + single_extension_characters;\n }\n\n return RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + '|' + \"[ \\xA0\\\\t,]*\" + \"(?:e?xt(?:ensi(?:o\\u0301?|\\xF3))?n?|\\uFF45?\\uFF58\\uFF54\\uFF4E?|\" + // \"доб.\"\n \"\\u0434\\u043E\\u0431|\" + '[' + single_extension_characters + \"]|int|anexo|\\uFF49\\uFF4E\\uFF54)\" + \"[:\\\\.\\uFF0E]?[ \\xA0\\\\t,-]*\" + CAPTURING_EXTN_DIGITS + '#?|' + '[- ]+([' + __WEBPACK_IMPORTED_MODULE_0__constants__[\"e\" /* VALID_DIGITS */] + ']{1,5})#';\n}",
"function getRegexSiteMap() {\n var urlRegexString = \"^(?:https?\\:\\/\\/)?(?:www\\.)?\";\n\n return [\n {siteURL: \"debug\", urlRegex: \"localhost\"},\n {siteURL: \"youtube\", urlRegex: urlRegexString + \"youtube\\.com\\/watch.*\"},\n {siteURL: \"pandora\", urlRegex: urlRegexString + \"pandora\\.com.*\"} \n ]\n}",
"function matchSearchFuncEngRegex (searchTerm) {\n return function(element) {\n var re = \".*\" + searchTerm + \".*\";\n if (element.definition.match(re)) {\n return true;\n } else {\n return false;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows a user to vote for a given poll. TODO: Add encryption | vote(event) {
var BN = this.props.objects.web3.utils.BN;
if (event) event.preventDefault();
let encryptedVote = getEncryptedVote(new BN(this.curVote.value));
console.log("vote " + encryptedVote);
// cast vote
this.props.objects.Voting.castVote(parseInt(this.votePollID.value), encryptedVote,
this.props.objects.web3.utils.toWei(this.curWeight.value, "ether"), {
from: this.props.objects.accounts[this.props.curAccount],
gas: GAS
})
.then(result => {
// update app state
document.getElementById("vote_form").reset();
alert('Vote casted!');
})
.catch(error => {
console.log(error);
alert("Unable to cast vote. Either you have already voted, the poll has ended, or your parameters are invalid.");
})
} | [
"_vote () {\n\t\tif(isUserAuthed()) {\n\t\t\t//update our state to show the different button state\n\t\t\tthis.setState({voted: !this.state.voted});\n\n\t\t\tvar newVoteCount = this.state.vote_count;\n\t\t\t//increment/decrement vote count\n\t\t\tif(this.state.voted) {\n\t\t\t\tnewVoteCount = newVoteCount - 1;\n\t\t\t\tthis.setState({vote_count: newVoteCount});\n\t\t\t\ttrack('unvote clicked', {\n\t\t\t\t\t'source': 'idea list'\n\t\t\t\t});\t\n\t\t\t} else {\n\t\t\t\tnewVoteCount = newVoteCount + 1;\n\t\t\t\tthis.setState({vote_count: newVoteCount});\n\t\t\t\ttrack('vote clicked', {\n\t\t\t\t\t'source': 'idea list'\n\t\t\t\t});\t\t\n\t\t\t}\n\t\t\t\n\t\t\t//send our vote\n\t\t\tapi_vote(this.props.idea.idea_id, this.state.voted); \n\t\t} else {\n\t\t\tshowModal('_modal-login');\n\t\t}\n\t}",
"function vote(a_Button, a_SongHash, a_VoteType, a_VoteValue)\n{\n\t// Highlight and disable the button for a while:\n\ta_Button.style.opacity = '0.5';\n\ta_Button.enabled = false\n\tsetTimeout(function()\n\t{\n\t\ta_Button.style.opacity = '1';\n\t\ta_Button.enabled = false;\n\t}, 1000);\n\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function()\n\t{\n\t\tif ((this.readyState === 4) && (this.status === 200))\n\t\t{\n\t\t\t// TODO: Update the relevant song's rating\n\t\t\t// document.getElementById(\"demo\").innerHTML = this.responseText;\n\t\t}\n\t};\n\txhttp.open(\"POST\", \"api/vote\", true);\n\txhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\txhttp.send(\"songHash=\" + a_SongHash + \"&voteType=\" + a_VoteType + \"&voteValue=\" + a_VoteValue);\n}",
"function handleUserVote(id, is_up, update_element) {\n var button_id = (is_up ? \"upvote\" : \"downvote\") + id;\n if ($(\"#\" + button_id).hasClass(\"disabled\")) {\n return;\n }\n var cur_vote = parseInt($(\"#\"+update_element).html());\n database_update(vote_table, \"id = \" + id, is_up ? {upvotes: \"upvotes + 1\"} : {downvotes: \"downvotes + 1\"});\n cur_vote += 1;\n $(\"#\" + update_element).html(String(cur_vote));\n if (is_up) {\n allVotes[id].up = cur_vote;\n } else {\n allVotes[id].down = cur_vote;\n }\n // Force them to reopen the dialog\n $(\"#\" + button_id).addClass(\"disabled\");\n}",
"voteOnChoice(choiceId, questionId) {\n let choiceUrl = choiceId;\n if (choiceId && questionId) {\n choiceUrl = \"/questions/\" + questionId + \"/choices/\" + choiceId;\n }\n if (!choiceUrl) return Promise.reject(Error(\"Invalid choice specified.\"));\n\n return new Promise((resolve, reject) => {\n axios.post(choiceUrl).then((res) => {\n resolve();\n }).catch((e) => {\n reject(e);\n });\n });\n }",
"function vote(redditId, oauth, direction) {\n // Called when an access token is ready, places the actual API call.\n const voter = ({accessToken, customUserAgentString}) => {\n const headers = {\n 'Authorization': 'bearer ' + accessToken,\n }\n\n if (customUserAgentString) {\n headers['User-Agent'] = customUserAgentString\n }\n\n const formData = new FormData()\n formData.append(\"id\", redditId)\n formData.append(\"dir\", \"\" + direction)\n\n const requestConfig = {\n method: 'POST',\n headers: headers,\n body: formData,\n }\n\n fetch('https://oauth.reddit.com/api/vote', requestConfig)\n .then((response) => {\n console.log('INFO: Completed reddit vote request: ', response.ok, response.status)\n })\n .catch((err) => {\n console.log(\"ERROR: \", err)\n })\n }\n\n // Called when the connection (authorization) check completes.\n // Either starts an access token retrieval or does nothing (if not authorized).\n const connectionCheck = (isConnected) => {\n if (!isConnected) {\n return\n }\n\n return oauth.getAccessToken('reddit')\n .then(voter)\n .catch((err) => {\n console.log(\"ERROR: \", err)\n })\n }\n\n // Trigger the vote by first checking if the reddit integration is enabled.\n oauth.isProviderConnected('reddit')\n .then(connectionCheck)\n .catch((err) => {\n console.log(\"ERROR: \", err)\n })\n}",
"_updateHint(voted){\n if(voted) {\n return(<p>Check your choosed candidate!</p>);\n }\n return(<p>You can choose your candidate!</p>)\n }",
"function toggleUserVideoVote(videoId)\n\t{\n var videoIndex = indexById(videoId);\n if (videoIndex == -1)\n {\n // Couldn't find video in list\n console.log(\"Error: attempted to vote on non-existent video [\" + videoId + \"]\");\n return;\n }\n \n var user = getUserById(userId);\n if (user)\n { \n if (!user.votedVideo || user.votedVideo.length == 0)\n {\n if (!videoVotes[videoId])\n {\n videoVotes[videoId] = 1;\n }\n else\n {\n videoVotes[videoId] += 1;\n }\n \n user.votedVideo = videoId;\n }\n else if (user.votedVideo == videoId)\n {\n videoVotes[videoId] -= 1;\n user.votedVideo = \"\";\n }\n }\n \n if (videoVotes[videoId] == 0)\n {\n // Remove video from vote list\n delete videoVotes[videoId];\n }\n \n var voteCount = videoVotes[videoId] ? videoVotes[videoId] : 0; \n \n // Tell everyone about the vote change\n io.sockets.emit('videoVoteSync', videoIndex, voteCount);\n }",
"function tallyVote(lobby) {\n getGame(lobby).votes++;\n}",
"function formatToVote(){\n votedStatus = false;\n $('#vote').html('Yay Curricula!').addClass('btn-success').removeClass('btn-default');\n }",
"voteOnPost(id, vote) {\n const { dispatch } = this.props\n dispatch(votingPost(id, vote))\n alert(\"Thanks for \"+ vote +\" this post!\")\n}",
"function voteUpHandler() {\n if (!loggedIn) {\n login(function () {\n $.fb_service.vote(articleId, true);\n });\n }\n else {\n $.fb_service.vote(articleId, true);\n }\n }",
"function edgeVote(voterId, voteableId, type, vote_points) {\n assert(isValidVoteType(type), \"vote type must be in \" + VOTE_TYPES);\n\n var voteableCollection = getCollectionNameFromId(voteableId);\n var tabulatedData;\n\n // While excecuting below transaction, both 'votes' and voteableCollection are locked to\n // ensure data isolation and consistency:\n // * No-one can modify those collections while transaction is being executed\n // * All database changes will be success or failure together\n db._executeTransaction({\n collections: {\n write: [ 'votes', voteableCollection ]\n },\n\n // If you need 100% durability, change waitForSync to true. The db will wait until transaction data\n // is written to disk before return the result\n waitForSync: false,\n\n action: function () {\n // UPSERT .. mean: If there is no vote _from voterId _to voteableId, create it with INSERT ...\n // Else update vote data with UPDATE ...\n var result = db._query(`\n UPSERT { _from: @voterId, _to: @voteableId }\n INSERT { _from: @voterId, _to: @voteableId, type: @type, count: 1, createdAt: DATE_NOW() }\n UPDATE { type: @type, count: OLD.count + 1, updatedAt: DATE_NOW() } IN votes\n RETURN { isNewVote: IS_NULL(OLD), isSameVote: !!OLD && (OLD.type == NEW.type) }\n `, {\n voterId: voterId,\n voteableId: voteableId,\n type: type\n }).toArray()[0];\n // console.log(result); /* DEBUG */\n\n if (result.isSameVote) {\n\n tabulatedData = db._query(`\n LET voteableObj = DOCUMENT(@voteableId)\n RETURN {\n id: voteableObj._id,\n upVotesCount: voteableObj.upVotesCount,\n downVotesCount: voteableObj.downVotesCount,\n totalVotePoint: voteableObj.totalVotePoint\n }\n `, { voteableId: voteableId }).toArray()[0];\n\n } else { // new-vote or re-vote\n\n var upVotesCountDelta = 0;\n var downVotesCountDelta = 0;\n\n if (result.isNewVote) {\n if (type === 'up') {\n upVotesCountDelta = 1;\n } else { // down vote\n downVotesCountDelta = 1;\n }\n } else { // re-vote\n if (type === 'up') {\n upVotesCountDelta = 1;\n downVotesCountDelta = -1;\n } else { // down vote\n upVotesCountDelta = -1;\n downVotesCountDelta = 1;\n }\n }\n\n // console.log(upVotesCountDelta); /* DEBUG */\n // console.log(downVotesCountDelta); /* DEBUG */\n\n tabulatedData = db._query(`\n LET voteableObj = DOCUMENT(@voteableId)\n\n LET upVotesCount = voteableObj.upVotesCount + @upVotesCountDelta\n LET downVotesCount = voteableObj.downVotesCount + @downVotesCountDelta\n\n UPDATE voteableObj WITH {\n upVotesCount: upVotesCount,\n downVotesCount: downVotesCount,\n totalVotePoint: ${vote_points[UP]}*upVotesCount + ${vote_points[DOWN]}*downVotesCount\n } IN @@voteableCollection\n\n RETURN {\n id: NEW._id,\n upVotesCount: NEW.upVotesCount,\n downVotesCount: NEW.downVotesCount,\n totalVotePoint: NEW.totalVotePoint\n }\n `, {\n voteableId: voteableId,\n upVotesCountDelta: upVotesCountDelta,\n downVotesCountDelta: downVotesCountDelta,\n '@voteableCollection': voteableCollection\n }).toArray()[0];\n }\n } // action\n }); // _executeTransaction\n return tabulatedData;\n}",
"function createInstanceOrRetrieveThem() {\n if (localStorage.votes) {\n votes = JSON.parse(localStorage.votes);\n }\n pics.addEventListener('click', votingOnPictures);\n}",
"function voteClick(index, isUpvote) {\n var bar = getBarContainerAtIndex(index);\n var voteType = isUpvote ? \"upvote\" : \"downvote\";\n var updatedNScore = !_.contains(votingPermissions, false) ? nScore + 1 : nScore;\n\n votingPermissions[index] = false;\n toggleTooltips(\"top\", bar, false);\n \n $.ajax({\n url: getCategoryNameAtIndex(index) + '/' + voteType,\n success: function(data) {\n if(data.success) {\n reloadChart(index, isUpvote, updatedNScore);\n } else {\n alert(\"A validation error occurred while voting: \" + data.message);\n }\n },\n error: function() {\n alert(\"An internal error occurred while voting. Try again in a few minutes.\");\n toggleTooltips(\"top\", bar, true);\n }\n });\n }",
"function nextVideoByVotes()\n { \n var votes = [];\n Object.keys(videoVotes).forEach(function (key) \n { \n var value = videoVotes[key];\n votes.push([key, value]);\n });\n \n // Find highest voted video\n var highestVoted = [\"\", 0];\n for (var i = 0; i < votes.length; i++)\n {\n if (votes[i])\n {\n if (votes[i][1] > highestVoted[1] && votes[i][1] >= videoByVoteThresh)\n {\n highestVoted = votes[i];\n }\n }\n }\n \n if (videoVotes.length == 0 || highestVoted[0].length == 0)\n {\n nextVideo();\n return;\n }\n \n var highestVotedId = highestVoted[0];\n sendVideoChange(highestVotedId);\n }",
"function castVote(user, vote) {\n var pokerCard = document.getElementById(user);\n pokerCard.setAttribute(\"src\", \"/images/poker_card.png\");\n consoleLog(\"pokerCard: \" + pokerCard);\n if (voteFinished()) {\n consoleLog(\"voting finished\");\n socket.emit(\"voting-finished\");\n }\n}",
"async incrementDownvote(reviewId, authenticateduser) {\n const downvoteAdded = await addDownvoter(reviewId, authenticateduser)\n if (downvoteAdded !== null) {\n let upvotes = await getUpvoters(this.props.reviewId)\n let downvotes = await getDownvoters(this.props.reviewId)\n upvotes = upvotes.data.length\n downvotes = downvotes.data.length\n this.setState({upvotes: upvotes})\n this.setState({downvotes: downvotes})\n }\n }",
"function increaseYakuzaVote(value)\n {\n setGame(\"yakuza\");\n setVotes(true);\n }",
"async FindVoteByCandidateKey(ctx, candidatekey) {\n let queryString = {};\n queryString.selector = {};\n queryString.selector.docType = 'vote';\n queryString.selector.key = candidatekey;\n return await this.GetQueryResultForQueryString(ctx, JSON.stringify(queryString)); //shim.success(queryResults);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
select the specified row via step value, if the step is not assigned, the current row is selected as the combogrid value. | function selectRow(target, step){
var opts = $.data(target, 'combogrid').options;
var grid = $.data(target, 'combogrid').grid;
if (opts.multiple) return;
if (!step){
var selected = grid.datagrid('getSelected');
if (selected){
setValues(target, [selected[opts.idField]]); // set values
$(target).combo('hidePanel'); // hide the drop down panel
}
return;
}
var selected = grid.datagrid('getSelected');
if (selected){
var index = grid.datagrid('getRowIndex', selected[opts.idField]);
grid.datagrid('unselectRow', index);
index += step;
if (index < 0) index = 0;
if (index >= grid.datagrid('getRows').length) index = grid.datagrid('getRows').length - 1;
grid.datagrid('selectRow', index);
} else {
grid.datagrid('selectRow', 0);
}
} | [
"function selectRow(target, step){\n\t\tvar opts = $.data(target, 'combogrid').options;\n\t\tvar grid = $.data(target, 'combogrid').grid;\n\t\tif (opts.multiple) return;\n\t\t\n\t\tif (!step){\n\t\t\tvar selected = grid.datagrid('getSelected');\n\t\t\tif (selected){\n\t\t\t\tsetValues(target, [selected[opts.idField]]);\t// set values\n\t\t\t\t$(target).combo('hidePanel');\t// hide the drop down panel\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tvar selected = grid.datagrid('getSelected');\n\t\tif (selected){\n\t\t\tvar index = grid.datagrid('getRowIndex', selected[opts.idField]);\n\t\t\tgrid.datagrid('unselectRow', index);\n\t\t\tindex += step;\n\t\t\tif (index < 0) index = 0;\n\t\t\tif (index >= grid.datagrid('getRows').length) index = grid.datagrid('getRows').length - 1;\n\t\t\tgrid.datagrid('selectRow', index);\n\t\t} else {\n\t\t\tgrid.datagrid('selectRow', 0);\n\t\t}\n\t}",
"function selectrow() {\n\n var grid = jQuery(\"#FieldGrid\");\n var roleKey = grid.getGridParam(\"selrow\");\n var ParentId = grid.jqGrid(\"getCell\", roleKey, \"ID\").toString();\n if (ParentId != null) {\n jQuery(\"#TestCaseFieldValuesGrid\").setGridParam({ url: \"/TestCaseFieldValues/GetFieldValues/?parentRowID=\" + ParentId });\n jQuery(\"#TestCaseFieldValuesGrid\").trigger(\"reloadGrid\", [{ page: 1 }]);\n\n jQuery(\"#TestCaseFieldValuesGrid\").setGridParam({ url: \"/TestCaseFieldValues/EditFieldValues/?parentRowID=\" + ParentId });\n jQuery(\"#TestCaseFieldValuesGrid\").trigger(\"reloadGrid\", [{ page: 1 }]);\n $(\"#TestCaseFieldValuesGrid\").show();\n\n }\n}",
"function updateSelectedRows() {\n var selectedList = [];\n if (grid.api) {\n var selectedRows = grid.api.selection.getSelectedRows();\n _.each(selectedRows, function (row) {\n selectedList.push(row[component.constants.ROW_IDENTIFIER]);\n });\n }\n component.onSelectRows(selectedList);\n }",
"action() {\n if (this.selectedRows().length > 0) {\n dispatch.action(this.element, this.selectedRows());\n }\n }",
"function highlight_curr_row()\r\n{\r\n\r\n\t// temporarily turn off table rendering\r\n\tdata_view.beginUpdate();\r\n\r\n // get current row\r\n\tvar curr_data_row = convert_row_ids([curr_row_selected])[0];\r\n var item = data_view.getItemById(curr_data_row);\r\n var num_cols = item.length;\r\n\r\n // update current row (set to draw box around it -- see select_rows())\r\n item[num_cols-1] = item[num_cols-1] + 10;\r\n\r\n // put row back in table\r\n data_view.updateItem(curr_data_row, item);\r\n\r\n // update previous row\r\n if (prev_row_selected != null) {\r\n\r\n // get previous row\r\n var prev_data_row = convert_row_ids([prev_row_selected])[0];\r\n item = data_view.getItemById(prev_data_row);\r\n\r\n // remove box around previous row\r\n item[num_cols-1] = item[num_cols-1] - 10;\r\n\r\n // put row back in table\r\n data_view.updateItem(prev_data_row, item);\r\n }\r\n\r\n\t// turn on table rendering\r\n\tdata_view.endUpdate();\r\n\r\n}",
"select(option) {\n this.selectValue(option.value);\n }",
"selectSlotItem(value) {\n const items = this.getSelectableElements();\n for (let i = 0; i < items.length; i += 1) {\n const item = items[i];\n if (this.getItemValue(item) === value) {\n item.selected = true;\n return true;\n }\n }\n return false;\n }",
"function scrollToSelectedRow(gridSelector) {\r\n var gridWrapper = document.querySelector(gridSelector);\r\n if (gridWrapper) {\r\n var selectedRow = gridWrapper.querySelector(\"tr.k-state-selected\");\r\n if (selectedRow) {\r\n selectedRow.scrollIntoView();\r\n }\r\n }\r\n}",
"function changeToNextField(e) {\n $sel = $sel.next(\"td.editable\");\n if($sel.length < 1) {\n $sel = $sel.parent(\"tr.griderRow\").siblings(\"tr:first\").find(\"td.editable:first\");\n }\n setSelectedCell($sel);\n $sel.trigger(\"click\");\n }",
"setStepperStep(state, step){\n\t\t\tVue.set(state, 'stepper_current_step', step);\n\t\t}",
"function SetRowColor(row)\r\n{\r\n if (row.getAttribute(\"selected\") == 1)\r\n {\r\n StyleSetAttributes(row, \"background-color: yellow;\");\r\n }\r\n else if (row.rowIndex % 2 == 1)\r\n {\r\n //StyleSetAttributes(row, \"background-color: lightgoldenrodyellow;\");\r\n StyleSetAttributes(row, \"background-color: #FFF3C3;\");\r\n }\r\n else\r\n {\r\n //StyleSetAttributes(row, \"background-color: #FFFF99;\");\r\n StyleSetAttributes(row, \"background-color: #F6CCC0;\");\r\n }\r\n}",
"function SDitemSelection(section, order, choice) {\n // get current section layout\n curOrder = api.parameters.get({name: section}, \"CommPlugin_1\").data[0].value;\n curOrderArr = curOrder.split(',');\n // access the right order to alter user selection\n curOrderArr[order] = choice;\n // update parameter\n api.parameters.updateAsync({\n name: section,\n value: curOrderArr.toString()\n });\n}",
"function buildSingleSelectCell(control, columnIndex) {\n // only one selection - selected is single index\n var $cell = buildControlCell(control, columnIndex);\n if (control.selected === columnIndex) {\n $cell.addClass(SELECTED_CLASS);\n }\n setSelectedText($cell, control, columnIndex);\n\n // only add the handler to non-disabled controls\n if (!$cell.hasClass(DISABLED_CLASS)) {\n $cell.click(function selectClick(ev) {\n var $cell = $(this);\n // don't re-select or fire event if already selected\n if (!$cell.hasClass(SELECTED_CLASS)) {\n // only one can be selected - remove selected on all others, add it here\n var $otherSelected = $cell\n .parent()\n .children(`.${SELECTED_CLASS}`)\n .removeClass(SELECTED_CLASS);\n $otherSelected.each(function() {\n setSelectedText($(this), control, columnIndex);\n });\n\n $cell.addClass(SELECTED_CLASS);\n setSelectedText($cell, control, columnIndex);\n\n // fire the event from the table itself, passing the id and index of selected\n var eventData = {};\n\n var key = $cell.parent().attr(\"id\");\n eventData[key] = $cell.data(COLUMN_INDEX_DATA_KEY);\n $cell.parents(\".peek\").trigger(CHANGE_EVENT, eventData);\n }\n });\n }\n return $cell;\n}",
"selectNext() {\n\n // select the next, or if it is the last entry select the first again\n if (this.selected >= this.sequence.length - 1) {\n this.selected = 0;\n }\n else {\n this.selected++;\n }\n\n // highlight the selected entry\n this.highlightSelected();\n\n }",
"function markSelected(btn) {\n if (lastRowSelected != null)\n lastRowSelected.classList.remove(\"selected\");// remove the last row selected(last row = DOM element)\n let row = (btn.parentNode).parentNode; // button is in TD which is in Row\n row.className = 'selected'; // mark as selected\n lastRowSelected = row;\n}",
"function unselect(self, value){\r\n var opts = self.options;\r\n var combo = self.combo;\r\n var values = combo.getValues();\r\n var index = $.inArray(value+'', values);\r\n if (index >= 0){\r\n values.splice(index, 1);\r\n setValues(self, values);\r\n opts.onUnselect.call(self, opts.finder.getRow(self, value));\r\n }\r\n }",
"function setGridViewCurrentRow(gridView, rowId) {\n for (var i = 0, len = gridView.rows.length; i < len; i++) {\n var nextRow = gridView.rows[i];\n if (nextRow.bindingContext.id === rowId) {\n nextRow.makeCurrent();\n return;\n }\n }\n }",
"function OnClickMoveDown()\r\n{\r\n var rows = iDoc.getElementById(\"dataTable\").rows;\r\n\r\n\r\n for (var i = rows.length - 2; i > 0; i--)\r\n {\r\n row1 = rows[i].getAttribute(\"selected\");\r\n row2 = rows[i + 1].getAttribute(\"selected\");\r\n\r\n\r\n if (row1 == 1 && row2 == 0)\r\n {\r\n rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);\r\n changesMade = true;\r\n }\r\n }\r\n SetAllRowColors();\r\n}",
"selectNextRegion() {\r\n let region = null;\r\n let i = 0;\r\n const length = this.regions.length;\r\n if (length === 1) {\r\n region = this.regions[0];\r\n }\r\n else if (length > 1) {\r\n while (i < length && region == null) {\r\n if (this.regions[i].isSelected) {\r\n region = (i === length - 1) ? this.regions[0] : this.regions[i + 1];\r\n }\r\n i++;\r\n }\r\n }\r\n if (region == null && length > 0) {\r\n region = this.regions[0];\r\n }\r\n this.selectRegion(region);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the select list for herdnames & settle event | function createSelectList(herdNames) {
herdList
.selectAll("option")
.data(herdNames)
.enter()
.append("option")
.attr("value", d => d)
.property("selected", d => d === herd)
.text(d => d)
herdList
.on("change", () => {
new Promise(resolve => {
d3.select("#traj-loading")
.append("div")
.attr("id", "traj-loading")
.attr("class", "spinner-border")
.attr("role", "status")
.append("span")
.attr("class", "visually-hidden")
.text("Loading...")
setTimeout(() => resolve(1), 1)
}).then(d => {
updateDataFromSelectedHerdName() //update current herd data
updateSlider() //update the slider accordingly
svg.call(zoom.transform, zoomTransform) //update map accordingly
d3.select("#traj-loading").remove();
})
})
} | [
"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 GenerateOptionsandList() {\n var optn = '';\n var li = '';\n try {\n if (MasterPlainLanguages.length > 0) {\n for (var i = 0; i < MasterPlainLanguages.length; i++) {\n optn = optn + '<option value=\"' + MasterPlainLanguages[i].PlainLanguageName + '\">' + MasterPlainLanguages[i].PlainLanguageName + '</option>';\n li = li + '<li class=\"list-group-item\"><a>' + MasterPlainLanguages[i].PlainLanguageName + '</a></li>';\n }\n } else {\n throw \"Plain Languages Not Available\";\n }\n } catch (err) {\n console.log(err);\n }\n $(\"#selectplainlang\").append(optn);\n $('.plainlanglist').append(li);\n $(\"#selectplainlang\").customselect();\n return;\n }",
"function createDropDown() {\t\r\n\t\tif(document.getElementById('programList')){\r\n\t\t\t\tvar sel = document.getElementById('programList');\r\n\t\t\t\tfor (const [id,name] of programsIDtoNAME.entries()) {\r\n\t\t\t\t\t\tvar opt = document.createElement('option');\t\t\r\n\t\t\t\t\t\t//console.log(name);\t\r\n\t\t\t\t\t\topt.innerHTML = name;\r\n\t\t\t\t\t\t//console.log(id);\t\r\n\t\t\t\t\t\topt.value = id;\r\n\t\t\t\t\t\tsel.appendChild(opt);\r\n\t\t\t\t}\t\t\r\n\t\t\t\tprogramListCreated=1;\t\t\t\r\n\t\t}\r\n}",
"function buildSelect(heroes) {\n var select = document.createElement(\"select\");\n heroes.forEach(h => {\n select.innerHTML += \"<option value='\" + h.link + \"' data-name='\" + h.name + \"'>\" + h.name + \"</option>\";\n })\n return select;\n }",
"function makeSelectField() {\n\t\tvar formTag = document.getElementsByTagName(\"form\"), //formTag is an array of all the form tags\n\t\t\tselectDiv = $(\"selectDiv\"),\n\t\t\tmakeSelect = document.createElement(\"select\");\n\t\t\tmakeSelect.setAttribute(\"id\", \"dropdownSelect\");\n\t\tfor(var i=0, j=pebbleGroups.length; i<j; i++){\n\t\t\tvar makeOption = document.createElement(\"option\");\n\t\t\tvar optText = pebbleGroups[i];\n\t\t\tmakeOption.setAttribute(\"value\", optText);\n\t\t\tmakeOption.innerHTML = optText;\n\t\t\tmakeSelect.appendChild(makeOption);\n\t\t}\n\t\tdocument.getElementById(\"selectDiv\").appendChild(makeSelect);\n\t}",
"function popEvtList() {\n var theTable = document.getElementById('FileLogTable');\n var calNames = \"\";\n var opt = document.createElement('option');\n var selecter = document.getElementById('evtDropDown');\n\n //reset the selecter\n selecter.options.length = 0;\n\n for(var i = theTable.rows.length -1; i > 0; i--) {\n calNames += \",\" + theTable.rows[i].cells[0].textContent;\n }\n\n //populate an array with the cal files\n calArr = calNames.split(',');\n\n //clear the selector\n selecter.innerHTML = \"\";\n\n //iterate over the array adding each element to the selecter\n for(var j = 1; j < calArr.length; j++) {\n var option = document.createElement(\"option\");\n var temp = calArr[j];\n option.textContent = temp;\n option.value = temp;\n selecter.add(option);\n }\n\n \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 getGroup() {\n\n for(var i = 0; i < data.length; i++) {\n\n $('<option value=' + data[i].id + '>' + data[i].firstName + ' ' + data[i].surname + '</option>').appendTo(\"#friendPicker\");\n }\n\n }",
"function populateBreedsSelect(breeds) {\n $breed_select.empty().append(function() {\n let output = '';\n $.each(breeds, function(key, value) {\n output += '<option id=\"' + value.id + '\">' + value.name + '</option>';\n });\n return output;\n });\n}",
"function setOptions() {\n optionList.html('');\n var count = 0;\n var optionLength = HTMLSelect.options().length;\n\n if (optionLength > 9) {\n optionList.addClass('is-scroll');\n }\n\n if (optionLength === 1 || optionLength === 0) {\n console.log('EEE ', HTMLSelect.getSelectVal())\n if (HTMLSelect.getSelectVal() == \"\" ||\n HTMLSelect.getSelectVal() == 0 ||\n HTMLSelect.getSelectVal() == null ||\n HTMLSelect.getSelectVal() == undefined) {\n $this.addClass('is-disabled');\n } else {\n $this.removeClass('is-disabled');\n }\n } else {\n $this.removeClass('is-disabled');\n }\n HTMLSelect.options().map(function (option) {\n\n var li = $('<li>');\n\n if (option.isSelected) {\n li.addClass('selected');\n }\n if (option.isDisabled) {\n li.addClass('disabled');\n }\n\n li.html(option.text);\n li.attr('data-val', option.val);\n optionList.append(li);\n count++;\n });\n\n }",
"function populate_as_dropdown(element, entries, default_text) {\n if (element) {\n var name_attr = $(element).attr(\"name\");\n var id_attr = $(element).attr(\"id\");\n var class_attr = $(element).attr(\"class\");\n var other_attr = $(element).attr(\"other\");\n my_events = $._data( $(element)[0], \"events\");\n if (entries.length > 0) {\n var new_element = $(\"<select></select>\", {\"id\": id_attr, \"class\": class_attr, \"name\": name_attr, \"other\": other_attr});\n if (my_events) {\n $.each(my_events, function (i, event) {\n $.each(event, function (j, v){\n $(new_element).on(i, v.handler); \n });\n });\n }\n $(element).replaceWith(new_element);\n $(new_element).html(\"<option value=''>\" + default_text + \"</option>\");\n for (var i = 0; i < entries.length; i++) {\n $(new_element).append(\"<option value='\" + entries[i] + \"'>\" + entries[i] + \"</option>\");\n }\n $(new_element).append(\"<option value='Other'>Other</option>\");\n if (entries.length == 1) {\n $(new_element).val(entries[0]);\n $(new_element).trigger(\"change\");\n }\n handle_other_option(new_element);\n }\n }\n}",
"function ajouterListe(l,liste){\n liste.append('<option value=' + l.id + '>' + l.name +'</option>');\n}",
"function createDropdowns(){\r\n\tdenominations.forEach(mainDropdown);\r\n\tupdateAddableCurrencies();\r\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 fillTeacherSelector() {\n var $dropdown = $(\"#teacher-select\");\n $($dropdown).empty();\n\n $.ajax({\n method: \"POST\",\n url: \"http://localhost:1340/graphql\",\n contentType: \"application/json\",\n data: JSON.stringify({\n query: teacherQuery\n })\n }).done(function(result) {\n // fill the teachers dropdown\n $.each(result.data.teachers, function() {\n // console.log(this);\n $dropdown.prepend($(\"<option />\").val(this.RefId).text(this.PersonInfo.Name.GivenName +\n \" \" + this.PersonInfo.Name.FamilyName));\n });\n // have to re-initialise component to render\n $($dropdown).formSelect();\n });\n}",
"function createGenresSelect(container, genres) {\n for (var i = 0; i < genres.length; i++) {\n var option = $(\".template option\").clone();\n option.val(genres[i][\"id\"]).text(genres[i][\"name\"])\n container.append(option);\n }\n}",
"function loadHoseTypes() {\n $.get(\"/api/general/hoseTypes\"\n ).done(function (data) {\n var hoseType = $(\"#hoseType\");\n $.each(data.hoseTypes, function (index, element) {\n hoseTypes[element.id] = element;\n hoseType.append($(\"<option/>\", {text: element.name, value: element.id}))\n });\n loadHoseEvents();\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 }",
"fillCountrySelect(data) {\n\n const countries = data.map(d => `<option value=\"${d.code}\">${d.name}</option>`).join(' ');\n this.countrySelect.innerHTML += countries;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put outpoint record in database. If the record already exists, add the request id to it. TODO: refactor so that it accepts an outpoint instead of an orecord | async putOutpointRecord(orecord, request) {
assert(orecord instanceof OutpointRecord);
if (await this.hasOutpointRecord(orecord)) {
assert(request instanceof Request);
assert(Buffer.isBuffer(request.id));
const r = await this.getOutpointRecord(
orecord.prevout.hash,
orecord.prevout.index
);
r.add(request.id);
orecord = r;
}
const {hash, index} = orecord.prevout;
const key = layout.o.encode(hash, index);
if (this.batch)
this.put(key, orecord.encode());
else
await this.db.put(key, orecord.encode());
return orecord;
} | [
"async addRequest(request) {\n // make sure these writes are atomic\n\n if (!this.batch)\n this.start();\n\n const r = await this.putRequest(request);\n let orecord, srecord;\n\n // index the outpoint when it contains data\n if (!request.spends.isNull()) {\n orecord = OutpointRecord.fromOptions({\n prevout: {\n hash: request.spends.hash,\n index: request.spends.index\n },\n requests: [r.id]\n });\n\n this.logger.debug('Index orecord: %s/%s',\n util.revHex(request.spends.hash), request.spends.index);\n\n await this.putOutpointRecord(orecord, r);\n }\n\n // index the script when it contains data\n if (!request.pays.raw.equals(Buffer.alloc(0))) {\n srecord = ScriptRecord.fromOptions({\n script: request.pays.raw,\n requests: [r.id]\n });\n\n this.logger.debug('Index srecord: %s',\n request.pays.raw.toString('hex'));\n\n await this.putScriptRecord(srecord, request);\n }\n\n await this.commit();\n\n return [r, orecord, srecord];\n }",
"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 addItem(req, res, next) {\n var userId = req.userId,\n offerId = req.body.offerId; // the id in the postgres table\n\n console.log(JSON.stringify(req.body));\n\n db.query('SELECT offerId FROM wallet WHERE userId=$1 AND offerId=$2', [userId, offerId], true)\n .then(function(offer) {\n if (offer) {\n return res.send(400, 'This offer is already in your wallet');\n }\n db.query('INSERT INTO wallet (userId, offerId) VALUES ($1, $2)', [userId, offerId], true)\n .then(function () {\n return res.send('ok');\n })\n .fail(function(err) {\n return next(err);\n });\n })\n .catch(next);\n}",
"static createOffice(req, res) {\n const { officename, officeAddress } = req.body;\n if (!officename) {\n return res.status(400).send({\n success: 'false',\n message: 'office name is required'\n });\n }\n if (!officeAddress) {\n return res.status(400).send({\n success: 'false',\n message: 'hqaddress is required'\n });\n }\n /*\n =========================================\n CHECK IF THE PARTY NAME ALREADY EXIST\n ==========================================\n */ \n const result = politicalOfficeDb.filter(officeName => officeName.officename === officename.toLowerCase());\n if (!result.length < 1) {\n return res.status(400).json({ message: 'party already exit' });\n }\n const data = {\n id: politicalOfficeDb.length + 1,\n officename: officename.toLowerCase(),\n officeAddress\n };\n /*\n =========================================\n PUSH DATA INTO DUMMY DATABASE\n ==========================================\n */\n\n politicalOfficeDb.push(data);\n return res.status(200).json({\n success: true,\n message: 'politiccal office created successfully',\n data\n });\n }",
"async addFarmToInvestmentMethod(req, res, next) {\n try {\n const {\n body,\n models: { Investments },\n } = req;\n var { farm, investment } = body;\n farm = JSON.parse(JSON.stringify(farm));\n console.log(farm);\n var inv = await Investments.findById(investment);\n if (!inv) {\n throw Error('Couldnt find this investment');\n }\n farm.position = {\n type: 'Point',\n coordinates: farm.coordinates || [],\n };\n inv.farm.photos = farm.photos;\n inv.farm.product.photos = farm.product.photos;\n inv.farm.name = farm.name;\n inv.farm.address = farm.address;\n inv.farm.position = farm.position;\n inv.farm.product.name = farm.product.name;\n inv.farm.product.category = farm.product.category;\n if (!inv.completed.includes('Farm')) {\n inv.completed.push('Farm');\n }\n await inv.save();\n return successResponse(res, 'Farm detail added successfully', 200, inv);\n } catch (error) {\n return errorHandler(error, req, res, next);\n }\n }",
"proposePlace(req, res, next) {\n // employee proposes a place\n req.assert('place', 'Place is missing').notEmpty();\n req.getValidationResult().then(result => {\n if (result.isEmpty()) {\n const eventId = req.query.eventId;\n const place = req.body.place;\n // Validate req data\n if (!eventId || !Utils.isValidObjectId(eventId) || !place) {\n return Callbacks.ValidationError('Invalid id or place' || 'Validation error', res);\n } else {\n // check for exisiting and update\n EventModel.findOne({\n _id: new ObjectID(eventId)\n }, (err, existinEvent) => {\n if (err) {\n return Callbacks.SuccessWithError(err, res);\n }\n if (existinEvent) {\n // if event is already finalized return err message\n if (existinEvent.isFinalized) {\n return Callbacks.SuccessWithError('Event already finalized', res);\n }\n // update proposed places array\n existinEvent.proposedPlaces.push(req.body.place);\n const eventUpdate = {\n $set: {\n eventName: existinEvent.eventName,\n proposedPlaces: existinEvent.proposedPlaces,\n isFinalized: existinEvent.isFinalized\n }\n };\n\n // update the event\n EventModel.update({ _id: new ObjectID(eventId) }, eventUpdate, function (err, result) {\n console.log('err', err);\n if (err) {\n return Callbacks.InternalServerError(err, res);\n }\n // mail template \n const emailtemplate = `<h1>Hi ${Constants.MANAGER_EMAIL}, a new place , \n ${place.locationName} has been added to the Event, ${existinEvent.eventName}.\n </h1><a href='${Constants.APP_REDIRECT_URL}'>Click Here to Goto App</a>`;\n // sending mail via emailer utility function\n Emailer.sendEmail(\n Constants.MANAGER_EMAIL, Constants.FROM_MAIL, Constants.EVENT_PLACE_ADDITION_SUBJECT,\n '', emailtemplate\n ).then(resp => {\n console.log('Emailer reponse', resp)\n const response = 'Event : propose place updated successfully!';\n return Callbacks.Success(response, res);\n })\n .catch(err => {\n return Callbacks.Failed(404, 'Couldnt Send mail', res)\n })\n\n });\n } else {\n return Callbacks.SuccessWithError('Event does not exist.', res);\n }\n });\n }\n } else {\n const errors = result.array();\n return Callbacks.ValidationError(errors[0].msg || 'Validation error', res);\n }\n });\n }",
"function upsert(endpoint, doc) {\n var http = require('http');\n var url = require('url');\n var parts = url.parse(endpoint);\n var options = {\n host: parts.hostname,\n path: parts.path,\n port: parts.port,\n method: 'POST'\n };\n console.log(options);\n\n var req = http.request(options, function(res) {\n console.log('STATUS: ' + res.statusCode);\n console.log('HEADERS: ' + JSON.stringify(res.headers));\n res.setEncoding('utf8');\n res.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n });\n req.write(JSON.stringify(doc));\n req.end();\n}",
"function savePosition(drawId) {\n var logUser = $(\"#logUser\").val();\n //find where the username is the same as the logged in user\n db.users.where(\"username\").equals(logUser).first().then\n (function (thisUser) {\n //take the user id and associate it with their position and drawing in the DB.\n var userId = JSON.stringify(thisUser.userId);\n var positionData = {\n position: {lat: marker.position.lat(), lng: marker.position.lng()\n },\n drawingsId: drawId,\n userId: userId\n };\n //add location, drawing id and user id to the db\n db.locations.add(positionData);\n });\n}",
"function saveRecord(record) {\n const transaction = db.transaction([\"pending\"], \"readwrite\");\n \n // object store for pending db data to be accessed\n const store = transaction.objectStore(\"pending\");\n console.log(\"store\")\n // adds the record with the store\n store.add(record);\n }",
"function upsert(req, res) {\n if (req.body._id) {\n delete req.body._id;\n }\n return _search2.default.findOneAndUpdate({ _id: req.params.id }, req.body, { new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true }).exec().then(respondWithResult(res)).catch(handleError(res));\n}",
"addMarkerToDatabase(newObservation, map) {\n\n let configObj = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify(newObservation)\n };\n\n fetch(this.baseURL, configObj)\n .then(function(response) {\n return response.json()\n })\n .then(json => {\n let obs = json.data\n let observation = new Observation(obs.id, obs.attributes.name, obs.attributes.description, obs.attributes.category_id, obs.attributes.latitude, obs.attributes.longitude)\n observation.renderMarker(map)\n })\n .catch(function(error) {\n alert(\"ERROR! Please Try Again\");\n console.log(error.message);\n });\n }",
"function addVisitId(db, p_id, v_id, v_date) {\n return new Promise((resolve, reject) => {\n return db.get(p_id)\n .then(function(doc) {\n if (!doc.visit_ids){doc.visit_ids = []} //needed for old record compatability\n patient = new pmodel.Patient(doc)\n patient.visit_ids.push(v_id);\n patient.last_visit = v_date;\n return db.put(patient)\n .then(result => {\n resolve(result);\n })\n .catch(err => {\n console.log(\"error in addVisitID\", err);\n reject(err);\n });\n });\n });\n}",
"function post_authorization_request(authorization_request) {\n return new Promise((resolve, reject) => {\n dbMgr\n .updateOne(\"authorization_request\", {\n client_id: {\n $eq: null\n }\n }, {\n $set: authorization_request\n }, {upsert: true})\n .then((result) => {\n if (result.upsertedCount === 1) {\n return resolve(result.upsertedId._id);\n } else {\n return reject(new Error(\"No authorization recoreds inserted\"));\n }\n }, (err) => {\n reject(err);\n });\n });\n}",
"function addLocation() {\n\n personAwardLogic.addLocation($scope.awardLocation, personReferenceKey).then(function (response) {\n\n var locationId = null;\n if (appConfig.APP_MODE == 'offline') {\n locationId = response.insertId;\n } else {\n\n locationId = response.data.InsertId;\n }\n\n addPersonAward(locationId);\n\n }, function (err) {\n appLogger.error('ERR' + err);\n });\n }",
"function upsertRegimen(req, res, next){\r\n var card = req.body.regimen;\r\n var pat = parseInt(req.params.pat_id);\r\n var card_id = req.body.test2;\r\n\r\n// if updating a card\r\n if (card_id) {\r\n req.app.get('db').regimens.update({id: card_id, card: card}, function(err, result){\r\n if (err) {\r\n console.log(\"Could not update card\");\r\n } else {\r\n console.log(\"Card successfully updated\");\r\n res.json(result);\r\n }\r\n });\r\n// if creating a card\r\n } else {\r\n req.app.get('db').regimens.save({doc_id: req.user.id, pat_id: pat, card: card}, function(err, result){\r\n if (err) {\r\n console.log(\"Could not create card\");\r\n } else {\r\n console.log(\"Card successfully created\");\r\n res.json(result);\r\n }\r\n });\r\n }\r\n}",
"async addFarmerToInvestmentMethod(req, res, next) {\n try {\n const {\n body,\n models: { Investments },\n } = req;\n var { farmer, investment } = body;\n var inv = await Investments.findById(investment);\n if (!inv) {\n throw Error('Couldnt find this investment');\n }\n farmer.position = {\n type: 'Point',\n coordinates: farmer.coordinates,\n };\n inv.farmer = farmer;\n if (!inv.completed.includes('Farmer')) {\n inv.completed.push('Farmer');\n }\n await inv.save();\n return successResponse(res, 'Farmer detail added successfully', 200, inv);\n } catch (error) {\n return errorHandler(error, req, res, next);\n }\n }",
"function add(accessPoint) {\n\tlog.debug('adding ap data to db: %O', accessPoint)\n\treturn redis.pset(ACCESS_POINT_KEY(accessPoint.accessPointId), JSON.stringify(accessPoint))\n}",
"function insertEVV(longitude, latitude) {\n //get user data to pull correct schedule\n $.ajax({\n url: \"/api/user_data\",\n type: \"GET\"\n }).then(function(userData) {\n //get shift record for shift occuring today\n $.ajax({\n url: \"/api/shiftRecord/\" + userData.id,\n type: \"GET\"\n }).then(function(currentShift) {\n //checks if today's shift clientSignature has a value which indicates shift end\n if (currentShift.clientSignature) {\n //creates Check Out object to send to db\n var EVVRecord = {\n checkOutLongitude: longitude,\n checkOutLatitude: latitude,\n checkOutTime: moment().format(\"h:mm:ss\"),\n UserID: userData.id,\n id: currentShift.id\n };\n } else {\n //creates Check In object if client signature is blank in database\n var EVVRecord = {\n checkInLongitude: longitude,\n checkInLatitude: latitude,\n checkInTime: moment().format(\"h:mm:ss\"),\n UserID: userData.id,\n id: currentShift.id\n };\n }\n //puts new EVVRecord data into database for respective Check In or Check Out\n $.ajax({\n method: \"PUT\",\n url: \"/api/EVVRecord\",\n data: EVVRecord\n }).then(\n console.log(\"successfully updated shift id: \" + currentShift.id)\n );\n });\n });\n }",
"addARequestToMempool(request){\r\n let self = this;\r\n\r\n //we use an array to hold the request index in mempool array based on the wallet address\r\n let indexToFind = this.walletList[request.walletAddress];\r\n let validInWalletList = this.validWalletList[request.walletAddress];\r\n\r\n //if user already validated the request sends an error\r\n if(validInWalletList){\r\n throw Boom.badRequest(\"There is a valid signature request already made and verified, you can now add star\");\r\n return;\r\n }\r\n\r\n //if this is the first request\r\n if(indexToFind == null){\r\n //calculates time left\r\n let timeElapse = this.getCurrentTimestamp()-request.requestTimeStamp;\r\n let timeLeft = (this.TimeoutRequestWindowTime/1000)-timeElapse;\r\n request.validationWindow = timeLeft;\r\n\r\n //add the request to the mempool\r\n indexToFind = this.mempool.push(request)-1;\r\n console.log(\"New index added: \"+indexToFind+\" - address: \"+request.walletAddress);\r\n this.walletList[request.walletAddress] = indexToFind;\r\n\r\n //sets a timeout of 5 minutes to remove the request\r\n this.timeoutRequests[request.walletAddress] = setTimeout(function (){self.removeValidationRequest(request.walletAddress)},self.TimeoutRequestWindowTime);\r\n return request; \r\n } else{ //if request is already in memory\r\n //gets the existent request\r\n let existentRequest = this.mempool[indexToFind];\r\n \r\n //calculates time left\r\n existentRequest.requestTimeStamp = this.mempool[indexToFind].requestTimeStamp;\r\n let timeElapse = (this.getCurrentTimestamp())-existentRequest.requestTimeStamp;\r\n let timeLeft = (this.TimeoutRequestWindowTime/1000) - timeElapse;\r\n existentRequest.validationWindow = timeLeft;\r\n\r\n return existentRequest;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'addiv' Write a function called arePalindromes that takes two strings as arguments and return true if one is the palindrome of the other returns returns false otherwise | function arePalindromes(a, b) {
const sortedA = a
.split(" ")
.join("")
.split("")
.sort()
.join("");
const sortedB = a
.split(" ")
.join("")
.split("")
.sort()
.join("");
return sortedA === sortedB;
} | [
"function isPalindrome() {\n\n}",
"function isPalindrome(word) {\n\treturn reversed(word) === word\n}",
"function checkIfPalindrome() {\n let userInput = getUserInput(\"Please enter a word to check to see if it's a palindrome:\");\n let backwardsWord = reverseAString(userInput);\n if(userInput === backwardsWord) {\n console.log(userInput + \" is a palindrome!\");\n return true;\n }\n else {\n console.log(userInput + \" is NOT a palindrome!\");\n return false;\n }\n}",
"function palindrome(str) {\n\n // set variables to the start and end of the string\n var start = 0;\n var end = str.length - 1;\n\n // only continue the loop until the variables meet in the middle\n // set to (start < end) because if there are an odd number of characters\n // there is no need to check the middle character\n while (start < end) {\n\n // skip over any characters that are not a word character\n if (str[start].match(/[\\W_]/)) {\n start++;\n continue;\n };\n\n if (str[end].match(/[\\W_]/)) {\n end--;\n continue;\n };\n \n // convert the characters to lower case and check for match\n // if the characters do not match, immediately return false\n // otherwise, move towards the center and loop again\n if (str[start].toLowerCase() != str[end].toLowerCase()) {\n return false;\n } else {\n start++;\n end--;\n };\n };\n\n // if the entire string has been matched, the input must be a palindrome.\n return true;\n\n}",
"function stringCheck(str1, str2){\nif (str1 == \"\" || str2 == \"\"){\n return true;\n}\nif (str1.length > str2.length){\n return false;\n}\n\nvar arr1 = str1.toLowerCase().split(\"\").sort();\nvar arr2 = str2.toLowerCase().split(\"\").sort();\n\nfor (var i = 0; i<str1.length; i++){\n if (arr1[i]!=arr2[i]){\n return false;\n }\n}\nreturn true;\n}",
"function isPalindrome(text, startPos) {\n for (var j = startPos; j < startPos + (text.length - startPos) / 2; j++) {\n let end = text[text.length - j - 1 + startPos];\n if (text[j] != end) {\n return false;\n }\n }\n\n return true;\n}",
"function isPalindrome(theList) {\r\n\tif(theList == null) return false;\r\n\t\r\n\t//set up the nodes; counter counts the number nodes in the list - I'm assuming that info isn't given to us \r\n\tvar listStart = theList, listEnd = theList, counter = 0; \r\n\twhile(listEnd.next != null) {\r\n\t\tlistEnd = listEnd.next;\r\n\t\tcounter++;\r\n\t} \r\n\tcounter++;\r\n\t\r\n\t//I use counter just so we can know if the list has an even or odd number of items; this determines how we'll end the loop\r\n\tif(counter % 2 != 0) {\r\n\t\t//an odd number of nodes means that the ends will converge into one middle node \r\n\t\twhile(listStart != listEnd) {\r\n\t\t\t//stop immediately if we are ever not equal\r\n\t\t\tif(listStart.value != listEnd.value) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t//move nodes closer to each other\r\n\t\t\tlistStart = listStart.next;\r\n\t\t\tlistEnd = listEnd.prev;\r\n\t\t}\r\n\t} else if(counter % 2 == 0) {\r\n\t\t//an even number of nodes means that we will have two center nodes \r\n\t\twhile(listStart.next != listEnd) {\r\n\t\t\t//stop immediately if we are ever not equal\r\n\t\t\tif(listStart.value != listEnd.value) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t//move nodes closer to each other\r\n\t\t\tlistStart = listStart.next;\r\n\t\t\tlistEnd = listEnd.prev;\r\n\t\t}\r\n\t\t//this loop stops before checking the final two nodes in the middle, so we do the check again \r\n\t\tif(listStart.value != listEnd.value) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}",
"function problem4() {\r\n\tdocument.getElementById(\"problem4\")\r\n\t\r\n\t// Creates a function to split the entered word, reverse the letters\r\n\t// and then join the letters back together in reverse order. \r\n\tfunction testWord(word1){\r\n\t\treturn word1.split(\"\").reverse().join(\"\");\r\n\t\tstr.split(\"\").reverse().join(\"\");\r\n\t}\r\n\t\r\n\tvar word1 = prompt(\"Please enter a word.\");\r\n\t\r\n\tvar originalWord = word1;\r\n\tvar reverseWord = word1.split(\"\").reverse().join(\"\");\r\n\t\r\n\t\r\n\tif(originalWord === reverseWord) {\r\n\t\tdocument.write(\"The reverse of \" + originalWord + \" is \" + testWord(word1) + \".\" + \" This is a palindrome!\");\r\n\t}\r\n\t\telse {\r\n\t\t\tdocument.write(\"The reverse of \" + originalWord + \" is \" + testWord(word1) + \".\" + \" This is not a palindrome!\");\r\n\t\t}\r\n\ts\r\n\trefreshIt();\r\n}",
"function buildPalindrome(a, b) {\n\n let aCounter = 0;\n let longestPal = \"\";\n\n while (true) {\n let bCounter = b.length - 1;\n let currentPal = \"\";\n let subStringA = \"\";\n let subStringB = \"\";\n \n while(true) {\n \n if(a[aCounter] === b[bCounter]) {\n console.log(\"a[aCounter] === b[bCounter]\", a[aCounter], b[bCounter])\n subStringA = subStringA + a[aCounter];\n subStringB = b[bCounter] + subStringB;\n currentPal = subStringA + subStringB;\n bCounter -= 1;\n }\n else if (currentPal.length >= 2) {\n\n if (b[bCounter + 1] === a[aCounter] && b[bCounter]) {\n console.log(\"b[bCounter + 1] === a[aCounter] && b[bCounter]\", b[bCounter + 1], a[aCounter], b[bCounter]);\n subStringB = b[bCounter] + subStringB;\n currentPal = subStringA + subStringB;\n bCounter -= 1;\n }\n else if (a[aCounter + 1] === b[bCounter + 1]) {\n console.log(\"a[aCounter + 1] === b[bCounter + 1]\", a[aCounter + 1], b[bCounter + 1]);\n aCounter += 1;\n subStringA = subStringA + a[aCounter];\n currentPal = subStringA + subStringB;\n }\n }\n else {\n bCounter -= 1;\n console.log(\"else\", \"aCounter\", aCounter, \"bCounter\", bCounter);\n }\n\n if(bCounter === 0) {\n longestPal = currentPal;\n aCounter += 1;\n break;\n }\n\n }\n\n if(aCounter === a.length - 1) {\n if(longestPal) {\n return longestPal;\n }\n else {\n return -1;\n }\n }\n\n }\n\n}",
"function isListPalindrome2(list) {\n var slow = null,\n fast = list,\n temp;\n // Find center point and reverse the first half of the list\n while (fast && fast.next) {\n fast = fast.next.next;\n temp = list.next;\n list.next = slow;\n slow = list;\n list = temp;\n }\n // If fast not null, list length is odd, ignore the center value\n if (fast) {\n list = list.next;\n }\n // Find the first difference\n while (list) {\n if (slow.value !== list.value) return false;\n slow = slow.next;\n list = list.next;\n }\n // Return true, if no diff\n return true;\n}",
"function allEqual(string) {\n var boolean = true;\n var array = string.split(\"\")\n for (i = 1; i < string.length; i++) {\n if (array[i] !== array[i - 1]) {\n boolean = false;\n }\n\n }\n return boolean;\n}",
"function sameLength(string1,string2){\n if(string1.length===string2.length)return true\n return false\n}",
"function isListPalindrome1(l) {\n // creating array from list\n // checking if array is palindrome\n // N time, N space\n if (!l) return true;\n let current = l;\n let arr = [];\n while (current) {\n arr.push(current.value);\n current = current.next;\n }\n if (arr.length <= 1) return true;\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] !== arr[arr.length-1-i]) {\n return false;\n }\n }\n return true;\n}",
"function palindromicDate(date) {\n\treturn date.split(\"/\").join(\"\") === date.split(\"/\").join(\"\").split(\"\").reverse().join(\"\");\n}",
"function isPermutation(str1, str2) {\n if(str1.length !== str2.length) {\n return false;\n }\n var a = str1.split(\"\").sort().join(\"\");\n var b = str2.split(\"\").sort().join(\"\");\n for(var i = 0; i < a.length; i++) {\n if(a.charAt(i) !== b.charAt(i)) {\n return false;\n }\n }\n return true;\n}",
"function isSameLength(word1, word2) {\n // your code here\n return (word1.length === word2.length) ? true : false;\n}",
"function palindromicDate(date) {\n\treturn date === `${date.split('/')[1]}/${date.split('/')[0]}/${date.split('/')[2]}` && date.split('/')[2] === date.split('/')[2].slice(2, 4) + date.split('/')[2].slice(0, 2);\n}",
"function doubleLetters(word) {\n\tfor (let i = 0; i < word.length; i ++) {\n\t\tif (word[i] === word[i+1]) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"function isSymmetrical(num) {\n\treturn (num.toString() === num.toString().split(\"\").reverse().join(\"\"));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lower bound for distance from a location to points inside a bounding box | function boxDist(lng, lat, minLng, minLat, maxLng, maxLat, cosLat, sinLat) {
if (minLng === maxLng && minLat === maxLat) {
return greatCircleDist(lng, lat, minLng, minLat, cosLat, sinLat);
}
// query point is between minimum and maximum longitudes
if (lng >= minLng && lng <= maxLng) {
if (lat <= minLat) return earthCircumference * (minLat - lat) / 360; // south
if (lat >= maxLat) return earthCircumference * (lat - maxLat) / 360; // north
return 0; // inside the bbox
}
// query point is west or east of the bounding box;
// calculate the extremum for great circle distance from query point to the closest longitude
const closestLng = (minLng - lng + 360) % 360 <= (lng - maxLng + 360) % 360 ? minLng : maxLng;
const cosLngDelta = Math.cos((closestLng - lng) * rad);
const extremumLat = Math.atan(sinLat / (cosLat * cosLngDelta)) / rad;
// calculate distances to lower and higher bbox corners and extremum (if it's within this range);
// one of the three distances will be the lower bound of great circle distance to bbox
let d = Math.max(
greatCircleDistPart(minLat, cosLat, sinLat, cosLngDelta),
greatCircleDistPart(maxLat, cosLat, sinLat, cosLngDelta));
if (extremumLat > minLat && extremumLat < maxLat) {
d = Math.max(d, greatCircleDistPart(extremumLat, cosLat, sinLat, cosLngDelta));
}
return earthRadius * Math.acos(d);
} | [
"function getSearchRadius(bounds) {\n\tvar ne = bounds.getNorthEast();\n\tvar sw = bounds.getSouthWest();\n\tvar nw = new google.maps.LatLng(ne.lat(), sw.lng());\n\tvar width = google.maps.geometry.spherical.computeDistanceBetween(ne, nw);\n\tvar height = google.maps.geometry.spherical.computeDistanceBetween(sw, nw);\n\treturn Math.min(width, height) / 2;\n}",
"SetBoundingDistances() {}",
"function checkInsideBoundingBox(bound, pt)\n{\n\tif (pt.x < bound.lower_bound.x || pt.x > bound.higher_bound.x) {\n\t\treturn false;\n\t}\n\tif (pt.y < bound.lower_bound.y || pt.y > bound.higher_bound.y) {\n\t\treturn false;\n\t}\n\tif (pt.z < bound.lower_bound.z || pt.z > bound.higher_bound.z) {\n\t\treturn false;\n\t} \n\treturn true;\n}",
"function getBoundsSearchFunction(boxes) {\n var index;\n if (!boxes.length) {\n // Unlike rbush, flatbush doesn't allow size 0 indexes; workaround\n return function() {return [];};\n }\n index = new Flatbush(boxes.length);\n boxes.forEach(function(ring) {\n var b = ring.bounds;\n index.add(b.xmin, b.ymin, b.xmax, b.ymax);\n });\n index.finish();\n\n function idxToObj(i) {\n return boxes[i];\n }\n\n // Receives xmin, ymin, xmax, ymax parameters\n // Returns subset of original @bounds array\n return function(a, b, c, d) {\n return index.search(a, b, c, d).map(idxToObj);\n };\n}",
"function BoundaryCollection(points, distanceThreshold) {\n var _this = this;\n\n this.distanceThreshold = distanceThreshold;\n this.points = points;\n this.rays = function () {\n var boundaries = [];\n for (var i = 0; i < points.length; i++) {\n var polygon = points[i];\n for (var j = 0; j < polygon.length - 1; j++) {\n boundaries.push([].concat(_toConsumableArray(polygon[j]), _toConsumableArray(polygon[j + 1])));\n }\n }\n return boundaries;\n }();\n this.vectors = function () {\n var bVecs = [];\n for (var i = 0; i < _this.rays.length; i++) {\n bVecs.push($(_this.rays[i]).coordPairToVector().$);\n }\n return bVecs;\n }();\n this.normals = function () {\n var bNorms = [];\n for (var i = 0; i < _this.vectors.length; i++) {\n bNorms.push($(_this.vectors[i]).leftNormal().$);\n }\n return bNorms;\n }();\n this.bboxes = function () {\n var boxes = [];\n for (var i = 0; i < _this.rays.length; i++) {\n boxes.push(frontOfRayBBox(_this.rays[i], _this.distanceThreshold));\n }\n return boxes;\n }();\n}",
"function BoundingBox() {\n this._internalModel = new BoundingBoxFilterModel();\n}",
"@computed\n get maxDistance() {\n const ne = this.mapBounds.getNorthEast();\n const sw = this.mapBounds.getSouthWest();\n const mapViewWidth = ne.lng - sw.lng;\n const mapViewHeight = ne.lat - sw.lat;\n return Math.max(mapViewWidth, mapViewHeight) / 2;\n }",
"fitBounds() {\n const { map } = this.context\n\n if (this.layer.getBounds) {\n map.fitBounds(this.layer.getBounds(), {\n padding: 40,\n duration: 0,\n bearing: map.getMapGL().getBearing(),\n })\n }\n }",
"function emptyBounds() {\n\treturn new google.maps.LatLngBounds();\n}",
"function BoundingBox2D(min, max) {\n if (typeof min === \"undefined\") { min = new Vapor.Vector2(); }\n if (typeof max === \"undefined\") { max = new Vapor.Vector2(); }\n this.min = min;\n this.max = max;\n }",
"visitBounds_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function findBoundingBox() {\n\t\n\n\t//first locate center-of-mass, as starting location for boundary box sides... \n\tCOMx = 0\n\tCOMy = 0\n\ttotalPredicates = 0\n\tbiggestRadius = 0\n\n\t//If no predicates are selected find bound box for all predicates...\n\tif(selectedPredicates.length==0){\n\n\n\t\tfor(i=0;i<myPredicates.length;i++){\n\n\t\t\tCOMx += myPredicates[i].stageX\n\t\t\tCOMy += myPredicates[i].stageY\n\t\t\ttotalPredicates++\n\t\t\t\n\t\t}\n\n\t\tCOMx = COMx/totalPredicates\n\t\tboundaryLeft = boundaryRight = COMx\n\t\tCOMy = COMy/totalPredicates\n\t\tboundaryTop = boundaryBottom = COMy\n\t\t\n\n\t\t//go through predicates, expanding bounding box as necessary...\n\t\tfor(i=0;i<myPredicates.length;i++){\n\n\t\t\t//keep track of biggest radius\n\t\t\tif(myPredicates[i].radius>biggestRadius){\n\t\t\t\tbiggestRadius = myPredicates[i].radius\n\t\t\t}\n\n\t\t\t//expand bounding box if needed\n\t\t\tif(myPredicates[i].stageX<boundaryLeft){\n\t\t\t\tboundaryLeft = myPredicates[i].stageX\n\t\t\t}\n\t\t\tif(myPredicates[i].stageX>boundaryRight){\n\t\t\t\tboundaryRight = myPredicates[i].stageX\n\t\t\t}\n\t\t\tif(myPredicates[i].stageY<boundaryTop){\n\t\t\t\tboundaryTop = myPredicates[i].stageY\n\t\t\t}\n\t\t\tif(myPredicates[i].stageY>boundaryBottom){\n\t\t\t\tboundaryBottom = myPredicates[i].stageY\n\t\t\t}\n\t\t\t\n\t\t}\n\n\n\t//Otherwise find bounding box only for selected predicates...\n\t}else{\n\n\n\t\tfor(i=0;i<myPredicates.length;i++){\n\t\t\tif(myPredicates[i].selected){\n\t\t\t\tCOMx += myPredicates[i].stageX\n\t\t\t\tCOMy += myPredicates[i].stageY\n\t\t\t\ttotalPredicates++\n\t\t\t}\n\t\t}\n\n\t\tCOMx = COMx/totalPredicates\n\t\tboundaryLeft = boundaryRight = COMx\n\t\tCOMy = COMy/totalPredicates\n\t\tboundaryTop = boundaryBottom = COMy\n\t\t\n\n\t\t//go through predicates, expanding bounding box as necessary...\n\t\tfor(i=0;i<myPredicates.length;i++){\n\t\t\tif(myPredicates[i].selected){\n\n\n\n\t\t\t\t//keep track of biggest radius\n\t\t\t\tif(myPredicates[i].radius>biggestRadius){\n\t\t\t\t\tbiggestRadius = myPredicates[i].radius\n\t\t\t\t}\n\n\n\n\t\t\t\t//expand bounding box if needed\n\t\t\t\tif(myPredicates[i].stageX<boundaryLeft){\n\t\t\t\t\tboundaryLeft = myPredicates[i].stageX\n\t\t\t\t}\n\t\t\t\tif(myPredicates[i].stageX>boundaryRight){\n\t\t\t\t\tboundaryRight = myPredicates[i].stageX\n\t\t\t\t}\n\t\t\t\tif(myPredicates[i].stageY<boundaryTop){\n\t\t\t\t\tboundaryTop = myPredicates[i].stageY\n\t\t\t\t}\n\t\t\t\tif(myPredicates[i].stageY>boundaryBottom){\n\t\t\t\t\tboundaryBottom = myPredicates[i].stageY\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\n\n\t//find center of bounding box\n\tclusterCenterX = (boundaryRight+boundaryLeft)/2\n\tclusterCenterY = (boundaryBottom+boundaryTop)/2\n\n//Debugging visual for bounding box, cluster center...\n/*\n\tfill(255,0,0)\n\tellipse(clusterCenterX,clusterCenterY,20,20)\n\tstroke(0,0,255)\n\tnoFill()\n\trectMode(CORNERS)\n\trect(boundaryLeft-(150*globalScale),boundaryTop-(150*globalScale),boundaryRight+(150*globalScale),boundaryBottom+(150*globalScale))\n*/\n}",
"raycastRoot(minx: number, miny: number, maxx: number, maxy: number, p: vec3Like, d: vec3Like, exaggeration: number = 1): ?number {\n const min = [minx, miny, -aabbSkirtPadding];\n const max = [maxx, maxy, this.maximums[0] * exaggeration];\n return aabbRayIntersect(min, max, p, d);\n }",
"function getXCoordinatesRange() {\n return (MAX_X_COORDINATE - MIN_X_COORDINATE);\n } // getXCoordinatesRange",
"getBetweenRangesPos(center, minRange, maxRange) {\n let res = [];\n for(let x = center.x - maxRange; x <= center.x + maxRange; x++) {\n let remainingDistance = maxRange - Math.abs(x-center.x);\n for(let y = center.y-remainingDistance; y <= center.y + remainingDistance; y++) {\n let pos = new Position(x, y);\n if(this.isInsideMap(pos) && center.getManDistance(pos) >= minRange) {\n res.push(pos);\n }\n }\n }\n return res;\n }",
"fitBounds() {\n const { map } = this.context;\n\n if (this.layer.getBounds) {\n map.fitBounds(this.layer.getBounds());\n }\n }",
"function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}",
"function boxBoundsStr(box) {\n var lt1=box.getBounds().getNorthEast().lat()\n var lg1=box.getBounds().getNorthEast().lng()\n var lt2=box.getBounds().getSouthWest().lat()\n var lg2=box.getBounds().getSouthWest().lng()\n return lt1+\", \"+lg1+\", \"+lt2+\", \"+lg2\n}",
"function bound (n, min, max) {\n return Math.min(max, Math.max(min, n))\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Below method is used to generate an noutofm Multisignature (multisig) PayToScriptHash (P2SH) bitcoin address | async function genP2SH() {
var privKeys = [bitcoin.ECKey.makeRandom(), bitcoin.ECKey.makeRandom(), bitcoin.ECKey.makeRandom()]
var pubKeys = privKeys.map(function(x) { return x.pub })
var redeemScript = bitcoin.scripts.multisigOutput(2, pubKeys) // 2 of 3
var scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash())
var multisigAddress = bitcoin.Address.fromOutputScript(scriptPubKey).toString()
console.log("multisigP2SH:", multisigAddress);
return multisigAddress;
} | [
"function generateNewAddress(){\n \n server.accounts()\n .accountId(source.publicKey())\n .call()\n .then(({ sequence }) => {\n const account = new StellarSdk.Account(source.publicKey(), sequence)\n const transaction = new StellarSdk.TransactionBuilder(account, {\n fee: StellarSdk.BASE_FEE\n })\n .addOperation(StellarSdk.Operation.createAccount({\n destination: destination.publicKey(),\n startingBalance: '2'\n }))\n .setTimeout(30)\n .build()\n transaction.sign(StellarSdk.Keypair.fromSecret(source.secret()))\n return server.submitTransaction(transaction)\n })\n .then(results => {\n console.log('Transaction', results._links.transaction.href)\n console.log('New Keypair', destination.publicKey(), destination.secret())\n })\n\n }",
"async function genSegWitAddr() {\n\n\tconst mnemonics = mnemonic.generateMnemonic(); //generates string\n const seed = await bip39.mnemonicToSeed(mnemonics);\n const root = hdkey.fromMasterSeed(seed);\n\n\tconst masterPrivateKey = root.privateKey.toString('hex');\n\tconst masterPublicKey = root.publicKey.toString('hex');\n\n\tconst addrnode = root.derive(\"m/44'/0'/0'/0/0\");\n\tconsole.log(addrnode._publicKey);\n\n\tconst step1 = addrnode._publicKey;//Get your public key\n\tconst step2 = createHash('sha256').update(step1).digest(); //Perform SHA-256 hashing on the public key\n\tconst step3 = createHash('rmd160').update(step2).digest(); //Perform RIPEMD-160 hashing on the result of SHA-256\n\n\tvar step4 = Buffer.allocUnsafe(21);//Add version byte in front of RIPEMD-160 hash (0x00 for mainnet, 0x6f for testnet)\n\tstep4.writeUInt8(0x00, 0);\n\tstep3.copy(step4, 1); //step4 now holds the extended RIPMD-160 result\n\n\tconst step9 = bs58check.encode(step4);\n\tconsole.log('Base58Check: ' + step9);\n\treturn step9;\n\t\n}",
"function addr2pksh(addr) {\n // console.log(\"Cryptography\");\n // var addr = \"ALjSnMZidJqd18iQaoCgFun6iqWRm2cVtj\";\n var uint8 = ThinNeo.Helper.GetPublicKeyScriptHash_FromAddress(addr);\n var hexstr = uint8.reverse().toHexString();\n console.log(\"addr=\" + addr);\n console.log(\"hex=\" + hexstr);\n return '0x' + hexstr;\n\n}",
"function pubKeyHash2bitAdd(k){\r\n var b = new Bitcoin.Address(hex2bytes(k));\r\n return b.toString();\r\n}",
"function expandInput (scriptSig, redeemScript) {\n var scriptSigChunks = bscript.decompile(scriptSig)\n var scriptSigType = bscript.classifyInput(scriptSigChunks, true)\n\n var hashType, pubKeys, signatures, prevOutScript\n\n switch (scriptSigType) {\n case 'scripthash':\n // FIXME: maybe depth limit instead, how possible is this anyway?\n if (redeemScript) throw new Error('Recursive P2SH script')\n\n var redeemScriptSig = scriptSigChunks.slice(0, -1)\n redeemScript = scriptSigChunks[scriptSigChunks.length - 1]\n\n var result = expandInput(redeemScriptSig, redeemScript)\n result.redeemScript = redeemScript\n result.redeemScriptType = result.prevOutType\n result.prevOutScript = bscript.scriptHashOutput(bcrypto.hash160(redeemScript))\n result.prevOutType = 'scripthash'\n return result\n\n case 'pubkeyhash':\n // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')\n var s = ECSignature.parseScriptSignature(scriptSigChunks[0])\n hashType = s.hashType\n pubKeys = scriptSigChunks.slice(1)\n signatures = [s.signature]\n\n if (redeemScript) break\n\n prevOutScript = bscript.pubKeyHashOutput(bcrypto.hash160(pubKeys[0]))\n break\n\n case 'pubkey':\n if (redeemScript) {\n pubKeys = bscript.decompile(redeemScript).slice(0, 1)\n }\n\n var ss = ECSignature.parseScriptSignature(scriptSigChunks[0])\n hashType = ss.hashType\n signatures = [ss.signature]\n break\n\n case 'multisig':\n if (redeemScript) {\n pubKeys = bscript.decompile(redeemScript).slice(1, -2)\n }\n\n signatures = scriptSigChunks.slice(1).map(function (chunk) {\n if (chunk === ops.OP_0) return undefined\n\n var sss = ECSignature.parseScriptSignature(chunk)\n\n if (hashType !== undefined) {\n if (sss.hashType !== hashType) throw new Error('Inconsistent hashType')\n } else {\n hashType = sss.hashType\n }\n\n return sss.signature\n })\n\n break\n }\n\n return {\n hashType: hashType,\n pubKeys: pubKeys,\n signatures: signatures,\n prevOutScript: prevOutScript,\n prevOutType: scriptSigType\n }\n}",
"function pubKey2pubKeyHash(k){ return bytes2hex(Bitcoin.Util.sha256ripe160(hex2bytes(k))); }",
"function generateAndSetKeypair () {\n opts.log(`generating ${opts.bits}-bit RSA keypair...`, false)\n var keys = peerId.create({\n bits: opts.bits\n })\n config.Identity = {\n PeerID: keys.toB58String(),\n PrivKey: keys.privKey.bytes.toString('base64')\n }\n opts.log('done')\n opts.log('peer identity: ' + config.Identity.PeerID)\n\n writeVersion()\n }",
"function NewNymSignature(sk, Nym , RNym , ipk , msg , rng ) {\n\tlet Nonce = RandModOrder(rng)\n\n\tlet HRand = ipk.HRand;\n\tlet HSk = ipk.HSk;\n\n\t// The rest of this function constructs the non-interactive zero knowledge proof proving that\n\t// the signer 'owns' this pseudonym, i.e., it knows the secret key and randomness on which it is based.\n\t// Recall that (Nym,RNym) is the output of MakeNym. Therefore, Nym = h_{sk}^sk \\cdot h_r^r\n\n\t// Sample the randomness needed for the proof\n\tlet rSk = RandModOrder(rng)\n\tlet rRNym = RandModOrder(rng)\n\n\t// Step 1: First message (t-values)\n\tlet t = HSk.mul2(rSk, HRand, rRNym) // t = h_{sk}^{r_sk} \\cdot h_r^{r_{RNym}\n\n\t// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\t// proofData will hold the data being hashed, it consists of:\n\t// - the signature label\n\t// - 2 elements of G1 each taking 2*FieldBytes+1 bytes\n\t// - one bigint (hash of the issuer public key) of length FieldBytes\n\t// - disclosed attributes\n\t// - message being signed\n let proofData = new ArrayBuffer(signLabel.length+2*(2*FieldBytes+1)+FieldBytes+msg.length);\n let v = new Uint8Array(proofData);\n\n let index = 0\n\n index = appendBytesString(v, index, signLabel)\n index = appendBytesG1(proofData, index, t)\n index = appendBytesG1(proofData, index, Nym)\n v.set(BigToBytes(ipk.Hash),index);\n index = index + FieldBytes\n v.set(Buffer.from(msg),index);\n let c = HashModOrder(v);\n\n\n // combine the previous hash and the nonce and hash again to compute the final Fiat-Shamir value 'ProofC'\n index = 0\n let proofData2 = new ArrayBuffer(2*FieldBytes);\n let v2 = new Uint8Array(proofData2);\n\n\tindex = appendBytesBig(proofData2, index, c)\n\tindex = appendBytesBig(proofData2, index, Nonce)\n ProofC = HashModOrder(v2)\n\n // Step 3: reply to the challenge message (s-values)\n\tlet ProofSSk = Modadd(rSk, FP256BN.BIG.modmul(ProofC, sk, GroupOrder), GroupOrder) // s_{sk} = r_{sk} + C \\cdot sk\n let ProofSRNym = Modadd(rRNym, FP256BN.BIG.modmul(ProofC, RNym, GroupOrder), GroupOrder) // s_{RNym} = r_{RNym} + C \\cdot RNym\n \n return {\n\t\tProofC: ProofC,\n\t\tProofSSk: ProofSSk,\n\t\tProofSRNym: ProofSRNym,\n Nonce: Nonce\n }\n}",
"async computeHashPOS( newTimestamp, posNewMinerAddress, balance ){\n\n let virtualBalance = balance;\n\n let whoIsMining = posNewMinerAddress || this.posMinerAddress || this.data.minerAddress;\n let whoIsReceivingMoney = this.data.minerAddress;\n\n try {\n\n // SHA256(prevhash + address + timestamp) <= 2^256 * balance / diff\n\n let buffer = Buffer.concat([\n\n Serialization.serializeBufferRemovingLeadingZeros( Serialization.serializeNumber4Bytes(this.height) ),\n Serialization.serializeBufferRemovingLeadingZeros( this.difficultyTargetPrev ),\n Serialization.serializeBufferRemovingLeadingZeros( this.hashPrev ),\n Serialization.serializeBufferRemovingLeadingZeros( whoIsMining ),\n Serialization.serializeBufferRemovingLeadingZeros( Serialization.serializeNumber4Bytes( newTimestamp || this.timeStamp) ),\n\n ]);\n\n let hash = await WebDollarCrypto.SHA256(buffer);\n\n if (balance === undefined)\n balance = Blockchain.blockchain.accountantTree.getBalance( whoIsMining );\n\n //reward already included in the new balance\n if ( Blockchain.blockchain.accountantTree.root.hash.equals( this.data.hashAccountantTree ) && balance !== null) {\n\n if ( whoIsReceivingMoney .equals( whoIsMining )) { //in case it was sent to the minerAddress\n\n balance -= this.reward;\n balance -= this.data.transactions.calculateFees();\n\n }\n\n for (let tx of this.data.transactions.transactions){\n\n for (let from of tx.from.addresses)\n if ( from.unencodedAddress.equals( whoIsMining ) )\n balance += from.amount;\n\n for (let to of tx.to.addresses)\n if ( to.unencodedAddress.equals( whoIsMining ))\n balance -= to.amount;\n\n }\n\n }\n\n //also solo miners need to subtract the transactions as well\n if ( !virtualBalance && !Blockchain.MinerPoolManagement.minerPoolSettings.minerPoolActivated ) {\n\n //console.log(\"Before Balance \", balance); let s = \"\";\n\n for (let i = this.height - 1; i >= 0 && i >= this.height - 1 - consts.BLOCKCHAIN.POS.MINIMUM_POS_TRANSFERS; i--) {\n\n let block = await this.blockValidation.getBlockCallBack( i );\n\n if ( !block ) continue;\n\n //s += block.height + \" \";\n\n for (let tx of block.data.transactions.transactions)\n for (let to of tx.to.addresses)\n if (to.unencodedAddress.equals(whoIsMining))\n balance -= to.amount;\n }\n\n //console.log(\"After Balance \", balance, s);\n }\n\n if (balance === null || balance < consts.BLOCKCHAIN.POS.MINIMUM_AMOUNT * WebDollarCoins.WEBD)\n return consts.BLOCKCHAIN.BLOCKS_MAX_TARGET_BUFFER;\n\n let number = new BigInteger( hash.toString(\"hex\"), 16);\n\n let hex = number.divide( balance ).toString(16);\n if (hex.length % 2 === 1) hex = \"0\"+hex;\n\n return Serialization.serializeToFixedBuffer( consts.BLOCKCHAIN.BLOCKS_POW_LENGTH, Buffer.from( hex , \"hex\") );\n\n } catch (exception){\n console.error(\"Error computeHash\", exception);\n //return Buffer.from( consts.BLOCKCHAIN.BLOCKS_MAX_TARGET_BUFFER);\n throw exception;\n }\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 GetHash160FromAddr(addr){\n const addrd = Address.fromString(addr);\n var script = bitcore.Script.buildPublicKeyHashOut(addrd).toString()\n script = script.split(\"0x\").pop();//Remove all text before 0x prefix of hash160\n script = script.replace(\" OP_EQUALVERIFY OP_CHECKSIG\",\"\");//Remove opcodes from output\n return script;\n}",
"function deriveKey(N, token) {\n // the exact bits of the string \"hash_derive_key\"\n const tagBits = sjcl.codec.hex.toBits(\"686173685f6465726976655f6b6579\");\n const h = new sjcl.misc.hmac(tagBits, sjcl.hash.sha256);\n\n const encodedPoint = sec1EncodePoint(N);\n const tokenBits = sjcl.codec.bytes.toBits(token);\n const pointBits = sjcl.codec.bytes.toBits(encodedPoint);\n\n h.update(tokenBits);\n h.update(pointBits);\n\n const keyBytes = sjcl.codec.bytes.fromBits(h.digest());\n return keyBytes;\n}",
"sign(privateKey) {\n // encrypts the private key calling getNodePrivateKey on Wallet instance\n const cert = wallet.getNodePrivateKey(this.from, privateKey);\n /*\n createSign creates and returns a Sign object that uses the given algorithm(SHA256).\n .update updates the hash content with the given data which are the signed with cert in hex base.\n */\n const signature = createSign('SHA256').update(this.hash()).sign(cert, 'hex');\n // creates a transaction updating the hash and adding the signature\n return new Transaction({...this, signature});\n }",
"async function main(wallet) {\n\n // Account discovery\n const enabled = await wallet.enable({network: 'testnet-v1.0'});\n const from = enabled.accounts[0];\n\n // Querying\n const algodv2 = await wallet.getAlgodv2();\n const suggestedParams = await algodv2.getTransactionParams().do();\n const txns = makeTxns(from, suggestedParams);\n\n // Sign and post txns\n const res = await wallet.signAndPost(txns);\n console.log(res);\n\n}",
"async function signOwnInput () {\n try {\n // console.log(`Tx: ${JSON.stringify(unsignedTx, null, 2)}`)\n // Convert the hex string version of the transaction into a Buffer.\n const paymentFileBuffer = Buffer.from(unsignedTx, 'hex')\n\n const allAddresses = [aliceAddr, bobAddr, samAddr]\n\n // Simulate signing own inputs for every individual address\n allAddresses.forEach(function (address) {\n const wif = wifForAddress(address)\n const ecPair = bchjs.ECPair.fromWIF(wif)\n\n // Generate a Transaction object from the transaction binary data.\n const csTransaction = Bitcoin.Transaction.fromBuffer(paymentFileBuffer)\n // console.log(`payments tx: ${JSON.stringify(csTransaction, null, 2)}`)\n\n // Instantiate the Transaction Builder.\n const csTransactionBuilder = Bitcoin.TransactionBuilder.fromTransaction(\n csTransaction,\n 'mainnet'\n )\n // console.log(`builder: ${JSON.stringify(csTransactionBuilder, null, 2)}`)\n\n // find index of the input for that address\n const inputIdx = inputForAddress(address, csTransactionBuilder.tx.ins)\n\n // TODO: user should check also if his own Outputs presents\n // in csTransactionBuilder.tx.outs[]\n\n const addressUTXO = utxoForAddress(address)\n let redeemScript\n csTransactionBuilder.sign(\n inputIdx,\n ecPair,\n redeemScript,\n Bitcoin.Transaction.SIGHASH_ALL,\n addressUTXO.value\n )\n // build tx\n const csTx = csTransactionBuilder.buildIncomplete()\n // output rawhex\n const csTxHex = csTx.toHex()\n // console.log(`Partially signed Tx hex: ${csTxHex}`)\n\n // 'Send' partialially signed Tx to the server\n fs.writeFileSync(`signed_tx_${inputIdx}.json`, JSON.stringify(csTxHex, null, 2))\n })\n\n console.log('signed txs for every user written successfully.')\n } catch (err) {\n console.error(`Error in signOwnInput(): ${err}`)\n throw err\n }\n}",
"function homeMakeEmailTx(){\r\n var to, from, amount, date, message, rawCode, rand, key, bita, pw\r\n var k1, redeem, recover, code\r\n to = removeWhiteSpace($('#homeSendToEmail').val().toLowerCase())\r\n if (to == ''){ alert('To Email must be given.'); return null; }\r\n from = G.email\r\n amount = parseFloat(removeWhiteSpace($('#homeSendAmount').val()))\r\n if (isNaN(amount)){ alert('Amount must be given.'); return null;}\r\n date = new Date().toUTCString()\r\n message = trimWhiteSpace($('#homeSendMessage').val())\r\n pw = trimWhiteSpace($('#homeSendPassword').val())\r\n// create the raw code string:\r\n rawCode = \"\\\r\nTo: \"+to+\"\\n\\\r\nFrom: \"+from+\"\\n\\\r\nAmount: \"+amount+\"\\n\\\r\nDate: \"+date+\"\\n\\\r\nMessage: \"+message+\"\\n\\\r\n\"\r\n// pick a random string\r\n rand = randomHex32()\r\n// create the key using hash of the rawCode and random number so that if anyone\r\n// changes the rawCode in transit, the key cannot be found; thus preventing someone\r\n// from fooling the recipient by changing the info in the rawCode\r\n key = hex2hexKey(hash256(rawCode+rand))\r\n// convert to bitcoin address\r\n bita = key2bitAdd(key)\r\n if (pw == ''){ pw = to }\r\n k1 = seed2key(Seed.main, 0)\r\n redeem = AESencrypt(rand, pw)\r\n recover = AESencrypt(rand, k1)\r\n rawCode = rawCode + \"\\\r\nredeem: \"+redeem+\"\\n\\\r\nrecover: \"+recover+\"\\n\\\r\nrand: \"+rand+\"\\n\\\r\n\"\r\n// encrypt the rawCode using the recipients email\r\n code = AESencrypt(rawCode, to)\r\n// alert(rawCode)\r\n// alert(bita)\r\n// alert(code)\r\n code = code.match(/.{1,40}/g).join('\\n')\r\n// $('#homeSendCodeForm').show()\r\n $('#debugSendCode').val(code)\r\n $('#homeSendCode').val(code)\r\n $('#homeSendCode').select()\r\n// $('#homeSendForm').hide()\r\n $('#homeSendTo').val(bita)\r\n//alert($('#homeSendTo').val())\r\n\r\n return {to:to, sender: from, code: code} //code = transaction code.\r\n }",
"getSignerAddress(hash, signature) {\n const self = this;\n assert_1.assert.isString('hash', hash);\n assert_1.assert.isString('signature', signature);\n const functionSignature = 'getSignerAddress(bytes32,bytes)';\n return {\n callAsync(callData = {}, defaultBlock) {\n return __awaiter(this, void 0, void 0, function* () {\n base_contract_1.BaseContract._assertCallParams(callData, defaultBlock);\n let rawCallResult;\n if (self._deployedBytecodeIfExists) {\n rawCallResult = yield self._evmExecAsync(this.getABIEncodedTransactionData());\n }\n else {\n rawCallResult = yield self._performCallAsync(Object.assign({ data: this.getABIEncodedTransactionData() }, callData), defaultBlock);\n }\n const abiEncoder = self._lookupAbiEncoder(functionSignature);\n base_contract_1.BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder);\n return abiEncoder.strictDecodeReturnValue(rawCallResult);\n });\n },\n getABIEncodedTransactionData() {\n return self._strictEncodeArguments(functionSignature, [hash, signature]);\n },\n };\n }",
"static async createProgramAddress(seeds, programId) {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([buffer, programId.toBuffer(), Buffer.from('ProgramDerivedAddress')]);\n let hash = await sha256$1(new Uint8Array(buffer));\n let publicKeyBytes = new bn$1(hash, 16).toArray(undefined, 32);\n\n if (is_on_curve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n\n return new PublicKey(publicKeyBytes);\n }",
"async function setupHeavyCommonCoin(tag, broker, reliableBroadcast, reliableReceive, newSecret = () => genSk()) {\n const n = broker.n, f = (n - 1)/3|0\n \n const { Z, G, As, shares:keys }\n = await setupKeygenProposalsStable(tag+'s', broker, reliableBroadcast, reliableReceive, newSecret)\n \n // combine threshold secrets to produce our share of the shared secret assigned to each node.\n const Akeys = arrayOf(n, i => As[i] && ({\n share: add(...As[i].map(j => keys[j].share)),\n pk: add(...As[i].map(j => keys[j].pk)),\n pubShares: arrayOf(n, x => add(...As[i].map(j => keys[j].pubShares[x])))\n }))\n \n function thresholdPRF(i, tag_) {\n const { share, pk } = Akeys[i]\n // we want to produce sk*hashToPoint(id), where sk is the shared secret assigned to i.\n const id = pk.encodeStr()+' '+i+' '+tag.length+tag+tag_\n return chaumPedersenProve(share, id)\n }\n \n function verifyPRFShare(i, tag_, sender, PRFShare) {\n const { pubShares, pk } = Akeys[i]\n const id = pk.encodeStr()+' '+i+' '+tag.length+tag+tag_\n return chaumPedersenVerify(pubShares[sender], id, PRFShare)\n }\n \n // after we've gone through the setup once, we return a much lighter function that can be called\n // with a subtag tag_ to run an individual coin instance.\n return (tag_) => {\n const result = defer()\n \n // produce our share of each node's shared secret for every node in G\n const shares = G.reduce((acc, i) => [...acc, [i, encodeData(thresholdPRF(i, tag_))]], [])\n broker.broadcast(tag+tag_, JSON.stringify(shares))\n \n // acceptedCoinShares[i][j] contains j's coin share of the local coin corresponding to i.\n const acceptedCoinShares = arrayOf(n, () => arrayOf(n))\n let count = 0\n broker.receive(tag+tag_, (i, m) => {\n const verifiedShares = arrayOf(n)\n \n // for each PRFshare i sent us, verify the CP proof on it\n let otherShares\n try {\n otherShares = JSON.parse(m).map(([j, PRFShareRaw]) => {\n // TODO we really only need to check the proofs for nodes in Z.\n decodeData(PRFShareRaw, chaumPedersenDecode, PRFShare => {\n if (verifyPRFShare(j, tag_, i, PRFShare)) verifiedShares[j] = PRFShare[0]\n })\n })\n } catch (e) { return }\n \n // i should have sent us a PRFshare for every node in Z. if not we reject.\n if (Z.every(j => verifiedShares[j])) {\n verifiedShares.forEach((sig, j) => acceptedCoinShares[j][i] = sig)\n count++\n } else return;\n \n if (count >= f+1) {\n // reconstruct all the local coins from nodes in Z and set common coin to 1 iff all\n // local coins didn't land on 0.\n result.resolve(Z.map(j => interpolate(acceptedCoinShares[j]))\n .every(sig => hashToScalar(sig.encodeStr()).val.modn(n+1) !== 0))\n }\n })\n \n return result.promise\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls POST /tale/:id/copy and returns the copied tale | copyTale(tale) {
return new Promise((resolve, reject) => {
if (tale._accessLevel > 0) {
// No need to copy, short-circuit
resolve(tale);
}
const token = this.get('tokenHandler').getWholeTaleAuthToken();
let url = `${config.apiUrl}/tale/${tale._id}/copy`;
let client = new XMLHttpRequest();
client.open('POST', url);
client.setRequestHeader("Girder-Token", token);
client.addEventListener("load", () => {
if (client.status === 200) {
const taleCopy = JSON.parse(client.responseText);
resolve(taleCopy);
} else {
reject(client.responseText);
}
});
client.addEventListener("error", reject);
client.send();
});
} | [
"function copyToClipboard() {\n const el = document.createElement('textarea');\n el.value = event.target.getAttribute('copy-data');\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}",
"function cloneTenantScript(axios$$1, identifier, tenantToken, scriptId, versionId, request) {\n return restAuthPost(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/scripting/scripts/' + scriptId + '/versions/' + versionId + '/clone', request);\n }",
"rebuildTale(taleId) {\n return $.ajax({\n url: `${config.apiUrl}/tale/${taleId}/build`,\n method: 'PUT',\n headers: {\n 'Girder-Token': this.get('tokenHandler').getWholeTaleAuthToken()\n },\n timeout: 3000, // ms\n success: function(response) {\n console.log('Building Tale image:', response);\n },\n error: function(err) {\n console.log('Failed to build Tale image:', err);\n }\n });\n }",
"postTale(httpCommand, taleID, imageId, folderId, instanceId, title, description, isPublic, configuration, success, fail) {\n let token = this.get('tokenHandler').getWholeTaleAuthToken();\n let url = config.apiUrl + '/tale/';\n let queryPars = \"\";\n if (httpCommand === \"post\") {\n if (!imageId) {\n fail(\"You must provide an image\");\n return;\n }\n if (!folderId) {\n fail(\"You must provide a folder\");\n return;\n }\n queryPars += \"imageId=\" + encodeURIComponent(imageId);\n queryPars += \"&\";\n queryPars += \"folderId=\" + encodeURIComponent(folderId);\n } else {\n url += taleID + \"/\";\n }\n\n if (instanceId) {\n if (queryPars !== \"\")\n queryPars += \"&\";\n queryPars += \"instanceId=\" + encodeURIComponent(instanceId);\n }\n if (title) {\n if (queryPars !== \"\")\n queryPars += \"&\";\n queryPars += \"title=\" + encodeURIComponent(title);\n }\n if (description != null) {\n queryPars += \"&\";\n queryPars += \"description=\" + encodeURIComponent(description);\n }\n\n if (isPublic) {\n queryPars += \"&\";\n queryPars += \"public=\" + encodeURIComponent(isPublic);\n }\n\n if (configuration) {\n queryPars += \"&\";\n queryPars += \"config=\" + encodeURIComponent(configuration);\n }\n\n if (queryPars) {\n url += \"?\" + queryPars;\n }\n let client = new XMLHttpRequest();\n client.open(httpCommand, url);\n client.setRequestHeader(\"Girder-Token\", token);\n client.addEventListener(\"load\", function () {\n if (client.status === 200) {\n success(client.responseText);\n } else {\n fail(client.responseText);\n }\n });\n\n client.addEventListener(\"error\", fail);\n\n client.send();\n }",
"function handlePartsListCopy() {\n var copyText = document.getElementById(\"parts-box\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }",
"copyToClipboard(e){\n e.preventDefault();\n var copyTextarea = document.getElementById('post');\n copyTextarea.select();\n try{\n document.execCommand('copy');\n console.log(\"Post copied succesfully.\");\n }\n catch(err){\n console.log(\"Unable to copy the post. Please, do it manually selecting the text and pressing Crtl + C keys.\");\n console.log(err)\n }\n }",
"async store ({ request, response }) {\n const dados = request.only([\"titulo\", \"descricao\", \"status\"]);\n await Tarefa.create(dados);\n }",
"copyTo(url, shouldOverWrite = true) {\n return spPost(File(this, `copyTo(strnewurl='${encodePath(url)}',boverwrite=${shouldOverWrite})`));\n }",
"function copy_json() {\n\tdocument.getElementById(\"json_box\").select();\n\tdocument.execCommand(\"copy\");\n}",
"copy() {\n return new ActiveUser(this.id, this.caret, this.colour);\n }",
"copyToFolder(destinationFolderId, parentType, resources, permanently, success, fail, copier, progress) {\n const token = this.get('tokenHandler').getWholeTaleAuthToken();\n let verb = permanently ? 'move' : 'copy';\n const httpVerb = permanently ? 'PUT' : 'POST';\n let url = `${config.apiUrl}/resource/${verb}?resources=${resources}&parentType=${parentType}&parentId=${destinationFolderId}`;\n if(progress) {\n url += '&progress=true';\n }\n let client = new XMLHttpRequest();\n let notifier = this.get('notificationHandler');\n client.open(httpVerb, url);\n client.setRequestHeader(\"Girder-Token\", token);\n client.addEventListener(\"load\", function () {\n if (client.status === 200) {\n let gerund = permanently ? 'moving' : 'copying';\n success(notifier, copier, gerund);\n } else {\n fail(notifier, client.responseText);\n }\n });\n\n client.addEventListener(\"error\", fail);\n\n client.send();\n }",
"function readyForTransfer() {\r\n const koalaId = $(this).data('id');\r\n // ^ NOTE: dependent on assigning id to transfer button: \r\n $.ajax({\r\n method: 'PUT',\r\n url: `/koala/${koalaId}`\r\n }).then(function(response) {\r\n console.log('change readyforTransfer');\r\n getKoalas();\r\n });\r\n}",
"function dc_copy_to_clipboard(div) {\n let copyText = document.getElementById(div).innerText;\n //console.log(copyText);\n /* Copy the text inside the text field */\n navigator.clipboard.writeText(copyText);\n}",
"function clone(instance) {\n let p1, p2;\n let body = instance.body;\n\n // don't allow cloning a used body\n if (instance.bodyUsed) {\n throw new Error(\"cannot clone body after it is used\");\n }\n\n // check that body is a stream and not form-data object\n // note: we can't clone the form-data object without having it as a dependency\n if (body instanceof Stream && typeof body.getBoundary !== \"function\") {\n // tee instance body\n p1 = new PassThrough();\n p2 = new PassThrough();\n body.pipe(p1);\n body.pipe(p2);\n // set instance body to teed body and return the other teed body\n instance[INTERNALS].body = p1;\n body = p2;\n }\n\n return body;\n }",
"function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}",
"function publishCopiedContent (id){\n const publishAPIUrl = publishUrl +'/'+id;\n const httpOptions = {\n headers: {\n 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIyZWU4YTgxNDNiZWE0NDU4YjQxMjcyNTU5ZDBhNTczMiJ9.7m4mIUaiPwh_o9cvJuyZuGrOdkfh0Nm0E_25Cl21kxE',\n 'Content-Type': 'application/json'\n }\n };\n const data = {\n request: {\n content: {\n lastPublishedBy: \"system\"\n }\n }\n }\n try {\n axios.post(publishAPIUrl,data,{headers: httpOptions.headers})\n .then((response) => {\n console.log(\"Successfully Uploaded:\"+ response);\n }).catch((error) => {\n console.log(\"Error in Response Publish Content API:\"+error);\n });\n } catch (error) {\n console.log(\"Error in Publish API Fail:\"+error);\n }\n }",
"static cloneAction(id, entryId){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('cuepoint_cuepoint', 'clone', kparams);\n\t}",
"copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$99faa760c7908e4f(this.calendar, this.era, this.year, this.month, this.day);\n else return new $625ad1e1f4c43bc1$export$99faa760c7908e4f(this.calendar, this.year, this.month, this.day);\n }",
"function editorPasteActivity() {\n if(copiedActivity) {\n editorDirty = true;\n \n let a = JSON.parse(copiedActivity);\n \n //Clear the mission\n a.mission_index = null;\n \n //Clear activity next indices\n if(a.input.next_index !== undefined) a.input.next_index = null;\n if(a.input.wrong_next_index !== undefined) a.input.wrong_next_index = null;\n a.position = getNextAvailablePoint();\n \n //Push the activity in the activities array and add a node for it\n loadedStory.activities.push(a);\n let node = addActivityNode(a);\n setNodeOutputs(a, node);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns target back to where it was before dragging | returnToLocation(target) {
target.setPosition(target.input.dragStartX, target.input.dragStartY);
} | [
"function BeginDragDropTarget() {\r\n return bind.BeginDragDropTarget();\r\n }",
"swap(dropTarget) {\n const previousDrag = dropTarget.draggable;\n previousDrag.revert();\n this.drop(dropTarget);\n }",
"_getUpEventTarget(originalTarget) {\n const that = this;\n let target = originalTarget;\n\n while (target) {\n if (target instanceof JQX.ListItem && target.ownerListBox === that.$.listBox) {\n if (target.unselectable || target.disabled) {\n return;\n }\n\n target = 'item';\n break;\n }\n else if (target === that.$.dropDownContainer) {\n target = 'dropDownContainer';\n break;\n }\n\n target = target.parentElement;\n }\n\n if (that.enableShadowDOM && target !== null) {\n target = originalTarget.getRootNode().host;\n\n while (target) {\n if (target === that.$.dropDownContainer) {\n target = 'dropDownContainer';\n break;\n }\n\n target = target.parentElement;\n }\n }\n\n return target;\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 }",
"dragged(vm, dx, dy) {\n // left to implementations\n }",
"function dragFixup(e, ui, col, row) {\n\n var targetId = idFromLocation(col, row);\n var targetX = parseInt($('#'+targetId).attr('data-col'));\n var targetY = parseInt($('#'+targetId).attr('data-row'));\n var targetSizeX = parseInt($('#'+targetId).attr('data-sizex'));\n var targetSizeY = parseInt($('#'+targetId).attr('data-sizey'));\n var targetGrid = $('#'+targetId);\n var startGrid = $('#'+dragStartId);\n if(targetId == dragStartId) {\n // startGrid.offset({\n // top: dragStartOffset.top\n // });\n // setTimeout(function(){\n // startGrid.offset({\n // left: dragStartOffset.left\n // });\n // },500);\n // startGrid.removeClass('player');\n \n } else {\n var startOffset = startGrid.offset();\n var targetOffset = targetGrid.offset();\n startGrid.attr({\n 'data-col': targetGrid.attr('data-col'),\n 'data-row': targetGrid.attr('data-row'),\n 'data-sizex': targetGrid.attr('data-sizex'),\n 'data-sizey': targetGrid.attr('data-sizey')\n });\n startGrid.offset({\n top: targetOffset.top,\n left: targetOffset.left\n });\n targetGrid.attr({\n 'data-col': dragStartX,\n 'data-row': dragStartY,\n 'data-sizex': dragStartSizeX,\n 'data-sizey': dragStartSizeY\n });\n setTimeout(function(){\n targetGrid.offset({\n top: dragStartOffset.top,\n left: dragStartOffset.left\n });\n }, 200);\n \n }\n }",
"function getInsertionIndicatorPositionTabItem(event, target, dragData, dropData) {\n var clientRect = target.getBoundingClientRect(),\n clientX = event.originalEvent.clientX;\n\n if (clientX <= clientRect.left + Math.floor(clientRect.width / 2)) {\n return insertionIndicatorPosition.before;\n }\n else {\n return insertionIndicatorPosition.after;\n }\n }",
"positionDrop() {\n const drop = this.drop;\n const windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n let dropWidth = drop.drop.getBoundingClientRect().width;\n let left = drop.target.getBoundingClientRect().left;\n let availableSpace = windowWidth - left;\n\n if (dropWidth > availableSpace) {\n let direction = dropWidth > availableSpace ? 'right' : 'left';\n drop.tether.attachment.left = direction;\n drop.tether.targetAttachment.left = direction;\n drop.position();\n }\n }",
"function getOffset(target) {\n\t\tif (target instanceof Array) {\n\t\t\treturn Rect(target[0], target[1], target[2] || target[0], target[3] || target[1]);\n\t\t}\n\n\t\tif (typeof target === 'string') {\n\t\t\t//`100, 200` - coords relative to offsetParent\n\t\t\tvar coords = target.split(/\\s*,\\s*/).length;\n\t\t\tif (coords === 2) {\n\t\t\t\treturn Rect(parseInt(coords[0]), parseInt(coords[1]));\n\t\t\t}\n\t\t}\n\n\t\tif (!target) {\n\t\t\treturn Rect();\n\t\t}\n\n\t\t//`.selector` - calc selected target coords relative to offset parent\n\t\treturn offset(target);\n\t}",
"function getClosestElement() {\n var $list = sections\n , wt = contTop\n , wh = contentBlockHeight\n , refY = wh\n , wtd = wt + refY - 1\n ;\n\n if (direction == 'down') {\n $list.each(function() {\n var st = $(this).position().top;\n if ((st > wt) && (st <= wtd)) {\n target = $(this);\n //console.log($target);\n return false; // just to break the each loop\n }\n });\n } else {\n wtd = wt - refY + 1;\n $list.each(function() {\n var st = $(this).position().top;\n if ((st < wt) && (st >= wtd)) {\n target = $(this);\n //console.log($target);\n return false; // just to break the each loop\n }\n });\n }\n\n return target;\n\n}",
"getDropParent(mouseComponent) {\n if (!mouseComponent) return undefined;\n\n const { dragComponents } = this.state;\n let parent = mouseComponent;\n while (parent) {\n if (parent.canDrop(dragComponents)) return parent;\n parent = this.getElement(parent._parent);\n }\n }",
"function snapToTargetMid(event, target) {\r\n var targetMid = mid(target);\r\n\r\n AXES.forEach(function(axis) {\r\n if (isMid(event, target, axis)) {\r\n setSnapped(event, axis, targetMid[ axis ]);\r\n }\r\n });\r\n}",
"get target() {\n\t\treturn this.#target;\n\t}",
"function getXmovement(fromIndex,toIndex){if(fromIndex==toIndex){return'none';}if(fromIndex>toIndex){return'left';}return'right';}",
"function unregDropTarget()\r\n\t{\r\n dropTarget = null;\r\n\t}",
"function moveToTarget() {\n if (targetEntity == null) return;\n\n var path = bot.navigate.findPathSync(targetEntity.position, {\n timeout: 1 * 1000,\n endRadius: 2\n });\n bot.navigate.walk(path.path, function() {\n if (targetEntity != null) { bot.lookAt(targetEntity.position.plus(vec3(0, 1.62, 0))); }\n });\n\n checkNearestEntity();\n\n timeoutId = setTimeout(moveToTarget, 1 * 1000); // repeat call after 1 second\n}",
"function retargetMouseEvent(e, target) {\n var clonedEvent = document.createEvent(\"MouseEvent\");\n clonedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);\n // Object.defineProperty(clonedEvent, \"target\", {value: target});\n clonedEvent.forwardedTouchEvent = e.forwardedTouchEvent;\n // IE 9+ creates events with pageX and pageY set to 0.\n // Trying to modify the properties throws an error,\n // so we define getters to return the correct values.\n // Solution based on the approach used in: https://github.com/jquery/jquery-simulate\n if (clonedEvent.pageX === 0 && clonedEvent.pageY === 0 && Object.defineProperty) {\n var doc = document.documentElement;\n var body = document.body;\n var clientX = e.clientX;\n var clientY = e.clientY;\n\n Object.defineProperty(clonedEvent, \"pageX\", {\n get: function() {\n return clientX +\n (doc && doc.scrollLeft || body && body.scrollLeft || 0) -\n (doc && doc.clientLeft || body && body.clientLeft || 0);\n }\n });\n Object.defineProperty(clonedEvent, \"pageY\", {\n get: function() {\n return clientY +\n (doc && doc.scrollTop || body && body.scrollTop || 0) -\n (doc && doc.clientTop || body && body.clientTop || 0);\n }\n });\n }\n return clonedEvent;\n }",
"onDragDrop() {\n this.onDragEnd();\n\n // If we dropped a flower at a new position, report that we made a move\n // and generate new flowers\n if (!Map(this._originalTargetCell).equals(Map(this._currentCell))) {\n this.board.resolveMoveAt(this._currentCell);\n }\n }",
"tilePos(){\n\t\treturn snapPoint(this.pos);\n\t}",
"function dragstart(element)\n {\n dragobject = element;\n dragx = posx - dragobject.offsetLeft + new_slider_pos;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mostrar loading en el contenedor del valor de volumen | function colocarLoadingValorVolumen(){
$("#loadingVolumen").show();
$("#valorVolumen").hide();
} | [
"function showLoadingStatus() {\n console.log(\"[menu_actions.js] Showing loading status\");\n showElementById(\"loading-status\");\n}",
"function loadingScreen() {\r\n textAlign(CENTER);\r\n textSize(40);\r\n image(player, width/4, width/4, width/2, width/2);\r\n text(\"LOADING. . .\", width/2, width/2);\r\n}",
"function displayLoading() {\n\t$('div#loadingDialog').show();\n\tloadingCounter++;\n} // displayLoading()",
"async watchLoading(isLoading) {\n await apolloClient.mutate({\n mutation: ChangeLoading,\n variables: {\n loading: isLoading,\n },\n });\n }",
"function progressUpdate() {\n // the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n // we put the percentage in the screen\n $('.txt-perc').text(`${loadingProgress}%`);\n}",
"loadSpinner(display){\n document.querySelector(\".contenido-spinner\").style.display = display;\n document.querySelector(\"#resultado\").style.display = \"none\";\n }",
"function state_loading() {\n status.loading = true;\n if (status.bar) status.bar.className = 'autopager_loading';\n }",
"function optionViewLoaded() {\r\n disableDataUpdate();\r\n LoadingBar.hide();\r\n }",
"function onProgress(e) {\n if (video.buffered.length > 0)\n {\n var end = video.buffered.end(0),\n start = video.buffered.start(0);\n load_bar.setAttribute(\"width\", Math.ceil((end - start) / video.duration * 100).toString());\n }\n}",
"function addLoading( up, file, $ul )\n\t{\n\t\t$ul.removeClass('hidden').append( \"<li id='\" + file.id + \"'><div class='pi-image-uploading-bar'></div><div id='\" + file.id + \"-throbber' class='pi-image-uploading-status'></div></li>\" );\n\t}",
"getLoadingCompletionPercentage(){\n\t\treturn this.getNumberOfImagesLoaded()/this.getTotalNumberOfImages();\n\t}",
"function showLoading(message) {\n var msg = message || 'Working...';\n updateDisplay('<em>' + msg + '</em>');\n}",
"function loadVolume() {\n chrome.storage.local.get('volume', function(cfg) {\n setVolume(cfg['volume'] || 1);\n });\n }",
"function showLoading(selector) {\n var html = \"<div>\";\n html += \"<img src='imagens/ajax-loader.gif'></div>\";\n insertHtml(selector, html);\n }",
"function showLoading() {\n loader.hidden = false;\n quoteContainer.hidden = true; \n}",
"function watchLoader(id){\n firebaseDataBase.ref('/content/' + userObject.uid + '/contentList/' + id )\n .on('value', function(snapshot){\n // console.log(snapshot.val())\n if(snapshot.val().progress.loader.show === true){\n //slight delay before bring up loader window .\n setTimeout(function(){\n document.getElementById('loaderStart').click()\n },300)\n }\n else{\n document.getElementById('closeLoaderModal').click();\n }\n })\n }",
"function load() {\n dashBoardService.getDashboardData().success(function(data) {\n var formatData = [];\n _.forEach(data, function(elem) {\n try {\n formatData.push({id: elem._id, title: elem._id.title, ip: elem._id.ip, count: elem.count, last: moment(elem.lastEntry).fromNow(), down: elem.timeIsOver});\n } catch (err) {\n console.log(err);\n }\n });\n vm.data = formatData;\n\n }).error( function(data, status, headers) {\n alert('Error: ' + data + '\\nHTTP-Status: ' + status);\n });\n }",
"display() {\r\n console.log(`Это роутер ${this.name}, дальность(км) ${this.rangeKm}, число антенн ${this.antennaCount}`);\r\n }",
"function LoadingBar(timeMs, speed) {\n\t\tconst _$e = $(`\n\t\t\t<div class='LoadingBar' style='font-size: 0px; height: 5px;'>\n\t\t\t\t<div class='loaded' style='height: 100%; position: relative; left: 0px; width: 0%'> </div>\n\t\t\t</div>\n\t\t`);\n\t\tconst _$loaded = _$e.find(\".loaded\");\n\t\tconst _startTime = (+new Date());\n\t\tconst _speed = 1 - (speed || .75);\n\t\tvar _timeout;\n\n\t\tconst timeStr = util.toTime(Math.round(timeMs / 1000));\n\t\t_$e.attr(\"title\", `This is an estimate of time (~${timeStr}), based on the chosen gas price.`);\n\t\tif (tippy) {\n\t\t\ttippy(_$e[0], {\n\t\t\t\ttrigger: \"mouseenter\",\n\t\t\t\tplacement: \"top\",\n\t\t\t\tanimation: \"fade\"\n\t\t\t});\n\t\t}\n\n\t\tfunction _update() {\n\t\t\tconst t = (+new Date()) - _startTime;\n\t\t\tvar pct = (1 - Math.pow(_speed, t/timeMs)) * 100\n\t\t\t_$loaded.css(\"width\", pct.toFixed(2) + \"%\");\n\t\t\t_timeout = setTimeout(_update, 30);\n\t\t}\n\n\t\tthis.finish = function(durationMs){\n\t\t\treturn new Promise((res,rej)=>{\n\t\t\t\tclearTimeout(_timeout);\n\t\t\t\tconst startTime = (+new Date());\n\t\t\t\tconst startPct = Number(_$loaded[0].style.width.slice(0, -1));\n\t\t\t\t(function update(){\n\t\t\t\t\tconst t = Math.min(1, (+new Date() - startTime)/durationMs);\n\t\t\t\t\tconst newPct = startPct + (100 - startPct)*t;\n\t\t\t\t\t_$loaded.css(\"width\", `${newPct.toFixed(2)}%`);\n\t\t\t\t\tif (t == 1) res();\n\t\t\t\t\telse setTimeout(update, 50);\n\t\t\t\t}());\n\t\t\t});\n\t\t}\n\t\tthis.$e = _$e;\n\n\t\tif (_speed <= 0 || _speed >= 1)\n\t\t\tthrow new Error(\"Speed must be between 0 and 1\");\n\t\t_update();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
animate background Background animation: Using remainder formula, cycle through array of background colors. Use animate effect to ensure smooth transition. Code inspired by last project. | function animateBackground() {
colors = ["#FDDFDF", "#FCF7DE", "#DEFDE0", "#DEF3FD", "#F0DEFD"];
animateLoop = function() {
$('.background').animate({
backgroundColor: colors[i++ % colors.length] // find the remainder of
}, ANIMATION_TIME, function() {
animateLoop();
});
};
animateLoop();
} | [
"function updateBackground() {\n if (++currBackground > backgroundColors.length - 1){\n currBackground = 0;\n }\n document.getElementById(\"bg\").style.backgroundColor = backgroundColors[currBackground];\n}",
"function updateBackground() {\n var whichBackgroundIndex = (currentStep / bgChangeStepInterval) - 1;\n // print(\"whichBackgroundIndex: \"+whichBackgroundIndex);\n bg = loadImage(\"images/\" + bgImageNames[whichBackgroundIndex]);\n}",
"function bgRoll() {\n const bgm = ['../../resources/SBISL02.png','../../resources/MTLSL04.png','../../resources/OSCSL08.png','../../resources/PGTSL04.png','../../resources/PTWSL02.png','../../resources/STCSL01.png'];\n \n $('body').css({\n 'background-image' : 'url('+ bgm[Math.floor(Math.random() * bgm.length)] + ')',\n });\n}",
"function draw() {\r\n background(0,5);\r\n // inside draw\r\n\r\nfor(let i = 0;i<particlesBg.length;i++) {\r\n \r\n particlesBg[i].createParticleBg();\r\n particlesBg[i].moveParticleBg();\r\n particlesBg[i].joinParticlesBg(particlesBg.slice(i));\r\n }\r\n}",
"function reduceBg(){\r\n if(bgOpacity < 0.2){\r\n randomBgColor();\r\n bgOpacity = 0.9;\r\n //gather_particles(stage.numChildren);\r\n }\r\n document.getElementById(\"two\").style.opacity = bgOpacity;\r\n bgOpacity = bgOpacity - 0.003;\r\n\r\n\r\n}",
"function bgSway() {\n var bg = $('#bg');\n TweenMax.to(bg, 12, {x:64, ease:Sine.easeInOut});\n TweenMax.to(bg, 12, {x:-64, ease:Sine.easeInOut, delay: 12, onComplete:bgSway});\n}",
"fade (nextState)\n {\n this.nextState = nextState;\n\n const fadeBackground = this.game.add.graphics(0, 0);\n fadeBackground.beginFill(0xFFFFFF, 1);\n fadeBackground.drawRect(0, 0, this.game.width, this.game.height);\n fadeBackground.alpha = 0;\n fadeBackground.endFill();\n\n const backgroundTween = this.game.add.tween(fadeBackground);\n backgroundTween.to({ alpha: 1 }, 500, null);\n backgroundTween.onComplete.add(this.changeState, this);\n backgroundTween.start();\n }",
"function changingFaceColor2() {\n $faceBg.animate({\n backgroundColor: '#006699;'\n }, COLOR_CHANGE_SPEED, function() {\n changingFaceColor();\n });\n}",
"_updateBackgroundOpacity() {\n let [backgroundColor, borderColor] = this._getBackgroundColor();\n if (backgroundColor) {\n // We check the background alpha for a minimum of .001 to prevent\n // division by 0 errors when calculating borderAlpha later\n let backgroundAlpha = Math.max(Math.round(backgroundColor.alpha/2.55)/100, .001);\n let newAlpha = this._settings.get_double('background-opacity');\n this._defaultBackground = \"rgba(\" + backgroundColor.red + \",\" + backgroundColor.green + \",\" + backgroundColor.blue + \",\" + backgroundAlpha + \")\";\n this._customBackground = \"rgba(\" + backgroundColor.red + \",\" + backgroundColor.green + \",\" + backgroundColor.blue + \",\" + newAlpha + \")\";\n\n if (borderColor) {\n // The border and background alphas should remain in sync\n // We also limit the borderAlpha to a maximum of 1 (full opacity)\n let borderAlpha = Math.round(borderColor.alpha/2.55)/100;\n borderAlpha = Math.min((borderAlpha/backgroundAlpha)*newAlpha, 1);\n this._defaultBorder = \"rgba(\" + borderColor.red + \",\" + borderColor.green + \",\" + borderColor.blue + \",\" + Math.round(borderColor.alpha/2.55)/100 + \")\";\n this._customBorder = \"rgba(\" + borderColor.red + \",\" + borderColor.green + \",\" + borderColor.blue + \",\" + borderAlpha + \")\";\n }\n\n if (this._settings.get_boolean('opaque-background')) {\n this._fadeInBackground(this._settings.get_double('animation-time'), 0);\n } else {\n this._fadeOutBackground(this._settings.get_double('animation-time'), 0);\n }\n }\n }",
"function _renderBackground () {\n\t_ctx.fillStyle = _getColor(\"background\");\n _ctx.fillRect(0, 0, _ctx.canvas.clientWidth, _ctx.canvas.clientHeight);\n}",
"function applyBG() {\n // Use 'currentCardCount'\n var count = currentCardCount;\n //console.log('applyBG: ' + currentCardCount);\n // Set background of card front\n // Select corresponding object in 'cards' to 'currentCardCount'\n var frontHandle = cards[count].frontBkgndFile;\n //console.log(\"current 'cards' object\\'s location: \" + frontHandle);\n // Change css background to match counter\n var str1 = \"url(\" + frontHandle + \") center no-repeat\";\n $('#cardFront').css({\n 'background': str1,\n 'background-size': 'contain',\n });\n // Set background of card back\n // Select corresponding object in 'cards' to 'currentCardCount'\n var backHandle = cards[count].backBkgndFile;\n //console.log(\"current 'cards' object\\'s location: \" + backHandle);\n // Change css background to match counter\n var str2 = \"url(\" + backHandle + \") center no-repeat\";\n $('#cardBack').css({\n 'background': str2,\n 'background-size': 'contain',\n });\n}",
"function loop() {\n\tcount = new Date().getHours();\n\tdocument.body.style.backgroundImage = ((count > 3 && count < 21) ? url_day : url_night);\n\tdocument.body.style.backgroundPosition = \"top, bottom\";\n\tdocument.body.style.backgroundRepeat = \"no-repeat, no-repeat\";\n\tdocument.body.style.backgroundSize = \"contain, contain\";\n\tdocument.body.style.backgroundColor = hourCodes[count];\n\tsetInterval(update, 1.5 * 1000);\n\tcount++;\n}",
"function changingFaceColor() {\n $faceBg.animate({\n backgroundColor: '#0077b3;'\n }, COLOR_CHANGE_SPEED, function() {\n changingFaceColor2();\n });\n}",
"function changeDisplayBackgroundColor() {\n iterations++;\n $(\"#display\").css(\"background-color\", DISPLAY_BACKGROUND_COLORS[iterations % DISPLAY_BACKGROUND_COLORS.length]);\n }",
"function setBg () \r\n\t{\r\n\t\tvar x = '0px';\r\n\t\tvar y = '0px';\r\n\r\n\t\tfor (var i = 0; i < puzzlePieces.length; i++) //iterates over the puzzle piece and specifies the part of the image to be shown\r\n\t\t{\r\n\t\t\tpuzzlePieces[i].style.backgroundPosition = x + \" \" + y;\r\n\r\n\t\t\tif (parseInt (x, 10) > -300)\r\n\t\t\t{\r\n\t\t\t\tx = parseInt (x, 10) + -100 + 'px';\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tx = '0px';\r\n\t\t\t\ty = parseInt (y, 10) + -100 + 'px';\r\n\t\t\t}\t\t\t\r\n\t\t\t\r\n\t\t}\r\n\t}",
"function drawGround() {\n //back layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[0], bg3_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[1], bg3_ground_x, bg_element_y, i + 1);\n }\n //middle layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[2], bg2_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[3], bg2_ground_x, bg_element_y, i + 1);\n }\n //front layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[4], bg1_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[5], bg1_ground_x, bg_element_y, i + 1);\n }\n}",
"function startColor() {\n $('#start').css('background-color', boxColor[Math.round(Math.random() * boxColor.length)]);\n}",
"_animatePalette()\r\n\t{\r\n\t\tconst curTime = performance.now() / 1000;\r\n\t\tconst totalDuration = curTime - this._startTime;\r\n\t\tconst paletteDuration = curTime - this._paletteStartTime;\t\t\r\n\t\tconst paletteOffset = totalDuration / this._options.paletteAnim.rotaDuration * this._startPalette.length;\r\n\t\r\n\t\tlet paletteToRotate = null;\r\n\t\r\n\t\tif( this._isPaletteTransition )\r\n\t\t{\r\n\t\t\tif( paletteDuration <= this._options.paletteAnim.transitionDuration )\r\n\t\t\t{\r\n\t\t\t\t// Still in transition phase.\r\n\t\t\t\tconst alpha = paletteDuration / this._options.paletteAnim.transitionDuration;\r\n\t\t\t\tz42color.blendPalette( this._startPalette, this._nextPalette, this._transitionPalette, alpha );\r\n\r\n\t\t\t\tpaletteToRotate = this._transitionPalette;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t// Transition phase finished. Start the constant phase.\r\n\t\t\t\tthis._isPaletteTransition = false;\r\n\t\t\t\tthis._paletteStartTime = curTime;\r\n\t\t\t\t\r\n\t\t\t\t// swap this._startPalette, this._nextPalette\r\n\t\t\t\t[ this._startPalette, this._nextPalette ] = [ this._nextPalette, this._startPalette ];\r\n\r\n\t\t\t\tpaletteToRotate = this._startPalette;\r\n\t\t\t}\t\t\t\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif( paletteDuration > this._options.paletteAnim.transitionDelay )\r\n\t\t\t{\r\n\t\t\t\t// Constant phase finished. Start the transition phase.\r\n\t\t\t\tthis._isPaletteTransition = true;\r\n\t\t\t\tthis._paletteStartTime = curTime;\r\n\r\n\t\t\t\tthis._generatePalette( this._nextPalette, this._colorRnd.random() * 360 ); \r\n\t\t\t}\r\n\t\t\t// else still in constant phase. Nothing to do.\r\n\r\n\t\t\tpaletteToRotate = this._startPalette;\r\n\t\t}\r\n\r\n\t\tz42color.rotatePalette( paletteToRotate, this._currentPalette, paletteOffset );\r\n\t}",
"function fadeColorIn() {\n $(\"#color-fade\").animate({\n backgroundColor: \"#ed3\"\n }, 4000, function() {\n fadeColorOut();\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs the current version. | function logVersion() {
logger.info(`skyux-cli: ${getVersion()}`);
} | [
"function logStatus() {\n if (logging) {\n console.log(\"Elevator \" + index + \" | Queue: \" + floorButtonsQueue + \" | Current Floor: \" + elevator.currentFloor() + \" | Direction: \" + elevator.travelDirection + \" | Current Load: \" + elevator.loadFactor() + \" | Capacity: \" + elevator.maxPassengerCount());\n }\n }",
"function onUpdate(fromVersion, toVersion) {\n\tconsole.log('Extension has been updated from version ', fromVersion, ' to version ', toVersion);\n}",
"log() {\n return this._send(format.apply(this, arguments), SysLogger.Severity.notice);\n }",
"onDatabaseVersionChange(_) {\n Log.debug('IndexedDb: versionchange event');\n }",
"function _log_change()\n\t\t{\n\t\t\tvar clone = data.valueCloned;\n\t\t\tvar timestamp = EZ.format.time('@ ms');\n\t\t\t//\ttimestamp = EZ.format.dateTime(data.timestamp,'@ ms');\n\n\t\t\tlogInfo.iconTitle = 'full compare via winmerge with last displayed value';\n\t\t\tlogInfo.summaryClass = 'summary';\n\t\t\tvar priorHeadTags = [this.getTag('dataFileLogHeading')].concat(logInfo.logTag.EZ(['summary'], null));\n\t\t\tEZ.removeClass(priorHeadTags.remove(), ['highlight', 'roundLess']);\n\n\t\t\tlogInfo.icon.class = 'unhide';\n\t\t\tvar count = data.compare.valueHistory.length;\n\t\t\tvar notable = count;\n\t\t\tvar equalsNote = '';\n\n\t\t\tvalue = value || data.value;\t\t\t\t\t\t//1st compare to last logged value\n\t\t\tvar priorValue = data.compare.valueHistory[data.compare.valueHistory.length-1];\n\n\t\t\tvar formattedLog = EZ.equals(priorValue, value, options.log.change.eqOpts)\n\t\t\t\t\t\t\t|| EZ.equals.formattedLog;\n\n\t\t\tif (formattedLog === true)\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t//bail if same as last logged value\n\t\t\t\tif (action != 'save')\t\t\t\t\t\t\t//...and not calld from save\n\t\t\t\t\treturn data.compare.skips++;\n\n\t\t\t\tequalsNote = data.compare.valueHistoryEquals[notable-1];\n\t\t\t\tif (equalsNote.includes('equals'))\n\t\t\t\t\tnotable = '';\n\t\t\t\telse\n\t\t\t\t\tequalsNote = 'equals '\n\n\t\t\t\tformattedLog = data.formattedLog || this.isValueChanged()\n\t\t\t\tif (formattedLog === true)\t\t\t\t\t\t//if samed as last saved value...\n\t\t\t\t{\n\t\t\t\t\ttimestamp = EZ.format.dateTime(data.timestamp_saved || data.timestamp_loaded, '@');\n\t\t\t\t\tlogInfo.icon.class = 'invisible';\n\t\t\t\t\tformattedLog = ['no changes from file saved ' + timestamp];\n\t\t\t\t\t//logInfo.detailHead = 'no TRACKED changed from file saved ' + timestamp;\n\t\t\t\t\tlogInfo.closeDetails = false;\n\t\t\t\t}\n\t\t\t\telse \t\t\t\t\t\t\t\t\t\t\t//otherwise show diff from last saved value\n\t\t\t\t\tlogInfo.iconTitle = 'full compare via with last SAVED value winmerge';\n\t\t\t}\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\t\t//check if equal to any history value\n\t\t\t{\n\t\t\t\tdata.compare.valueHistory.slice(0,-1).every(function(value, idx)\n\t\t\t\t{\n\t\t\t\t\tif (!EZ.equals(value, data.value, options.log.change.eqOpts))\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\tequalsNote = 'equals '\n\t\t\t\t\tnotable = (idx === 0) ? data.compare.valueHistoryTitle[0] : idx;\n\n\t\t\t\t\tlogInfo.summaryClass += ' highlight roundLess';\n\t\t\t\t\tEZ.addClass(priorHeadTags[notable], logInfo.summaryClass);\n\t\t\t\t});\n\t\t\t}\n\t\t\tcount = count.pad(2);\n\t\t\tif (data.compare.skips)\n\t\t\t\tcount += '/' + data.compare.skips.pad(-2);\n\t\t\tthis.setTag('updatesCount', count);\n\t\t\tif (data.compare.skips >= 99)\n\t\t\t\tdata.compare.skips = 0;\n\n\t\t\tnotable = equalsNote + (notable ? notable.wrap('()'): '');\n\n\t\t\tdata.compare.valueHistoryEquals.push(notable);\n\t\t\tdata.compare.valueHistoryTitle.push(timestamp);\n\t\t\tdata.compare.valueHistory.push(clone || __.cloneValue(value));\n\n\t\t\tlogInfo.notable = notable;\n\t\t\tlogInfo.detailsHead = formattedLog.shift(),\n\t\t\tlogInfo.detailsBody = formattedLog.join('\\n')\n\n\t\t\tlogInfo.timestamp = timestamp;\n\n\t\t\tvar args = data.key.wrap(\"'\") + ',this,' + count+''\t//compare args: 'key', this, historyIdx\n\t\t\tlogInfo.icon.onClick = \"window.EZ.dataFile.compare(\" + args + \")\";\n\n\t\t\tEZ.log.addDetails(logInfo);\n\t\t}",
"version() {\n console.log(\"HSA.version\");\n this._log.debug(\"HSA.version\");\n return this._version;\n }",
"getLogDownload() {\r\n this.awsConnect.getLog().download();\r\n }",
"_log() {\n let args = Array.prototype.slice.call(arguments, 0);\n\n if (!args.length) {\n return;\n }\n\n if (args.length > 1)\n this.emit('log', args.join(', '));\n else\n this.emit('log', args[0]);\n }",
"info() {\n return this._send(format.apply(this, arguments), SysLogger.Severity.info);\n }",
"function log(log){\n console.log(log);\n logbook.push(new Date(Date.now()).toLocaleString() + \":\" + log);\n if(log_channel != null){\n log_channel.send(\"`\"+log+\"`\");\n }\n}",
"function system_version_update(version) {\n var version_span = $(jq('system_version'));\n\n if (!version_span.length) {\n return;\n }\n\n version_span.text(version);\n}",
"function log() {\n if (!started)\n started = Date.now();\n var elapsed = Math.round((Date.now() - started) / 1000);\n console.log.\n bind(undefined, '[' + elapsed + 's]').\n apply(undefined, arguments);\n}",
"function logFileOp(message) {\n events.emit('verbose', ' ' + message);\n}",
"function setLogger(argv) {\n logger.level = argv.debug ? 'debug' : argv.verbose ? 'verbose' : 'info';\n}",
"setLogLevel() {\n this.chefWorkers.forEach(cw => {\n cw.worker.postMessage({\n action: \"setLogLevel\",\n data: log.getLevel()\n });\n });\n\n if (!this.dishWorker.worker) return;\n this.dishWorker.worker.postMessage({\n action: \"setLogLevel\",\n data: log.getLevel()\n });\n }",
"log() {\n console.info('Internal Playlist Model:')\n this.items.forEach((video, index) => {\n console.info('\\t️', `${index}.`, 'ℹ️', '(',video.position,')', '[Title]', video.title, '[Channel]', video.channel, '[Duration]', `${video.duration}s`, '[Language]', video.language)\n })\n }",
"_generateTagLine(newVersion, currentVersion) {\n if (this.repoUrl && Str.weaklyHas(this.repoUrl, 'github.com')) {\n return (`## [${newVersion}](${this.repoUrl}/compare/v${currentVersion}...v${newVersion}) - ` +\n `(${Moment().format('YYYY-MM-DD')})`)\n } else {\n return (`## ${newVersion} - (${Moment().format('YYYY-MM-D')}) `)\n }\n }",
"function updateLoggerInfo() {\n var hostName = document.getElementById(\"loggerIpAddress\").value;\n var portNumber = document.getElementById(\"loggerPortNumber\").value;\n closePopUp();\n setRemoteLoggerConfig(hostName, portNumber);\n }",
"function logEvent(data) {\n winston.log('info', data);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes edit or remove buttons, reverts 'Cancel' button to 'Edit PC' or 'Remove PC' | function removeInlineButtons () {
const pcDivs = PCdiv.children;
for (let i = 0; i < pcDivs.length; i++) { pcDivs[i].querySelector('button').remove() };
if (editPCbutton.textContent === 'Cancel') alterButton(editPCbutton, 'Edit PC', removeInlineButtons, editPC);
if (removePCbutton.textContent === 'Cancel') alterButton(removePCbutton, 'Remove PC', removeInlineButtons, removePC);
} | [
"function clearAddOnButtons(addOnButtons) {\r\n}",
"function removePC () {\n\t// To avoid bugs, disallow function if currently editing PCs or if no PCs are being displayed\n\tif (editPCbutton.textContent !== 'Edit PC') return false;\n\tif (!PCdiv.childNodes.length) return false;\n\n\t// Change text content to 'Cancel' and alter alter event listeners\n\talterButton(removePCbutton, 'Cancel', removePC, removeInlineButtons);\n\n\t// Add a 'delete' button to the div for each PC\n\tconst pcDivs = PCdiv.children;\n\tfor (let i = 0; i < pcDivs.length; i++) {\n\t\tconst b = document.createElement('button');\n\t\tb.innerHTML = '✖';\n\t\tb.className = 'inline-button';\n\t\tb.addEventListener('click', deletePcFromArray);\n\t\tpcDivs[i].appendChild(b);\n\t};\n}",
"function editPC () {\n\t// To avoid bugs, disallow function if currently deleting PCs or if no PCs are being displayed\n\tif (removePCbutton.textContent != 'Remove PC') return false;\n\tif (!PCdiv.childNodes.length) return false;\n\n\t// Change text content to 'Cancel' and alter alter event listeners\n\talterButton(editPCbutton, 'Cancel', editPC, removeInlineButtons);\n\n\t// Add an 'edit' button to the div for each PC\n\tconst pcDivs = PCdiv.children;\n\tfor (let i = 0; i < pcDivs.length; i++) {\n\t\tconst b = document.createElement('button');\n\t\tb.innerHTML = '✐';\n\t\tb.className = 'inline-button';\n\t\tb.addEventListener('click', createEditDiv);\n\t\tpcDivs[i].appendChild(b);\n\t};\n}",
"function removeVisualiserButton(){\r\n\teRem(\"buttonWaves\");\r\n\teRem(\"buttonBars\");\r\n\teRem(\"buttonBarz\");\r\n\teRem(\"buttonCircleBars\");\r\n\teRem(\"buttonCirclePeaks\");\r\n\tremoveSliderSelector();\r\n}",
"revert() {\n this.innerHTML = this.__canceledEdits;\n }",
"function cancelEdit() {\n var currentBurger = $(this).data(\"burger\");\n if (currentBurger) {\n $(this).children().hide();\n $(this).children(\"input.edit\").val(currentBurger.text);\n $(this).children(\"span\").show();\n $(this).children(\"button\").show();\n }\n }",
"function cancelEditOp(editItem, dispItem, opt_setid) {\r\n switchItem2(editItem, dispItem);\r\n var editwrapper = document.getElementById(editItem);\r\n var inputElems = cbTbl.findNodes(editwrapper,\r\n function (node) {\r\n return node.nodeName.toLowerCase() == 'input' &&\r\n (!node.type || node.type.toLowerCase() != 'hidden') &&\r\n node.value;\r\n });\r\n for (var i = 0; i < inputElems.length; ++i) {\r\n var inputElem = inputElems[i];\r\n var newVal = '';\r\n if (inputElem.id) {\r\n var origElem = document.getElementById(inputElem.id + '.orig');\r\n newVal = (origElem && origElem.value) ? origElem.value : newVal;\r\n }\r\n inputElems[i].value = newVal;\r\n }\r\n set_isset(false, opt_setid);\r\n}",
"function hideStopEditingBtn() {\n $('#stopEditBtn')[0].className += ' hidden';\n }",
"function resetAddButton() {\n let oldAddButton = id(\"add\");\n var newAddButton = oldAddButton.cloneNode(true);\n oldAddButton.parentNode.replaceChild(newAddButton, oldAddButton);\n }",
"function clearTipBtn() {\n tipBtnCustom.value = \"\";\n clearTipBtnInvalidInput();\n}",
"function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.confirmBtnDisabled(true);\n }",
"undoButton() {\n this.state.undo();\n }",
"function deactivateButtons(){\n $scope.clickMemoryButton = null;\n }",
"function on_edit_button_click(){\n\t\tif ($(this).text()=='Edit'){\n\t\t\t$(\"#middle\").find(\"button.edit\").text('Edit')\n\t\t\t\t.siblings('span').hide()\n\t\t\t\t.siblings('span.value').show();\n\n\t\t\t$(this).siblings('span').show()\n\t\t \t\t\t .siblings('span.value').hide();\n\t\t\t$(this).text('Cancel');\n\t\t} else {\n\t\t\t$(this).siblings('span').hide().siblings('span.value').show();\n\t\t\t$(this).text('Edit');\n\t\t}\n}",
"function disable_button() {\n allow_add = false;\n}",
"function clear_control_panel_options() {\n\tvar control_panel_options_buttons = document.querySelectorAll(\".control_panel .options .button\");\n\tvar control_panel_options_buttons_length = control_panel_options_buttons.length;\n\tfor(var i=0; i<control_panel_options_buttons_length; i++) {\n\t\tcontrol_panel_options_buttons[i].parentNode.removeChild(control_panel_options_buttons[i]);\n\t}\n\tpart+=1;\n\tdeactivate_continue_button()\n\tselect_part();\n}",
"function f_resetAll(){\n fdoc.find('.spEdit').removeAttr('contenteditable').removeClass('spEdit');\n fdoc.find('.targetOutline').removeAttr('contenteditable').removeClass('targetOutline');\n fdoc.find('#ipkMenu').hide();\n fdoc.find('.ipkMenuCopyAnime').removeClass('ipkMenuCopyAnime');\n $('.sp-show-edit-only-place').css('opacity','0.2');\n f_resetHiddenBox();\n }",
"function guessClearResetButtonsOff() {\n guessButton.disabled = false;\n clearButton.disabled = false;\n resetButton.disabled = false;\n }",
"ensureButtonsHidden() {\n // TODO(fanlan1210)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Distribute space among the given sizing items. The distributes the given layout spacing among the sizing items according the following algorithm: 1) Initialize the item's size to its size hint and compute the sums for each of size hint, min size, and max size. 2) If the total size hint equals the layout space, return. 3) If the layout space is less than the total min size, set all items to their min size and return. 4) If the layout space is greater than the total max size, set all items to their max size and return. 5) If the layout space is less than the total size hint, distribute the negative delta as follows: a) Shrink each item with a stretch factor greater than zero by an amount proportional to the sum of stretch factors and negative space. If the item reaches its minimum size, remove it and its stretch factor from the computation. b) If after adjusting all stretch items there remains negative space, distribute it equally among items with a stretch factor of zero. If an item reaches its minimum size, remove it from the computation. 6) If the layout space is greater than the total size hint, distribute the positive delta as follows: a) Expand each item with a stretch factor greater than zero by an amount proportional to the sum of stretch factors and positive space. If the item reaches its maximum size, remove it and its stretch factor from the computation. b) If after adjusting all stretch items there remains positive space, distribute it equally among items with the `expansive` flag set. If an item reaches its maximum size, remove it from the computation. c) If after adjusting all stretch and expansive items there remains positive space, distribute it equally among items with a stretch factor of zero. If an item reaches its maximum size, remove it from the computation. | function distributeSpace(items, space) {
var count = items.length;
if (count === 0) {
return;
}
// Setup the counters.
var totalMin = 0;
var totalMax = 0;
var totalSize = 0;
var totalStretch = 0;
var stretchCount = 0;
var expansiveCount = 0;
for (var i = 0; i < count; ++i) {
var item = items[i];
var size = startSize(item);
item.done = false;
item.size = size;
totalSize += size;
totalMin += item.minSize;
totalMax += item.maxSize;
if (item.stretch > 0) {
totalStretch += item.stretch;
stretchCount++;
}
if (item.expansive) {
expansiveCount++;
}
}
// 1) If the space is equal to the total size, return.
if (space === totalSize) {
return;
}
// 2) If the space is less than the total min, minimize each item.
if (space <= totalMin) {
for (var i = 0; i < count; ++i) {
var item = items[i];
item.size = item.minSize;
}
return;
}
// 3) If the space is greater than the total max, maximize each item.
if (space >= totalMax) {
for (var i = 0; i < count; ++i) {
var item = items[i];
item.size = item.maxSize;
}
return;
}
// The loops below perform sub-pixel precision sizing. A near zero
// value is used for compares instead of zero to ensure that the
// loop terminates when the subdivided space is reasonably small.
var nearZero = 0.01;
// A counter which decreaes monotonically each time an item is
// resized to its limit. This ensure the loops terminate even
// if there is space remaining to distribute.
var notDoneCount = count;
// 5) Distribute negative delta space.
if (space < totalSize) {
// 5a) Shrink each stretch item by an amount proportional to its
// stretch factor. If it reaches its limit it's marked as done.
// The loop progresses in phases where each item gets a chance to
// consume its fair share for the phase, regardless of whether an
// item before it reached its limit. This continues until the
// stretch items or the free space is exhausted.
var freeSpace = totalSize - space;
while (stretchCount > 0 && freeSpace > nearZero) {
var distSpace = freeSpace;
var distStretch = totalStretch;
for (var i = 0; i < count; ++i) {
var item = items[i];
if (item.done || item.stretch === 0) {
continue;
}
var amt = item.stretch * distSpace / distStretch;
if (item.size - amt <= item.minSize) {
freeSpace -= item.size - item.minSize;
totalStretch -= item.stretch;
item.size = item.minSize;
item.done = true;
notDoneCount--;
stretchCount--;
}
else {
freeSpace -= amt;
item.size -= amt;
}
}
}
while (notDoneCount > 0 && freeSpace > nearZero) {
var amt = freeSpace / notDoneCount;
for (var i = 0; i < count; ++i) {
var item = items[i];
if (item.done) {
continue;
}
if (item.size - amt <= item.minSize) {
freeSpace -= item.size - item.minSize;
item.size = item.minSize;
item.done = true;
notDoneCount--;
}
else {
freeSpace -= amt;
item.size -= amt;
}
}
}
}
else {
// 6a) Expand each stretch item by an amount proportional to its
// stretch factor. If it reaches its limit it's marked as done.
// The loop progresses in phases where each item gets a chance to
// consume its fair share for the phase, regardless of whether an
// item before it reached its limit. This continues until the
// stretch items or the free space is exhausted.
var freeSpace = space - totalSize;
while (stretchCount > 0 && freeSpace > nearZero) {
var distSpace = freeSpace;
var distStretch = totalStretch;
for (var i = 0; i < count; ++i) {
var item = items[i];
if (item.done || item.stretch === 0) {
continue;
}
var amt = item.stretch * distSpace / distStretch;
if (item.size + amt >= item.maxSize) {
freeSpace -= item.maxSize - item.size;
totalStretch -= item.stretch;
item.size = item.maxSize;
item.done = true;
notDoneCount--;
stretchCount--;
if (item.expansive) {
expansiveCount--;
}
}
else {
freeSpace -= amt;
item.size += amt;
}
}
}
while (expansiveCount > 0 && freeSpace > nearZero) {
var amt = freeSpace / expansiveCount;
for (var i = 0; i < count; ++i) {
var item = items[i];
if (item.done || !item.expansive) {
continue;
}
if (item.size + amt >= item.maxSize) {
freeSpace -= item.maxSize - item.size;
item.size = item.maxSize;
item.done = true;
expansiveCount--;
notDoneCount--;
}
else {
freeSpace -= amt;
item.size += amt;
}
}
}
while (notDoneCount > 0 && freeSpace > nearZero) {
var amt = freeSpace / notDoneCount;
for (var i = 0; i < count; ++i) {
var item = items[i];
if (item.done) {
continue;
}
if (item.size + amt >= item.maxSize) {
freeSpace -= item.maxSize - item.size;
item.size = item.maxSize;
item.done = true;
notDoneCount--;
}
else {
freeSpace -= amt;
item.size += amt;
}
}
}
}
} | [
"_update() {\r\n // Clear the dirty flag to indicate the update occurred.\r\n this._dirty = false;\r\n // Bail early if there are no widgets to layout.\r\n let widgets = this.order || this.widgets;\r\n if (widgets.length === 0) {\r\n return;\r\n }\r\n // Set spacing by margins\r\n let spacing = this.minimumSpacing.toString() + 'px';\r\n if (this.isHorizontal()) {\r\n for (let i = 0; i < widgets.length - 1; ++i) {\r\n widgets[i].node.style.marginRight = spacing;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < widgets.length - 1; ++i) {\r\n widgets[i].node.style.marginBottom = spacing;\r\n }\r\n }\r\n // Update stretch styles if set\r\n if (this._evenSizes || this.stretchType) {\r\n let basis = null;\r\n let grow = null;\r\n let shrink = null;\r\n if (this._evenSizes) {\r\n basis = 0;\r\n grow = 1;\r\n }\r\n else {\r\n switch (this._stretchType) {\r\n case 'grow':\r\n // Allow items to grow from default size\r\n grow = 1;\r\n shrink = 0;\r\n break;\r\n case 'shrink':\r\n // Allow items to shrink from default size\r\n grow = 0;\r\n shrink = 1;\r\n break;\r\n case 'both':\r\n // Both growing and shrinking is allowed.\r\n grow = 1;\r\n shrink = 1;\r\n break;\r\n case 'fixed':\r\n // Disallow both growing and shrinking.\r\n grow = 0;\r\n shrink = 0;\r\n break;\r\n default:\r\n throw new TypeError('Invalid stretch type: ' + this._stretchType);\r\n }\r\n }\r\n for (let i = 0; i < widgets.length; ++i) {\r\n let style = widgets[i].node.style;\r\n if (basis !== null) {\r\n // Can only be 0, so no unit needed\r\n style.flexBasis = basis.toString();\r\n }\r\n if (grow !== null) {\r\n style.flexGrow = grow.toString();\r\n }\r\n if (shrink !== null) {\r\n style.flexShrink = shrink.toString();\r\n }\r\n }\r\n }\r\n // Update display order\r\n for (let i = 0; i < widgets.length; ++i) {\r\n let widget = widgets[i];\r\n widget.node.style.order = this.order ? i.toString() : null;\r\n }\r\n }",
"function growItem(items, index, delta) {\n for (var i = 0, n = items.length; i < n; ++i) {\n var item = items[i];\n item.sizeHint = item.size;\n }\n var growLimit = 0;\n for (var i = 0; i <= index; ++i) {\n var item = items[i];\n growLimit += item.maxSize - item.size;\n }\n var shrinkLimit = 0;\n for (var i = index + 1, n = items.length; i < n; ++i) {\n var item = items[i];\n shrinkLimit += item.size - item.minSize;\n }\n delta = Math.min(delta, growLimit, shrinkLimit);\n var grow = delta;\n for (var i = index; i >= 0 && grow > 0; --i) {\n var item = items[i];\n var limit = item.maxSize - item.size;\n if (limit >= grow) {\n item.sizeHint = item.size + grow;\n grow = 0;\n }\n else {\n item.sizeHint = item.size + limit;\n grow -= limit;\n }\n }\n var shrink = delta;\n for (var i = index + 1, n = items.length; i < n && shrink > 0; ++i) {\n var item = items[i];\n var limit = item.size - item.minSize;\n if (limit >= shrink) {\n item.sizeHint = item.size - shrink;\n shrink = 0;\n }\n else {\n item.sizeHint = item.size - limit;\n shrink -= limit;\n }\n }\n }",
"calculateLayoutSizes() {\n const gridItemsRenderData = this.grid.getItemsRenderData();\n this.layoutSizes =\n Object.keys(gridItemsRenderData)\n .reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: [gridItemsRenderData[cur].width, gridItemsRenderData[cur].height] })), {});\n }",
"function maintainScale(item) {\n var small = 5; // smallest allowed size (diameter, not radius)\n var large = 20; // largest allowed size (diameter, not radius)\n\n if ((item.bounds.width >= large) || (item.bounds.width <= small)) {\n item.data.scale.direction *= -1; // reverse direction\n }\n}",
"function adjustSize(elements, requiredSize, creator, deleter) {\n var currentSize = elements.length;\n if (currentSize > requiredSize) {\n // We need to delete some elements\n var deleteStartIndex = requiredSize;\n elements.splice(deleteStartIndex).forEach(deleter);\n }\n else if (currentSize < requiredSize) {\n // We need to add some elements\n var numToAdd = requiredSize - currentSize;\n for (var i = 0; i < numToAdd; ++i) {\n elements.push(creator());\n }\n }\n}",
"function distribute(boxes, len, maxDistance) {\n var origBoxes = boxes, // Original array will be altered with added .pos\n reducedLen = origBoxes.reducedLen || len, sortByRank = function (a, b) {\n return (b.rank || 0) - (a.rank || 0);\n }, sortByTarget = function (a, b) {\n return a.target - b.target;\n };\n var i, overlapping = true, restBoxes = [], // The outranked overshoot\n box, target, total = 0;\n // If the total size exceeds the len, remove those boxes with the lowest\n // rank\n i = boxes.length;\n while (i--) {\n total += boxes[i].size;\n }\n // Sort by rank, then slice away overshoot\n if (total > reducedLen) {\n stableSort(boxes, sortByRank);\n i = 0;\n total = 0;\n while (total <= reducedLen) {\n total += boxes[i].size;\n i++;\n }\n restBoxes = boxes.splice(i - 1, boxes.length);\n }\n // Order by target\n stableSort(boxes, sortByTarget);\n // So far we have been mutating the original array. Now\n // create a copy with target arrays\n boxes = boxes.map(function (box) { return ({\n size: box.size,\n targets: [box.target],\n align: pick(box.align, 0.5)\n }); });\n while (overlapping) {\n // Initial positions: target centered in box\n i = boxes.length;\n while (i--) {\n box = boxes[i];\n // Composite box, average of targets\n target = (Math.min.apply(0, box.targets) +\n Math.max.apply(0, box.targets)) / 2;\n box.pos = clamp(target - box.size * box.align, 0, len - box.size);\n }\n // Detect overlap and join boxes\n i = boxes.length;\n overlapping = false;\n while (i--) {\n // Overlap\n if (i > 0 &&\n boxes[i - 1].pos + boxes[i - 1].size >\n boxes[i].pos) {\n // Add this size to the previous box\n boxes[i - 1].size += boxes[i].size;\n boxes[i - 1].targets = boxes[i - 1]\n .targets\n .concat(boxes[i].targets);\n boxes[i - 1].align = 0.5;\n // Overlapping right, push left\n if (boxes[i - 1].pos + boxes[i - 1].size > len) {\n boxes[i - 1].pos = len - boxes[i - 1].size;\n }\n boxes.splice(i, 1); // Remove this item\n overlapping = true;\n }\n }\n }\n // Add the rest (hidden boxes)\n origBoxes.push.apply(origBoxes, restBoxes);\n // Now the composite boxes are placed, we need to put the original boxes\n // within them\n i = 0;\n boxes.some(function (box) {\n var posInCompositeBox = 0;\n // Exceeded maxDistance => abort\n return (box.targets || []).some(function () {\n origBoxes[i].pos = box.pos + posInCompositeBox;\n // If the distance between the position and the target exceeds\n // maxDistance, abort the loop and decrease the length in\n // increments of 10% to recursively reduce the number of\n // visible boxes by rank. Once all boxes are within the\n // maxDistance, we're good.\n if (typeof maxDistance !== 'undefined' &&\n Math.abs(origBoxes[i].pos - origBoxes[i].target) > maxDistance) {\n // Reset the positions that are already set\n origBoxes\n .slice(0, i + 1)\n .forEach(function (box) { return delete box.pos; });\n // Try with a smaller length\n origBoxes.reducedLen =\n (origBoxes.reducedLen || len) - (len * 0.1);\n // Recurse\n if (origBoxes.reducedLen > len * 0.1) {\n distribute(origBoxes, len, maxDistance);\n }\n // Exceeded maxDistance => abort\n return true;\n }\n posInCompositeBox += origBoxes[i].size;\n i++;\n return false;\n });\n });\n // Add the rest (hidden) boxes and sort by target\n stableSort(origBoxes, sortByTarget);\n return origBoxes;\n }",
"function sizeItem(id, toHeight){\n\n\tvar toShrink = $(id);\n\t\n\tvar oldHeight = toShrink.offsetHeight < 0 ? 0 : toShrink.offsetHeight;\n\t\n\ttoShrink.style.height = \"auto\";\n\t\n\tvar newHeight = toShrink.offsetHeight;\n\t\n\tif (!toHeight){\n\t\ttoHeight = newHeight;\n\t};\n\t\n\ttoShrink.style.height = oldHeight+\"px\";\n\ttoShrink.style.overflow = \"hidden\";\n\t\n\tif (toHeight < oldHeight ) {\n\t\tnew Shrink(id, toHeight, 10);\n\t\treturn false;\n\t} else {\n\t\tnew Grow(id, toHeight, 10);\n\t\treturn false;\n\t};\n}",
"set minimumSpacing(value) {\r\n value = Private.clampSpacing(value);\r\n if (this._minimumSpacing === value) {\r\n return;\r\n }\r\n this._minimumSpacing = value;\r\n if (!this.parent) {\r\n return;\r\n }\r\n this.parent.node.style.flexWrap = value ? 'wrap' : 'nowrap';\r\n this.parent.fit();\r\n }",
"function updateDimSize(dim, dim_size, isActual) {\r\n\r\n var gO = NewGridObj;\r\n var dimsz = parseInt(dim_size);\r\n\r\n if (!isActual) { // if we are updating display size\r\n\r\n gO.dimShowSize[dim] = dimsz;\r\n\r\n\tif (gO.dimHasTitles[dim]) // if this dim has titles\r\n\t gO.dimActSize[dim] = dimsz; // actual = disp, if titles\r\n\r\n // If we increased the # of dims, push init values\r\n //\r\n for (var i = gO.dimTitles[dim].length; i < dimsz; i++) {\r\n\r\n //gO.dimTitles[dim].push( \"d\" + (dim+1) + DefDimTitleRoot + i ); \r\n gO.dimTitles[dim].push(getTabName(dim, i));\r\n gO.dimComments[dim].push(null);\r\n }\r\n //\r\n // if we reduced the value, pop trailing entries\r\n //\r\n while (gO.dimTitles[dim].length > dimsz) {\r\n gO.dimTitles[dim].pop();\r\n gO.dimComments[dim].pop();\r\n }\r\n\r\n\tif (gO.dimSelectTabs[dim] >= dimsz) // if selected tab is deleted\r\n\t gO.dimSelectTabs[dim] = dimsz-1; // set it to the last \r\n\r\n\tif (gO.typesInDim == dim) { // push data types\r\n\t while (gO.dataTypes.length < dimsz) {\r\n\t\tgO.dataTypes.push(0);\r\n\t }\r\n\t}\r\n\r\n } else { // updating actual size\r\n\r\n gO.dimActSize[dim] = dimsz;\r\n }\r\n\r\n\r\n\r\n reDrawConfig(); // redraw with updates\r\n\r\n}",
"function createSizingItem(stretch) {\n var item = new SizingItem();\n item.stretch = stretch;\n return item;\n }",
"function createFixedSpacer(dir, size) {\n if (isHorizontal(dir)) {\n return new SpacerItem(size, 0, 0 /* Fixed */, SizePolicy.Minimum);\n }\n return new SpacerItem(0, size, SizePolicy.Minimum, 0 /* Fixed */);\n }",
"function makeSafe(intial){\n var size=0;\n var limit=intial;\n var storage=\"\";\n\n function addItem(item,itemSize){\n if(itemSize===\"big\")\n itemSize=3\n\n else if(itemSize===\"medium\")\n itemSize=2;\n\n else if(itemSize===\"small\")\n itemSize=1;\n\n if(size+itemSize>limit)\n return \"Can't fit\";\n\n if(size+itemSize===limit)\n return storage=storage+item;\n\n else {\n storage += item + ' '\n size += itemSize\n }\n }\n return addItem\n\n\n }",
"function startSize(item) {\n return Math.max(item.minSize, Math.min(item.sizeHint, item.maxSize));\n }",
"function wRange(h, defaults, deltas, isLarge, isMinimal, isTrack, isMerch, isTracklist, isSmallArt) {\n deltas = deltas || {};\n\n if(!isLarge) {\n // fixed height; width is unrelated to height or options\n return make_range(defaults.min_width, defaults.max_width);\n }\n if(isSmallArt) {\n return make_range(STANDARD_SMALLART_WIDTH_MIN, defaults.max_width);\n }\n if(isMinimal) {\n // fixed: w == h\n return make_range(h, h);\n }\n\n // from here down we assume 'large' player that is not 'minimal'\n var scaled_portion = h - (deltas.infopanel || 0);\n\n var range = 0;\n\n if(isTrack) {\n // fixed height change due to track player is not scaled\n scaled_portion -= (deltas.track || 0);\n }\n if(isMerch) {\n // fixed height change due to merch section\n scaled_portion -= (deltas.merch_absolute || 0);\n }\n\n if(isTracklist) {\n // fixed height change due to inclusion of tracklist is not scaled\n var listdelta = (deltas.list_base || 0) + MIN_LIST_ITEMS * (deltas.list_item || 0);\n scaled_portion -= listdelta;\n range += (MAX_LIST_ITEMS - MIN_LIST_ITEMS) * (deltas.list_item || 0);\n }\n\n // at this point, we have a height (or range of heights for the scaled\n // portion, and we want to back-calculate what widths could possibly lead to that\n // scaled_portion height.\n var scaled_portion_min = Math.max(defaults.min_width, scaled_portion - range);\n var scaled_portion_max = Math.max(defaults.min_width, scaled_portion);\n\n // knowing the nominal scaled portion height for these options will\n // let us calculate the min/max scale values that result in our height\n var scaled_portion_nominal_height = defaults.height;\n if(isMerch) {\n scaled_portion_nominal_height += (deltas.merch_nominal || 0);\n }\n\n // calculate those min/max scale values\n var scale_min = scaled_portion_min / scaled_portion_nominal_height;\n var scale_max = scaled_portion_max / scaled_portion_nominal_height;\n\n // min/max width are default widths, scaled by min/max scale\n var minwidth = Math.round(defaults.width * scale_min);\n var maxwidth = Math.round(defaults.width * scale_max);\n\n // finally, pin the min/max width values to the limits in 'defaults'\n var width_limits = make_range(defaults.min_width, defaults.max_width);\n return make_range(pin(minwidth, width_limits), pin(maxwidth, width_limits));\n }",
"function drawOnGrid(shapeFn, originalSizeAsScreenFraction, paddingAsShapeFraction) {\n\tconst smallestDim = min(width, height);\n\tconst largestDim = max(width, height);\n\n\tconst calcPaddedSize = (screenFraction) => screenFraction * (1 + paddingAsShapeFraction) * smallestDim;\n\tconst originalSizeWithPadding = calcPaddedSize(originalSizeAsScreenFraction)\n\tconst numThatFitFully = floor(smallestDim / originalSizeWithPadding);\n\tconst actualSizeWithPadding = smallestDim / numThatFitFully;\n\n\t//long axis: distribute any space on the long axis for an exact fit\n\tconst spareSpace = largestDim - numThatFitFully * actualSizeWithPadding;\n\tconst extraPadding = spareSpace / numThatFitFully;\n\n\tconst yStep = actualSizeWithPadding + (height <= width ? 0 : extraPadding);\n\tconst xStep = actualSizeWithPadding + (height >= width ? 0 : extraPadding);\n\n\tif (xStep < 30 || yStep < 30) {\n\t\tconsole.error(\"too small xStep or yStep\", {\n\t\t\txStep,\n\t\t\tyStep\n\t\t});\n\t\treturn;\n\t}\n\tconst correctiveScaling = actualSizeWithPadding / originalSizeWithPadding;\n\n\tfor (let y = yStep / 2; y <= height; y += yStep) {\n\t\tfor (let x = xStep / 2; x <= width; x += xStep) {\n\t\t\tpush();\n\t\t\ttranslate(x, y);\n\t\t\tif (dbg.isDebugging) {\n\t\t\t\trectMode(CENTER);\n\t\t\t\tsquare(0, 0, actualSizeWithPadding)\n\t\t\t}\n\t\t\tscale(correctiveScaling);\n\t\t\tshapeFn();\n\t\t\tpop();\n\t\t}\n\t}\n\n\tif (dbg.isDebugging) {\n\n\t\tdbg.debugObjRoundingValues({\n\t\t\txStep,\n\t\t\tyStep,\n\t\t\twidth,\n\t\t\theight,\n\t\t\tnumThatFitFully\n\t\t}, 100, height - 70, true);\n\t\tdbg.debugObjRoundingValues({\n\t\t\toriginalSizeAsScreenFraction,\n\t\t\t//originalSize,\n\t\t\toriginalSizeWithPadding,\n\t\t\tpaddingAsShapeFraction,\n\t\t}, 100, height - 40, true);\n\t}\n\n}",
"_updateBounds() {\n if (this.autoShrink || this.size === 0) {\n if (this.sections.length) {\n this.bounds.left = Number.MAX_SAFE_INTEGER\n this.bounds.right = Number.MIN_SAFE_INTEGER\n this.bounds.top = Number.MAX_SAFE_INTEGER\n this.bounds.bottom = Number.MIN_SAFE_INTEGER\n } else {\n this.bounds.left = undefined\n this.bounds.right = undefined\n this.bounds.top = undefined\n this.bounds.bottom = undefined\n this.size = 0\n }\n }\n this.fillSize = 0\n this.sections.forEach(section => this._updateBoundsForSection(section))\n }",
"function makeMaxSize(sizeHint, minHint, maxHint, minSize, maxSize, hPolicy, vPolicy, alignment) {\n var w = Infinity;\n var h = Infinity;\n if ((alignment & Alignment.H_Mask) === 0) {\n if (hPolicy !== SizePolicy.Ignored) {\n if (hPolicy & 1 /* GrowFlag */) {\n w = Math.max(minHint.width, maxHint.width);\n }\n else {\n w = Math.max(minHint.width, sizeHint.width);\n }\n }\n w = Math.max(minSize.width, Math.min(w, maxSize.width));\n }\n if ((alignment & Alignment.V_Mask) === 0) {\n if (vPolicy !== SizePolicy.Ignored) {\n if (vPolicy & 1 /* GrowFlag */) {\n h = Math.max(minHint.height, maxHint.height);\n }\n else {\n h = Math.max(minHint.height, sizeHint.height);\n }\n }\n h = Math.max(minSize.height, Math.min(h, maxSize.height));\n }\n return new Size(w, h);\n }",
"function getDistributionList(entries, filesize, callback){\n\tvar remainNo = entries.length;\n\tvar retError = null;\n\tvar capacities = new Array(entries.length);\n\tvar totalCapacity = 0;\n\tvar dist = [];\n\tif (remainNo == 0){\n\t\tcallback(\"No enough space\", []);\n\t\treturn;\n\t}\n\tfor (var i = 0; i < entries.length; i++){\n\t\tgetCapacity(i, entries[i], function(err, id, capacity){\n\t\t\tif (err) retError = err;\n\t\t\telse{\n\t\t\t\tcapacities[id] = capacity.space - capacity.usedSpace;\n\t\t\t\ttotalCapacity += capacity.space - capacity.usedSpace;\n\t\t\t}\n\t\t\tremainNo--;\n\t\t\tif (remainNo == 0){\n\t\t\t\tif (retError) callback(retError, []);\n\t\t\t\telse if (totalCapacity < filesize) callback(\"No enough space\", []);\n\t\t\t\telse{\n\t\t\t\t\tfor (var i = 0; i < entries.length; i++){\n\t\t\t\t\t\tif (filesize <= capacities[i]){\n\t\t\t\t\t\t\tdist.push(filesize);\n\t\t\t\t\t\t\tcallback(null, dist);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tdist.push(capacities[i]);\n\t\t\t\t\t\t\tfilesize -= capacities[i];\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}\n}",
"function greedyStrategy(items, capacity) {\n let changed = false;\n const possibleItems = items;\n let weight = 0;\n const inventory = {\n selectedItems: [],\n totalCost: 0,\n totalValue: 0, \n };\n\n console.log(\"Capacity is: \", capacity);\n\n // sort the array by value/size ratio score\n possibleItems.sort(function(a, b) {\n return parseFloat(b.score) - parseFloat(a.score);\n });\n\n for(let i = 0; weight <= capacity && i < possibleItems.length; i++) {\n weight += possibleItems[i].size;\n if(weight <= capacity){\n inventory.selectedItems.push(possibleItems[i].index);\n inventory.totalCost = weight;\n inventory.totalValue += possibleItems[i].value;\n } else{\n weight -= possibleItems[i].size;\n }\n }\n\n console.log(\"\\nInventory to GREED: \\nItems to select: \", inventory.selectedItems, \"\\nTotal cost: \", inventory.totalCost, \"\\nTotal value: \", inventory.totalValue)\n\n return inventory;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the total value of each of the darts in the Throw and assigns it to the Throw.total. | calculateTotal() {
this.total = [this.darts.one, this.darts.two, this.darts.three]
.map(dart => this.getDartValueFromID(dart))
.reduce((a, b) => a + b, 0);
} | [
"getTotalValue() {\n var totalVal = 0.0;\n for (var i in this.state.stocks) {\n //check if not null\n if (this.state.stocks[i][\"totalValue\"]) {\n totalVal += this.state.stocks[i][\"totalValue\"];\n }\n }\n // return totalVal.toFixed(3) + \" \" + currSymbol;\n return parseFloat(totalVal).toFixed(3) + this.getCurrencySymbol();\n }",
"function sumOf() {\n sum = newDieValues.reduce(function (a, b) {\n return a + b.info.value;\n }, 0);\n alert(\"Sum of dice equals: \" + sum);\n console.log(newDieValues);\n}",
"getSumOfDssRatios() {\n let sum = 0;\n for (let disease of this.diseases) {\n sum += this.getDssRatio(disease);\n }\n return sum;\n }",
"totalFood() {\n return this.passengers.reduce((accumulator, passenger) => accumulator + passenger.food, 0)\n \n }",
"totalExpense() {\n let totalExpense = 0;\n if (this.itemExpenseList.length > 0) {\n totalExpense = this.itemExpenseList.reduce(function (valAcum, valCorriente) {\n valAcum += valCorriente.amount; //Le sumo el valor actual al acumulado (x cada item de la lista)\n return valAcum; // Tengo que devolver este valor para que la funcion ande correctamente\n }, 0);\n\n }\n this.expenseAmount.text(totalExpense); // Muestro el total en el balance\n return totalExpense;\n }",
"statsSum() {\n let sum = 0;\n for (let key in this.stats) {\n sum += this.stats[key];\n }\n\n console.log(`La suma de tus estadísticas es ${sum}`);\n }",
"function totalPrice(){\n\t\t\t\tvar totalPrice = 0;\n\t\t\t\tfor (var i in cart){\n\t\t\t\t\ttotalPrice += cart[i].price;\n\t\t\t\t}\n\t\t\t\treturn totalPrice;\n\t\t\t}",
"function getTotalPrice() {\n var totalPrice = 0;\n _.each(createSaleCtrl.saleProducts, function(product) {\n totalPrice += product.price*createSaleCtrl.bought[product.barCode];\n });\n createSaleCtrl.totalPrice = totalPrice;\n }",
"total() {\n return Menu.getSodaPrice();\n }",
"function total() \n{\n // create var to store total\n var total = 0\n \n // check if there are items in the cart:\n if(cart.length > 0)\n {\n \n // check the cart prices\n for(let i = 0; i < cart.length; i++)\n {\n // tally it up!\n total += cart[i].itemPrice\n }\n }\n // return what has been summed up\n return total\n}",
"totalBill() {\n let billclass = this;\n _.map(this.diners, function(index) {\n let indvTotal = index.total + index.tax + index.tip;\n billclass.tBill.push(indvTotal);\n });\n billclass.tBill = _.sum(billclass.tBill);\n }",
"function question1() {\n let listItems = 0;\n for (let i = 0; i < data.length; i++) {\n listItems += data[i].price;\n console.log(listItems);\n }\n let averageprice = (listItems / data.length);\n console.log(\"averageprice\");\n\n}",
"add(stats) {\n let sum = new BirdStats({});\n this.forEachStat((name, value) => {\n sum[name] = value + stats[name];\n });\n return sum;\n }",
"calDiscount(){\n this._discount = this._totalCharged * (10/100) ;\n }",
"function getTotalDiscountAmount()\n {\n return getDiscountAmountOfThisMainOrder(getSubTotalAmount());\n }",
"function totalCalories() {\n calories = order.reduce((sum, item) => sum + item.getCalories(), 0);\n document.querySelector('.calories-value').innerHTML = calories + ' калорий';\n return calories;\n }",
"totalTip() {\n let billclass = this;\n _.map(this.diners, function(index) {\n billclass.tTip.push(index.tip);\n });\n billclass.tTip = _.sum(billclass.tTip);\n }",
"get summary(){\n let totals = this.totals;\n let fluxes = this.fluxes;\n return {\n Q: this.Q,\n COD: [totals.COD.total, fluxes.totals.COD.total], //chemical oxygen demand\n TKN: [totals.TKN.total, fluxes.totals.TKN.total], //total kjeldahl nitrogen\n NH4: [totals.TKN.FSA, fluxes.totals.TKN.FSA], //inorganic nitrogen (NH4, ammonia)\n NOx: [this.components.S_NOx, fluxes.components.S_NOx], //nitrate (NO3) and nitrite (NO2) is not TKN\n TP: [totals.TP.total, fluxes.totals.TP.total], //total phosphorus\n PO4: [totals.TP.PO4, fluxes.totals.TP.PO4], //inorganic phosphorus\n VSS: [totals.TSS.VSS, fluxes.totals.TSS.VSS], //volatile suspended solids\n iSS: [totals.TSS.iSS, fluxes.totals.TSS.iSS], //inorganic suspended solids\n TSS: [totals.TSS.total, fluxes.totals.TSS.total], //total suspended solids\n TOC: [totals.TOC.total, fluxes.totals.TOC.total], //total organic carbon\n }\n }",
"function calculateItemTotal(numItems, itemValue){\r\n\tvar total;\r\n\ttotal = numItems * itemValue;\r\n\ttotal = Number(total); //Needed to add this or else no output was recieved.\r\n\treturn total;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert into the tail | insertToTail(data) {
const node = new Node(data);
let tail = null;
//if empty, make it head
if (!this.head) {
this.head = node;
} else {
tail = this.head;
while (tail.next) {
tail = tail.next;
}
tail.next = node;
}
this.size++;
} | [
"addToTail(value) {\n const newNode = {\n value: value,\n next: null\n };\n\n if (!this.head && !this.tail) {\n this.head = newNode;\n this.tail = newNode;\n return;\n }\n this.tail.next = newNode;\n this.tail = newNode;\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 }",
"insert(value){\n this.data.push(value);\n this.siftUp(this.data.length-1)\n }",
"insert() {\n let newNode = new Node(1);\n newNode.npx = XOR(this.head, null);\n // logic to update the next pointer of the previous element once the next element is being set.\n\n // (null ^ 1)^ null will nullify null and the output will be 1\n if(this.head !== null) {\n let next = XOR(this.head.npx, null);\n this.head.npx = XOR(newNode, next)\n }\n\n // change the head node to the last node\n this.head = newNode;\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 insert_elt_after(new_elt, old_elt){\n old_elt.parentNode.insertBefore(new_elt, old_elt.nextSibling);\n}",
"addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }",
"insert(value, nth){\n if (nth === 0) return this.push_front(value);\n if (this.get(nth)) {\n let newNode = new LLNode(value);\n let oldNode = this.get(nth);\n newNode.next = oldNode;\n newNode.prev = oldNode.prev;\n oldNode.prev.next = newNode;\n oldNode.prev = newNode;\n this.length++;\n return this;\n }\n }",
"append(data) {\n if (this.head == null) {\n this.head = new Node(data);\n return;\n } \n\n let currentNode = this.head;\n while (currentNode.next != null) {\n currentNode = currentNode.next;\n }\n currentNode.next = new Node(data);\n }",
"addToBack(value){\n let newNode = new DLNode(value);\n if(this.isEmpty()){\n this.tail = newNode;\n this.head = newNode;\n return this;\n }\n\n newNode.prev = this.tail;\n this.tail.next = newNode;\n this.tail = newNode;\n return this;\n }",
"function insertXY(arr, num, idx){\n var temp;\n arr.push(num);\n for (var i = arr.length-1; i > idx; i--){\n temp = arr[i];\n arr[i] = arr[i-1];\n arr[i-1] = temp;\n }\n console.log(arr);\n}",
"addAfter(key, data) {\n if (this.head == null) return;\n\n let currentNode = this.head;\n while (currentNode != null && currentNode.data != key) {\n currentNode = currentNode.next;\n }\n\n if (currentNode) {\n let tempNode = currentNode.next;\n currentNode.next = new Node(data);\n currentNode.next.next = tempNode;\n return;\n }\n }",
"setTail(node) {\n if (!this.tail) {\n this.head = node;\n this.tail = node;\n } else {\n node.prev = this.tail;\n this.tail = node;\n }\n }",
"function ELEMENT_TAIL$static_(){LinkListBEMEntities.ELEMENT_TAIL=( LinkListBEMEntities.BLOCK.createElement(\"tail\"));}",
"function insertAfter(parent, insert, node)\n{\n\tif (insert != null)\n\t{\n\t\tparent.insertBefore( node, insert.nextSibling );\n\t}\n\telse\n\t{\n\t\tparent.insertBefore( node, parent.firstElementChild );\n\t}\n}",
"insertAfter(value, newVal) {\n let current = this.head;\n\n while(current) {\n if (current.value === value) {\n let node = new Node(newVal);\n node.next = current.next;\n current.next = node;\n return;\n } \n current = current.next;\n }\n }",
"addToBack(value) {\n var newNode = new SLLNode(value);\n\n if (this.head == null) {\n this.head = newNode;\n return;\n }\n\n var runner = this.head;\n\n while (runner.next != null) {\n // console.log(runner.value)\n runner = runner.next;\n }\n runner.next = newNode;\n }",
"function insert(array, start, end, v) {\n while (start + 1 < end && array[start + 1] < v) {\n var tmp = array[start];\n array[start] = array[start + 1];\n array[start + 1] = tmp;\n start++;\n }\n array[start] = v;\n }",
"prependData(target, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner === target){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }",
"function showNextTail() {\n if (tailHistory.length == 0) {\n $(\"#no_tiles_msg\").hide();\n }\n if (tails.length > 0 || currentTailIdx < tailHistory.length - 1) {\n currentTailIdx += 1;\n if (currentTailIdx == tailHistory.length) { \n var newTail = popRandomTail();\n tailHistory.push(newTail);\n addTailToHistoryList(newTail);\n }\n showCurrTail();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
max() that takes three number | function maxofThree(a,b,c){
return max(max(a,b),c);
} | [
"function biggestOfThree (a,b,c){\n\tif (a > b){\n\t\tif (a > c){\n\t\t\treturn a;\n\t\t} else {\n\t\t\treturn c;\n\t\t} \n\t\t}\n\t\tif (c > b) {\n\t\t\treturn c;\n\t\t} else {\n\t\t\treturn b;\n\t\t}\n\t}",
"function MaximumProductOfThree(arr) {\n let maxArr = [];\n for (let i = 0; i < arr.length; i++) {\n let maxNum = Math.max(...arr);\n maxArr.push(maxNum);\n if (maxArr.length === 3) {\n return maxArr[0] * maxArr[1] * maxArr[2];\n }\n }\n return \"error\";\n}",
"function max(num1,num2){\n return Math.max(num1,num2)\n}",
"function findMaximumValue(array) {\n\n}",
"function findMaxProduct(array) {\n\n}",
"function maxOfTwoNumbers(a, b) {\n if (a > b) return a;\n else return b;\n}",
"function highestProductOf3(array) {\n //check that array has at least 3 elements\n if (array.length < 3) {throw new Error('Less than 3 items!')}\n\n // start at the 3rd item (index 2)\n // so pre-populate highest and lowest based on\n // the first 2 items\n\n let highest = Math.max(array[0], array[1]);\n let lowest = Math.min(array[0], array[1]);\n\n let highestProductOf2 = array[0] * array[1];\n let lowestProductOf2 = array[0] * array[1];\n\n let highestProductOf3 = array[0] * array[1] * array[2];\n\n //walk thorugh the items, starting at index 2\n for (let i = 2; i < array.length ; i++) {\n let current = array[i]\n\n //do we have a highest product of 3?\n // it's either the current highest,\n // or the current times the highest prod of 2\n // or the current times the lowest prod of 2\n highestProductOf3 = Math.max(\n highestProductOf3,\n current * highestProductOf2,\n current * lowestProductOf2\n );\n\n // do we have a new highest product of two?\n highestProductOf2 = Math.max(\n highestProductOf2,\n current * highest,\n current * lowest\n );\n\n lowestProductOf2 = Math.min(\n lowestProductOf2,\n current * highest,\n current * lowest\n )\n\n // do we have a new highest?\n highest = Math.max(highest, current);\n\n //do we have a new lowest?\n lowest = Math.min(lowest, current);\n }\n return highestProductOf3;\n}",
"function maxLoot_(arr){\n let n = arr.length;\n if(n==0)\n return 0;\n let value1 = arr[0];\n if(n==1)\n return value1;\n \n let value2 = Math.max(arr[0] , arr[1]);\n if(n == 2)\n return value2;\n let maxValue = 0;\n for(let i = 2 ; i < n ; i++){\n maxValue = Math.max(arr[i]+ value1 , value2);\n value1= value2;\n value2 = maxValue;\n }\n return maxValue;\n}",
"function maxb(a, b) {\n if (a > b) return a;\n return b;\n}",
"highestMarks(marks) {\n let mark = Object.values(marks[0]).map(element => {\n return parseInt(element);\n });\n return Math.max(...mark);\n }",
"function findMinMax(array, minmax) {\n if ( minmax == \"max\" ) {\n return Math.max.apply(Math, array);\n }\n else if ( minmax == \"min\" ) {\n return Math.min.apply(Math, array);\n }\n return 'incorrect arguments';\n }",
"function max(object) {\n let valArray = Object.values(object);\n let currMax = valArray[0];\n let error = 0;\n valArray.forEach(function (n) {\n // if array contains a non number return the whole array\n if (typeof (n) != 'number') {\n error = 1;\n }\n else if (n > currMax) {\n currMax = n;\n }\n\n })\n if (error === 1) { return null; }\n else { return currMax; }\n}",
"function solution(digits){\n var temp = String(digits);\n //save the inserted value as a string\n var greatest = parseInt(temp.slice(0,5));\n // The parseInt function parses a string and returns an integer.\n //create a variable to save the greatest 5 digits, start with the first five\n for (var i = 0;i<temp.length;i++){\n //iterate through the length of the temp\n if(temp.slice(i, i+5) > greatest){ \n greatest = parseInt(temp.slice(i,i+5))\n //for every index, i can join it with the next 4 characters\n //then i can convert it to an integer\n //and compare it to the previously stored largest number (0 if first index)\n //if the current is greater, assign the value to the largest number variable\n //else the variable retains the same value and we move onto the next index\n }\n }\n return greatest \n }",
"function _getMax(allowedCards){\n\t\tvar max = 0;\n\t\tfor(var i in allowedCards){\n\t\t\tif(cardPrefixesAndLengths[allowedCards[i]].max > max){\n\t\t\t\tmax = cardPrefixesAndLengths[allowedCards[i]].max;\n\t\t\t}\n\t\t}\n\t\treturn max;\n\t}",
"function max_1(x, y) /* (x : double, y : double) -> double */ {\n return ((x >= y)) ? x : y;\n}",
"function maxRecurse(...num) {\n const array = num[0];\n const array2 = [...array];\n let max = array2[0];\n\n if (array2.length === 1) {return max}\n array2.shift();\n let newMax = maxRecurse(array2);\n if (max < newMax) {max = newMax}\n \n return max; \n}",
"function largestMult(x,y,grid,directions){\n let largest = 0\n directions.forEach((e)=>{\n let localRes = mult(x,y,grid,e[0],e[1])\n // console.log(localRes)\n if (localRes>largest){\n largest = localRes\n }\n })\n return largest\n}",
"function greatestOfInts(int1, int2) {\n try {\n var variable1 = parseInt(int1);\n var variable2 = parseInt(int2);\n return variable1 > variable2 ? 1 : variable1 == variable2 ? 0 : -1;\n } catch (ex) {\n alert(\"Enter only Integers\")\n return -2;\n }\n}",
"function multiOf(num , num2 ,num3)\n {\n\n \tif(num3 != 0)\n \t{\n \t\treturn num2*multiOf(num , num2 , num3-1);\n \t}\n return num;\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notifies the layout that the bounds of the currently selected item have changed. | onItemBoundsModifiedNotification(bounds) {
this._setBounds(bounds, false);
} | [
"selectionSetDidChange() {}",
"itemsChanged() {\n this._processItems();\n }",
"function updateActiveDropdownPosition() {\n $rootScope.$broadcast('lx-dropdown__update');\n }",
"function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }",
"childrenChanged() {\n if (true === this.adjustGroupWhenChildrenChange) {\n this.adjustChildrenVertically();\n this.adjustChildrenHorizontally();\n }\n }",
"_updateDirtyDomComponents() {\n // An item is marked dirty when:\n // - the item is not yet rendered\n // - the item's data is changed\n // - the item is selected/deselected\n if (this.dirty) {\n this._updateContents(this.dom.content);\n this._updateDataAttributes(this.dom.box);\n this._updateStyle(this.dom.box);\n \n // update class\n const className = this.baseClassName + ' ' + (this.data.className ? ' ' + this.data.className : '') +\n (this.selected ? ' vis-selected' : '') + ' vis-readonly';\n this.dom.box.className = 'vis-item ' + className;\n \n if (this.options.showStipes) {\n this.dom.line.className = 'vis-item vis-cluster-line ' + (this.selected ? ' vis-selected' : '');\n this.dom.dot.className = 'vis-item vis-cluster-dot ' + (this.selected ? ' vis-selected' : '');\n }\n \n if (this.data.end) {\n // turn off max-width to be able to calculate the real width\n // this causes an extra browser repaint/reflow, but so be it\n this.dom.content.style.maxWidth = 'none';\n }\n }\n }",
"handleSelectedEdited(item){\n\n\t\t//if this is the currently selected object, let's fire our change event\n\t\tif(item.ID == this.selectedClassItem)\n\t\t\tthis.eventSelectionEdited.fire(item);\n\t}",
"function theClickedItem(item) {\n setHighlightItem(item);\n }",
"_updateSelection() {\n\t\t// If there is no selection - remove DOM and fake selections.\n\t\tif ( this.selection.rangeCount === 0 ) {\n\t\t\tthis._removeDomSelection();\n\t\t\tthis._removeFakeSelection();\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst domRoot = this.domConverter.mapViewToDom( this.selection.editableElement );\n\n\t\t// Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.\n\t\tif ( !this.isFocused || !domRoot ) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Render selection.\n\t\tif ( this.selection.isFake ) {\n\t\t\tthis._updateFakeSelection( domRoot );\n\t\t} else {\n\t\t\tthis._removeFakeSelection();\n\t\t\tthis._updateDomSelection( domRoot );\n\t\t}\n\t}",
"_updateBounds() {\n if (this.autoShrink || this.size === 0) {\n if (this.sections.length) {\n this.bounds.left = Number.MAX_SAFE_INTEGER\n this.bounds.right = Number.MIN_SAFE_INTEGER\n this.bounds.top = Number.MAX_SAFE_INTEGER\n this.bounds.bottom = Number.MIN_SAFE_INTEGER\n } else {\n this.bounds.left = undefined\n this.bounds.right = undefined\n this.bounds.top = undefined\n this.bounds.bottom = undefined\n this.size = 0\n }\n }\n this.fillSize = 0\n this.sections.forEach(section => this._updateBoundsForSection(section))\n }",
"commit() {\n if (this.isDirty && this.elt) {\n let top = ((this.cellSize * this.y) + this.padding) + \"px\";\n let left = ((this.cellSize * this.x) + this.padding) + \"px\";\n this.elt.css({\n top: top,\n left: left\n });\n }\n this.reset();\n }",
"highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }",
"_updateSVG() {\n this.SVGInteractor.updateView(this.currentXRange, this.currentYRange, this.width, this.height);\n this.SVGInteractor.updateSelectView(this._currentSelectionPoints);\n }",
"_updateHeight() {\n this._updateSize();\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 }",
"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 }",
"function FileList::SelectionChanged() \r\n\t\t{\r\n\t\t\tSelChanged();\r\n\t\t}",
"_calculateOverlayPosition() {\n const itemHeight = this._getItemHeight();\n const items = this._getItemCount();\n const panelHeight = Math.min(items * itemHeight, SELECT_PANEL_MAX_HEIGHT);\n const scrollContainerHeight = items * itemHeight;\n // The farthest the panel can be scrolled before it hits the bottom\n const maxScroll = scrollContainerHeight - panelHeight;\n // If no value is selected we open the popup to the first item.\n let selectedOptionOffset;\n if (this.empty) {\n selectedOptionOffset = 0;\n }\n else {\n selectedOptionOffset = Math.max(this.options.toArray().indexOf(this._selectionModel.selected[0]), 0);\n }\n selectedOptionOffset += _countGroupLabelsBeforeLegacyOption(selectedOptionOffset, this.options, this.optionGroups);\n // We must maintain a scroll buffer so the selected option will be scrolled to the\n // center of the overlay panel rather than the top.\n const scrollBuffer = panelHeight / 2;\n this._scrollTop = this._calculateOverlayScroll(selectedOptionOffset, scrollBuffer, maxScroll);\n this._offsetY = this._calculateOverlayOffsetY(selectedOptionOffset, scrollBuffer, maxScroll);\n this._checkOverlayWithinViewport(maxScroll);\n }",
"handlePositionChangeEvent() {\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
6. Write a function that has 4 function inside and returns an object of all those 4 function with keys as function names and values as function calling. | function name() {
function one() {return "one"}
function two() {return "two"}
function three() {return "three"}
function four() {return "four"}
return {one: one(),
two: two(),
three: three(),
four: four(),}
} | [
"function listFunctionsRecursive(list) \n{\n\tvar obj = {};\n\tfor (var key in list) \n\t{\n\t\tif (list.hasOwnProperty(key))\n\t\t{\n\t\t\tobj = list[key];\n\t\t\tswitch (obj.type)\n\t\t\t{\n\t\t\t\tcase \"FunctionDeclaration\":\n\t\t\t\t\t/*\n\t\t\t\t\t * In our design we like the input code to be in an array. \n\t\t\t\t\t * Esprima gives the line numbers starting from 1, hence we\n\t\t\t\t\t * subtract the line numbers by 1\n\t\t\t\t\t */\n\t\t\t\t\tfunctionList[obj.id.name] = {\"name\": obj.id.name, \n\t\t\t\t\t\t\t\t\t\t\t \"lstart\": obj.loc.start.line-1, \n\t\t\t\t\t\t\t\t\t\t\t\t \"lend\": obj.loc.end.line-1};\n\t\t\t\t\tlistFunctionsRecursive(obj.body.body);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"VariableDeclaration\":\n\t\t\t\t\tlistFunctionsRecursive(obj.declarations);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"VariableDeclarator\":\n\t\t\t\t\tif (obj.init && (obj.init.type === \"FunctionExpression\")) {\n\t\t\t\t\t\tfunctionList[obj.id.name] = {\"name\": obj.id.name, \n\t\t\t\t\t\t\t\t\t\t\t\t\t \"lstart\": obj.init.loc.start.line-1, \n\t\t\t\t\t\t\t\t\t\t\t\t\t \"lend\": obj.init.loc.end.line-1};\n\t\t\t\t\t\tlistFunctionsRecursive(obj.init.body.body);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tcase \"ExpressionStatement\":\n\t\t\t\t\t/* This is for a = function(); kind of expressions*/\n\t\t\t\t\tif (obj.expression.right !== undefined){\n\t\t\t\t\t\tif((obj.expression.type === \"AssignmentExpression\") && \n\t\t\t\t\t\t\t(obj.expression.right.type === \"FunctionExpression\")) {\n\t\t\t\t\t\t\tvar functionName = \n\t\t\t\t\t\t\t\tgetNameLeftOfAssignmentExpression(obj.expression.left);\n\t\t\t\t\t\t\tfunctionList[functionName] = {\"name\": functionName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"lstart\": obj.expression.right.loc.start.line -1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"lend\": obj.expression.right.loc.end.line-1};\n\t\t\t\t\t\t\tlistFunctionsRecursive(obj.expression.right.body.body);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t/* Here we want to deal with (function(){})(); kidn of expressions */\n\t\t\t\t\t/* obj.expression.right will be undefined in this case */\n\t\t\t\t\tif((obj.expression.type === \"CallExpression\")) {\n\t\t\t\t\t\tif (obj.expression.callee.type === \"FunctionExpression\") {\n\t\t\t\t\t\t\tvar functionName = \"anonymous\" + anonymousNumber;\n\t\t\t\t\t\t\tanonymousNumber += 1;\n\t\t\t\t\t\t\tfunctionList[functionName] = {\"name\": functionName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"lstart\": obj.expression.callee.loc.start.line -1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"lend\": obj.expression.callee.loc.end.line-1};\n\t\t\t\t\t\t\tlistFunctionsRecursive(obj.expression.callee.body.body);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* Takes care of the definitions like foo.bar(function(){});*/\n\t\t\t\t\t\tif (obj.expression.arguments !== undefined) {\n\t\t\t\t\t\t\tlistFunctionsRecursive(obj.expression.arguments);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"FunctionExpression\":\n\t\t\t\t\tvar functionName = \"anonymous\" + anonymousNumber;\n\t\t\t\t\tanonymousNumber += 1;\n\t\t\t\t\tfunctionList[functionName] = {\"name\": functionName,\n\t\t\t\t\t\t\t\t\t\t\t\t \"lstart\": obj.loc.start.line -1,\n\t\t\t\t\t\t\t\t\t\t\t\t \"lend\": obj.loc.end.line-1};\n\t\t\t\t\tlistFunctionsRecursive(obj.body.body);\n\t\t\t\t\tbreak;\n\n\t\t\t\t/*case \"ReturnStatement\":\n\t\t\t\t\t \tvar returnFuncList = obj.argument.properties;\n\t\t\t\t\t \tfor(var x in returnFuncList)\n\t\t\t\t\t \t{\n\t\t\t\t\t \t\tconsole.log(returnFuncList);\n\t\t\t\t\t \t\tif(returnFuncList.value.type == \"FunctionExpression\")\n\t\t\t\t\t \t\t{\n\t\t\t\t\t \t\t\tfunctionList[returnFuncList.key.name] = {\"name\": returnFuncList.key.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"lstart\": obj.expression.callee.loc.start.line -1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"lend\": obj.expression.callee.loc.end.line-1};\n\t\t\t\t\t\t\t\t//listFunctionsRecursive(obj.expression.callee.body.body);\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\tdefault:\n\t\t\t\t\t/* do nothing */\n\t\t\t}\n\t\t}\n\t}\n}",
"function AnyFunction4() {\r\n return function FunctionReturnsAfunction() {\r\n console.log(\"function returns another function\");\r\n //this is second funtion that returns another function\r\n };\r\n}",
"function getOperations(){ //-------------> working\n\nvar count = codeLines.length;\n\nfor(var i=0; i<count; i++){ \n\n\t\tvar commentTest = (/@/.test(codeLines[i].charAt(0))); //Checking for comments\n\t\tvar textTest = (/.text/.test( codeLines[i])); //checking for .text keyword \n\t\tvar globalTest = /.global/.test( codeLines[i]); //checking for .global keyword\n\t\tvar mainTest = /main:/.test( codeLines[i]); //checking for main: label -------> Just for now!! should change later!!!!\n\t\tvar labelTest = labels.hasItem(codeLines[i]); \n\t\n\t\tif(!(commentTest||textTest||globalTest||mainTest||!codeLines[i]||labelTest)){ //(!codeLines[i]) check if the line is blank\n\n\t\t\tvar splitLine = codeLines[i].split(/[ ,\\t]+/).filter(Boolean); //-----> working. filter(Boolean) removes null values\n\t\t\tfunctionsHash.setItem(i, splitLine[0]); //Store function names with their line numbers\n\t\t\t\n\t\t}\n\t}\t\n}",
"function parseFunc() {\n var fnName = t.identifier(getUniqueName(\"func\"));\n var typeRef;\n var fnBody = [];\n var fnParams = [];\n var fnResult = []; // name\n\n if (token.type === _tokenizer.tokens.identifier) {\n fnName = identifierFromToken(token);\n eatToken();\n } else {\n fnName = t.withRaw(fnName, \"\"); // preserve anonymous\n }\n\n maybeIgnoreComment();\n\n while (token.type === _tokenizer.tokens.openParen || token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) {\n // Instructions without parens\n if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) {\n fnBody.push(parseFuncInstr());\n continue;\n }\n\n eatToken();\n\n if (lookaheadAndCheck(_tokenizer.keywords.param) === true) {\n eatToken();\n fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam()));\n } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) {\n eatToken();\n fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult()));\n } else if (lookaheadAndCheck(_tokenizer.keywords.export) === true) {\n eatToken();\n parseFuncExport(fnName);\n } else if (lookaheadAndCheck(_tokenizer.keywords.type) === true) {\n eatToken();\n typeRef = parseTypeReference();\n } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === \"keyword\" // is any keyword\n ) {\n // Instruction\n fnBody.push(parseFuncInstr());\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in func body\" + \", given \" + tokenToString(token));\n }();\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.func(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult), fnBody);\n }",
"function stringifyWithFunctions(obj) {\n // first stringify except mark off functions with markers\n var str = JSON.stringify(obj, function (key, value) {\n // if the value is a function, we want to wrap it with markers\n if (!!(value && value.constructor && value.call && value.apply)) {\n return FUNC_START + value.toString() + FUNC_STOP;\n }\n else {\n return value;\n }\n });\n // now we use the markers to replace function strings with actual functions\n var startFuncIdx = str.indexOf(FUNC_START);\n var stopFuncIdx, fn;\n while (startFuncIdx >= 0) {\n stopFuncIdx = str.indexOf(FUNC_STOP);\n // pull string out\n fn = str.substring(startFuncIdx + FUNC_START.length, stopFuncIdx);\n fn = fn.replace(/\\\\n/g, '\\n');\n str = str.substring(0, startFuncIdx - 1) + fn + str.substring(stopFuncIdx + FUNC_STOP.length + 1);\n startFuncIdx = str.indexOf(FUNC_START);\n }\n return str;\n}",
"function make_function_value(parameters, locals, body, env) {\n return { tag: \"function_value\",\n parameters: parameters,\n locals: locals,\n body: body,\n environment: env,\n // we include a prototype property, initially\n // the empty object. This means, user programs\n // can do: my_function.prototype.m = ...\n prototype: {},\n // another way of calling a function is by\n // invoking it via my_function.call(x,y,z)\n // This is actually an object method application,\n // and thus it becomes\n // (my_function[\"call\"])(my_function,x,y,z)\n // Therefore, we add an argument (let's call it\n // __function__) in front of the parameter list.\n call: { tag: \"function_value\",\n parameters: pair(\"__function__\",\n parameters),\n locals: locals,\n body: body,\n environment: env\n },\n // the property Inherits is available for all functions f\n // in the given program. This means that we can call\n // f.Inherits(...), using object method application\n Inherits: inherits_function_value\n };\n}",
"function four(){\n return 4;\n}",
"function makeCalculator() {\n var sum = 0;\n return {\n add: function(x) {\n sum += x;\n },\n subtract: function(x) {\n sum -= x;\n },\n times: function(x) {\n sum *= x;\n },\n getNumber: function() {\n return sum;\n }\n };\n\n}",
"function restoreFunctionNames(ast) {\n var functionNames = [];\n t.traverse(ast, {\n FunctionNameMetadata: function FunctionNameMetadata(_ref) {\n var node = _ref.node;\n functionNames.push({\n name: node.value,\n index: node.index\n });\n }\n });\n\n if (functionNames.length === 0) {\n return;\n }\n\n t.traverse(ast, {\n Func: function (_Func) {\n function Func(_x) {\n return _Func.apply(this, arguments);\n }\n\n Func.toString = function () {\n return _Func.toString();\n };\n\n return Func;\n }(function (_ref2) {\n var node = _ref2.node;\n // $FlowIgnore\n var nodeName = node.name;\n var indexBasedFunctionName = nodeName.value;\n var index = Number(indexBasedFunctionName.replace(\"func_\", \"\"));\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n var oldValue = nodeName.value;\n nodeName.value = functionName.name;\n nodeName.numeric = oldValue; // $FlowIgnore\n\n delete nodeName.raw;\n }\n }),\n // Also update the reference in the export\n ModuleExport: function (_ModuleExport) {\n function ModuleExport(_x2) {\n return _ModuleExport.apply(this, arguments);\n }\n\n ModuleExport.toString = function () {\n return _ModuleExport.toString();\n };\n\n return ModuleExport;\n }(function (_ref3) {\n var node = _ref3.node;\n\n if (node.descr.exportType === \"Func\") {\n // $FlowIgnore\n var nodeName = node.descr.id;\n var index = nodeName.value;\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n node.descr.id = t.identifier(functionName.name);\n }\n }\n }),\n ModuleImport: function (_ModuleImport) {\n function ModuleImport(_x3) {\n return _ModuleImport.apply(this, arguments);\n }\n\n ModuleImport.toString = function () {\n return _ModuleImport.toString();\n };\n\n return ModuleImport;\n }(function (_ref4) {\n var node = _ref4.node;\n\n if (node.descr.type === \"FuncImportDescr\") {\n // $FlowIgnore\n var indexBasedFunctionName = node.descr.id;\n var index = Number(indexBasedFunctionName.replace(\"func_\", \"\"));\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n // $FlowIgnore\n node.descr.id = t.identifier(functionName.name);\n }\n }\n }),\n CallInstruction: function (_CallInstruction) {\n function CallInstruction(_x4) {\n return _CallInstruction.apply(this, arguments);\n }\n\n CallInstruction.toString = function () {\n return _CallInstruction.toString();\n };\n\n return CallInstruction;\n }(function (nodePath) {\n var node = nodePath.node;\n var index = node.index.value;\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n var oldValue = node.index;\n node.index = t.identifier(functionName.name);\n node.numeric = oldValue; // $FlowIgnore\n\n delete node.raw;\n }\n })\n });\n}",
"function compose(...funcs) {\n return funcs.reduce((a, b) => {\n // console.log(a.toString(), 'aaaaa');\n // console.log(b.toString());\n // console.log('===================', a, b)\n return (...args) => a(b(...args));\n })\n}",
"function call(){\n\t\t\t$.each(funstack, function(index, value){\n\t\t\t\tvalue();\n\t\t\t});\n\t\t}",
"function miFuncion(){}",
"function optimise_obj(obj, funcnames) {\r\n var funcname, funcparts, newfuncs = [];\r\n for (funcname in obj) {\r\n if (funcnames.indexOf(funcname) >= 0) {\r\n funcparts = /function\\s*\\(([^(]*)\\)\\s*\\{([\\s\\S]+)\\}/.exec('' + obj[funcname]);\r\n if (DEBUG) {\r\n newfuncs.push(funcname + ':function ' + funcname + '(' + funcparts[1] + '){' + optimise(funcparts[2]) + '}');\r\n }\r\n else {\r\n newfuncs.push(funcname + ':function(' + funcparts[1] + '){' + optimise(funcparts[2]) + '}');\r\n }\r\n }\r\n }\r\n extend(obj, eval('({' + newfuncs.join() + '})'));\r\n }",
"function createFunction() {\n\tlet hello = \"hello\";\n\tfunction holla() {\n\t\tconsole.log(hello);\n\t}\n\treturn holla;\n}",
"visitStandard_function(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function combineOperations(startVal,arrOfFuncs){\n\n //////////solution 1\n // return arrOfFuncs.reduce((acc,func)=> {\n // return func(acc)\n // },startVal)\n\n ///////////solution 2\n // let output = startVal\n // arrOfFuncs.forEach(element=>{\n // output = element(output)\n // })\n // return output\n}",
"function four() {\n return 4;\n}",
"function someFunctionDefinition(){\n console.log(\"this is a function statement\");\n}",
"_evalExpression(exp) {\n exp = exp.trim();\n\n // catch special cases, with referenced properties, e.g. resourceGroup().location\n let match = exp.match(/(\\w+)\\((.*)\\)\\.(.*)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n let funcProps = match[3].toLowerCase();\n if(funcName == 'resourcegroup' && funcProps == 'id') return 'resource-group-id'; \n if(funcName == 'resourcegroup' && funcProps == 'location') return 'resource-group-location'; \n if(funcName == 'subscription' && funcProps == 'subscriptionid') return 'subscription-id'; \n if(funcName == 'deployment' && funcProps == 'name') return 'deployment-name'; \n }\n \n // It looks like a function\n match = exp.match(/(\\w+)\\((.*)\\)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n //console.log(`~~~ function: *${funcName}* |${funcParams}|`);\n \n if(funcName == 'variables') {\n return this._funcVariables(this._evalExpression(funcParams));\n }\n if(funcName == 'uniquestring') {\n return this._funcUniquestring(this._evalExpression(funcParams));\n } \n if(funcName == 'concat') {\n return this._funcConcat(funcParams, '');\n }\n if(funcName == 'parameters') {\n // This is a small cop out, but we can't know the value of parameters until deployment!\n // So we just display curly braces around the paramter name. It looks OK\n return `{{${this._evalExpression(funcParams)}}}`;\n } \n if(funcName == 'replace') {\n return this._funcReplace(funcParams);\n } \n if(funcName == 'tolower') {\n return this._funcToLower(funcParams);\n } \n if(funcName == 'toupper') {\n return this._funcToUpper(funcParams);\n } \n if(funcName == 'substring') {\n return this._funcSubstring(funcParams);\n } \n if(funcName == 'resourceid') {\n // Treat resourceId as a concat operation with slashes \n let resid = this._funcConcat(funcParams, '/');\n // clean up needed\n resid = resid.replace(/^\\//, '');\n resid = resid.replace(/\\/\\//, '/');\n return resid;\n } \n }\n\n // It looks like a string literal\n match = exp.match(/^\\'(.*)\\'$/);\n if(match) {\n return match[1];\n }\n\n // It looks like a number literal\n match = exp.match(/^(\\d+)/);\n if(match) {\n return match[1].toString();\n }\n\n // Catch all, just return the expression, unparsed\n return exp;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
change the state of the selectedStyle once we click on a thumbnail | selectStyleThumbnail(style) {
this.setState({ selectedStyle: style }, () => {
this.checkOutOfStock();
this.props.changeSelectedStyle(this.state.selectedStyle);
// need to check quantity too once we change a style
});
} | [
"onClick() {\n if (this.state.backgroundSelection === \"Header-background-1\") {\n this.setState({\n backgroundSelection: \"Header-background-2\",\n backgroundText: this.imageTextTwo()\n })\n } else if (this.state.backgroundSelection === \"Header-background-2\") {\n this.setState({\n backgroundSelection: \"Header-background-3\",\n backgroundText: this.imageTextThree()\n })\n } else {\n this.setState({\n backgroundSelection: \"Header-background-1\",\n backgroundText: this.imageTextOne()\n })\n }\n }",
"onSelect() {\n const attachment = this.frame.state().get('selection').first().toJSON()\n\n if (this.model.get('width') === attachment.width\n && this.model.get('height') === attachment.height\n && !this.model.get('flex_width')\n && !this.model.get('flex_height')) {\n this.setImageFromAttachment(attachment)\n this.frame.close()\n } else {\n this.frame.setState('cropper')\n }\n }",
"setSelected () {\n if (this.el.classList.contains(MenuItem.OVER_CLASS)) {\n this.animateSelected()\n } else {\n this.animateOnOver(() => {\n this.animateSelected(() => {\n this.setState()\n })\n })\n }\n }",
"function switchBtnClasses() {\n if(thumbnailElement.classList.contains(\"small\")){\n thumbnailElement.classList.remove(\"small\");\n }\n else {\n thumbnailElement.classList.add('small');\n }\n }",
"swapImage(flag, imgUrl, value) {\n flag\n ? this.setState({ selected: value })\n : this.setState({ selected: null });\n\n this.props.swapImage(flag, imgUrl, value);\n }",
"function _highlightTile() {\n var itemSelected = lv_cockpits.winControl.selection.getItems()._value[0];\n if (!itemSelected.data.spotlighted_at) {\n itemSelected.data.spotlighted_at = new Date();\n }\n else\n itemSelected.data.spotlighted_at = null;\n lv_cockpits.winControl.itemDataSource.change(itemSelected.key, itemSelected.data);\n }",
"function drawSelectionChanged() {\n drawType = drawSelector.value();\n setImage();\n}",
"function update_style_selection() {\n\tvar style = get_style();\n\tif (style !== null) {\n\t\tvar elem = document.getElementById(\"style_selection\");\n\t\tfor (i = 0; i < elem.options.length; i++) {\n\t\t\tvar option = elem.options[i];\n\t\t\tif (option.value == style) {\n\t\t\t\toption.selected = true;\n\t\t\t}\n\t\t}\n\t}\n}",
"function menuHighlightClick() {\n Data.Edit.Mode = EditModes.Highlight;\n updateMenu();\n}",
"function theClickedItem(item) {\n setHighlightItem(item);\n }",
"function select_color() {\n\tvar selected_color = $(this).css('background-color');\n\t$('#selected-color.swatch').css('background-color', selected_color);\n}",
"function highlightFeature(e) {\n e.target.setStyle(highLightStyle);\n}",
"function blockClassSelected() {selectedBlock.attr('class', 'selected')}",
"function switchBackground() {\n owner = publicPhotos[index].owner;\n photoURL = mapUrlLink(publicPhotos[index]);\n setBackground();\n }",
"function html_applyDefaultStyleToImg(target)\n{\n target.style.border = html_getDefaultBorderStyle();\n target.style.zIndex = html_default_zIndex ;\n target.wasClicked = false ;\n}",
"highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }",
"function select_style() {\n\tvar elem = document.getElementById(\"style_selection\");\n\tvar style = elem.value;\n\tset_style(style);\n}",
"function showImage(event) {\n\tresetClassNames(); // Klasu \"selected\" treba da ima onaj link cija je slika trenutno prikazana u \"mainImage\" elementu.\n\t\t\t\t\t // Pre stavljanja ove klase na kliknuti link, treba da sklonimo tu klasu sa prethodno kliknutog linka. To onda\n\t\t\t\t\t // postizemo tako sto sklonimo sve klase sa svih linkova, i time smo sigurni da ce i klasa \"selected\" biti uklonjena.\n\tthis.className = \"selected\"; // Stavljamo klasu \"selected\" na kliknuti link.\n\tmainImage.setAttribute(\"src\", this.getAttribute(\"href\")); // Atribut \"src\" elementa \"mainImage\" menjamo tako da postane jednak \"href\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // atributu kliknutog linka. A kako se u \"href\" atributu linka nalazi putanja\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // ka slici, postavljanjem \"src\" atributa na tu putanju, unutar elementa\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // \"mainImage\" ce se prikazati slika iz linka na koji se kliknulo.\n\tevent.preventDefault(); // Na ovaj nacin sprecavamo defoltno ponasanje browser-a, kojim bi se slika iz linka otvorila zasebno.\n\tscale = 1; // Nakon promene slike treba da vratimo zoom nivo na 1, da novoprikazana slika ne bi bila zumirana.\n\tsetScale(); // Kako smo u liniji iznad promenili vrednost \"scale\" globalne promenljive, potrebno je pozvati funkciju \"setScale\", koja onda\n\t\t\t\t// uzima vrednost promenljive \"scale\" i integrise je u CSS.\n\tleftPos = 0; // Nakon promene slike treba da vratimo sliku u inicijalnu poziciju.\n\tsetPosition(); // Kako smo u liniji iznad promenili vrednost \"leftPos\" globalne promenljive, potrebno je pozvati funkciju \"setPosition\"\n\t\t\t\t // koja onda uzima vrednost promenljive \"leftPos\" i integrise je u CSS.\n}",
"highlight() {\n this.model.set('isSelected', true);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the Media tree | static getMediaTree(req, res) {
MediaHelper.getTree(req.project, req.environment)
.then((tree) => {
res.status(200).send(tree);
})
.catch((e) => {
res.status(404).send(ApiController.printError(e));
});
} | [
"get tree() {\n return this.buffer ? null : this._tree._tree\n }",
"get thumb() {\n const animatedThumb = this.thumbRef.current;\n return animatedThumb && animatedThumb.getNode();\n }",
"function getMediaList( err ) {\n if( err ) {\n Y.log( 'error in deleting attachments', 'error', NAME );\n callback( err );\n return;\n }\n\n Y.doccirrus.mongodb.runDb( {\n 'migrate': true,\n 'action': 'get',\n 'model': 'media',\n 'user': user,\n 'query': {'ownerId': activity._id.toString()},\n 'callback': deleteFiles\n } );\n }",
"function htmlMediaIndex(data)\n{\n\treturn PrintIndex('M', _('Media Index'), true, htmlMediaIndexTable, null, data);\n}",
"readMedia(){\n\n }",
"function SplayTree() { }",
"function MediaElement(entry) {\n\n\tvar link = document.createElement('a');\n\tlink.href = entry.content.src;\n\tvar videoid = link.pathname.substr(link.pathname.length - 11);\n\n\tvar li_node = document.createElement(\"LI\");\n\tli_node.ontouchstart = function() {\n\t\tLoadVideo(this.childNodes[0]);\n\t\treturn false;\n\t}\n\tli_node.innerHTML = \"<a href=\\\"#\" + videoid + \"\\\" onclick=\\\"LoadVideo(this); return false;\\\" class=\\\"item-link item-content\\\">\"\n\t\t+ \"<div class=\\\"item-inner\\\">\"\n\t\t\t+ \"<div class=\\\"item-title-row\\\">\"\n\t\t\t+ \"<div class=\\\"item-title\\\">\" + entry.title.$t + \"</div>\"\n\t\t+ \"</div>\"\n\t\t+ \"<div class=\\\"item-text\\\">\" + entry.summary.$t + \"</div>\"\n\t\t+ \"</div></a>\"\n\treturn li_node;\n}",
"function MediaContent() {\n\tthis.arr_backgroundImages = [];\n\tthis.arr_characterImages = [];\n\tthis.arr_buttonImages = [];\n\tthis.arr_soundEffects = [];\n\tthis.goalImage;\n\n\tthis.arr_backgroundImages.push(\"img/Background-wood.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-beach.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-forrest.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-heaven.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-machu.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-moai.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-outerspace.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-chess.jpg\");\n\tthis.arr_backgroundImages.push(\"img/Background-field.jpg\");\n\n\tthis.arr_buttonImages.push(\"img/recycle.png\");\n\tthis.arr_buttonImages.push(\"img/stop.png\");\n\tthis.arr_buttonImages.push(\"img/play.png\");\n\n\tthis.arr_characterImages.push(\"img/Character-bear.png\");\n\tthis.arr_characterImages.push(\"img/Character-snaillightblue.png\");\n\tthis.arr_characterImages.push(\"img/Character-snaildarkblue.png\");\n\tthis.arr_characterImages.push(\"img/Character-albert.png\");\n\n\tthis.goalImage = \"img/star.png\";//\"img/goal.png\";\n\n\tthis.arr_soundEffects.push(\"audio/cartoonhop,mp3\");\n\tthis.arr_soundEffects.push(\"audio/cartoonwalk.mp3\");\n}",
"static getMediaElement(mediaElementId,type){const mediaElement=document.getElementById(mediaElementId);if(!mediaElement){throw new ArgumentException(`element with id '${mediaElementId}' not found`);}if(mediaElement.nodeName.toLowerCase()!==type.toLowerCase()){throw new ArgumentException(`element with id '${mediaElementId}' must be an ${type} element`);}return mediaElement;}",
"getStream() {\n if (this.mediaStream !== null && (typeof (this.mediaStream) !== null) && this.mediaStream !== undefined) { return this.mediaStream; }\n return null;\n }",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'get', kparams);\n\t}",
"get tree() {\n let syntax = this.facet(EditorState.syntax);\n return syntax.length ? syntax[0].getTree(this) : Tree.empty;\n }",
"static createBinaryBitmapFromMediaElem(mediaElement){const canvas=BrowserCodeReader$1.createCanvasFromMediaElement(mediaElement);return BrowserCodeReader$1.createBinaryBitmapFromCanvas(canvas);}",
"addMedia() {\n\n this.mediaFrame.open();\n }",
"function createArtifactMediaFolder(artifact) {\n\tvar site = getSiteByNode(artifact);\n\tif (site == null) {\n\t\tlogger.warn(\"Can't determine which site node belongs to. Media attachments folder wasn't created.\");\n\t\treturn null;\n\t}\n\n\tvar artistName = artifact.properties['ucm:artist_name'] || 'UNKNOWN_ARTIST';\n\n\tvar artifactName = artifact.properties['cm:name'];\n\tif (!artifactName) {\n\t\t// \"workspace://SpacesStore/1bcdb278-acf4-4477-a0ca-8d50d91be8d1\" ->\n\t\t// \"1bcdb278-acf4-4477-a0ca-8d50d91be8d1\"\n\t\tvar artifactId = artifact.getNodeRef().toString().replaceAll(\".*/\", \"\");\n\t\tartifactName = 'UNKNOWN_ARTIFACT_' + artifactId;\n\t}\n\n\tvar systemFolder = getOrCreateFolder(site, 'system');\n\tvar mediaFolder = getOrCreateFolder(systemFolder, 'artifact_attachments');\n\tvar artistFolder = getOrCreateFolder(mediaFolder, artistName);\n\tvar artifactFolder = getOrCreateFolder(artistFolder, artifactName);\n\n\t// set media folder caption\n\tartifactFolder.properties['cm:title'] = \"Media content for \" + artifactName;\n\tartifactFolder.save;\n\n\t// clean up existing associations\n\ttry {\n\t\tvar assocs = artifact.childAssocs['ucm:artifact_contains'];\n\t\tfor each (var assoc in assocs) {\n\t\t\tartifact.removeAssociation(assoc, 'ucm:artifact_contains');\n\t\t}\n\t\tartifact.removeAssociation(artifactFolder, 'ucm:artifact_contains');\n\t} catch (e) {}\n\n\t// save reference to folder in artifact association\n\tartifact.createAssociation(artifactFolder, 'ucm:artifact_contains');\n\tartifact.save();\n\n\treturn artifactFolder;\n}",
"function musicJSON(root) {\n if (!root) {\n return false;\n }\n\n // Create the main MusicJSON root\n var musicJSON = {};\n\n // Start the recursive serializing of the MusicXML document\n musicJSON[root.tagName.toLowerCase()] = parseElement(root);\n\n return musicJSON;\n}",
"get binaryMediaTypes() {\n return this.getListAttribute('binary_media_types');\n }",
"getMediaplayerSettings() {\n return {\n \n stream: { src: App.getPath(`DStv_Promo_(The_Greatest_Show).mp4`) }\n }\n }",
"static setMediaTreeItem(req, res) {\n let id = req.params.id;\n let item = req.body;\n\n MediaHelper.setTreeItem(req.project, req.environment, id, item)\n .then(() => {\n res.status(200).send(item);\n })\n .catch((e) => {\n res.status(502).send(ApiController.printError(e));\n }); \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
submit button click handler to update reservation and table when sat | async function submitHandler(event) {
event.preventDefault()
const abortController = new AbortController()
setErrors(null)
const select = document.querySelector('select')
const selectedId = select.options[select.selectedIndex].id
try {
await seatReservation(reservation_id, selectedId, abortController.signal)
const data = {
reservation_id: reservation_id,
status: "seated"
}
await setStatus(data, reservation_id, abortController.signal)
history.push('/dashboard')
} catch(error) {
setErrors(error)
}
} | [
"function handleUpdateTrip() {\n\t$('main').on('submit','.edit-trip-form', function(event) {\n\t\tevent.preventDefault();\n\t\tconst tripId = $(this).data('id');\n\t\tconst toUpdateData = {\n\t\t\tid: tripId,\n\t\t\tname: $('.trip-name').val(),\n\t\t\tstartDate: new Date($('.start-date').val()),\n\t\t\tendDate: new Date($('.end-date').val()),\n\t\t\tcountry: $('.country').val(),\n\t\t\tdescription: $('.description').val()\n\t\t}\n\t\tupdateTrip(tripId, toUpdateData);\n\t})\n}",
"function _editVoterRegistration(e){\n\n // submitting state\n e.preventDefault();\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdating\");\n document.querySelector(\"#submit-button\").setAttribute(\"disabled\", \"\");\n\n // validate registration lookup fields\n //TODO\n\n // add new history item\n entry['status'] = \"pending\";\n entry['stateStorage']['history'].push({\n \"type\": \"runChecking\",\n \"created\": (new Date).toISOString(),\n \"updated\": (new Date).toISOString(),\n \"checkingMessage\": \"Checking...\", // TODO: i18n\n \"lookup\": {\n \"firstName\": document.querySelector(\"#first-name\").value,\n \"lastName\": document.querySelector(\"#last-name\").value,\n \"dateOfBirth\": document.querySelector(\"#date-of-birth\").value,\n \"county\": document.querySelector(\"#county\").value,\n \"zipCode\": document.querySelector(\"#zip-code\").value,\n },\n \"result\": null,\n \"error\": {},\n \"voter\": {},\n });\n\n // status updates while running\n var intervalID = null;\n function _monitorStatus(){\n // stop monitoring when no longer listening\n if(entry['status'] !== \"pending\"){\n clearInterval(intervalID);\n return;\n }\n\n // still running, so show the latest status message\n for(var i = (entry['stateStorage']['history'].length - 1); i >= 0; i--){\n var historyItem = entry['stateStorage']['history'][i];\n if(historyItem['type'] === \"runChecking\"){\n document.querySelector(\"#results\").innerHTML = `\n <div class=\"text-muted\">${historyItem['checkingMessage']}</div>\n `;\n break;\n }\n }\n }\n\n // done trying to look up the voter\n function _processResults(entry){\n\n // get what voters were found (assume the lookup\n var result = entry['stateStorage']['history'][entry['stateStorage']['history'].length - 1]['result'];\n var voter = entry['stateStorage']['history'][entry['stateStorage']['history'].length - 1]['voter'];\n\n // found the voter, so save the db entry and close the window\n if(result === \"success\"){\n var dbUpdates = {};\n dbUpdates[entry['key']] = entry;\n browser.storage.local.set(dbUpdates).then(function(){\n\n // show success message\n document.querySelector(\"#results\").innerHTML = `\n <h4 class=\"d-inline-block text-success\">\n <svg class=\"icon\"><use href=\"/assets/sprite-fontawesome-4.7.0.svg#fa-check\"/></svg>\n </h4>\n ${browser.i18n.getMessage(\"editEntrySuccess\")}\n <button id=\"close-window\" class=\"btn btn-link\">\n ${browser.i18n.getMessage(\"editEntryCloseWindow\")}\n </button>\n `;\n\n // reset the submit button\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n\n // close the add-registration interface\n document.querySelector(\"#close-window\").addEventListener(\"click\", function(e){\n e.preventDefault();\n browser.windows.getCurrent().then(function(w){\n browser.windows.remove(w.id);\n });\n });\n\n });\n }\n\n // couldn't find a matching voter, so ask to correct and retry\n else if(result === \"no_voter_found\"){\n // show the error\n document.querySelector(\"#results\").innerHTML = `\n <h4 class=\"d-inline-block text-danger\">\n <svg class=\"icon\"><use href=\"/assets/sprite-fontawesome-4.7.0.svg#fa-times-circle\"/></svg>\n </h4>\n ${browser.i18n.getMessage(\"voterNotFoundError\")}\n `;\n // reset the submit button\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n }\n\n // request blocked by cloudflare >:(\n else if(result === \"blocked_by_cloudflare\"){\n // show the error\n document.querySelector(\"#results\").innerHTML = `\n <h4 class=\"d-inline-block text-warning\">\n <svg class=\"icon\"><use href=\"/assets/sprite-fontawesome-4.7.0.svg#fa-minus-circle\"/></svg>\n </h4>\n ${browser.i18n.getMessage(\"blockedByCloudflare\")}\n `;\n // reset the submit button\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n //TODO: add recovery options\n }\n\n // didn't have permission to access the TX SOS site >:(\n else if(result === \"need_permission\"){\n // show modal to prepare the user for the popup\n var permissionModal = new BSN.Modal(document.querySelector(\"#permission-modal\"));\n permissionModal.show();\n // reset the submit button\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n }\n\n // some other error occurred\n else if(result === \"other_error\"){\n // show the error\n document.querySelector(\"#results\").innerHTML = `\n <h4 class=\"d-inline-block text-danger\">\n <svg class=\"icon\"><use href=\"/assets/sprite-fontawesome-4.7.0.svg#fa-exclamation-triangle\"/></svg>\n </h4>\n ${browser.i18n.getMessage(\"voterLookupError\")}\n `;\n // reset the submit button\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n //TODO: add recovery options\n }\n }\n\n // ask for permission if don't already have it\n browser.permissions.contains({\n origins: [\"*://*.sos.texas.gov/*\"],\n }).then(function(hasPermission){\n\n // has permission, so run the checker now\n if(hasPermission){\n PurgeAlert['TX'].checkRegistration(entry, _processResults);\n intervalID = setInterval(_monitorStatus, 100);\n }\n\n // doesn't have permission, so ask the user to provide permission\n else {\n\n // show modal to prepare the user for the popup\n var permissionModal = new BSN.Modal(document.querySelector(\"#permission-modal\"));\n permissionModal.show();\n\n // reset the submit button\n document.querySelector(\"#results\").innerHTML = \"\";\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n }\n });\n\n // ask for permission when the user says to show the prompt\n document.querySelector(\"#grant-permission\").addEventListener(\"click\", function(e){\n e.preventDefault();\n\n // extension permission request\n browser.permissions.request({\n origins: [\"*://*.sos.texas.gov/*\"],\n }).then(function(givenPermission){\n\n // close the modal\n var permissionModal = new BSN.Modal(document.querySelector(\"#permission-modal\"));\n permissionModal.hide();\n\n // given permission, so check the submitted registration\n if(givenPermission){\n PurgeAlert['TX'].checkRegistration(entry, _processResults);\n intervalID = setInterval(_monitorStatus, 100);\n }\n\n // permission denied, so show the same permission prep\n else {\n\n document.querySelector(\"#results\").innerHTML = \"\";\n document.querySelector(\"#submit-button\").value = browser.i18n.getMessage(\"editEntryUpdateButton\");\n document.querySelector(\"#submit-button\").removeAttribute(\"disabled\");\n }\n });\n });\n }",
"function submitReservation(e){\n\n //prevents submit refreshing page\n e.preventDefault();\n\n //getting the user elements from form inputs by id\n var event = document.getElementById('event').value;\n var date = document.getElementById('date').value;\n var reservation_name = document.getElementById('user_name').value;\n var reservation_email = document.getElementById('reserve_email').value;\n var reservation_id = firebase.database().ref().child('reservation').push().key;\n\n //defining the data to be put into the database\n var data = {\n uid: reservation_id,\n user_name: reservation_name,\n user_email: reservation_email,\n event: event,\n date: date\n }\n\n //declaring the reservation object to be sent\n var reservationDetails = {};\n\n //putting the data into database by id\n reservationDetails['/reservation/' + reservation_id] = data;\n\n firebase.database().ref().update(reservationDetails);\n console.log('Reservation created');\n}",
"function submitFindRoom() {\n var isValid, checkin, checkout;\n isValid = true;\n\n // Validate checkin date\n checkin = getDateFromForm(\"#checkinday\", \"#checkinmonth\", \"#checkinyear\");\n\n\n // Validate checkout date\n checkout = getDateFromForm(\"#checkoutday\", \"#checkoutmonth\", \"#checkoutyear\");\n\n\n // If OK, set up the booking form\n if (isValid) {\n $(\"#checkinDate\").val(checkin);\n $(\"#checkoutDate\").val(checkout);\n $(\"#findRoomForm :input\").prop(\"disabled\", true);\n $(\"#searchingForRooms\").show();\n setupBookRoom(checkin, checkout);\n }\n\n return false;\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 }",
"function submitButtonClick(e) {\n\t$('#hiddenField').val(row.first().text());\n\tif ('updtButton' == lastButtonClicked) {\t//Old Contact is updated\n\t\t$.post(\"contacts/update\", $('form').serialize(), function (data) {\n\t\t\tindex = $('tr').index(row.parents('tr')) - 1;\n\t\t\tarr[index] = data.obj;\t//update the array\n\t\t\t// $('#tables_page_id').show();\n\t\t\t$('#contacts_page_id').hide();\n\t\t\treRenderTable();\n\t\t\tmymap.removeLayer(markers[index]);\n\t\t\tlet lat = (arr[index].latitude);\n\t\t\tlet lng = (arr[index].longitude);\n\t\t\tlet marker = L.marker([lat, lng]).addTo(mymap);\n\t\t\t//Bind popup to the marker.\n\t\t\tlet p = $('<p></p>');\n\t\t\tp.append((arr[index]).firstName.toUpperCase());\n\t\t\tp.attr('class', 'emphasis');\n\t\t\tmarker.bindPopup(p[0]);\t//add user input text to pop up.\n\t\t\tmarkers[index] = marker;\n\t\t\tmymap.flyTo([lat, lng], 4);\n\t\t\tmarker.on('mouseover', function (e) {\n\t\t\t\tthis.openPopup();\n\t\t\t});\n\t\t\tmarker.on('mouseout', function (e) {\n\t\t\t\tthis.closePopup();\n\t\t\t});\n\t\t\tlastButtonClicked = \"updateSubmitBtn\";\n\t\t});\n\t} else if ('createButton' == lastButtonClicked) {\t//New Contact is Created\n\t\t$.post(\"contacts/create\", $('form').serialize(), function (data) {\n\t\t\tarr.push(data.obj);\t//update the array\n\t\t\t// $('#tables_page_id').show();\n\t\t\t$('#contacts_page_id').hide();\n\t\t\treRenderTable();\n\t\t\tlet lat = (data.obj.latitude);\n\t\t\tlet lng = (data.obj.longitude);\n\t\t\tlet marker = L.marker([lat, lng]).addTo(mymap);\n\t\t\t//Bind popup to the marker.\n\t\t\tlet p = $('<p></p>');\n\t\t\tp.append(data.obj.firstName.toUpperCase());\n\t\t\tp.attr('class', 'emphasis');\n\t\t\tmarker.bindPopup(p[0]);\t//add user input text to pop up.\n\t\t\tmarker.on('mouseover', function (e) {\n\t\t\t\tthis.openPopup();\n\t\t\t});\n\t\t\tmarker.on('mouseout', function (e) {\n\t\t\t\tthis.closePopup();\n\t\t\t});\n\t\t\tmarkers.push(marker);\n\t\t\tmymap.flyTo([lat, lng], 4);\n\t\t\tlastButtonClicked = \"createSubmitBtn\";\n\t\t});\n\t}\n}",
"async function okCreateShift() {\n if (userRole === \"Admin\") {\n try {\n let thisShift = undefined;\n let newStart = startTimeInput.value;\n let newEnd = endTimeInput.value;\n let startDate = new Date(SelectedDate + \"T\" + newStart + \"Z\");\n let endDate = new Date(SelectedDate + \"T\" + newEnd + \"Z\");\n let newEmployee = undefined;\n let update = createUpdate(thisShift, startDate, endDate, newEmployee);\n updates.push(update);\n ShiftModalCloseAction();\n saveButtonEnable();\n alert(\"Vagten er nu oprettet! Tryk gem for at tilføje vagten\");\n } catch (e) {\n console.log(e.name + \": \" + e.message);\n }\n }\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}",
"async function updateReservation(req, res, next) {\n const { reservation_id } = req.params;\n if (reservation_id) {\n res.json({\n data: await service.update(reservation_id, req.body.data),\n });\n }else{\n next({\n status: 404,\n message: \"no reservation_id found\"\n })\n }\n}",
"function completeEdition(e) {\n \n var id = e.currentTarget.id;\n var name = document.getElementById('form-edit-name');\n var url = document.getElementById('form-edit-url');\n\n getList(function(result){\n var list = result.stations;\n var station = list.find(e => e.id == id);\n station.name = name.value;\n station.url = url.value;\n saveList(list);\n });\n\n // clears form\n var form = document.getElementById('form-edit');\n getTable().deleteRow(form.rowIndex);\n\n window.location.reload();\n}",
"function editTrain() {\n if (CurrentUser === undefined || CurrentUser === null) {\n $('#authModal').modal(); // Restrict access to logged in users only. \n return;\n }\n\n var uniqueKey = $(this).closest('tr').data('key');\n\n rowArray = [];\n $(this).closest('tr').children().each(function () {\n rowArray.push($(this).text());\n });\n\n for (var i = 0; i < rowArray.length; i++) {\n var inputID = \"#\" + scheduleTableFields[i];\n $(inputID).val(rowArray[i]);\n }\n\n $(\"#add-train-form\").data(\"key\", uniqueKey);\n $(\"#add-train-form\").data(\"action\", \"update\");\n var plusIcon = $(\"<i>\").addClass(\"fas fa-plus\");\n $(\"#add-train\").html(\"Update \").append(plusIcon);\n\n}",
"function processTripIdSaveResponse(data){\n\t\t// if validation errors exist, display them.\n\t\tif(data.validationErrors.errors != undefined){\n\t\t\tprocessTripIdValidationErrors(data.validationErrors.errors);\n\t\t\tsaveValidationErrors = true;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// if multiple appointments found for the given date range,\n\t\t// prompt user to choose an appointment\n\t\tif(data.validationErrors.appointments != null){\n\t\t\thandleMultipleAppointments(dojo.fromJson(data.validationErrors.appointments[0]), \"Travel Requisitions\");\n\t\t\tsaveValidationErrors = true;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// display errors in error grid\n\t\tif((data.errors != null)){\n\t\t\tupdateErrorsGrid(data.errors);\n\t\t}\n\t\t\n\t\t// if save successful\n\t\tif(data.response.treqEventId != null){\n\t\t\t// update request Id\n\t\t\tdojo.byId('treqEventId').value = data.response.treqEventId;\n\t\t\t\n\t\t\t// update revision no\n\t\t\tdojo.byId('revNo').innerHTML = data.response.revisionNo;\n\t\t\t\n\t\t\t// update prev next button state\n\t\t\tif(data.response.revisionNo > 0){\n\t\t\t\tdojo.byId('prevRevBtn').disabled = false;\n\t\t\t\tdojo.byId('nextRevBtn').disabled = true;\n\t\t\t}\n\t\t\t\n\t\t\t// show save confirmation\n\t\t\tnotifyTripId('Saved successfully', false);\n\t\t\t// refresh details tab if save was performed through the pop up\n\t\t\tif (dijit.byId('travel_req_tab_container').selectedChildWidget.id != \"idTab\"){\n\t\t\t\tdijit.byId('travel_req_tab_container').selectedChildWidget.refresh();\n\t\t\t}\n\t\t\t\n\t\t\t// if modify was saved, set the tabs to reload\n\t\t\t/*if(modifyBtnClicked){ \n\t\t\t\tif(findElementPositionInArray(tabsToReload, 'expenseDetailsTab') < 0)\n\t\t\t\t\ttabsToReload.push('expenseDetailsTab');\n\t\t\t\tif(findElementPositionInArray(tabsToReload, 'liquidationsTab') < 0)\n\t\t\t\t\ttabsToReload.push('liquidationsTab');\n\n\t\t\t\t// reset variable state\n\t\t\t\tmodifyBtnClicked = false;\n\t\t\t}\t*/\n\t\t}else{\n\t\t\t// expense event Id is always returned, if operation is successful\n\t\t\tnotifyTripId('Save failed!', true);\n\t\t\t// this return will evaluate to problemsDuringSave = true;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t}",
"function updateSoupKitchen() {\n //build kitchen object we will pass to the back end\n var kitchen = {\n parent_site: currSite,\n description: $scope.currentKitchen.description,\n hours: $scope.currentKitchen.hours,\n kitchen_condition: $scope.currentKitchen.kitchen_condition,\n seating_capacity: $scope.kitchenEditCap\n };\n\n if (kitchen.seating_capacity == null) {\n showReEnter();\n } else {\n $http.put('webapi/kitchen/update', kitchen)\n .then(function (response) {\n //show success message or failure\n if (response.status === 200) {\n hideAllOptions();\n $scope.successMessage = true;\n $scope.currentKitchen.seating_capacity = $scope.kitchenEditCap;\n } else {\n hideAllOptions();\n $scope.nonSuccessMessage = true;\n }\n });\n }\n }",
"function handleUpdatePlace() {\n\t$('main').on('submit','.edit-place-form', function(event) {\n\t\tevent.preventDefault();\n\t\tconst placeId = $(this).data('id');\n\t\tconst tripId = $(this).data('trip');\n\t\tconst toUpdateData = {\n\t\t\tid: placeId,\n\t\t\tname: $('.place-name-entry').val(),\n\t\t\tdate: $('.form-place-date').val(),\n\t\t\tdescription: $('#place-desc').val()\n\t\t}\n\t\tupdatePlace(tripId, toUpdateData);\n\t})\n}",
"function makeReservation(rCell){\n \n rCell.setAttribute(\"class\", \"reserved-self\");\n rCell.onmousedown = mouseDownSelfReserved;\n rCell.onmouseover = mouseOverSelfReserved;\n if(rCell.hasToolTip){\n removeToolTip(rCell);\n rCell.hasToolTip = false;\n }\n \n var sCell = progressData[rCell.part].segments[rCell.segm];\n \n var jCell = reservationsJSONarr[rCell.part].segments[rCell.segm];\n var compCell = reservCompare[rCell.part].segments[rCell.segm];\n \n //set reservation data\n if(!jCell.isReserved){\n jCell.user = user;\n jCell.isReserved = true;\n if(!(rCell.part in updateData)){\n updateData[rCell.part] = { segments: {} };\n }\n updateData[rCell.part].segments[rCell.segm] = jCell;\n }else{ //better update data on screen\n\n getProgressData();\n }\n}",
"function handleUpdateIdea() {\n $('body').on(\"submit\", \"#form-update-idea\", (event) => {\n event.preventDefault();\n const ideaID = $(event.currentTarget).data('id');\n const statusElement = document.getElementById('status-selector');\n const statusVal = statusElement.options[statusElement.selectedIndex].value;\n const likabilityElement = document.getElementById('likability-selector');\n const likabilityVal = likabilityElement.options[likabilityElement.selectedIndex].value;\n\n const updatedIdea = {\n title: $('#title-txt').val(),\n description: document.getElementById(\"description-txt\").value,\n status: statusVal,\n likability: likabilityVal\n }\n\n updateIdea({\n jwToken: user,\n ideaID,\n updatedIdea,\n onSuccess: getAndDisplayIdeas,\n onError: \"\"\n });\n });\n}",
"function quoteReservation(formObject) {\n var name = formObject.name.trim()\n var email = formObject.email.trim()\n var phone = formObject.phone.trim()\n var adults = formObject.adults.trim()\n var kids = formObject.kids.trim()\n var checkin = formObject.checkin.trim()\n var checkout = formObject.checkout.trim()\n // Basic Validation\n if (!name || name.length < 3) {\n return {status: \"error\", reason: \"Name too short\"}\n }\n if (!phone || phone.length < 10) {\n return {status: \"error\", reason: \"Invalid phone\"}\n }\n phone = \"+1\" + phone.replace(/\\D/g, '').slice(-10)\n \n var settings = getSheetSettings()\n var start_date = new Date(checkin + \"T00:00:00\")\n var stop_date = new Date(checkout + \"T00:00:00\")\n var now = new Date()\n if (now > start_date || now > stop_date || start_date >= stop_date) {\n return {status: \"error\", reason: \"Invalid dates\"}\n }\n checkin_time = settings.CHECKIN_TIME\n if (checkin_time) {\n var checkin_parts = checkin_time.split(':')\n start_date.setHours(parseInt(checkin_parts[0]))\n start_date.setMinutes(parseInt(checkin_parts[1]))\n } else {\n start_date.setHours(16) // Default: 4pm\n }\n checkout_time = settings.CHECKOUT_TIME\n if (checkout_time) {\n var checkout_parts = checkout_time.split(':')\n stop_date.setHours(parseInt(checkout_parts[0]))\n stop_date.setMinutes(parseInt(checkout_parts[1]))\n } else {\n stop_date.setHours(11) // Default: 11am\n }\n \n // Check for conflicting reservations\n var events = CalendarApp.getDefaultCalendar().getEvents(start_date, stop_date)\n if (events && events.length > 0) {\n return {status: \"error\", reason: \"Conflict with other reservation\"}\n }\n \n // Create quote\n var input = {}\n input.name = name\n input.email = email\n input.phone = phone\n input.adults = adults\n input.kids = kids\n input.checkin = checkin\n input.checkout = checkout\n var quote = {}\n quote.nights = ((stop_date - start_date)/86400000).toFixed(0)\n quote.customer = getWaveCustomer(email)\n if (Object.keys(quote.customer).length !== 0) {\n quote.customer_discount = settings.CUSTOMER_DISCOUNT\n } else {\n quote.customer_discount = 0\n }\n quote.cleaning_fee = settings.CLEANING_FEE\n quote.rent = quote.nights * settings.NIGHTLY_RATE\n quote.tax = (quote.rent - quote.customer_discount) * 0.06\n quote.total = (quote.rent - quote.customer_discount) + quote.tax + quote.cleaning_fee\n \n var ret = {status: \"quoted\", quote: quote, input: input}\n \n // Save all quotes to a sheet\n addSheetQuote(ret)\n return ret\n}",
"function editAsset() {\n alert(\"hi\");\n var currentAsset = $(this).data(\"asset\");\n \n $(\"#updateCategory\").val(currentAsset.category);\n $(\"#updateItemName\").val(currentAsset.itemName);\n $(\"#updateMake\").val(currentAsset.make);\n $(\"#updateModel\").val(currentAsset.model);\n $(\"#updateSerialNumber\").val(currentAsset.serial_num);\n $(\"#updateDate\").val(currentAsset.bought);\n $(\"#updatePrice\").val(currentAsset.price);\n $(\"#updateItemInfo\").val(currentAsset.info);\n\n $(document).on(\"submit\", \"#update-asset-form\", updateAsset(currentAsset));\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: isRightMouseButton Returns true if the right mouse button was pressed. Note that this button might not be available on some systems. For handling a popup trigger should be used. | function isRightMouseButton(evt){
if ('which' in evt)
{
return evt.which === 3;
}
else
{
return evt.button === 2;
}
} | [
"isRightClicking() {\r\n return this.activeClick === RIGHT_CLICK_ID;\r\n }",
"function detectLeftButton(evt) {\n evt = evt || window.event;\n if (\"buttons\" in evt) {\n return evt.buttons == 1;\n }\n var button = evt.which || evt.button;\n return button == 1;\n}",
"_handleRowRightClick(event)\r\n {\r\n if (this.view.contextMenu)\r\n {\r\n Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__CONTEXTMENU_SHOW, {top: event.pageY,\r\n left: event.pageX,\r\n items: this.view.contextMenu});\r\n }\r\n return false;\r\n }",
"function IsMouseReleased(button) {\r\n return bind.IsMouseReleased(button);\r\n }",
"isLeftClicking() {\r\n return this.activeClick === LEFT_CLICK_ID;\r\n }",
"function isNearLeftEdge(element, event) {\n\tlet ret = false;\n\tlet offset = getElementOffset(element);\n\tlet rightEdge = element.getBoundingClientRect().right - offset.left;\n\tlet mouseClickPosition = event.pageX - offset.left;\n\n\tlet buttonWidth = element.getBoundingClientRect().width * .30;\n\n\tif (buttonWidth > 50){\n\t\tbuttonWidth = 50;\n\t}\n\n\tif (rightEdge - mouseClickPosition < buttonWidth) {\n\t\tret = true;\n\t}\n\n\treturn ret;\n}",
"function checkHitLeftRight(ball) {\n\t\tif (ball.offsetLeft <= 0 || ball.offsetLeft >= 975) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"function handleRightClick(event) {\n var target = event.target || event.toElement;\n\n if (!target) {\n return;\n }\n\n var figure = findFigure(scribe, target);\n\n if (figure) {\n event.preventDefault();\n event.stopPropagation();\n contextMenu.show(figure);\n }\n }",
"function handleRightClick() {\n event.preventDefault();\n if (game.state === 'In Play') {\n var position = getPosition(event),\n x = position[0],\n y = position[1],\n coordinate = gameBoard.board[x][y],\n displayCoordinate = '.row_' + x + '.col_' + y;\n // Flag if Not Flagged || Un-Flag if Flagged, Adjust Bomb count\n if (coordinate != null && !coordinate.includes('revealed')) {\n if (coordinate.includes('flag-')) {\n gameBoard.board[x][y] = coordinate.replace(\"flag-\",'');\n $(displayCoordinate)[0].classList.remove('flag')\n gameBoard.flags.splice(gameBoard.flags.indexOf([x,y]),1)\n $('#bombs').html(gameBoard.bombs.length - gameBoard.flags.length);\n } else {\n gameBoard.flags.push([x,y]);\n gameBoard.board[x][y] = 'flag-'+ gameBoard.board[x][y];\n $(displayCoordinate)[0].classList.add('flag')\n $('#bombs').html(gameBoard.bombs.length - gameBoard.flags.length);\n }\n }\n }\n gameBoard.checkWin();\n }",
"function rightCursor() {\n let beforeScroll = menu.scrollLeft;\n menu.scrollLeft += 1;\n if (beforeScroll == menu.scrollLeft) {\n rightArrow.style.display = \"none\";\n } else {\n rightArrow.style.display = \"inline\";\n }\n menu.scrollLeft = beforeScroll;\n}",
"function IsItemClicked(mouse_button = 0) {\r\n return bind.IsItemClicked(mouse_button);\r\n }",
"function wasCmdFromTagMenu()\n {\n var elt;\n\n // Commands can only be fired from the tag menu via the context menu\n // => document.popupNode exists. onpopupshowing for the corresponding\n // popups here in the sidebar, we manually set popupNode to null.\n elt= document.popupNode;\n if (!elt) return false;\n return ((elt.hasAttribute(\"bmt-bmid\") &&\n elt.localName === \"menuitem\") ||\n (elt.hasAttribute(\"bmt-tagid\") &&\n elt.localName === \"menu\"));\n }",
"function isRightTriangle(side, base, hypotenuse) {\n if (side ** 2 + base ** 2 === hypotenuse ** 2) {\n return true\n } else {\n return false\n }\n }",
"function getMouseButton(evt) {\n\tif (evt.which == null) { // internet explorer\n\t\treturn ((evt.button < 2)?MOUSE_BUTTON.LEFT:((evt.button == 4)?MOUSE_BUTTON.MIDDLE:MOUSE_BUTTON.RIGHT));\n\t}\n\t// other browsers\n\treturn ((evt.which < 2)?MOUSE_BUTTON.LEFT:((evt.which == 2)?MOUSE_BUTTON.MIDDLE:MOUSE_BUTTON.RIGHT));\n}",
"isTriggered() {\n return this.buttonClicked;\n }",
"isMouseOver() {\n return this.button.isMouseOver()\n }",
"_isRtl() {\n return this._dir && this._dir.value === 'rtl';\n }",
"_isInteractionDisabled() {\n return this.listbox.disabled || this._disabled;\n }",
"static rightClickElement(element) {\n this.waitElement(element, timeToWait);\n //this.moveToComponent(element);\n element.rightClick();\n }",
"function rightArrowKey(e) {\n if (e.keyCode === RIGHTARROW_KEY) {\n if (zoomedIn === true) {\n document.body.removeChild(document.getElementById('popup'));\n fillZoom(nextImage);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Translates the given message given the `TranslationBundle` This is used for translating elements / blocks see `_translateAttributes` for attributes noop when called in extraction mode (returns []) | _translateMessage(el, message) {
if (message && this._mode === _VisitorMode.Merge) {
const nodes = this._translations.get(message);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${this._translations.digest(message)}"`);
}
return [];
} | [
"function translate(messageParts, substitutions) {\n const message = parseMessage(messageParts, substitutions);\n const translation = $localize.TRANSLATIONS[message.translationKey];\n const result = (translation === undefined ? [messageParts, substitutions] : [\n translation.messageParts,\n translation.placeholderNames.map(placeholder => message.substitutions[placeholder])\n ]);\n return result;\n}",
"addTranslatedMessagesToDom_() {\n const elements = document.querySelectorAll('.i18n');\n for (const element of elements) {\n const messageId = element.getAttribute('msgid');\n if (!messageId)\n throw new Error('Element has no msgid attribute: ' + element);\n const translatedMessage =\n chrome.i18n.getMessage('switch_access_' + messageId);\n if (element.tagName == 'INPUT')\n element.setAttribute('placeholder', translatedMessage);\n else\n element.textContent = translatedMessage;\n element.classList.add('i18n-processed');\n }\n }",
"getMessagesList() {\n return Object.keys(i18nMessages).map( (language) => {\n return bcp47normalize(language);\n });\n }",
"function getTranslationDeclStmts(variable, closureVar, message, meta, params, transformFn) {\r\n if (params === void 0) { params = {}; }\r\n var statements = [];\r\n statements.push.apply(statements, __spread(i18nTranslationToDeclStmt(variable, closureVar, message, meta, params)));\r\n if (transformFn) {\r\n statements.push(new ExpressionStatement(variable.set(transformFn(variable))));\r\n }\r\n return statements;\r\n }",
"function parseMessage(messageParts, expressions) {\n const replacements = {};\n let translationKey = messageParts[0];\n for (let i = 1; i < messageParts.length; i++) {\n const messagePart = messageParts[i];\n const expression = expressions[i - 1];\n // There is a problem with synthesizing template literals in TS.\n // It is not possible to provide raw values for the `messageParts` and TS is not able to compute\n // them since this requires access to the string in its original (non-existent) source code.\n // Therefore we fall back on the non-raw version if the raw string is empty.\n // This should be OK because synthesized nodes only come from the template compiler and they\n // will always contain placeholder name information.\n // So there will be no escaped placeholder marker character (`:`) directly after a substitution.\n if ((messageParts.raw[i] || messagePart).charAt(0) === PLACEHOLDER_NAME_MARKER) {\n const endOfPlaceholderName = messagePart.indexOf(PLACEHOLDER_NAME_MARKER, 1);\n const placeholderName = messagePart.substring(1, endOfPlaceholderName);\n translationKey += `{$${placeholderName}}${messagePart.substring(endOfPlaceholderName + 1)}`;\n replacements[placeholderName] = expression;\n }\n else {\n const placeholderName = `ph_${i}`;\n translationKey += `{$${placeholderName}}${messagePart}`;\n replacements[placeholderName] = expression;\n }\n }\n return { translationKey, substitutions: replacements };\n}",
"function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n}",
"function loadTranslations(translations) {\n // Ensure the translate function exists\n if (!$localize.translate) {\n $localize.translate = translate;\n }\n if (!$localize.TRANSLATIONS) {\n $localize.TRANSLATIONS = {};\n }\n Object.keys(translations).forEach(key => {\n $localize.TRANSLATIONS[key] = parseTranslation(translations[key]);\n });\n}",
"function getMessageBody() {\n // If selected message is a system message then returns the corresponding language json file entry\n if (props.message.examBodyMessageTypeId != null && props.message.examBodyMessageTypeId !== enums.SystemMessage.None) {\n return translatedMessageContents.content;\n }\n else {\n return props.messageDetails.body;\n }\n }",
"translateMesh (translationVector) {\n this.vertices.forEach(arr => arr = Mesh.translateVertices(arr, translationVector))\n }",
"function translate(key) {\n var lang = getLang(),\n text = translations[key];\n\n if (typeof text === 'undefined') {\n if (SC_DEV) { console.log('Unable to get translation for text code: \"'+ key + '\" and language: \"' + lang + '\".'); }\n return '-';\n }\n\n return text;\n }",
"translate(text, target, callback){\n\t\t\t\t// Assume that our default language on every JS or HTML template is en_US\n\t\t\t\ttranslates('en_US', target, text, callback);\n\t\t\t}",
"function translation() {\n return gulp\n .src(theme.php.src)\n .pipe(wpPot({\n domain: 'wpg_theme',\n package: 'Powiat Bartoszycki',\n bugReport: 'http:/powiatbartoszyce.pl'\n }))\n .pipe(gulp.dest(theme.lang.dist + 'powiat-bartoszycki.pot'))\n}",
"function gettext(msgid) {\n if (bundle) {\n if (typeof bundle[msgid] === \"string\") {\n return bundle[msgid];\n }\n console.warn(\"[i18n]\", bundle_path, msgid, undefined);\n }\n return msgid;\n}",
"async function getTranslatedString(string, targetLang){\n AWS.config.region = \"us-east-1\";\n var ep = new AWS.Endpoint(\"https://translate.us-east-1.amazonaws.com\");\n AWS.config.credentials = new AWS.Credentials(\"AKIAJQLVBELRL5AAMZOA\", \"Kl0ArGHFySw+iBEdGXZDrTch2V5VAaDbSs+EKKEZ\");\n var translate = new AWS.Translate();\n translate.endpoint = ep;\n var params = {\n Text: string,\n SourceLanguageCode: \"en\",\n TargetLanguageCode: targetLang\n };\n var promise = new Promise((resolve, reject)=>{\n translate.translateText(params, (err, data)=>{\n if (err) return reject(err);\n else {\n return resolve(data);\n }\n });\n });\n var result = await promise;\n return result.TranslatedText;\n}",
"function parseTranslationsSection(section) {\n let tables = section.body.match(/^{{(?:check)?trans-top(?:-also)?(?:\\|.*?)?}}[\\s\\S]*?^{{trans-bottom}}/mg);\n\n if (!tables) {\n tables = section.body.match(/^{{trans-see\\|.*?}}/mg);\n\n if (!tables) {\n console.log(\"UNEXPECTED 1026\", section.body);\n }\n }\n\n const tablemap = tables.map(table => parseTranslationTable(table));\n\n return tablemap;\n}",
"function flattenBeamMessage(message) {\n\tvar result = '';\n\tif (message.length !== undefined) {\n\t\tif(message.length > 1 ) {\n\t\t\tresult = message.reduce(function (previous, current) {\n\t\t\t\tif (!previous) {\n\t\t\t\t\tprevious = '';\n\t\t\t\t}\n\t\t\t\tif (typeof previous === 'object') {\n\t\t\t\t\tprevious = extractTextFromMessagePart(previous);\n\t\t\t\t}\n\t\t\t\treturn previous + extractTextFromMessagePart(current);\n\t\t\t});\n\t\t} else if(message.length === 1) {\n\t\t\tresult = extractTextFromMessagePart(message[0]);\n\t\t} else {\n\t\t\treturn '';\n\t\t}\n\t} else {\n\t\tresult = message;\n\t}\n\treturn ent.decode(result);\n}",
"function substituteForTranslationFailures(translationResult) {\n var foundSubstitute = false;\n var substituteText;\n translationResult.targets.forEach(function(target) {\n if (target.success && target.language === 'en') {\n substituteText = target.text;\n foundSubstitute = true;\n }\n });\n if (!foundSubstitute) {\n substituteText = translationResult.source.text;\n }\n translationResult.targets.forEach(function(target) {\n if (!target.success) {\n target.text = substituteText;\n }\n });\n}",
"function getMessageDecoding( msg )\n{\n\tlet dec = new TextDecoder();\n\treturn dec.decode( msg );\n}",
"function mergeGettextArrays(po, pot) {\n\t// Holder array for valid strings\n\tvar filteredPo = {};\n\n\t// Iterate POT translations (only valid ones)\n\tObject.keys(pot.translations[\"\"]).forEach(function (key) {\n\t\t// If translation is found..\n\t\tif (po.translations[\"\"].hasOwnProperty(key)) {\n\t\t\t// Copy it back\n\t\t\tfilteredPo[key] = po.translations[\"\"][key];\n\t\t} else {\n\t\t\t// ..else, copy the pot (untranslated) version\n\t\t\tfilteredPo[key] = pot.translations[\"\"][key];\n\t\t}\n\t});\n\t// Replace the translations with the filtered ones and return\n\tpo.translations[\"\"] = filteredPo;\n\treturn po;\n}",
"getMessages(language) {\n let languageKey = Object.keys(i18nMessages).find( (currentLanauge) => {\n return language === bcp47normalize(currentLanauge);\n });\n \n return i18nMessages[languageKey];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copyright 2020 Inrupt Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Verify whether a given value has the required DatasetCore properties. | function internal_isDatasetCore(input) {
return (typeof input === "object" &&
input !== null &&
typeof input.size === "number" &&
typeof input.add === "function" &&
typeof input.delete === "function" &&
typeof input.has === "function" &&
typeof input.match === "function" &&
Array.from(input).length === input.size);
} | [
"function validateDataElementReference() {\n\tvar ids = {};\n\n\n\t//Data elements/data sets from indicator formulas\n\tvar result;\n\tif (metaData.indicators) {\n\t\t\n\t\tfor (var i = 0; metaData.indicators && i < metaData.indicators.length; i++) {\n\t\t\tresult = utils.idsFromIndicatorFormula(metaData.indicators[i].numerator, \n\t\t\t\tmetaData.indicators[i].denominator, true);\n\t\t\t\n\t\t\tfor (var j = 0; j < result.length; j++) {\n\t\t\t\tids[result[j]] = \"indicator \" + metaData.indicators[i].id;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//Data elements/data sets from predictor formulas\n\tfor (var i = 0; metaData.predictors && i < metaData.predictors.length; i++) {\n\t\tresult = utils.idsFromFormula(\n\t\t\tmetaData.predictors[i].generator.expression, \n\t\t\ttrue\n\t\t);\n\t\t\t\n\t\tfor (var j = 0; j < result.length; j++) {\n\t\t\tids[result[j]] = \"predictor \" + metaData.predictors[i].id;\n\t\t}\n\t}\n\t\n\t//Data elements/data sets from validation rule formulas\n\tfor (var i = 0; metaData.validationRules && i < metaData.validationRules.length; i++) {\n\t\tresult = utils.idsFromFormula(\n\t\t\tmetaData.validationRules[i].leftSide.expression, \n\t\t\ttrue\n\t\t);\n\t\t\t\n\t\tfor (var j = 0; j < result.length; j++) {\n\t\t\tids[result[j]] = \"validationRule \" + metaData.validationRules[i].id;\n\t\t}\n\t\t\n\t\tresult = utils.idsFromFormula(\n\t\t\tmetaData.validationRules[i].rightSide.expression, \n\t\t\ttrue\n\t\t);\n\t\t\t\n\t\tfor (var j = 0; j < result.length; j++) {\n\t\t\tids[result[j]] = \"validationRule \" + metaData.validationRules[i].id;\n\t\t}\n\t}\n\t\n\tvar missing = [];\n\tfor (var id in ids) {\n\t\tif (!objectExists(\"dataElements\", id) && !objectExists(\"dataSets\", id)) {\n\t\t\tmissing.push({\"id\": id, \"type\": ids[id]});\n\t\t}\n\t}\n\t\n\tif (missing.length > 0) {\n\t\tconsole.log(\"\\nERROR | Data elements/data sets referenced, but not included in export:\");\n\t\tfor (var issue of missing) {\n\t\t\tconsole.log(issue.id + \" referenced in \" + issue.type);\n\t\t}\n\t\treturn false;\n\t}\n\telse return true;\n}",
"function isDataSet( stream, typeSource ){\n\n let readStream = new RW.ReadStream( stream );\n\n //readStream.increment( 23 );//для тестирования\n\n let checkDataElement = true;\n\n if (typeSource === 'File'){\n\n console.log('File');\n\n //1 признак\n //let sum = 0; for(i = 0; i < 32; i++) sum+=readStream.read(C.TYPE_UINT32);\n let checkPrefix = true; for(i = 0; i < 32; i++) checkPrefix = checkPrefix&&( readStream.read(C.TYPE_UINT32) === 0 );\n\n //2 признак\n let checkSign = (readStream.readString(4,C.TYPE_ASCII) === 'DICM');\n\n\n checkDataElement = checkPrefix&&checkSign;\n\n\n console.log( checkPrefix + ' ; ' + checkSign );\n\n\n }\n else{\n console.log('Other');\n }\n\n\n if(checkDataElement){//делаем анализ, если checkDataElement = true и не был изменен на false в блоке if(typeSource === 'File') {}\n\n\n }\n else{\n console.log(' it is not DataSet !!! ');\n return false;\n }\n\n}",
"function validateFavoriteDataDimension() {\n\t\n\tvar issues = [];\n\tfor (var type of [\"charts\", \"mapViews\", \"reportTables\", \"eventReports\", \"eventCharts\"]) {\n\t\tfor (var i = 0; metaData.hasOwnProperty(type) && i < metaData[type].length; i++) {\n\t\t\tvar item = metaData[type][i];\n\t\t\tvar nameableItem;\n\t\t\tif (item.hasOwnProperty(\"dataElementGroupSetDimensions\") \n\t\t\t\t\t&& item.dataElementGroupSetDimensions.length > 0) {\n\t\t\t\tnameableItem = (type == \"mapViews\") ? \n\t\t\t\t\tmapFromMapView(item.id) : item;\n\t\t\t\t\n\t\t\t\tissues.push({\n\t\t\t\t\t\"id\": nameableItem.id,\n\t\t\t\t\t\"name\": nameableItem.name,\n\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\"error\": \"dataElementGroupSet\"\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (item.hasOwnProperty(\"organisationUnitGroupSetDimensions\") \n\t\t\t\t\t&& item.organisationUnitGroupSetDimensions.length > 0) {\n\t\t\t\tnameableItem = (type == \"mapViews\") ? \n\t\t\t\t\tmapFromMapView(item.id) : item;\n\t\t\t\t\n\t\t\t\tissues.push({\n\t\t\t\t\t\"id\": nameableItem.id,\n\t\t\t\t\t\"name\": nameableItem.name,\n\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\"error\": \"organisationUnitGroupSet\"\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (item.hasOwnProperty(\"categoryDimensions\") \n\t\t\t\t\t&& item.categoryDimensions.length > 0) {\n\t\t\t\tnameableItem = (type == \"mapViews\") ? \n\t\t\t\t\tmapFromMapView(item.id) : item;\n\t\t\t\t\n\t\t\t\tissues.push({\n\t\t\t\t\t\"id\": nameableItem.id,\n\t\t\t\t\t\"name\": nameableItem.name,\n\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\"error\": \"category\"\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tif (issues.length > 0) {\t\n\t\tconsole.log(\"\\nERROR | Favourites using unsupported data dimension:\");\n\t\t\n\t\tvar printed = {};\n\t\tfor (var issue of issues) {\n\t\t\tif (!printed[issue.id + issue.error]) {\n\t\t\t\tconsole.log(issue.type + \": \" + issue.id + \" - '\" + issue.name + \n\t\t\t\t\t\"': \" + issue.error);\n\t\t\t\tprinted[issue.id + issue.error] = true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\telse return true;\n}",
"function validateArt (input) {\n // creating the dimension schema\n \n // creating the pixel schema\n const pixelSchema = Joi.array().items(Joi.string());\n\n// the real schema for this function\n const schema = Joi.object({\n name: Joi.string()\n .required()\n .min(1),\n\n pixel: pixelSchema\n });\n\n const result = schema.validate(input);\n return result;\n}",
"function checkData(xmlobject)\n{\n var output = \"\";\n\n // TODO - make sure each field has a name, type, op, label (warning), and perspective\n\n // TODO - make sure, depending upon the op, that the other fields are there\n // (the array below is the current requirements)\n\n var reqFields = { count: [\"target\"],\n\t\t average: [\"target\"],\n\t\t combine: [\"target\"],\n\t\t delta: [\"start\",\"end\"],\n\t\t sum: [\"target\"],\n\t\t percent: [\"target\",\"targetVal\"],\n\t\t weight: [\"target\",\"multiplier\"],\n\t\t contains:[\"target\",\"targetVal\"],\n\t\t containsAny:[\"target\",\"targetVal\"],\n\t\t max: [\"target\"],\n\t\t min: [\"target\"],\n\t\t defEffect: [\"target\"],\n\t\t compare: [\"target\"],\n\t\t divide: [\"target\"],\n\t\t multiply:[\"target\"],\n\t\t subtract:[\"target\"],\n\t\t constant:[\"target\"]\n\t\t };\n\n var optFields = { weight: [\"high\",\"low\"],\n\t\t compare: ['ltVal','gtVal','eqVal']\n\t\t };\n\t\n\t\n // TODO - should check that all of the right things are there for the ops\n // (like start and end for delta, etc.)\n\n // TODO - make sure all sections are there\n\n // TODO - make sure the layout looks good relative to elements\n\n var rawData = xmlobject.rawData;\n\n var rawDataFields = [];\n for(var i=0; i < rawData.length; i++) {\n\trawDataFields.push(rawData[i].name);\n }\n\n var metaData = xmlobject.metaData;\n\n if(metaData === null) {\n\toutput += \"METADATA ERROR: I can't find any metaData specs.<br>\\n\";\n\toutput += \"Did you forget to capitalize the D in \\\"metaData\\\" in the XML?\";\n\treturn(output);\n }\n\n // need to check the perspectives in order, from lowest to highest\n \n var perspectives = [ \"match\", \"competition\", \"robot\", \"year\", \"top\" ];\n var previousLevelFields = null; // allows upper levels to check lower levels\n\n var allMetaDataFields = [];\n \n for(var perspective in perspectives) {\n\tvar thisMetaData = metaData[perspectives[perspective]];\n\n\t// first, gather the names of all of the metaData fields at this perspective\n\tvar thisMetaDataFields = [];\n\tfor(var i=0; i < thisMetaData.length; i++) {\n\t thisMetaDataFields.push(thisMetaData[i].name);\n\t allMetaDataFields.push(thisMetaData[i].name);\n\t}\n\n\t// now check to see that they refer to rawData, the current metaData, or lower MetaData\n\n\tfor(var i=0; i < thisMetaData.length; i++) {\n\n\t // need to check the targets, start list, and end list\n\n\t var checks = [\"target\",\"start\",\"end\"];\n\n\t for(var check in checks) {\n\t\tvar thisCheck = checks[check];\n\t\t\n\t\tif(thisMetaData[i].hasOwnProperty(thisCheck)) {\n\t\t for(var j=0; j < thisMetaData[i][thisCheck].length; j++) {\n\t\t\tif(!thisMetaDataFields.includes(thisMetaData[i][thisCheck][j])) {\n\t\t\t if(!rawDataFields.includes(thisMetaData[i][thisCheck][j])) {\n\t\t\t\tif(!previousLevelFields || !previousLevelFields.includes(thisMetaData[i][thisCheck][j])) {\n\n\t\t\t\t // special case for constants - just catch it here\n\t\t\t\t if(thisCheck == 'target' && thisMetaData[i]['op'] == 'constant') {\n\t\t\t\t\t// this is OK, if there is just one target if more, warn\n\t\t\t\t\tif(j > 0) {\n\t\t\t\t\t output += \"METADATA WARNING: \" +\n\t\t\t\t\t\tperspectives[perspective] + \":\" + thisMetaData[i].name + \" - \" +\n\t\t\t\t\t\t'multiple targets for constant! ignoring: ' +\n\t\t\t\t\t\tthisMetaData[i][thisCheck][j] + '<br>' + '\\n';\n\t\t\t\t\t}\n\t\t\t\t } else {\n\t\t\t\t\t// otherwise not\n\t\t\t\t\toutput += \"METADATA ERROR: \" +\n\t\t\t\t\t perspectives[perspective] + \":\" + thisMetaData[i].name + \" - \" +\n\t\t\t\t\t 'bad reference in ' + thisCheck + ' - ' +\n\t\t\t\t\t thisMetaData[i][thisCheck][j] + '<br>' + '\\n';\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t}\n\tpreviousLevelFields = thisMetaDataFields;\n }\n\n output += checkViews(xmlobject.views,rawDataFields,allMetaDataFields);\n \n if(output == \"\"){\n\toutput += \"NO ERRORS FOUND\";\n }\n \n return(output);\n}",
"function main(\n datasetId = 'my_dataset' // Existing dataset\n) {\n // [START bigquery_delete_label_dataset]\n // Import the Google Cloud client library\n const {BigQuery} = require('@google-cloud/bigquery');\n const bigquery = new BigQuery();\n\n async function deleteLabelDataset() {\n // Deletes a label on a dataset.\n // This example dataset starts with existing label { color: 'green' }\n\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // const datasetId = 'my_dataset';\n\n // Retrieve current dataset metadata.\n const dataset = bigquery.dataset(datasetId);\n const [metadata] = await dataset.getMetadata();\n\n // Add label to dataset metadata\n metadata.labels = {color: null};\n const [apiResponse] = await dataset.setMetadata(metadata);\n\n console.log(`${datasetId} labels:`);\n console.log(apiResponse.labels);\n }\n // [END bigquery_delete_label_dataset]\n deleteLabelDataset();\n}",
"function hasAccessibleAcl(dataset) {\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\n}",
"function isMetaDataValid(){\r\n\torgUnit_id_metadata = metaDataArray[0].OrgUnitId;\r\n\tconsole.log(\"org unit id excel: \" + orgUnit_id_metadata);\r\n\tconsole.log(\"org unit id form: \" + org_unit_id);\r\n\t\r\n\tprogram_id_metadata = metaDataArray[0].ProgramId;\r\n\tconsole.log(\"program id excel: \" + program_id_metadata);\r\n\t\t\t\t\r\n\t//get the id of the selected program\r\n\tvar program_id_form=$(\"#programList\").val();\r\n\tconsole.log(\"program id form: \" + program_id_form);\r\n\t//get the id of the selected org unit: org_unit_id\r\n\t\r\n\t//test if the ids of program and org unit match with metadata in third sheet\r\n\tif(!(program_id_metadata === program_id_form)){\r\n\t\tadd(\"Error! The selected program id: \"+program_id_form+\" does not match the id in the spreadsheet: \" +program_id_metadata+\" !\", 4);\r\n\t\tconsole.log(\"Error! The selected program id: \"+program_id_form+\" does not match the id in the spreadsheet: \" +program_id_metadata+\" !\");\r\n\t\treturn false;\r\n\t}\r\n\tif(!(orgUnit_id_metadata === org_unit_id)){\r\n\t\tadd(\"Error! The selected org unit id: \"+org_unit_id+\" does not match the id in the spreadsheet: \" +orgUnit_id_metadata+\" !\", 4);\r\n\t\tconsole.log(\"Error! The selected org unit id: \"+org_unit_id+\" does not match the id in the spreadsheet: \" +orgUnit_id_metadata+\" !\");\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}",
"isSubset(dataObjectContainer,dataObject){\n if ( dataObject.children && dataObject.children.length > 0 ){\n if ( dataObjectContainer !== dataObject.children ){\n return Object.keys(dataObject.children).some( key=>{\n this.isSubset (dataObjectContainer,dataObject.children[key])\n })\n }\n }\n return dataObjectContainer === dataObject.children\n }",
"function dbHasData(){\n const selectStatement = 'SELECT * FROM characters';\n return client.query(selectStatement)\n .then( result => {\n if(result.rowCount > 0){\n return true;\n }else {\n return false;\n }\n });\n}",
"function ensureAllDatasetsMapToCancer(){\n\t\t\tdatasets.forEach(function(db){\n\t\t\t\tif (!datasetToCancer[db]){\n\t\t\t\t\tconsole.log(\"Unknown cancer type: \" + db);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function exampleData() {\n\t\t\treturn [{\n\t\t\t\t\"label\" : \"One\",\n\t\t\t\t\"value\" : 29.765957771107\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Two\",\n\t\t\t\t\"value\" : 0\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Three\",\n\t\t\t\t\"value\" : 32.807804682612\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Four\",\n\t\t\t\t\"value\" : 196.45946739256\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Five\",\n\t\t\t\t\"value\" : 0.19434030906893\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Six\",\n\t\t\t\t\"value\" : 98.079782601442\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Seven\",\n\t\t\t\t\"value\" : 13.925743130903\n\t\t\t}, {\n\t\t\t\t\"label\" : \"Eight\",\n\t\t\t\t\"value\" : 5.1387322875705\n\t\t\t}];\n\t\t}",
"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 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}",
"calculateHasConfidence(){\n return this.props.techniques.find(r => r.confidence !== undefined) !== undefined;\n }",
"function testEval_In_WithoutNull() {\n var sampleRows = getSampleRows(6);\n var inValues = ['sampleName0', 'sampleName2', 'sampleName4'];\n checkEval_In(sampleRows, inValues, inValues, false);\n}",
"getDataSubset(allowed) {\n \n const subsetData = Object.keys(this.data)\n .filter(name => allowed.includes(name))\n .reduce((obj, key) => {\n obj[key] = this.data[key];\n return obj;\n }, {});\n\n return subsetData\n }",
"function verifyIfExists(data, array) {\n //If the given data is an array\n if (data.constructor === Array) {\n // console.log(data);\n // console.log(array);\n\n let count = 0;\n\n //Verifies if any of the data content is equal to the data in the given array\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j < array.length; j++) {\n if (typeof(data[i]) == \"object\" && typeof(array[j]) == \"object\") {\n if (data[i].name == array[j].name) {\n count++;\n }\n }\n else if (typeof(data[i]) == \"string\" && typeof(array[j]) == \"object\") {\n if (data[i] == array[j].name) {\n count++;\n }\n }\n else if (typeof(data[i]) == \"string\" && typeof(array[j]) == \"string\") {\n if (data[i] == array[j]) {\n count++;\n }\n }\n else if (data[i].name == array[j]) {\n count++;\n }\n }\n }\n if (count == data.length) {\n return true;\n }\n else {\n return false;\n }\n }\n //If the given data is not an array\n else {\n \n for (let i = 0; i < array.length; i++) {\n if (typeof(array[i]) == \"object\" && array[i].name == data) {\n return true;\n }\n else if (array[i] == data) {\n return true;\n }\n \n }\n return false;\n }\n}",
"_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 }",
"function isHeatmapDataEqual(objA, objB) {\n var isEql = !emptyXOR(objA, objB);\n _.forEach(objA, function (xBucket, x) {\n if (objB[x]) {\n if (emptyXOR(xBucket.buckets, objB[x].buckets)) {\n isEql = false;\n return false;\n }\n _.forEach(xBucket.buckets, function (yBucket, y) {\n if (objB[x].buckets && objB[x].buckets[y]) {\n if (objB[x].buckets[y].values) {\n isEql = _.isEqual(_.sortBy(yBucket.values), _.sortBy(objB[x].buckets[y].values));\n if (!isEql) {\n return false;\n }\n else {\n return true;\n }\n }\n else {\n isEql = false;\n return false;\n }\n }\n else {\n isEql = false;\n return false;\n }\n });\n if (!isEql) {\n return false;\n }\n else {\n return true;\n }\n }\n else {\n isEql = false;\n return false;\n }\n });\n return isEql;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expand and normalize finder options | function mapFinderOptions(options, Model) {
if (options.attributes && Array.isArray(options.attributes)) {
options.attributes = Model._injectDependentVirtualAttributes(options.attributes);
options.attributes = options.attributes.filter(v => !Model._virtualAttributes.has(v));
}
mapOptionFieldNames(options, Model);
return options;
} | [
"function toggleOptions() {\n\t\t\tif (optsView.className.indexOf('adi-hidden') !== -1) {\n\t\t\t\tremoveClass(optsView, 'adi-hidden');\n\t\t\t} else {\n\t\t\t\taddClass(optsView, 'adi-hidden');\n\t\t\t\tpathView.textContent = '';\n\t\t\t\tattrView.querySelector('.adi-content').innerHTML = '';\n\t\t\t\trefreshUI();\n\t\t\t\tdrawDOM(document, domView.querySelector('.adi-tree-view'), true);\n\t\t\t\tif (options.saving) {\n\t\t\t\t\tsaveOptions();\n\t\t\t\t} else {\n\t\t\t\t\tresetOptions();\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"function doExpand() {\n _result = expand(_specs);\n}",
"function customSelectsAdjust() {\n $('.sel').each(function () {\n let value = ($(this).find('.sel__opt-val').length > 0) // if .sel__opt-val exists\n ? $(this).find('.sel__opt-val').first().text()\n : $(this).find('.sel__opt').first().text();\n $(this).find('.sel__rslt').text(value);\n \n $(this).width($(this).find('.sel__opts').width());\n })\n }",
"function Pathfinder(options) {\n this.initialize(options);\n}",
"function drawOptions() {\n\t\t\tvar ui = newElement('div', { id: 'adi-opts-view', class: 'adi-hidden' }),\n\t\t\t\thead1 = newElement('span', { class: 'adi-opt-heading' }),\n\t\t\t\thead2 = newElement('span', { class: 'adi-opt-heading' }),\n\t\t\t\tclose = newElement('span', { class: 'adi-opt-close' });\n\n\t\t\thead1.textContent = 'General options';\n\t\t\thead2.textContent = 'Observed nodes';\n\n\t\t\tui.appendChild(head1);\n\t\t\tui.appendChild(drawOptionRow('saving', 'Enable saving of settings'));\n\t\t\tui.appendChild(drawOptionRow('makeVisible', 'Scroll to the active element in DOM View'));\n\t\t\tui.appendChild(drawOptionRow('omitEmptyText', 'Hide empty text nodes'));\n\t\t\tui.appendChild(drawOptionRow('foldText', 'Fold the text nodes'));\n\t\t\tui.appendChild(drawOptionRow('transparent', 'Enable transparent background'));\n\t\t\tui.appendChild(head2);\n\t\t\tui.appendChild(drawOptionRow('nodeTypes-3', 'Text node'));\n\t\t\tui.appendChild(drawOptionRow('nodeTypes-8', 'Comment node'));\n\t\t\t// ui.appendChild(drawOptionRow('nodeTypes-1', 'Element node'));\n\t\t\t// ui.appendChild(drawOptionRow('nodeTypes-9', 'Document node'));\n\t\t\tui.appendChild(close);\n\n\t\t\treturn ui;\n\t\t}",
"function normaliseOpenOptions(options) {\n var _a, _b;\n // Validate `encoding`.\n let encoding = (_a = options === null || options === void 0 ? void 0 : options.encoding) !== null && _a !== void 0 ? _a : 'ISO-8859-1';\n assertValidEncoding(encoding);\n // Validate `readMode`.\n let readMode = (_b = options === null || options === void 0 ? void 0 : options.readMode) !== null && _b !== void 0 ? _b : 'strict';\n if (readMode !== 'strict' && readMode !== 'loose') {\n throw new Error(`Invalid read mode ${readMode}`);\n }\n // Return a new normalised options object.\n return { encoding, readMode };\n}",
"search(config, options) {\n let documents = [];\n const selector = {\n $distinct: { vpath: 1 }\n };\n if (options.pathmatch) {\n if (typeof options.pathmatch === 'string') {\n selector.vpath = new RegExp(options.pathmatch);\n } else if (options.pathmatch instanceof RegExp) {\n selector.vpath = options.pathmatch;\n } else {\n throw new Error(`Incorrect PATH check ${options.pathmatch}`);\n }\n }\n if (options.renderpathmatch) {\n if (typeof options.renderpathmatch === 'string') {\n selector.renderPath = new RegExp(options.renderpathmatch);\n } else if (options.renderpathmatch instanceof RegExp) {\n selector.renderPath = options.renderpathmatch;\n } else {\n throw new Error(`Incorrect PATH check ${options.renderpathmatch}`);\n }\n }\n if (options.mime) {\n if (typeof options.mime === 'string') {\n selector.mime = { $eeq: options.mime };\n } else if (Array.isArray(options.mime)) {\n selector.mime = { $in: options.mime };\n } else {\n throw new Error(`Incorrect MIME check ${options.mime}`);\n }\n }\n if (options.layouts) {\n if (typeof options.layouts === 'string') {\n selector.docMetadata = {\n layout: { $eeq: options.layouts }\n }\n } else if (Array.isArray(options.layouts)) {\n selector.docMetadata = {\n layout: { $in: options.layouts }\n }\n } else {\n throw new Error(`Incorrect LAYOUT check ${options.layouts}`);\n }\n }\n let coll = this.getCollection(this.collection);\n let paths = coll.find(selector, {\n vpath: 1,\n $orderBy: { renderPath: 1 }\n });\n for (let p of paths) {\n let info = this.find(p.vpath);\n documents.push(info);\n }\n\n if (options.tag) {\n documents = documents.filter(doc => {\n if (!doc.metadata) return false;\n return (doc.metadata.tags.includes(options.tag))\n ? true : false;\n });\n }\n\n if (options.rootPath) {\n documents = documents.filter(doc => {\n return (doc.renderPath.startsWith(options.rootPath))\n ? true : false;\n });\n }\n\n if (options.glob) {\n documents = documents.filter(doc => {\n return minimatch(doc.vpath, options.glob);\n });\n }\n\n if (options.renderglob) {\n documents = documents.filter(doc => {\n return minimatch(doc.renderPath, options.renderglob);\n });\n }\n\n if (options.renderers) {\n documents = documents.filter(doc => {\n if (!options.renderers) return true;\n let renderer = config.findRendererPath(doc.vpath);\n for (let renderer of options.renderers) {\n if (renderer instanceof renderer) {\n return true;\n }\n }\n return false;\n });\n }\n\n if (options.filterfunc) {\n documents = documents.filter(doc => {\n return options.filterfunc(config, options, doc);\n });\n }\n\n return documents;\n }",
"visitView_options(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function findOptsFromArgs(args, allowExtra) {\n var startArg;\n var endArg;\n var svcs = [];\n var insts = [];\n var extra = [];\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n var eq = arg.indexOf('=');\n if (eq === -1) {\n if (allowExtra) {\n extra.push(arg);\n continue;\n } else {\n throw new errors.UsageError('invalid argument, no \"=\": ' + arg);\n }\n }\n var field = arg.slice(0, eq);\n var value = arg.slice(eq + 1);\n switch (field) {\n case 'service':\n case 'svc':\n case 's':\n svcs.push(value);\n break;\n case 'instance':\n case 'inst':\n case 'i':\n insts.push(value);\n break;\n case 'start':\n startArg = value;\n break;\n case 'end':\n endArg = value;\n break;\n default:\n if (allowExtra) {\n extra.push(arg);\n } else {\n throw new errors.UsageError('unknown field: ' + field);\n }\n }\n }\n\n var dates = parseStartEnd(startArg, endArg);\n\n return {svcs: svcs, insts: insts, start: dates.start, end: dates.end,\n extra: extra};\n}",
"function mergeDefaultOptions(options) {\n\n //apply simple defaults\n var trueOptions = {\n filter: options.filter || null,\n properties: options.properties || ['dependencies']\n };\n\n //if options.path was supplied, resolve it relative to the parent.\n // if not, just use the parent itself\n var modulePromise;\n var modulePath;\n if (options.path) {\n modulePath = options.relative ? path.dirname(options.relative) : path.dirname(module.parent.filename);\n modulePromise = moduleDirectory(options.path, modulePath);\n } else {\n modulePromise = moduleDirectory(module.parent.filename, '.');\n }\n\n //return a promise that resolves to the true path\n return modulePromise.then(function (modulePath) {\n trueOptions.path = modulePath;\n return trueOptions;\n });\n}",
"function normalizeOptions(options) {\n try {\n options.schemeDefinition = getSchemeDefinition(options);\n }\n catch (e) {\n console.error(e.message);\n throw e; // rethrow to stop process\n }\n}",
"function variablesViewExpandTo(options) {\n let root = options.rootVariable;\n let expandTo = options.expandTo.split(\".\");\n let jsterm = (options.webconsole || {}).jsterm;\n let lastDeferred = promise.defer();\n\n function fetch(prop) {\n if (!prop.onexpand) {\n ok(false, \"property \" + prop.name + \" cannot be expanded: !onexpand\");\n return promise.reject(prop);\n }\n\n let deferred = promise.defer();\n\n if (prop._fetched || !jsterm) {\n executeSoon(function () {\n deferred.resolve(prop);\n });\n } else {\n jsterm.once(\"variablesview-fetched\", function _onFetchProp() {\n executeSoon(() => deferred.resolve(prop));\n });\n }\n\n prop.expand();\n\n return deferred.promise;\n }\n\n function getNext(prop) {\n let name = expandTo.shift();\n let newProp = prop.get(name);\n\n if (expandTo.length > 0) {\n ok(newProp, \"found property \" + name);\n if (newProp) {\n fetch(newProp).then(getNext, fetchError);\n } else {\n lastDeferred.reject(prop);\n }\n } else if (newProp) {\n lastDeferred.resolve(newProp);\n } else {\n lastDeferred.reject(prop);\n }\n }\n\n function fetchError(prop) {\n lastDeferred.reject(prop);\n }\n\n if (!root._fetched) {\n fetch(root).then(getNext, fetchError);\n } else {\n getNext(root);\n }\n\n return lastDeferred.promise;\n}",
"static getMarkedOptions () {\n\n\t\treturn {\n\t\t\tgfm: true,\n\t\t\t//highlight: highlight_syntax_code_syntaxhiglighter,\n\t\t\ttables: true,\n\t\t\tbreaks: false,\n\t\t\tpedantic: false,\n\t\t\tsanitize: true,\n\t\t\tsmartLists: true,\n\t\t\tsmartypants: false,\n\t\t\tlangPrefix: 'lang-'\n\t\t};\n\n\t}",
"function setupShowOpt() {\n queries.showoptbody = $(\">div#showoptbody\", queries.fcnlist);\n}",
"get options() {\n return this._options;\n }",
"static get parseOptionTypes() {\n return {\n ...super.parseOptionTypes,\n ext: 'Array',\n };\n }",
"buildDownloadOptions() {\n // Build all the query strings based on the dataset.\n this.buildQueryStrings();\n\n // Add the base download options menu configurations.\n this._downloadOptions = [\n {\n ...this._downloadOptionsTemplate[this._downloadOptionsTemplateIndex['raw-sequencing-files']],\n query: this._rawSequencingFileQueryString,\n },\n ];\n\n // Build the index of this class's custom download options.\n this._downloadOptionsIndex = buildDownloadOptionsIndex(this._downloadOptions);\n }",
"fillOptions(source, target) {\n // Overrride with settings from user and child class\n function eachRecursive(source, target, level) {\n for (var k in source) {\n // Find variable in default settings\n if (typeof source[k] == \"object\" && source[k] !== null) {\n // If the current level is not defined in the target, it is\n // initialized with empty object.\n if (target[k] === undefined) {\n target[k] = {};\n }\n eachRecursive(source[k], target[k]);\n }\n else {\n // We store each leaf property into the default settings\n target[k] = source[k];\n }\n }\n }\n eachRecursive(source, target);\n }",
"function show_codeLink_normalization_parameters() {\n\tvar normalize_method = $(\"select[name='normalize_method']\").val(); \n\n // No method selected\n if (normalize_method == 'none') {\n $(\"div#loess_div\").hide();\n $(\"div#limma_div\").hide();\n // loess\n } else if (normalize_method == 'loess') {\n $(\"div#loess_div\").show();\n $(\"div#limma_div\").hide();\n // vsn\n } else if (normalize_method == 'vsn') {\n $(\"div#loess_div\").hide();\n $(\"div#limma_div\").hide();\n\n // limma\n } else if (normalize_method == 'limma') {\n $(\"div#loess_div\").hide();\n $(\"div#limma_div\").show();\n }\n}",
"resetCommandLineOptions () {\n this.setCommandLineOption(\"url\", undefined);\n this.setCommandLineOption(\"dir\", undefined);\n\n super.resetCommandLineOptions();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CREATED: David Levine 03/12/2018 Description: calculates the value of a unary function given a string representing the function and the corresponding value to evaluate. parameters: funcString: A string representing one of five supported functions, "fact" for factorial, "sin" for sine, "cos" for cosine, "tan" for tangent, and "sqrt" for square root. funcParam: The parameter to pass into the function. trigMode: A string giving the interpretation of the argument to trigonometric functions. Either "rad" or "deg". return: the value of the factor. | function evaluateFunction(funcString, funcParam, trigMode) {
var valToReturn;
switch (funcString) {
case "fact":
valToReturn = factorial(funcParam);
break;
case "inv":
valToReturn = 1 / funcParam;
break;
case "sin":
if(trigMode == "rad"){
valToReturn = Math.sin(funcParam);
}else{
valToReturn = Math.sin(funcParam * Math.PI/180.0);
}
break;
case "cos":
if(trigMode == "rad"){
valToReturn = Math.cos(funcParam);
}else{
valToReturn = Math.cos(funcParam * Math.PI/180.0);
}
break;
case "tan":
if(trigMode == "rad"){
valToReturn = Math.tan(funcParam);
}else{
valToReturn = Math.tan(funcParam * Math.PI/180.0);
}
break;
case "sqrt":
if (checkSqrtArg(funcParam)) {
valToReturn = Math.sqrt(funcParam);
} else {
valToReturn = "ERR: SQRT DOMAIN (NEGATIVE)";
}
break;
}
return valToReturn;
} | [
"function calculateFactor(tokenQueue, trigMode) {\n console.log(tokenQueue);\n /* Functions names that may appear in the factor. */\n var funcNames = [\"inv\",\"fact\", \"sin\", \"cos\", \"tan\", \"sqrt\"];\n var value;\n var token = tokenQueue.shift();\n\n /* Case expression wrapped in parenthesis */\n if (token == \"(\") {\n value = calculateExpressionRecursive(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof value == \"string\"){\n return value;\n }\n if (tokenQueue.shift() != \")\") { /* It true, mismatched parenthesis */\n value = \"ERR: SYNTAX\";\n }\n /* Case function call */\n } else if (funcNames.includes(token)) {\n if (tokenQueue.shift() == \"(\") {\n var funcString = token;\n var funcParam = calculateExpressionRecursive(tokenQueue, trigMode);\n value = evaluateFunction(funcString, funcParam, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof funcParam == \"string\"){\n return funcParam;\n }\n if (tokenQueue.shift() != \")\") {\n value = \"ERR: SYNTAX\";\n }\n } else {\n value = \"ERR: SYNTAX\";\n }\n\n /* Case two expressions wrapped in a power function*/\n } else if (token == \"pow\") {\n if (tokenQueue.shift() == \"(\") {\n /* Evaluate first and second expression in pow */\n var expr1val = calculateExpressionRecursive(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof expr1val == \"string\"){\n return expr1val;\n }\n if (tokenQueue.shift() == \",\") {\n var expr2val = calculateExpressionRecursive(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof expr2val == \"string\"){\n return expr2val;\n }\n value = Math.pow(expr1val, expr2val);\n if (tokenQueue.shift() != \")\") {\n value = \"ERR: SYNTAX\";\n }\n } else { /* If no comma, then input here is wrong */\n value = \"ERR: SYNTAX\";\n }\n } else { /* missing parenthesis */\n value = \"ERR: SYNTAX\";\n }\n\n /* Case number */\n } else if (!isNaN(token)) {\n value = parseFloat(token);\n } else {\n value = \"ERR: SYNTAX\"\n }\n return value;\n}",
"function evaluateExpression(equation, inputs) {\n //I'm pretty sure this removes all whitespace.\n equation = equation.replace(/\\s/g, \"\");\n //if equation is an input (like 't'), return the value for that input.\n if (equation in inputs) {\n return inputs[equation];\n }\n //make each variable x like (x) so that 5(x) can work\n //to avoid infinite recursion, make sure each substring like (((x))) is turned into (x)\n for (var variable in inputs) {\n var prevLength = 0;\n while (prevLength!=equation.length) {\n //it looks like this will only go through the loop once, but actually the length of equation might change before the end of the loop\n prevLength = equation.length;\n equation = equation.replace(\"(\"+variable+\")\", variable);//first remove parenthesis from ((x)), if they exist\n }\n \n equation = equation.replace(variable, \"(\"+variable+\")\");//then add parenthesis back\n }\n //if start with - or $ (my negative replacement), negate entire expression\n if (equation.indexOf(\"-\")==0 || equation.indexOf(\"$\")==0) {\n return -1*evaluateExpression(equation.slice(1), inputs);\n }\n for (var i=1; i<equation.length; i++) {//phantom multiplication (first char cannot have a phantom *)\n //5(3) should become 5*(3)\n //5cos(3) should become 5*cos(3)\n if (equation.charAt(i)==\"(\") {\n var insertionIndex = i;\n //size of unary operation\n for (var size=MAX_FUNCTION_LENGTH; size>=MIN_FUNCTION_LENGTH; size--) {\n if (i>=size) {\n var charsBefore = equation.slice(i-size,i);\n if (charsBefore in functions) {\n insertionIndex = i-size;\n break;\n }\n }\n }\n if (insertionIndex) {\n var prevChar = equation.charAt(insertionIndex-1);\n if (prevChar==\"*\" || prevChar==\"+\" || prevChar==\"/\" || prevChar==\"-\" || prevChar==\"^\" || prevChar==\"(\") {\n \n } else {\n equation=equation.slice(0,insertionIndex).concat(\"*\",equation.slice(insertionIndex));\n i++;\n }\n }\n }\n }\n //parenthesis\n //get rid of all parentheses\n while (equation.indexOf(\"(\")>=0) {\n //use for (a*(m+a)) and (a+m)*(a+a). thus you can't just take the first '(' and last ')' and you can't take the first '(' and first ')' parentheses. You have to make sure the nested parentheses match up\n //start at the first '('\n var startIndex = equation.indexOf(\"(\");\n var endIndex = startIndex+1;\n var nestedParens = 0;\n //find end index\n //stop when outside of nested parentheses and the character is a ')'\n while (equation.charAt(endIndex)!=\")\" || nestedParens) {\n if (equation.charAt(endIndex)==\")\") {\n nestedParens--;\n }\n if (equation.charAt(endIndex)==\"(\") {\n nestedParens++;\n }\n endIndex++;\n }\n //find what's in the parentheses and also include the parenthesis.\n var inParens = equation.slice(startIndex+1, endIndex);\n var includingParens = equation.slice(startIndex, endIndex+1);\n \n var value = evaluateExpression(inParens, inputs);\n //size of unary operation\n //in range. Must enumerate backwards so acos(x) does not get interpreted as a(cos(x))\n for (var size=4; size>=2; size--) {\n if (startIndex>=size) {\n var charsBefore = equation.slice(startIndex-size, startIndex);\n if (charsBefore in functions) {\n value = functions[charsBefore](value);\n includingParens=equation.slice(startIndex-size, endIndex+1);\n break;\n }\n }\n }\n \n if (includingParens==equation) {//like (5) or cos(3)\n return value;\n } else {\n //replace in equation.\n equation = equation.replace(includingParens, value);\n }\n }\n //done with parentheses\n \n //deal with negatives. replace with dollar sign\n //this is so 4/-7 doesn't get interpreted as (4/)-7, which could raise a divide by zero error\n equation = equation.replace(\"*-\", \"*$\");\n equation = equation.replace(\"--\", \"+\");//minus negative is plus\n equation = equation.replace(\"+-\", \"-\");//add negative is minus\n equation = equation.replace(\"/-\", \"/$\");\n equation = equation.replace(\"(-\", \"($\");\n \n //now the divide and conquer algorithm (or whatever this is)\n \n //check if equation contains any operations like \"+\", \"-\", \"/\", etc.\n\tif (equation.indexOf(\"+\")>=0) {\n //start at zero and add from there\n var sum = 0;\n var toAdd = equation.split(\"+\");//divide\n for (var operand in toAdd) {\n sum += evaluateExpression(toAdd[operand], inputs);//conquer\n }\n //everything has been taken care of.\n return sum;\n }\n if (equation.indexOf(\"-\")>=0) {\n var diff = 0;\n var toSub = equation.split(\"-\");\n var first = true; //if looking at the first operand, it's positive. Subtract all others.\n //this is much easier in Haskell\n //first:toSum = first - (sum toSub)\n for (var op in toSub) {\n if (first) diff = evaluateExpression(toSub[op], inputs);\n else diff -= evaluateExpression(toSub[op], inputs);\n first=false;\n }\n return diff;\n }\n\tif (equation.indexOf(\"*\")>=0) {\n\t\tvar multiple = 1;//start with one (multiplicative identity)\n\t\tvar toMultiply = equation.split(\"*\");\n\t\tfor (var factor in toMultiply) {\n\t\t\tmultiple *= evaluateExpression(toMultiply[factor], inputs);\n\t\t}\n\t\treturn multiple;\n\t}\n if (equation.indexOf(\"/\")>=0) {\n var quot = 0;\n var toDiv = equation.split(\"/\");\n var first = true;\n for (var op in toDiv) {\n if (first) quot = evaluateExpression(toDiv[op], inputs);\n else quot /= evaluateExpression(toDiv[op], inputs);\n first=false;\n }\n return quot;\n }\n if (equation.indexOf(\"^\")>=0) {\n var exp = 0;\n var toPow = equation.split(\"^\");\n var first = true;\n for (var op in toPow) {\n if (first) exp = evaluateExpression(toPow[op], inputs);\n else exp = Math.pow(exp, evaluateExpression(toPow[op], inputs));\n first=false;\n }\n return exp;\n }\n \n //no function. assume it's a number (base 10 of course)\n var value = parseFloat(equation, 10);\n if (equation.charAt(0)==\"$\") {//negative\n value = parseFloat(equation.slice(1), 10) * -1;\n }\n\treturn value;\n}",
"function parseCSSFunc(value) {\n\t\tif (typeof value !== 'string') throw new CustomError('Argument error', 'value is not a valid string');\n\t\tconst rxSignature = /^([a-zA-Z]+)(\\(.+\\))$/i;\n\t\tconst rxArgs = /\\(\\s*([+-]?(?:\\d*?\\.)?\\d+%?)\\s*,\\s*([+-]?(?:\\d*?\\.)?\\d+%?)\\s*,\\s*([+-]?(?:\\d*?\\.)?\\d+%?)\\s*(?:,\\s*([+-]?(?:\\d*?\\.)?\\d+%?)\\s*)?\\)/;\n\t\t\n\t\t// map of non-numbers as parameters\n\t\tconst NUMMAP_RGB = [false, false, false];\n\t\tconst NUMMAP_HSL = [false, true, true];\n\t\t\n\t\t// gets function name and argument set\n\t\tlet [ , funcName = '', argSet = ''] = value.trim().match(rxSignature) || [];\n\t\t// matches the list of arguments (trimmed)\n\t\tlet args = argSet.match(rxArgs);\n\t\tif (args === null) throw new CustomError('Type error', 'the value provided is not a CSS function');\n\t\t// remove full match and alpha from array, store alpha in variable\n\t\tlet alpha = (args = args.slice(1)).pop();\n\t\t// truthy map if argument evaluates as NaN\n\t\tlet pType = args.map(isNaN);\n\t\t\n\t\tlet output;\n\t\t\n\t\t// select the format of parameters\n\t\tswitch (true) {\n\t\t\tcase funcName === 'rgb':\n\t\t\tcase funcName === 'rgba':\n\t\t\t\tif (!isEqual(pType, NUMMAP_RGB)) throw new CustomError('Argument error', 'RGB arguments are not valid');\n\t\t\t\toutput = args.map((num) => {\n\t\t\t\t\treturn parseFloat(num / 255);\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\tcase funcName === 'hsl':\n\t\t\tcase funcName === 'hsla':\n\t\t\t\tif (!isEqual(pType, NUMMAP_HSL)) throw new CustomError('Argument error', 'HSL parameters are not valid');\n\t\t\t\toutput = args.map(parseFloat).map((num, i) => {\n\t\t\t\t\treturn num * (pType[i] ? 0.01 : 1);\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new CustomError('Argument error', `${funcName} is not a recognized CSS function`);\n\t\t}\n\t\t\n\t\tif (typeof alpha !== 'undefined') {\n\t\t\tif (funcName.length === 3) throw new CustomError('Argument error', `${funcName} function only recieves 3 arguments`);\n\t\t\toutput.push(parseFloat(alpha) * (isNaN(alpha) ? 0.01 : 1));\n\t\t}\n\t\t\n\t\treturn [funcName].concat(output);\n\t}",
"function calculateExpressionRecursive(tokenQueue, trigMode){\n var exprValue = calculateTerm(tokenQueue, trigMode);\n\n // If a string is returned then it is an error message, return the message.\n if(typeof exprValue == \"string\"){\n return exprValue;\n }\n\n while(tokenQueue[0] == \"+\" || tokenQueue[0] == \"\\u2212\" ){\n var operation = tokenQueue.shift();\n if(operation == \"+\"){\n var exprValueTemp = calculateTerm(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof exprValueTemp == \"string\"){\n return exprValueTemp;\n }\n exprValue = exprValue + exprValueTemp;\n }else if (operation == \"\\u2212\"){\n var exprValueTemp = calculateTerm(tokenQueue, trigMode);\n // If a string is returned then it is an error message, return the message.\n if(typeof exprValueTemp == \"string\"){\n return exprValueTemp;\n }\n exprValue = exprValue - exprValueTemp;\n }\n else {\n\n }\n }\n\n return exprValue;\n}",
"[symbols.call](obj=0.0)\n\t{\n\t\tif (typeof(obj) === \"string\")\n\t\t\treturn parseFloat(obj);\n\t\telse if (typeof(obj) === \"number\")\n\t\t\treturn obj;\n\t\telse if (obj === true)\n\t\t\treturn 1.0;\n\t\telse if (obj === false)\n\t\t\treturn 0.0;\n\t\tthrow new TypeError(\"float() argument must be a string or a number\");\n\t}",
"function calculateExpression(tokenQueue, trigMode=\"rad\"){\n var exprValue = calculateExpressionRecursive(tokenQueue, trigMode);\n if(tokenQueue.length != 0){\n return \"ERR: SYNTAX\";\n }\n\n return exprValue;\n}",
"function getFunctionValue(func, point) {\n return func[0] * point.x + func[1] * point.y + func[2] * point.x * point.y + func[3];\n }",
"factor() {\n const token = this.currentToken;\n\n if (token.type === tokens.plus) {\n this.eat(tokens.plus);\n return new UnaryOp(token, this.factor());\n }\n\n if (token.type === tokens.minus) {\n this.eat(tokens.minus);\n return new UnaryOp(token, this.factor());\n }\n\n if (token.type === tokens.integerConst) {\n this.eat(tokens.integerConst);\n return new Num(token);\n }\n\n if (token.type === tokens.realConst) {\n this.eat(tokens.realConst);\n return new Num(token);\n }\n\n if (token.type === tokens.lparen) {\n this.eat(tokens.lparen);\n const result = this.expr();\n this.eat(tokens.rparen);\n return result;\n }\n\n const node = this.variable();\n return node;\n }",
"function parseFunc() {\n var fnName = t.identifier(getUniqueName(\"func\"));\n var typeRef;\n var fnBody = [];\n var fnParams = [];\n var fnResult = []; // name\n\n if (token.type === _tokenizer.tokens.identifier) {\n fnName = identifierFromToken(token);\n eatToken();\n } else {\n fnName = t.withRaw(fnName, \"\"); // preserve anonymous\n }\n\n maybeIgnoreComment();\n\n while (token.type === _tokenizer.tokens.openParen || token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) {\n // Instructions without parens\n if (token.type === _tokenizer.tokens.name || token.type === _tokenizer.tokens.valtype) {\n fnBody.push(parseFuncInstr());\n continue;\n }\n\n eatToken();\n\n if (lookaheadAndCheck(_tokenizer.keywords.param) === true) {\n eatToken();\n fnParams.push.apply(fnParams, _toConsumableArray(parseFuncParam()));\n } else if (lookaheadAndCheck(_tokenizer.keywords.result) === true) {\n eatToken();\n fnResult.push.apply(fnResult, _toConsumableArray(parseFuncResult()));\n } else if (lookaheadAndCheck(_tokenizer.keywords.export) === true) {\n eatToken();\n parseFuncExport(fnName);\n } else if (lookaheadAndCheck(_tokenizer.keywords.type) === true) {\n eatToken();\n typeRef = parseTypeReference();\n } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === \"keyword\" // is any keyword\n ) {\n // Instruction\n fnBody.push(parseFuncInstr());\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in func body\" + \", given \" + tokenToString(token));\n }();\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.func(fnName, typeRef !== undefined ? typeRef : t.signature(fnParams, fnResult), fnBody);\n }",
"function addNewFuncExpr() {\r\n\r\n // if any grid is currently highlighted, remove that highlight first\r\n // This is important if the user replaces a grid expression with an\r\n // operator\r\n //\r\n removeGridHighlight();\r\n\r\n\r\n // Get the new function name from the user and check for duplicate names\r\n // TODO: Check among grid names of function and let names of the step\r\n //\r\n var isdup = true;\r\n\r\n do {\r\n var fname = prompt(\"Name of new function\", DefFuncName);\r\n\r\n // If user pressed cancel, just return\r\n //\r\n if (!fname)\r\n return;\r\n\r\n isdup = isExistingFuncName(CurModObj, fname);\r\n\r\n if (isdup) {\r\n alert(\"Function name \" + fname + \" already exists!\");\r\n }\r\n\r\n } while (isdup);\r\n\r\n\r\n // main root expression for the function\r\n //\r\n var funcExpr = new ExprObj(false, ExprType.FuncCall, fname);\r\n\r\n // Create a new func obj and record in the current module\r\n //\r\n var fO = new FuncObj();\r\n fO.funcCallExpr = funcExpr; // set reference to func expr\r\n\r\n CurModObj.allFuncs.push(fO); // add function to current module\r\n\r\n assert((fO.argsAdded < 0), \"Can't have any args yet\");\r\n\r\n // STEP A: -------------------------------------------------- \r\n //\r\n // Add return value (scalar grid).\r\n // NOTE: Return value is always a scalar. \r\n //\r\n // Create a scalar grid and add it to the Function Grids/Header\r\n //\r\n var newGId = fO.allGrids.length;\r\n //\r\n var newgO = new GridObj(newGId, DefRetValName, 1, 1,\r\n\t\t\t 1, 1, false, false, false, false);\r\n newgO.isRetVal = true;\r\n //\t\r\n // Record this grid in function header\r\n // Note: We add return value as the very first grid to function.\r\n // This is necessary for having a unique grid ID for each \r\n // Grid (return value is a grid). This is useful in showing\r\n // return *data* value. Also, user can directly assign to this.\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.allSteps[FuncHeaderStepId].allGridIds.push(newGId);\r\n //\r\n fO.argsAdded = 0; // indicates return value added\r\n\r\n // Add the data type to the arg grid. Return value is always integer\r\n //\r\n newgO.dataTypes.push(DataTypes.Integer);\r\n assert((newgO.dataTypes.length == 1), \"must have only global type\");\r\n newgO.typesInDim = -1;\r\n\r\n // Redraw step to reflect the addition of the function\r\n //\r\n drawProgStructHead(); // update program structre heading\r\n replaceOrAppendExpr(funcExpr);\r\n drawCodeWindow(CurStepObj); // redraw code window\r\n}",
"function realValue(val, bool){\n var undefined;\n // only evaluate strings\n if (typeof val != 'string') return val;\n if (bool) {\n if (val === '0') {\n return false;\n }\n if (val === '1') {\n return true;\n }\n }\n if (isNumeric(val)) {\n return +val;\n }\n switch(val) {\n case 'true':\n return true;\n case 'false':\n return false;\n case 'undefined':\n return undefined;\n case 'null':\n return null;\n default:\n return val;\n }\n }",
"function getFuncCallStr(fexpr) {\r\n\r\n assert(fexpr.isFuncCall());\r\n\r\n // TODO: add args (with data types)\r\n //\r\n return (fexpr.str);\r\n}",
"executeFunctionString() {\n this.setProperties({\n isProcessing: true\n });\n post('/evalFunctionString', { 'function': this.functionString }, this, 'json')\n .then(this.showFunctionStringResults.bind(this), this.runScriptFailure.bind(this), this.runScriptError.bind(this));\n }",
"function calculate(equation){\n return eval(equation);\n}",
"function evaluate(numbers, op) {\n if(op === '+')\n return numbers.reduce(add);\n else if(op === '-')\n return numbers.reduce (subtract);\n else if(op === '*')\n return numbers.reduce(multiply);\n else if(op === '/')\n return numbers.reduce(divide);\n else if(op === '%')\n return numbers.reduce(modulo);\n }",
"function doDemo(formulaStr) {\n formulaElem.value = formulaStr;\n doBalance();\n}",
"function numberFact (num, fn) {\n return fn(num);\n}",
"function Function() {\n this.id = \"\";\n this.lang = \"\";\n this.returnType = \"\";\n this.code = \"\";\n }",
"function convertToMath() {\n\treturn eval(getId('result').value);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convierte las coordenadas en formato cartesiano a un punto | function Coordenadas_Cartesianas_APunto(Cartesiano)
{
try
{
var Noroeste = MapaCanvas.getProjection().fromLatLngToPoint(Bordes.getNorthEast());
var SurEste = MapaCanvas.getProjection().fromLatLngToPoint(Bordes.getSouthWest());
var Escala = Math.pow(2, ZoomMinimo);
var CoordenadasEsfericas = new google.maps.Point(Cartesiano.x / Escala + SurEste.x, Cartesiano.y / Escala + Noroeste.y);
return MapaCanvas.getProjection().fromPointToLatLng(CoordenadasEsfericas);
}
catch (Excepcion)
{
var Noroeste = MapaCanvas.getProjection().fromLatLngToPoint(MapaCanvas.getBounds().getNorthEast());
var SurEste = MapaCanvas.getProjection().fromLatLngToPoint(MapaCanvas.getBounds().getSouthWest());
var Escala = Math.pow(2, MapaCanvas.getZoom());
var CoordenadasEsfericas = new google.maps.Point(Cartesiano.x / Escala + SurEste.x, Cartesiano.y / Escala + Noroeste.y);
return MapaCanvas.getProjection().fromPointToLatLng(CoordenadasEsfericas);
}
} | [
"function hexToCartesian(hexCoordinates) {\n\tvar x = X_UNIT_VEC.x * hexCoordinates.x + Y_UNIT_VEC.x * hexCoordinates.y \n\t\t\t+ Z_UNIT_VEC.x * hexCoordinates.z;\n\tvar y = X_UNIT_VEC.y * hexCoordinates.x + Y_UNIT_VEC.y * hexCoordinates.y \n\t\t\t+ Z_UNIT_VEC.y * hexCoordinates.z;\n\treturn {x: x, y: y};\n}",
"getRealCoords(x, y) {\n const real_x = (x - this.x_min) * this.x_scale + this.x;\n const real_y = this.height - (y - this.y_min) * this.y_scale + this.y;\n\n return [real_x, real_y];\n }",
"function convertCoordinates (ele)\r\n\t{\r\n\t\tvar gps = coordinates (ele); //gets the coordinates of the puzzle piece\r\n\r\n\t\tvar l = parseInt (gps[0], 10); //left value: x coordinate\r\n\t\tvar t = parseInt (gps[1], 10); //top value: y coordinate\r\n\r\n\t\tl = l/100;\r\n\t\tt = t/100;\r\n\r\n\t\treturn l + \" \" + t;\r\n\t}",
"function toCoordinate(id_num) {\n // Math doesnn't work properly for last cell\n if (id_num === \"256\") {\n return [15, 15];\n }\n else {\n id_num = parseInt(id_num);\n var x = Math.floor((id_num-1)/16);\n var y = id_num-(16*x);\n return [x, y-1];\n }\n}",
"function convertArrayToXY(array) {\n const newArray = [];\n for(let i = 0; i < array.length; i += 2) {\n newArray.push({\n x: array[i],\n y: array[i + 1]\n });\n }\n return newArray;\n}",
"function from_A1_to_XY(a1) {\n return [from_A_to_X(a1.charAt(0)), from_1_to_Y(a1.charAt(1))];\n }",
"function sukeistiMasyvo2elementus(x, y) {\n let t = prekiautojai[x];\n prekiautojai[x] = prekiautojai[y];\n prekiautojai[y] = t;\n}",
"static transformPoint(x, y, matrix) {\r\n return {\r\n x: Math.round(x * matrix[0] + y * matrix[2] + matrix[4]),\r\n y: Math.round(x * matrix[1] + y * matrix[3] + matrix[5]),\r\n };\r\n }",
"function sinToCoords(x) {\n\treturn 450 + 120 * x;\n}",
"function verticesProjection(vertices,axis){var _vertices$map=vertices.map(function(v){return axis.dot(new sprite_math__WEBPACK_IMPORTED_MODULE_0__[\"Vector\"](v));}),_vertices$map2=(0,_slicedToArray6['default'])(_vertices$map,4),p1=_vertices$map2[0],p2=_vertices$map2[1],p3=_vertices$map2[2],p4=_vertices$map2[3];return[Math.min(p1,p2,p3,p4),Math.max(p1,p2,p3,p4)];}",
"toCoordinate() {\n assertParameters(arguments);\n \n return new Coordinate(this._width, this._height);\n }",
"function pointsToZone(points)\n{\n\tlet zone = [];\n\tfor(let p of points) {\n\t\tzone.push(g_TOMap.gCells[p.x][p.y]);\n\t}\t\t\n\treturn zone;\n}",
"toUTM() {\n return new UTMPoint().fromLatLng(this);\n }",
"function sukeistiMasyvo2Elementus(x, y) {\n var z = prekiautojai[x];\n prekiautojai[x] = prekiautojai[y];\n prekiautojai[y] = z;\n\n}",
"plotFromGeoCoords(planet, lat, long)\n {\n var phi = (90-lat) * (Math.PI / 180);\n var theta = (long + 180) * (Math.PI / 180);\n \n this.dome.position.x = -((planet.radius) * Math.sin(phi) * Math.cos(theta));\n this.dome.position.y = ((planet.radius) * Math.cos(phi));\n this.dome.position.z = ((planet.radius) * Math.sin(phi) * Math.sin(theta));\n }",
"function build2points() {\n points += (4 * b2multi);\n totalpoints += (4 * b2multi);\n }",
"function perifocalToCartesianMatrix(argumentOfPeriapsis, inclination, rightAscension, result) {\n \n\n var cosap = Math.cos(argumentOfPeriapsis);\n var sinap = Math.sin(argumentOfPeriapsis);\n\n var cosi = Math.cos(inclination);\n var sini = Math.sin(inclination);\n\n var cosraan = Math.cos(rightAscension);\n var sinraan = Math.sin(rightAscension);\n if (!defined(result)) {\n result = new Matrix3(\n cosraan * cosap - sinraan * sinap * cosi,\n -cosraan * sinap - sinraan * cosap * cosi,\n sinraan * sini,\n\n sinraan * cosap + cosraan * sinap * cosi,\n -sinraan * sinap + cosraan * cosap * cosi,\n -cosraan * sini,\n\n sinap * sini,\n cosap * sini,\n cosi);\n } else {\n result[0] = cosraan * cosap - sinraan * sinap * cosi;\n result[1] = sinraan * cosap + cosraan * sinap * cosi;\n result[2] = sinap * sini;\n result[3] = -cosraan * sinap - sinraan * cosap * cosi;\n result[4] = -sinraan * sinap + cosraan * cosap * cosi;\n result[5] = cosap * sini;\n result[6] = sinraan * sini;\n result[7] = -cosraan * sini;\n result[8] = cosi;\n }\n return result;\n }",
"function from_XY_to_A1(xy) {\n return from_X_to_A(xy[0]) + from_Y_to_1(xy[1]);\n }",
"createTransformedPolygon() {\r\n this.transformedPolygon = [];\r\n\r\n for(let i=0; i<this.polygon.length; i++) {\r\n this.transformedPolygon.push(\r\n [\r\n this.polygon[i][0] * this.scale + this.origin.x,\r\n this.polygon[i][1] * this.scale + this.origin.y\r\n ]\r\n );\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for getV3GroupsIdIssues | getV3GroupsIdIssues(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.GroupsApi()
/*let id = "id_example";*/ // String | The ID of a grou
/*let opts = {
'state': "'opened'", // String | Return opened, closed, or all issues
'labels': "labels_example", // String | Comma-separated list of label names
'milestone': "milestone_example", // String | Return issues for a specific milestone
'orderBy': "'created_at'", // String | Return issues ordered by `created_at` or `updated_at` fields.
'sort': "'desc'", // String | Return issues sorted in `asc` or `desc` order.
'page': 56, // Number | Current page number
'perPage': 56 // Number | Number of items per page
};*/
apiInstance.getV3GroupsIdIssues(incomingOptions.id, incomingOptions.opts, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"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 }",
"get ids() {\n return issues.map(obj => obj.id);\n }",
"function initIssues() {\n\t//ids start at 5 so fill in 0-4 to make retrieval bawed on array index trivial\n\tissues = [0, 0, 0, 0, 0,\n {id:5,\tname:\"Alumni\"},\n\t\t\t{id:6,\tname:\"Animals\"},\n\t\t\t{id:7,\tname:\"Children\"},\n\t\t\t{id:8,\tname:\"Disabilities\"},\n\t\t\t{id:9,\tname:\"Disasters\"},\n\t\t\t{id:10,\tname:\"Education\"},\n\t\t\t{id:11,\tname:\"Elderly\"},\n\t\t\t{id:12,\tname:\"Environment\"},\n\t\t\t{id:13,\tname:\"Female Issues\"},\n\t\t\t{id:14, name:\"Fine Arts\"},\n\t\t\t{id:15,\tname:\"General Service\"},\n\t\t\t{id:16,\tname:\"Health\"},\n\t\t\t{id:17,\tname:\"Male Issues\"},\n\t\t\t{id:18, name:\"Minority Issues\"},\n\t\t\t{id:19,\tname:\"Office\"},\n\t\t\t{id:20,\tname:\"Patriotic\"},\n\t\t\t{id:21,\tname:\"Poverty\"},\n\t\t\t{id:22,\tname:\"PR\"},\n\t\t\t{id:23,\tname:\"Recreation\"},\n\t\t\t{id:24,\tname:\"Religious\"},\n\t\t\t{id:25,\tname:\"Service Leaders\"},\n\t\t\t{id:26,\tname:\"Technology\"}\n\t\t\t];\n}",
"get withPullRequest() {\n return issues.filter(obj => obj.pull_request !== undefined\n && obj.pull_request !== null)\n .map(obj => obj.id);\n }",
"get withAssignee() {\n return issues.filter(obj => obj.assignee !== null)\n .map(obj => obj.id);\n }",
"getIssues(...ids) {\n let allIssues = this.getState();\n\n let issues = new OrderedMap();\n\n issues = issues.asMutable();\n\n ids.forEach(function(id) {\n issues.set(id, allIssues[id]);\n });\n\n return issues.asImmutable();\n }",
"function getGitLabProjectIssues() {\n return getRemainingGitLabProjectIssues(0, 100)\n .then(function(result) {\n log_progress(\"Fetched \" + result.length + \" GitLab issues.\");\n var issues = _.indexBy(result, 'iid');\n return gitLab.gitlabIssues = issues;\n });\n}",
"function getIssues() {\n TestService.getTestCaseWorkItemsByType(test.id, 'BUG').\n then(function(rs) {\n if (rs.success) {\n vm.issues = rs.data;\n if (test.workItems.length && vm.attachedIssue) {\n angular.copy(vm.attachedIssue, vm.newIssue);\n }\n } else {\n messageService.error(rs.message);\n }\n });\n }",
"getV3ProjectsIdMergeRequestsMergeRequestIdClosesIssues(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.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number |\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdMergeRequestsMergeRequestIdClosesIssues(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"getV3ProjectsIdMergeRequestMergeRequestIdClosesIssues(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.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number |\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdMergeRequestMergeRequestIdClosesIssues(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\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 }",
"userGroups (id) {\n return this._apiRequest(`/user/${id}/groups`)\n }",
"getGroup (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}`)\n }",
"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 }",
"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 }",
"postV3ProjectsIdIssues(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.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssues(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 }",
"function listMyIssues(){\n\n logDebug('listMyIssues: Starting getting my issues for...');\n log( ['comments', 'title', 'state', 'body', 'id' ].join(sep) );\n\n var request = $.ajax({\n\n url: 'https://api.github.com/issues?access_token=' + oauthToken.token,\n type: 'GET',\n\n \n success: function(data, textStatus, jqXHR){\n logDebug('listMyIssues: Yea, it worked...' + textStatus + ' - ' + JSON.stringify(data) );\n\n $.each( data, function(index, value) {\n value.body = value.body.replace(/(\\r\\n|\\n|\\r)/gm,\"\");\n\n log( [value.comments, value.title, value.state, value.body, value.id ].join(sep) );\n });\n\n parseHttpHeaders(jqXHR);\n\n },\n\n error: function(data){\n logErr('listMyIssues: Shit hit the fan...' + JSON.stringify(data));\n\n }\n\n });\n\n return request;\n\n}",
"async function createRepositoryIssues({ issues }) {\n const issuesHTML = HtmlBuilder.div()\n .addClass('repository-detail__issues mb-3 border p-3')\n let issueDetailHTML = createIssueDetail({ issue: undefined })\n\n if (!issues || issues.length <= 0) {\n return issuesHTML.append(HtmlBuilder.div(\"Não há issues\"))\n }\n\n async function fetchAndFillIssueDetail({ issue }) {\n const { comments_url } = issue\n const issueComments = await _gitHubService.fetchIssueComments(comments_url)\n issueDetailHTML.html(createIssueDetail({ issue, issueComments }))\n moveToPageElemnt(\"#issue-detail\")\n }\n\n const issuesTableHTML = HtmlBuilder.table(\"\")\n .addClass('table table-striped border')\n .attr('id', 'issues-table')\n const theadHTML = HtmlBuilder.thead(\"\")\n .append(HtmlBuilder.tr()\n .append(HtmlBuilder.th(\"Nome\"))\n .append(HtmlBuilder.th(\"Status\").attr(DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN, DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN))\n .append(HtmlBuilder.th(\"Detalhes\")))\n const tbodyHTML = HtmlBuilder.tbody(\"\")\n\n for (issue of issues) {\n const issueWithoutCache = issue\n const { title, state } = issueWithoutCache\n\n function onOpenIssueDetail() { fetchAndFillIssueDetail({ issue: issueWithoutCache }) }\n\n const trHTML = HtmlBuilder.tr(\"\")\n .append(HtmlBuilder.td(`${title}`))\n .append(HtmlBuilder.td(`${state}`))\n .append(HtmlBuilder.td(HtmlBuilder.button(\"Mais\")\n .addClass('btn btn-primary')\n .click(onOpenIssueDetail)))\n\n tbodyHTML.append(trHTML)\n }\n\n issuesTableHTML.append(theadHTML).append(tbodyHTML)\n issuesHTML\n .append(HtmlBuilder.h3(\"Issues\"))\n .append(issuesTableHTML)\n .append(HtmlBuilder.hr())\n .append(issueDetailHTML)\n\n _dataTableFactory.of(issuesTableHTML)\n\n return issuesHTML\n }",
"getV3ProjectsIdIssuesIssueIdAwardEmoji(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.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let issueId = 56;*/ // Number | The ID of an Issue, Merge Request or Snippe\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdIssuesIssueIdAwardEmoji(incomingOptions.id, incomingOptions.issueId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove `position`s from `tree`. | function removePosition(node, force) {
visit(node, force ? hard : soft)
return node
} | [
"prune(callback) {\n if (_.isArray(this.contents)) {\n const length = this.contents.length;\n\n if ((this.type === \"REPEAT\" && length > 0) || (this.type === \"REPEAT1\" && length > 1)) {\n // Any subtree may be removed\n for (let i = 0; i < length; i++) {\n const tree = _.cloneDeep(this);\n tree.contents.splice(i, 1);\n if (!callback(tree)) {\n return;\n }\n }\n }\n\n for (let i = 0; i < length; i++) {\n let callbackResult = true;\n\n this.contents[i].prune(t => {\n const tree = _.cloneDeep(this);\n tree.contents[i] = t;\n callbackResult = callback(tree);\n return callbackResult;\n });\n\n if (!callbackResult) {\n return;\n }\n }\n }\n }",
"function _remove(predicate, tree) {\n\tif (isEmpty(tree)) {\n\t\treturn tree;\n\t} else if (R.pipe(R.view(lenses.data), predicate)(tree)) {\n\t\tif (!isEmpty(tree.left) && !isEmpty(tree.right)) {\n\t\t\t// Get in-order successor to `tree`; \"delete\" it; replace values in `tree`.\n\t\t\tconst successorLens =\n\t\t\t\tlensForSuccessorElement(tree);\n\t\t\t// assert(successorLens != null);\n\n\t\t\tconst successor = \n\t\t\t\tR.view(successorLens, tree);\n\t\t\t/*\n\t\tassert.notEqual(\n\t\t\tsuccessor,\n\t\t\tnull,\n\t\t\t`Expected successor of ${JSON.stringify(tree)}`);\n\t\t\t*/\n\n\t\t\treturn R.pipe(\n\t\t\t\tR.set(successorLens, empty),\n\t\t\t\tR.set(lenses.data, R.view(lenses.data, successor))\n\t\t\t)(tree);\n\t\t} else if (!isEmpty(tree.left)) {\n\t\t\treturn tree.left;\n\t\t} else if (!isEmpty(tree.right)) {\n\t\t\treturn tree.right;\n\t\t} else {\n\t\t\treturn empty;\n\t\t}\n\t} else {\n\t\treturn R.pipe(\n\t\t\tR.over(lenses.leftChild, remove(predicate)),\n\t\t\tR.over(lenses.rightChild, remove(predicate))\n\t\t)(tree);\n\t}\n}",
"function removeExpr() {\r\n\r\n var sO = CurStepObj;\r\n var pos;\r\n\r\n // If an expression is active, we remove that expression AND activate\r\n // the space just before that removed expression (i.e., the sapce\r\n // id same as that of removed expression)\r\n //\r\n if (!sO.isSpaceActive) { // expression highlighted\r\n\r\n // console.log(\"no space\");\r\n\r\n pos = sO.activeChildPos;\r\n\r\n if (pos != ROOTPOS) {\r\n\r\n //console.log(\"not root\");\r\n\r\n // If we are deleting an arg of a function call, update the\r\n // header\r\n // \r\n var removed = true;\r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n removed = removeFuncArg(sO.activeParentExpr, pos);\r\n }\r\n\t //\r\n if (removed) {\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n sO.isSpaceActive = true; // activate space before removed expr\r\n }\r\n\r\n } else { // can't remove root str (e.g., if/else)\r\n\r\n\r\n if (sO.activeParentExpr.exprArr.length ||\r\n sO.activeParentExpr.isCondition()) {\r\n\r\n // Cannot delete non-empty 'foreach' OR any mask box \r\n //\r\n showTip(TipId.RootEdit);\r\n\r\n } else {\r\n\r\n // if no children, mark as deleted (e.g., bare 'foreach')\r\n //\r\n sO.activeParentExpr.deleted = DeletedState.Deleted;\r\n }\r\n }\r\n\r\n } else { // if space highlighted\r\n\r\n // console.log(\"space @\" + sO.activeChildPos);\r\n\r\n //pos = -1; // remove at very end by default\r\n\r\n if (sO.activeChildPos > 0) {\r\n pos = --sO.activeChildPos; // -- to move to previous space\r\n\r\n /*\r\n\t if (pos < 0) { // if we moved to ROOTPS\r\n\t\tsO.isSpaceActive = false; // space no longer active\r\n\t }\r\n\t */\r\n\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n }\r\n\r\n\r\n\r\n // var expr = sO.activeParentExpr.exprArr[pos];\r\n // if (expr.isDefinition()) expr.str = 'DELETED';\r\n\r\n\r\n\r\n }\r\n\r\n}",
"delete(val) {\n debugger\n let currentNode = this.root;\n let found = false;\n let nodeToRemove;\n let parent = null;\n\n // find the node we want to remove\n while (!found) {\n if (currentNode === null || currentNode.val === null) {\n return 'the node was not found'\n }\n if (val === currentNode.val) {\n nodeToRemove = currentNode;\n found = true;\n } else if (val < currentNode.val) {\n parent = currentNode;\n currentNode = currentNode.left;\n } else {\n parent = currentNode;\n currentNode = currentNode.right;\n }\n }\n\n console.log(\"We found the node\");\n console.log('parent node', parent);\n\n // helper variable which returns true if the node we've removing is the left\n // child and false if it's right\n const nodeToRemoveIsParentsLeftChild = parent.left === nodeToRemove;\n\n // if nodeToRemove is a leaf node, remove it\n if (nodeToRemove.left === null && nodeToRemove.right === null) {\n if (nodeToRemoveIsParentsLeftChild) parent.left = null;\n else parent.right = null\n } else if (nodeToRemove.left !== null && nodeToRemove.right === null) {\n // only has a left child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.left;\n } else {\n parent.right = nodeToRemove.left;\n }\n } else if (nodeToRemove.left === null && nodeToRemove.right !== null) {\n // only has a right child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.right;\n } else {\n parent.right = nodeToRemove.right;\n }\n } else {\n // has 2 children\n const rightSubTree = nodeToRemove.right;\n const leftSubTree = nodeToRemove.left;\n // sets parent nodes respective child to the right sub tree\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = rightSubTree;\n } else {\n parent.right = rightSubTree;\n }\n\n // find the lowest free space on the left side of the right sub tree\n // and add the leftSubtree\n let currentLeftNode = rightSubTree;\n let currentLeftParent;\n let foundSpace = false;\n while (!foundSpace) {\n if (currentLeftNode === null) foundSpace = true;\n else {\n currentLeftParent = currentLeftNode;\n currentLeftNode = currentLeftNode.left;\n }\n }\n currentLeftParent.left = leftSubTree;\n return 'the node was successfully deleted'\n }\n }",
"function resetOrder() {\n data.sort(function (a, b) {\n return a.position - b.position;\n });\n}",
"_removeNode(tree, path) {\n if(tree){\n if (path.length === 1) {\n delete tree[path[0]];\n return;\n }\n return this._removeNode(tree[path[0]], path.slice(1));\n }\n }",
"function removeChildren(node) {\n\t\tjQuery(node).empty();\n\t}",
"remove(point) {\n if (this.divided) {\n // If there are children then perform the removal on them\n this.children.forEach(child => {\n child.remove(point);\n });\n // Check if quads can be merged, being placed here is performed recursively from inner to outer quads\n this.merge();\n }\n\n // There are no children so check the current quad\n if (this.boundary.contains(point)) {\n // Filter the points that coincide with the target to remove\n this.points = this.points.filter(p => p.x !== point.x || p.y !== point.y);\n }\n }",
"function removeCandidatePosition() {\n \t candidatePositions.pop();\n \t numCandidates -= 1;\n } // removeCandidatePosition",
"function removeOrphanedChildren(children, unmountOnly) {\n\tfor (var i = children.length; i--;) {\n\t\tif (children[i]) {\n\t\t\trecollectNodeTree(children[i], unmountOnly);\n\t\t}\n\t}\n}",
"unwrapNodes(editor) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n Editor.withoutNormalizing(editor, () => {\n var {\n mode = 'lowest',\n split = false,\n voids = false\n } = options;\n var {\n at = editor.selection,\n match\n } = options;\n\n if (!at) {\n return;\n }\n\n if (match == null) {\n match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);\n }\n\n if (Path.isPath(at)) {\n at = Editor.range(editor, at);\n }\n\n var rangeRef = Range.isRange(at) ? Editor.rangeRef(editor, at) : null;\n var matches = Editor.nodes(editor, {\n at,\n match,\n mode,\n voids\n });\n var pathRefs = Array.from(matches, (_ref5) => {\n var [, p] = _ref5;\n return Editor.pathRef(editor, p);\n });\n\n var _loop = function _loop(pathRef) {\n var path = pathRef.unref();\n var [node] = Editor.node(editor, path);\n var range = Editor.range(editor, path);\n\n if (split && rangeRef) {\n range = Range.intersection(rangeRef.current, range);\n }\n\n Transforms.liftNodes(editor, {\n at: range,\n match: n => Element$1.isAncestor(node) && node.children.includes(n),\n voids\n });\n };\n\n for (var pathRef of pathRefs) {\n _loop(pathRef);\n }\n\n if (rangeRef) {\n rangeRef.unref();\n }\n });\n }",
"removeOverlaps(overlapsOptions) {\n let rectangels = new Map();\n let layout = this.layout;\n let childrenLookup = this.childrenLookup;\n\n this.graph.forEachNode(node => {\n // todo: need to have notion of sizes.\n let pos = layout.getNodePosition(node.id);\n let child = childrenLookup.get(node.id);\n let childWidth = 20;\n let childHeight = 20;\n let dx = 0;\n let dy = 0;\n if (child) {\n let childBBox = child.getBoundingBox();\n childWidth = childBBox.width;\n childHeight = childBBox.height;\n dx = childBBox.cx;\n dy = childBBox.cy;\n }\n\n let rect = new Rect({\n left: dx + pos.x - childWidth / 2,\n top: dy + pos.y - childHeight / 2,\n width: childWidth,\n height: childHeight,\n dx, dy,\n id: node.id\n });\n rectangels.set(node.id, rect);\n })\n removeOverlaps(rectangels, overlapsOptions);\n\n rectangels.forEach(rect => {\n layout.setNodePosition(rect.id, rect.cx - rect.dx, rect.cy - rect.dy);\n });\n normalizePositions(this.graph, this.layout);\n }",
"unsetNodes(editor, props) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!Array.isArray(props)) {\n props = [props];\n }\n\n var obj = {};\n\n for (var key of props) {\n obj[key] = null;\n }\n\n Transforms.setNodes(editor, obj, options);\n }",
"function removeLinesOf(node) {\n let newSplits = [];\n lines.splits.forEach(function(spl) {\n if (spl.o.n != node.n && spl.t.n != node.n) {\n newSplits.push(spl);\n } else {\n //console.log(\"Removed splits: \", spl.o.n, \" \", spl.t.n);\n }\n });\n lines.splits = newSplits;\n\n let newMerges = [];\n lines.merges.forEach(function(mrg) {\n if (mrg.o.n != node.n && mrg.t.n != node.n) {\n newMerges.push(mrg);\n } else {\n //console.log(\"Removed merges: \", mrg.o.n, \" \", mrg.t.n);\n }\n });\n lines.merges = newMerges;\n\n let newRenames = [];\n lines.renames.forEach(function(rnm) {\n if (rnm.o.n != node.n && rnm.t.n != node.n) {\n newRenames.push(rnm);\n } else {\n //console.log(\"Removed renames: \", rnm.o.n, \" \", rnm.t.n);\n }\n });\n\n lines.renames = newRenames;\n\n let newEquals = [];\n lines.equals.forEach(function(eql) {\n if (eql.o.n != node.n && eql.t.n != node.n) {\n newEquals.push(eql);\n } else {\n //console.log(\"Removed merges: \", eql.o.n, \" \", eql.t.n);\n }\n });\n lines.equals = newEquals;\n\n let newMoves = [];\n lines.moves.forEach(function(mov) {\n if (mov.o.n != node.n && mov.t.n != node.n) {\n newMoves.push(mov);\n } else {\n //console.log(\"Removed merges: \", mov.o.n, \" \", mov.t.n);\n }\n });\n lines.moves = newMoves;\n\n //console.log(lines);\n}",
"function deleteNode() {\n nodeToDelete = deleteNodeInp.value();\n nodes.splice(nodeToDelete,1);\n numnodes -= 1;\n //nodes.remove[0];\n //numnodes -= 1;\n}",
"function clearChildren() {\n while(board.firstChild) {\n board.removeChild(board.firstChild);\n }\n }",
"pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }",
"assignPosition(node, position) {\n this.spot = Math.max(this.spot, position);\n node.position = position;\n if (node.children.length > 0) {\n this.assignPosition(node.children[0], position);\n }\n for (let i = 1; i < node.children.length; i++) {\n if (this.spot > position) {\n this.assignPosition(node.children[i], this.spot+1);\n } else {\n this.assignPosition(node.children[i], position+1);\n }\n }\n }",
"handleRemoveQuestion(e, position) {\n const newState = {questions: this.state.questions.slice()};\n console.log('Removing question: ',newState.questions[position].text);\n console.log('position removed is ', position);\n newState.questions.splice(position, 1);\n this.setState(newState);\n }",
"dropEmptyBlocks() {\n Object.keys(this.emptyMap).forEach((parentBlockId) => {\n const node = this.emptyMap[parentBlockId];\n if (node.updateReference !== this.updateReference) {\n node.parent.removeChild(node);\n delete this.emptyMap[parentBlockId];\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts the next game in the game sequence | moveToNextGame() {
this._startGame(this._getNextGame());
} | [
"startGame() {\r\n this.generateInitialBoard();\r\n this.printBoard();\r\n this.getMoveInput();\r\n }",
"function startNewGame(){\n\ttoggleNewGameSettings();\n\tnewGame();\n}",
"checkNextGame (){\n\n }",
"function startGame() {\n removeWelcome();\n questionIndex = 0;\n startTimer();\n generateQuestions();\n}",
"function resumeGame() {\n \t\treturn generateGameLoop();\n \t}",
"function startGame() {\n createButtons();\n createCards();\n displayCards();\n}",
"function startGame() {\n removeWelcomePage();\n createGamePage();\n createCards();\n}",
"function startGame() {\n initialise();\n setInterval(timer, 10);\n}",
"function startGameMinimax(){\r\n isMinimax = true;\r\n startGame();\r\n}",
"function startGame()\n{\n if(mediaCount.image == 0 && mediaCount.audio==0 && canStart==1)\n {\n //Initiate the game\n gameRestart();//initiate the game\n\n //Start the game\n gameLoop();//this sets automatically the game looping\n //var interval = setInterval(gameLoop, 30); //runs gameLoop ciclicly\n }\n else\n {\n console.log(\"Wait for \" + (canStart==1?\"media\":\"Main\") );\n }\n}",
"start() {\n \n //Start the game loop\n this.gameLoop();\n }",
"startGame() {\n let self = this\n this.props.changeSetupConfigClass(\"setupconfig__holder setupconfig__holder__deactive\")\n setTimeout(()=>{\n self.props.changeResetCoords(true)\n self.props.changeMarkerCoords([0,0])\n self.props.changeResetCoords(false)\n self.props.changeActiveHandler(this.props.game.id, false, true)\n self.props.changeActiveState(this.props.game.id, true)\n }, 1600)\n }",
"function startGame() {\n questionCounter = 0;\n score = 0;\n availableQuestions = [...questions];\n getNewQuestion();\n}",
"function startGame() {\n getDifficulty();\n startTimer();\n addCards();\n $(\"refresh\").addEventListener(\"click\", addCards);\n toggleGame();\n currSetCount = 0;\n $(\"set-count\").innerHTML = currSetCount;\n deselectAll();\n }",
"function startNewGame() {\n audioGame.pause();\n audioGame.currentTime = 0;\n document.getElementById(\"pacman_life1\").style.display = \"block\";\n document.getElementById(\"pacman_life2\").style.display = \"block\";\n document.getElementById(\"pacman_life3\").style.display = \"block\";\n clearAllInterval();\n Start(globalNumberOfBall, globalNumberOfGhost);\n}",
"function animateGame(){\n var i = 0;\n var intervalId = setInterval(function() {\n if(i >= sequenceArray.length) {\n clearInterval(intervalId);\n }\n animate(i);\n i++;\n }, 800);\n }",
"function start(){\n\n // this is the real number of players updated\n updateNumberOfPlayers();\n\n plEvenOdd = numberOfPlayers;\n\n plEvenOdd % 2 !== 0 ? ++numberOfPlayers : numberOfPlayers;\n\n plEvenOdd % 2 == 0 ? updateTotalRounds() : updateTotalRoundsOdd();\n\n // update totalRounds\n // updateTotalRounds();\n\n // change classes to display screen 3\n screen3(); \n\n\n plEvenOdd % 2 == 0 ? getNames() : getNamesOdd();\n\n // get the player names\n // getNames();\n // put all the names inside position array\n // getPosition(); ******************ready to delete*****************\n\n\n\n \n\n plEvenOdd % 2 == 0 ? makeCouple() : makeCoupleOdd();\n\n // create couples based on player position\n // makeCouple();\n\n // diplay round\n displayRound();\n\n \n // update the current round\n updateCurrentRound();\n\n plEvenOdd % 2 == 0 ? displayCouples() : displayCouplesOdd();\n\n // display couple + passes input\n // displayCouples(); \n}",
"function runSequence(playNum) {\n let squares = $(\"div\").find(\".box\");\n playNum--;\n if (playNum < 0) {\n inPlay = true;\n return;\n }else {\n\n let randomNum = Math.floor(Math.random() * gameColors.length);\n gameClicks.push(gameColors[randomNum]);\n squares[randomNum].style.opacity = \"1\";\n setTimeout(function () {\n squares[randomNum].style.opacity = \"0.5\";\n setTimeout(function () {\n runSequence(playNum);\n }, 100)\n }, 500);\n }\n}",
"goNextScene() {\r\n this.scene.launch(this.nextScene).launch();\r\n this.scene.stop(this.scene.key);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
utilized ideas from here: and here: returns true if css is disabled in users browsers else returns false | function disabledCssCheck() {
// check color style of 'cssCheck' div tag (should be set to red)
if(window.getComputedStyle(document.getElementById("cssCheck"), null)["color"] == "rgb(255, 39, 39)" ||
window.getComputedStyle(document.getElementById("cssCheck"), null)["color"] == "rgb(255, 0, 0)"){
return true;
}
return false;
} | [
"function isCssLoaded(name) {\n\n for (var i = 0; i < document.styleSheets.length; ++i) {\n\n var styleSheet = document.styleSheets[i];\n\n if (styleSheet.href && styleSheet.href.indexOf(name) > -1)\n return true;\n }\n ;\n\n return false;\n }",
"function isGecko() {\n\t\tconst w = window\n\t\t// Based on research in September 2020\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'buildID' in navigator,\n\t\t\t\t'MozAppearance' in (document.documentElement?.style ?? {}),\n\t\t\t\t'onmozfullscreenchange' in w,\n\t\t\t\t'mozInnerScreenX' in w,\n\t\t\t\t'CSSMozDocumentRule' in w,\n\t\t\t\t'CanvasCaptureMediaStream' in w,\n\t\t\t]) >= 4\n\t\t)\n\t}",
"function isCookieLockEnabled() {\n return isChromium();\n}",
"static get offline_enabled() {\n if (!PageCache.enabled) return false;\n\n // disable offline in production for now\n // if location.hostname =~ /^whimsy.*\\.apache\\.org$/\n // return false unless location.hostname.include? '-test'\n // end\n return true\n }",
"function CSSExists() {\n return fs.existsSync(testCSSPath);\n}",
"function hasCSSImport(files) {\n for (const file of files) {\n const code = fs.readFileSync(file, 'utf-8');\n const [imports] = parse(code);\n for (const {s, e} of imports.filter(({d}) => d === -1)) {\n const spec = code.substring(s, e);\n if (spec.endsWith('.css.proxy.js')) return true; // exit as soon as we find one\n }\n }\n return false;\n}",
"function getActiveStyleSheet() {\n var i, a;\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\") && !a.disabled) return a.getAttribute(\"title\");\n }\n return null;\n}",
"function checkOptions()\n{\n var c, t;\n\n for (c of document.body.classList)\n if (c === 'noclick')\n noclick = true;\n else if ((t = c.match(/^hidemouse(=([0-9.]+))?$/)))\n hideMouseTime = 1000 * (t[2] ?? 5); // Default is 5s if no time given\n}",
"isNodeLocked(node) {\n return node.el.matches('[aria-disabled=\"true\"], [aria-disabled=\"true\"] *');\n }",
"function isEnabled() {\n return tray != undefined;\n}",
"function isEmulatingIE7() {\n var metaTags = document.getElementsByTagName(\"meta\"),\n content,\n i;\n for (i = 0; i < metaTags.length; i = i + 1) {\n content = metaTags[i].getAttribute(\"content\");\n if (content !== null && metaTags[i].getAttribute(\"http-equiv\") === \"X-UA-Compatible\" && (content.indexOf(\"IE=EmulateIE7\") > -1 || content.indexOf(\"IE=7\") > -1)) {\n return true;\n }\n }\n return false;\n }",
"is_edge_or_ie() {\n\t\t//ie11\n\t\tif( !(window.ActiveXObject) && \"ActiveXObject\" in window )\n\t\t\treturn true;\n\t\t//edge\n\t\tif( navigator.userAgent.indexOf('Edge/') != -1 )\n\t\t\treturn true;\n\t\treturn false;\n\t}",
"function testBackgroundPage() {\n if (TARGET === \"firefox\" || TARGET === \"chrome\") {\n return backgroundPage.bg.test();\n } else {\n return false;\n }\n}",
"function isEdgeHTML() {\n\t\t// Based on research in October 2020\n\t\tconst w = window\n\t\tconst n = navigator\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'msWriteProfilerMark' in w,\n\t\t\t\t'MSStream' in w,\n\t\t\t\t'msLaunchUri' in n,\n\t\t\t\t'msSaveBlob' in n,\n\t\t\t]) >= 3 && !isTrident()\n\t\t)\n\t}",
"function elementIsFocusable(elem)\n{\n while ( elem != null )\n {\n var visibility = getCascadedStyle(elem, \"visibility\", \"visibility\");\n var display = getCascadedStyle(elem, \"display\", \"display\");\n if ( display == 'none' || visibility == 'hidden' || visibility == 'hide' )\n return false;\n elem = elem.parentNode;\n }\n return true;\n}",
"function isStylesheet(link) {\n return stylesheet.test($(link).attr(\"rel\"));\n}",
"function isPageStyle(link) {\n return isStylesheet(link) && $(link).attr(\"title\");\n}",
"function lookForPrivateUseUnicode(element) {\n return (hasPrivateUseUnicode(\"before\") || hasPrivateUseUnicode(\"after\"));\n\n function hasPrivateUseUnicode(psuedo) {\n var content = (oldIE) ? \"\" : window.getComputedStyle(element, \":\" + psuedo).content;\n if (content !== \"none\" && content !== \"normal\" && content !== \"counter\" && content !== \"\\\"\\\"\") {//content is not none or empty string\n var unicode;\n //starts at 1 and end at length-1 to ignore the starting and ending double quotes\n for (var i = 1; i < content.length - 1; i++) {\n unicode = content.charCodeAt(i);\n if (unicode >= 57344 && unicode <= 63743) {\n //unicode is in the private use range\n return true;\n }\n }\n }\n return false;\n }\n }",
"isEnabled() {\n //Override.\n return $gameMessage.currentWindow === this.SETTINGS.UNIQUE_ID;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clears the save timer that tracks when to update google drive | function clearSaveTimer()
{
if (UpdateTimeOut)
{
window.clearTimeout(UpdateTimeOut);
UpdateTimeOut = null;
}
} | [
"function deleteTimeDetails() {\n let timeDetails = myStorage.timeDetails;\n timeDetails = null;\n myStorage.timeDetails = timeDetails;\n myStorage.sync();\n}",
"clear() {\n\t\tthis.watchList.forEach((item) => this.remove(item.uri));\n\t\tthis.watchList = [];\n\n\t\tchannel.appendLocalisedInfo('cleared_all_watchers');\n\t\tthis._updateStatus();\n\t}",
"function clearText() {\n browser.storage.local.clear();\n window.location.reload();\n}",
"clear() {\n this._storage.clear();\n this._allDependenciesChanged();\n this._updateLength();\n }",
"function clearSavedState()\n{\n localStorage.clear(); // nuclear option\n console.info(\"All saved states have been cleared.\");\n}",
"function dwscripts_clearDocEdits()\n{\n docEdits.clearAll();\n}",
"function clear() {\n localStorage.clear();\n location.reload();\n}",
"reset () {\n this.total = this.seconds * 1000.0;\n this._remaining = this.total;\n this._clearInterval();\n this.tick();\n }",
"function DriveStop() {\n wheels.both.stop();\n driveCmds = {};\n cmdCount = 0;\n}",
"clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}",
"function resetRunningServant(caseID) {\n delete localStorage['smaAnalyticsCase' + caseID];\n}",
"deleteTasks(){\n\t\tlocalStorage.clear();\n\t}",
"save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }",
"function 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}",
"static async clearCurrentWallpaper() {\n let { cacheFiles = [], index } = await fs.readJSON(_cache);\n\n try {\n if (index === 0) {\n return Util.logWarning(\n \"Cannot clear the currently used wallpaper cause you have no more wallpaper cached\"\n );\n }\n\n await fs.unlink(cacheFiles[index].path);\n cacheFiles.splice(index, 1);\n\n await fs.writeJSON(_cache, {\n index: index - 1,\n cacheFiles\n });\n\n await wallpaper.set(cacheFiles[index - 1].path);\n\n Util.logSuccess(\"Cleared the currently used wallpaper\");\n } catch (error) {\n Util.logError(error.message);\n }\n }",
"function clearNotes() {\n clear: localStorage.clear();\n}",
"resetCount() {\n this.lastTicket = 0;\n this.tickets = [];\n this.lastFour = [];\n\n this.saveData();\n console.log('Reset Days and Last tiket on server');\n }",
"function revokeWaitingGIF() {\n//\tRichfaces.hideModalPanel('loadingPanel');\n//\tdocument.body.style.cursor = 'default';\n\trevokeWaitingGIfForSave();\n}",
"function autosaveThread(mode) {\n\t// Start/restart the wait.\n\tif (mode === 'start') {\n\t\tclearInterval(autosaveTimer);\n\t\tautosaveTimer = setInterval(function(){ autosaveNotepad(); }, AUTOSAVE_SECONDS * 1000);\n\t}\n\t// Destroy the event.\n\telse if (mode === 'stop') {\n\t\tclearInterval(autosaveTimer);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : enableSelection AUTHOR : Juvindle C Tina DATE : March 26, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : enable/disable selection session type PARAMETERS : src,deviceresid | function enableSelection(src,deviceresid){
if(src != ""){
var cnt2 = 0;
var cnt = 0;
$('.openSelectedDevice').each(function(){
var did = $(this).attr('did');
if($(this).is(':checked')){
cnt++;
$('#open_'+did).removeAttr("disabled");
}else{
$('#open_'+did).attr("disabled",true);
}
cnt2++;
});
if(cnt == cnt2 && cnt != 0){
$('#selectAllConsole').prop('checked',true);
}else{
$('#selectAllConsole').prop('checked',false);
}
}
} | [
"function LoadSaveOption(source,opt,opt2,from) {\n if (source.checked == true) {\n $('input[name=\"'+opt2+from+'Sel\"]').each(function() {\n $(this).prop('checked',true);\n $(this).parent().parent().addClass('highlight');\n var dev = $(this).val();\n enableRow1(opt2+from,dev);\n });\n } else {\n $('input[name=\"'+opt2+from+'Sel\"]').each(function() {\n $(this).parent().parent().removeClass('highlight');\n $(this).prop('checked',false);\n var dev = $(this).val();\n enableRow1(opt2+from,dev);\n });\n }\n}",
"enable() {\n this._enabled = true;\n this._model = new SelectionModel(this._bufferService);\n }",
"function setSelectStatus(status){\n var algorithmSelectBox = document.getElementById(\"algorithm-selection\");\n var speedSelectBox = document.getElementById(\"speed-selection\");\n\n if(status == 1){ //ENABLED\n algorithmSelectBox.disabled = false;\n speedSelectBox.disabled = false;\n }\n else if(status == 0){ //DISABLED\n algorithmSelectBox.disabled = true;\n speedSelectBox.disabled = true;\n }\n}",
"function initSelection() {\n canvas.on({\n \"selection:created\": function __listenersSelectionCreated() {\n global.console.log(\"**** selection:created\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n \"before:selection:cleared\": function __listenersBeforeSelectionCleared() {\n global.console.log(\"**** before:selection:cleared\");\n },\n \"selection:cleared\": function __listenersSelectionCleared() {\n global.console.log(\"**** selection:cleared\");\n toolbar.hideActiveTools();\n },\n \"selection:updated\": function __listenersSelectionUpdated() {\n global.console.log(\"**** selection:updated\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n });\n}",
"function clickDeviceType(val){\n\tgetMapPartnerPortInfo();\n\tnewDeviceAvailableDom();\n\tnewDevAttribute();\n\tvar itm = [\"newdevmanufacturer\",\"newdevoperatingsystem\",\"newdevdescription\",\"newdevmanagementip\",\"newdevmanageinterface\",\"newdevconsoleip\",\"newdevauxiliary\"]\n\tif(val!=\"Select\") {\n\t\tif(globalDeviceType==\"Mobile\"){\t\n\t\t\tfor(var i=0; i<itm.length;i++){\n\t\t\t\t$(\"#\"+itm[i]).textinput(\"enable\");\t\n\t\t\t}\t\n\t\t\t$(\"#newdevproductfamily\").textinput(\"enable\");\t\n\t\t\t$(\"#newdevmodel\").textinput(\"enable\");\t\n\t\t\t\n\t\t}else{\n\t\t\t$(\"#newdevmanufacturer\").removeAttr('disabled');\n\t\t\t$(\"#newdevmanufacturer1\").removeAttr('disabled');\n\t\t\t$(\"#newdevoperatingsystem1\").removeAttr('disabled');\n\t\t\t$(\"#newdevproductfamily1\").removeAttr('disabled');\n\t\t\t$(\"#newdevmodel1\").removeAttr('disabled');\n\t\t\t$(\"#newdevmanufacturer\").removeAttr('disabled');\n\t\t\t$(\"#newdevoperatingsystem\").removeAttr('disabled');\n\t\t\t$(\"#newdevproductfamily\").removeAttr('disabled');\n\t\t\t$(\"#newdevmodel\").removeAttr('disabled');\n\t\t\t$(\"#newdevdescription\").removeAttr('disabled');\n\t\t\t//$(\"#dropdownstruction\").removeAttr('disabled');\n\t\t\t$(\"#newdevmanagementip\").removeAttr('disabled');\n\t\t\t$(\"#newdevmanageinterface\").removeAttr('disabled');\n\t\t\t$(\"#newdevconsoleip\").removeAttr('disabled');\n\t\t\t$(\"#newdevauxiliary\").removeAttr('disabled');\n\t\t}\n\t}else{\n\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\tfor(var i=0; i<itm.length;i++){\n\t\t\t\t$(\"#\"+itm[i]).textinput(\"disable\");\n\t\t\t}\n\t\t\t$(\"#newdevproductfamily\").textinput(\"disabl\");\n\t\t\t$(\"#newdevmodel\").textinput(\"disabl\");\n\t\t}else{\n\t\t\t$(\"#lablemanufacturer\").attr('onclick',true);\n\t\t\t$(\"#libeloperatingsystem\").attr('onclick',true);\n\t\t\t$(\"#labelproductfamily\").attr('onclick',true);\n\t\t\t$(\"#labelmodel\").attr('onclick',true);\n\t\t\t$(\"#newdevmanufacturer1\").attr('disabled',true);\n\t\t\t$(\"#newdevoperatingsystem1\").attr('disabled',true);\n\t\t\t$(\"#newdevproductfamily1\").attr('disabled',true);\n\t\t\t$(\"#newdevmodel1\").attr('disabled',true);\n\t\t\t$(\"#newdevmanufacturer\").attr('disabled',true);\n\t\t\t$(\"#newdevoperatingsystem\").attr('disabled',true);\n\t\t\t$(\"#newdevproductfamily\").attr('disabled',true);\n\t\t\t$(\"#newdevmodel\").attr('disabled',true);\n\t\t\t$(\"#newdevdescription\").attr('disabled',true);\n\t\t\t//$(\"#dropdownstruction\").attr('disabled',true);\n\t\t\t$(\"#newdevmanagementip\").attr('disabled',true);\n\t\t\t$(\"#newdevconsoleip\").attr('disabled',true);\n\t\t\t$(\"#newdevauxiliary\").attr('disabled',true);\n\t\t\t$(\"#newdevportcheckbox\").attr('disabled',true);\n\t\t\t$(\"#newdevportaddress\").attr('disabled',true);\n\t\t\t$(\"#newdevusername\").attr('disabled',true);\n\t\t\t$(\"#newdevpassword\").attr('disabled',true);\n\t\t\t$(\"#newdevmanageinterface\").attr('disabled',true);\n\t\t}\n\t}\n}",
"function sel_change(v, check, F, objs) {\n if (v == check) {\n sel_enable_objs(F, objs);\n } else {\n sel_disable_objs(F, objs);\n }\n}",
"function setSelectMode() {\n mode = modes.SELECT\n GameScene.setRegionSelectPlaneVis(true)\n }",
"function check_selection(){\n\n console.log(\"here\")\n\n var slected = $('#TradingStrategiesList').find('.selected');\n console.log(slected.length)\n if(slected.length!==0){ // Which strategy was originally selected\n\n $(\"#editStrategy\").prop(\"disabled\",false)\n }\n}",
"function enableList(argValue)\n{\n if(argValue==\"Subscriber(s)\")\n {\n document.getElementById('frmSubscriberList[]').disabled=false;\t\n }\n else\n {\n document.getElementById('frmSubscriberList[]').disabled=true;\n }\n}",
"function showDevicetoSelect(devicesArr,myArray){\n\tvalidDevices = devicesArr;\n\tvalidSessionDevices = myArray;\n\t$( \"#openConsoleSelect\" ).dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"60%\",\n\t\theight: \"auto\"\n\t});\n\t$( \"#openConsoleSelect\" ).dialog(\"open\");\n\t$( \"#openConsoleSelect\" ).empty().load('pages/ConfigEditor/selectOpenConsole.html',function(){\n\t\t$('span.ui-dialog-title').text('Open Console');\n\t\t$('.ui-dialog-title').css({'margin-left':'14px','margin-top':'7px','text-align':'center'});\n\t\t$('#showOpenconsoleDiv div[role=\"dialog\"]').css({\"max-width\":\"80%\"});\n\t\tvar str = \"\";\n\t\tfor(var t=0; t<devicesArr.length ; t++){\n\t\t\tvar mgtip = devicesArr[t].ManagementIp;\n\t\t\tvar conIp = devicesArr[t].ConsoleIp;\n\t\t\tvar model = devicesArr[t].Model;\n\t\t\tvar devname = devicesArr[t].DeviceName;\n\t\t\tvar devresid = devicesArr[t].DeviceResId;\n\t\t\tif(devname != \"\"){\n\t\t\t\tif(devicesArr.length == 1){\n\t\t\t\t\tstr += \"<tr><td class='defaultGrid'><input class='openSelectedDevice' type='checkbox' checked='true' did='\"+devresid+\"' onclick='enableSelection(this,\\\"\"+devresid+\"\\\");' did='\"+devresid+\"'/></td>\";\n\t\t\t\t}else{\n\t\t\t\t\tstr += \"<tr><td class='defaultGrid'><input class='openSelectedDevice' type='checkbox' did='\"+devresid+\"' onclick='enableSelection(this,\\\"\"+devresid+\"\\\");' did='\"+devresid+\"'/></td>\";\n\t\t\t\t}\n\t\t\t\tstr += \"<td class='defaultGrid'>\"+devname+\"</td>\";\n\t\t\t\tstr += \"<td class='defaultGrid'>\"+mgtip+\"</td>\";\n\t\t\t\tstr += \"<td class='defaultGrid'>\"+conIp+\"</td>\";\n\t\t\t\tstr += \"<td class='defaultGrid'>\"+model+\"</td>\";\n\t\t\t\tstr += \"<td class='defaultGrid' style='width:20%'>\";\n\t\t\t\tif(devicesArr.length == 1){\n\t\t\t\t\tstr += \"<select id='open_\"+devresid+\"'>\";\n\t\t\t\t}else{\n\t\t\t\t\tstr += \"<select id='open_\"+devresid+\"' disabled>\";\n\t\t\t\t}\n\t\t\t\tstr += \"<option value='Telnet'> Telnet </option>\";\n\t\t\t\tstr += \"<option value='SSH'> SSH </option>\";\n\t\t\t\tstr += \"<option value='SSL'> SSL </option></select></td></tr>\";\n\t\t\t}\t\n\t\t}\n\t\t$('.openSelectedDevice').trigger('click');\n\t\t$('#selectAllConsole').trigger('click');\n\t\tif(devicesArr.length == 1){\n \t$(\"#selectAllConsole\").attr(\"checked\",true);\n\t\t}else{\n \t$(\"#selectAllConsole\").attr(\"checked\",false);\n\t\t}\n\t\t$('#showOpenconsoleTable > tbody').empty().append(str)\n\t\tsetTimeout(function(){\n\t\t\tenableSelection(\"\",\"\");\n\t\t},500);\n\t});\n}",
"function isSelectID(choice, productsArr) {\n if (choice == \"Add to Inventory\") {\n selectID(productsArr);\n } else {\n quitOrNot();\n }\n}",
"function selectdevicestructure(val){\n\t$(\"#portperdevice\").val(\"\");\n\t$('#devicetypetabs').empty();\n\t$(\"#devportphysicalporttype\").css(\"display\",\"none\");\n\t$('#physicalporttypespan').css(\"display\",\"none\");\n\t$(\"#dropdownphysicalporttype\").css(\"display\",\"none\");\n\t$(\"#pagenumber\").css(\"display\",\"none\");\n\t$(\"#newdevapplyalltxt\").css(\"display\",\"none\");\n\tif(val==\"devport\"){\n\t\t$('#physicalporttypespan').css(\"display\",\"inline\");\n\t\t$(\"#devportphysicalporttype\").css(\"display\",\"inline\");\n\t\t$(\"#dropdownphysicalporttype\").css(\"display\",\"inline\");\n\t\t//$(\"#pagenumber\").css(\"display\",\"inline\");\n\t\t$(\"#newdevapplyalltxt\").css(\"display\",\"inline\");\n\t\t$(\"#structuredice\").text(\"Port per Device\");\n\t}else if(val==\"devslotport\"){\n\t\t$(\"#structuredice\").text(\"Slot per Device\");\n\t}else if(val==\"devmodport\"){\n\t\t$(\"#structuredice\").text(\"Module per Device\");\n\t}else if(val==\"devslotmod\"){\n\t\t$(\"#structuredice\").text(\"Slot per Device\");\n\t}else{\n\t\t$(\"#structuredice\").text(\"Rack per Device\");\n\t}\n\t//portdynamictab(0);\n\t//deviceStructureDynamicTab(0);\n}",
"function onSelectStart(event){\n\n if (event instanceof MouseEvent && !renderer.xr.isPresenting()){\n\t// Handle mouse click outside of VR.\n\n\t// Determine screen coordinates of click.\n\tvar mouse = new THREE.Vector2();\n\tmouse.x = (event.clientX / window.innerWidth) * 2 - 1;\n\tmouse.y = - (event.clientY / window.innerHeight) * 2 + 1;\n\t// Create raycaster from the camera through the click into the scene.\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.setFromCamera(mouse, camera);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n\n } else if (!(event instanceof MouseEvent) && renderer.xr.isPresenting()){\n\t// Handle controller click in VR.\n\n\t// Bug workaround, Oculus Go browser doubles onSelectStart\n\t// event.\n\tif (navigator.platform == \"Linux armv8l\"){\n\t if (oculus_double_click_skip){\n\t\tconsole.log(\"SKIPPING\");\n\t\toculus_double_click_skip = false;\n\t\treturn;\n\t }\n\t oculus_double_click_skip = true;\n\t}\n\n\t// Retrieve the pointer object.\n\tvar controller = event.target;\n\tvar controllerPointer = controller.getObjectByName('pointer');\n\n\t// Create raycaster from the controller position along the\n\t// pointer line.\n\tvar tempMatrix = new THREE.Matrix4();\n\ttempMatrix.identity().extractRotation(controller.matrixWorld);\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);\n\traycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n\n\t//DEBUG.displaySession(renderer.xr);\n\t//DEBUG.displaySources(renderer.xr);\n\t//DEBUG.displayNavigator(navigator);\n\n }\n}",
"function educatorSelected() {\n userType = \"educator\";\n sessionStorage.setItem(\"selection\", JSON.stringify({ \"studentRadio\": \"unchecked\" }));\n showKeyElements();\n}",
"enableSelectingChooser(shouldEnable) {\n this.chooserButton.enable(shouldEnable);\n }",
"function enable_vat () {\n $('#no_Vat').prop({'checked': 'false'});\n $('#with_Vat').prop({'checked': 'true'});\n $('#sid-with-Vat').prop({'checked': 'true'});\n $('.vatControl.add').addClass('active');\n $('.select-vat, .billing-profile-vat').removeClass('hide');\n // Andreas 20/06/2019\n $('.shared-hosting-plans .vatControlsTrigger').text(COMMON_LANG.VAT.DISCLAIMER.VAT_ON_2);\n // Andreas end\n }",
"function getAutoDSelectedPartnerAdd(opt,type){\n var optAdd = \"<option value=''>Select</option>\";\n switch(opt) {\n case \"Select\":\n if(type==\"device\"){\n $('#autoDPartnerInfoTable > tbody').empty();\n $('#autoDPartnerInfoTableCont').hide();\n $('#autoDPartInfo1').hide();\n \t\t$('#newDevPartnerDevModel').empty().append(\"<input id='newDevPartnerDevModelS' type='text' value='' disabled='disabled'/>\");\n\t\t\t\t$('#newDevPartnerDevHost').empty().append(\"<input id='newDevPartnerDevHostS' type='text' value='' disabled='disabled'/>\");\n\t\t\t\t$('#newDevPartnerDevManu').empty().append(\"<input id='newDevPartnerDevManuS' type='text' value='' disabled='disabled'/>\");\n $('#autoDPartInfo2').hide();\n\t\t\t\t$(\"#autoDPartAddOpt > option:contains('Select')\").prop('selected',true);\n $('#autoDOptIncMappChk').hide();\n $('#autoDPartPortsSrchLblCont').hide();\n $('#autoDDevSlotsIncCont').hide();\n $('#autoDDevSlotsIncCountCont').hide()\n\t\t\t\t$('#autoDDevSlotInfoTableCont').hide();\n\t\t\t\t$('#autoDDevSlotInfoTbody').empty();\n\t\t\t\t$('#autoDDevSlotsIncCount').val('');\n\t\t\t\t$('#autoDDevSlotsIncChk').prop('checked',false);\n\t\t\t\t$('#addNewDevAuxIpTR').hide();\n\n }else if(type==\"testtool\"){\n $('#autoDTestTPartnerInfoTable > tbody').empty();\n $('#autoDTestTPartnerInfoTableCont').hide();\n $('#autoDTestTPartInfo1').hide();\n\t\t $('#newTestTPartnerDevHost').empty().append(\"<input id='newTestTPartnerDevHostS' type='text' value='' disabled='disabled'/>\");\n \t \t$('#newTestTPartnerDevManu').empty().append(\"<input id='newTestTPartnerDevManuS' type='text' value='' disabled='disabled'/>\");\n \t \t$('#newTestTPartnerDevModel').empty().append(\"<input id='newTestTPartnerDevModelS' type='text' value='' disabled='disabled'/>\");\n $('#autoDTestTPartInfo2').hide();\n $('#autoDTestTPartAddOpt-button > span').empty().append(\"Select\");\n $('#autoDTestTOptIncMappChk').hide();\n $('#autoDTestTPartPortsSrchLblCont').hide();\n $('#autoDTestTSlotsIncCont').hide();\n $('#autoDTestTSlotsIncCountCont').hide();\n\t\t\t\t$('#autoDTestTSlotInfoTableCont').hide();\n\t\t\t\t$('#autoDTestTSlotInfoTbody').empty();\n\t\t\t\t$('#autoDTestTSlotsIncChk').prop('checked',false);\n\t\t\t\t$('#autoDTestTSlotsIncCount').val(\"\");\n\t\t }\n break;\n case \"Networking Device\":\n var dataS = autoDDevLists[0].NetworkingDevices;\n for(var i=0; i<dataS.length; i++){\n optAdd += dataS[i].opt;\n }\n\t\t break;\n case \"L1 Switch\":\n var dataS = autoDDevLists[0].L1Switch;\n for(var i=0; i<dataS.length; i++){\n optAdd += dataS[i].opt;\n }\n\t\t break;\n case \"L2 Switch\":\n var dataS = autoDDevLists[0].L2Switch;\n for(var i=0; i<dataS.length; i++){\n optAdd += dataS[i].opt;\n }\n\t\t break;\n }\n if(type==\"device\"){$('#autoDPartAddOpt').empty().append(optAdd);}\n if(type==\"testtool\"){$('#autoDTestTPartAddOpt').empty().append(optAdd);}\n\tif(type==\"admin\"){$('#partipadd').empty().append(optAdd);}\n\n}",
"function enableIntInit(){\n\tvar enableStat='';\n\tvar enableSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n \t var devices = getDevicesNodeJSON();\n }else{\n\t var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tenableStat+=\"<tr>\";\n\t\tenableStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tenableStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"<td>Init</td>\";\n\t\tenableStat+=\"</tr>\";\n\t}\n//2nd Table of Device Sanity\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n var allline =[];\n for(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n allline = gettargetmap(devices[i].ObjectPath,allline);\n }\n for(var t=0; t<allline.length; t++){\n\t\tenableSanityStat+=\"<tr>\";\n var source = allline[t].Source;\n var destination = allline[t].Destination;\n var srcArr = source.split(\".\");\n var srcObj = getDeviceObject2(srcArr[0]);\n var dstArr = destination.split(\".\");\n var dstObj = getDeviceObject2(dstArr[0]);\n var portobject = getPortObject2(source);\n var portobject2 = getPortObject2(destination);\n if(portobject.SwitchInfo != \"\" && portobject2.SwitchInfo != \"\"){\t\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td>\"+srcObj.DeviceName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+portobject.PortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td>\"+dstObj.DeviceName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td>\"+portobject2.PortName+\"</td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\tenableSanityStat+=\"<td></td>\";\n\t\t\t\t\n\t\t}\n\t\tenableSanityStat+=\"</tr>\";\n\t}\n\t$(\"#enaSanityTableStat > tbody\").empty().append(enableSanityStat);\n\t$(\"#enaSanityTable > tbody\").empty().append(enableStat);\t\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#enableTotalNo').empty().append(devices.length);\n\tif(globalDeviceType==\"Mobile\"){\n\t\t$(\"#enaSanityTableStat\").table(\"refresh\");\n\t\t$(\"#enaSanityTable\").table(\"refresh\");\n\t}\n}",
"function selectDataforOpenConsole(id){\n\tvar linkArray = new Array();\n\t$('.openSelectedDevice').each(function(){\n\t\tif($(this).is(':checked')){\n\t\t\tvar did = $(this).attr('did');\n\t\t\tvar id = $(this).attr('did') + \"::\" + $('#open_'+did).val();\n\t\t\tlinkArray.push(id);\n\t\t}\n\t});\n\tif(linkArray.length == 0){\n\t\talerts(\"Please select one entry.\");\n\t\treturn;\n\t}\n\tvar mayArray = new Array();\n\tfor(var f=0; f<validSessionDevices.length; f++){\n\t\tvar flag = false;\n\t\tfor(var t=0; t<linkArray.length; t++){\n\t\t\tvar mydata = linkArray[t].split(\"::\");\n\t\t\tif(mydata[0] == validSessionDevices[f].DeviceId){\n\t\t\t\tvalidSessionDevices[f].Type = mydata[1];\n\t\t\t\tflag = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(flag){\n\t\t\tmayArray.push(validSessionDevices[f]);\n\t\t}\n\t}\n\tvar mayArray2 = new Array();\n\tfor(var f=0; f<validDevices.length; f++){\n\t\tvar flag = false;\n\t\tfor(var t=0; t<linkArray.length; t++){\n\t\t\tvar mydata = linkArray[t].split(\"::\");\n\t\t\tif(mydata[0] == validDevices[f].DeviceId){\n\t\t\t\tflag = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(flag){\n\t\t\tmayArray2.push(validDevices[f]);\n\t\t}\n\t}\n\t$('#'+id).empty();\n\tcloseDialog(id);\n\tloadOpenConsole(mayArray,mayArray2);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve all the model instances, paginated | getAll(req, res, next) {
var
request = new Request(req),
response = new Response(request, this.expandsURLMap),
criteria = this._buildCriteria(request);
this.Model.paginate(criteria, request.options, function(err, paginatedResults, pageCount, itemCount) {
/* istanbul ignore next */
if (err) { return next(err); }
response
.setPaginationParams(pageCount, itemCount)
.formatOutput(paginatedResults, function(err, output) {
/* istanbul ignore next */
if (err) { return next(err); }
res.json(output);
});
});
} | [
"paginate({ unlimited = false } = {}) {\r\n const { page: qPage, limit: qLimit, skip: qskip } = this.queryObj;\r\n\r\n const page = qPage * 1 || 1;\r\n let limit = unlimited ? undefined : defaultRecordPerQuery;\r\n if (qLimit)\r\n limit = qLimit * 1 > maxRecordsPerQuery ? maxRecordsPerQuery : qLimit * 1;\r\n const skip = qskip\r\n ? qskip * 1\r\n : (page - 1) * (limit || defaultRecordPerQuery);\r\n\r\n this.query.skip = skip;\r\n this.query.take = limit;\r\n return this;\r\n }",
"findAll() {\n return new Promise((resolve, reject) => {\n let results = []\n\n base('Recipients')\n .select()\n .eachPage(\n (records, fetchNextPage) => {\n results = [...results, ...records]\n fetchNextPage()\n },\n async (err) => {\n if (err) return reject(err)\n resolve(results)\n }\n )\n })\n }",
"getByPagination(offset, limit, callback){\n this.purchase.findAll({\n include: [\n {model: this.user, attributes: [UserField.fullName.f, UserField.email.f]},\n {model: this.product, attributes: [ProductField.product.f, ProductField.name.f, ProductField.price.f]}\n ],\n offset: parseInt(offset), limit: parseInt(limit)\n })\n .then((item)=>{\n callback(null, item);\n })\n .catch((err)=>{\n callback(err.message, null);\n })\n ;\n }",
"getAllDocuments () {\n return this.getAllModels().map(model => model.document)\n }",
"function showPageObjects() {\n db.allDocs({ include_docs: true, descending: true }, function(err, doc) {\n redrawPageObjectsUI(doc.rows)\n })\n }",
"getPaged() {\n return this.using(PagedItemParser(this))();\n }",
"async readAll (page) {\n try {\n const ENTRIES_PER_PAGE = 20\n\n if (!page) page = 0\n\n // Pull data from MongoDB.\n // Get all entries in the database.\n const data = await this.KeyValue.find({})\n // Sort entries so newest entries show first.\n .sort('-createdAt')\n // Skip to the start of the selected page.\n .skip(page * ENTRIES_PER_PAGE)\n // Only return 20 results.\n .limit(ENTRIES_PER_PAGE)\n\n // console.log('data: ', data)\n\n return data\n } catch (err) {\n console.error('Error in p2wdb.js/readAll()')\n throw err\n }\n }",
"function retreiveArticles(viewsOptions) {\n paginationOptions.pageLast =\n paginationOptions.pageLast === undefined\n ? 0\n : paginationOptions.pageLast;\n\n var defer = $q.defer();\n ViewsResource.retrieve(viewsOptions)\n .then(function(response) {\n console.log(viewsOptions);\n console.log(response);\n // console.clear();\n // console.log(response.data);\n // if (response.data.length != 0) {\n // articles = mergeItems(\n // response.data,\n // articles,\n // undefined,\n // prepareArticle\n // );\n // }\n paginationOptions.maxPage = viewsOptions.page;\n if (response.data.length == 0) {\n viewsOptions.page--;\n paginationOptions.pageLast = viewsOptions.page;\n \n }\n\n var filteredArticles = [];\n var today = new Date();\n for (var i = 0; i < response.data.length; i++) {\n var article = response.data[i];\n var startDate = new Date(article.field_start_date.und[0].value);\n var endDate = new Date(article.field_end_date.und[0].value);\n if (startDate <= today && endDate >= today) {\n filteredArticles.push(article);\n }\n }\n articles = filteredArticles;\n console.log(article, filteredArticles);\n defer.resolve(filteredArticles);\n })\n .catch(function(error) {\n defer.reject(error);\n });\n\n return defer.promise;\n }",
"function fetch() {\n $http.get(resourceUrl + $scope.search + '&maxResults=20&orderBy=newest')\n .success(function(data) {\n $scope.data = data;\n $scope.bookFeed = data.items;\n });\n }",
"async listAll() {\n\t\tlet searchParams = this.type ? { type: this.type } : {};\n\t\tlet records = await StockModel\n\t\t\t.find(searchParams)\n\t\t\t.select({ 'name': 1, 'latest': 1, '_id': 0, 'type': 1 })\n\t\t\t.sort({ 'type': 'asc', 'latest': 'desc' });\n\t\treturn { 'status': 200, records };\n\t}",
"async getListPublished(page) {\n const posts = await Post.query().paginate(page, 10);\n return posts;\n }",
"constructor(collection, itemsPerPage) {\n\n let paginate = function paginate(arr, n) {\n if (arr.length === 0) return [];\n return [].concat([arr.slice(0, n)]).concat(paginate(arr.slice(n), n));\n };\n\n this.collection = collection;\n this.itemsPerPage = itemsPerPage;\n this.paginatedArray = paginate(collection, itemsPerPage);\n }",
"function loadMoreRecords(){\n if(count == 0){\n count++;\n }else{\n getAllVideos(self.videos.length,10);\n }\n }",
"function fetchAll(fetchxml, opt_page) {\n\n // defered object - promise for the \"all\" operation.\n var dfd = $.Deferred(),\n allRecords = [],\n pageNumber = opt_page || 1,\n pagingFetchxml = null;\n\n // execute the fetch an receive the details (paging-cookie..)\n fetchMore(fetchxml, true).then(function (result) {\n\n // add the elements to the collection\n allRecords = allRecords.concat(result.entities);\n\n if (result.moreRecords) {\n\n // increase the page-number\n pageNumber++;\n\n // add page-number & paging-cookie\n pagingFetchxml = injectPagingDetails(fetchxml, pageNumber, result.pagingCookie);\n\n // recursive call\n fetchAll(pagingFetchxml, pageNumber).then(function (collection) {\n\n // add the items to the collection\n allRecords = allRecords.concat(collection);\n\n dfd.resolve(allRecords);\n\n }, dfd.reject);\n }\n else {\n // in case less then 50 records are included in the resul-set\n dfd.resolve(allRecords);\n }\n }, dfd.reject);\n\n return dfd.promise();\n }",
"getItems(offset, limit) {\n if (this.list.length < offset + limit && !this.lastItem) {\n // All the requested items don't exist and it's not the last page either.\n return null;\n }\n\n if (this.lastItem === 'empty') {\n // empty state\n return [];\n }\n\n const result = [];\n let curr;\n for (let i = offset; i < offset + limit; i++) {\n curr = this.items[this.list[i]];\n if (!curr) {\n // There's a gap in the list of items so the items are not there yet.\n return null;\n }\n result.push(curr);\n\n if (this.lastItem === curr[this.key]) {\n // That should be all items in the collection.\n break;\n }\n }\n\n return result;\n }",
"async getPokemons() {\n if (!this.store.list) {\n const count = await this.get('pokemon').then((data) => data.count);\n this.store.list = await this.get('pokemon', { limit: count }).then((data) => data.results);\n }\n }",
"function listAll() {\n $scope.voters = VoterService.listAllVoters();\n }",
"getAllNews() {\n\n this.dataBase.findByIndex(\"/news\", [\"_id\", \"title\", \"attachment\"],\"categoryId\", mvc.routeParams.id).then( data => {\n if (data) {\n let length = data.docs.length;\n this.liftNewsInCategory = data.docs.slice(0, length / 2);\n this.rightNewsInCategory = data.docs.slice(length / 2, length);\n mvc.apply();\n } else {\n this.getAllNews()\n }\n }, () => {\n this.getAllNews();\n });\n\n }",
"function paginateProducts(page) {\n const productsPerPage = 10;\n const offset = productsPerPage * (page -1);\n db('amazong_products')\n .select('product_id', 'name', 'price', 'category')\n .limit(productsPerPage)\n .offset(offset)\n .then(result => { console.log(result); } );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fileInputChanged will read the selected file and attempt to load the configuration settings. All loaded settings will be made visible for inspection by the user. | async fileInputChanged () {
Doc.hide(this.errMsg)
if (!this.fileInput.value) return
const loaded = app().loading(this.form)
const config = await this.fileInput.files[0].text()
if (!config) return
const res = await postJSON('/api/parseconfig', {
configtext: config
})
loaded()
if (!app().checkResponse(res)) {
this.errMsg.textContent = res.msg
Doc.show(this.errMsg)
return
}
if (Object.keys(res.map).length === 0) return
this.dynamicOpts.append(...this.setConfig(res.map))
this.reorder(this.dynamicOpts)
const [loadedOpts, defaultOpts] = [this.loadedSettings.children.length, this.defaultSettings.children.length]
if (loadedOpts === 0) Doc.hide(this.loadedSettings, this.loadedSettingsMsg)
if (defaultOpts === 0) Doc.hide(this.defaultSettings, this.defaultSettingsMsg)
if (loadedOpts + defaultOpts === 0) Doc.hide(this.showOther, this.otherSettings)
} | [
"function inputFileOnChange () {\n $(config.inputfile).on('change', $('body'), function(event) {\n parent = $(this).parent();\n submitForm();\n });\n }",
"function upload_config(){\n\tvar fileInput = document.getElementById('file_upload');\n\tvar file = fileInput.files[0];\n\tconsole.log('processing upload of:' + file.name + ' detected type: ' + file.type);\n\tvar reader = new FileReader();\n\t//define function to run when reader is done loading the file\n\treader.onload = function(e) {\n\t\t//detect the type of file\n\t\tvar textType = /text.*/\n\t\tif(file.type.match(textType) ){\n\t\t\tconsole.log('file type ok ')\n\t\t\tvar uploaded_config = JSON.parse(reader.result)\n\t\t\tpatient_config = uploaded_config.patient_config\n\t\t\tward_config = uploaded_config.ward_config\n\t\t\tsimulation_config = uploaded_config.simulation_config\n\t\t\tinit_user_interface(patient_config, ward_config, 'cy')\n\t\t\t$(\"#change-hospital-modal\").modal('hide')\n\t\t\t//refresh the ward editor\n\t\t\tshow_config('Emergency')\n\t\t\t\n\t\t} else {\n\t\t\talert(\"Error: Not a valid file type.\")\n\t\t}\n\n\t}\n\t\n\t//now load the files\n\treader.readAsText(file);\n}",
"function showCheckConfig(fileName) {\n if (fileName.indexOf(\".default\") != -1) {\n $(\"#checks_description\").html(\"Changing a default configuration file creates a new, non-default configuration file.\");\n } else {\n $(\"#checks_description\").html(\"Edit the configuration file, then save and reload.\");\n }\n\n sendMessage(\"checks/getConfig/\" + fileName, \"\", \"post\",\n function(data, status, xhr) {\n $(\".right\").html('<div id=\"check_input\">' +\n '<div id=\"save_check\">Save</div>' +\n '<div id=\"disable_check\">Disable</div>' +\n '</div>');\n $('#check_input').data('file_name', fileName);\n\n var editor = attachEditor(\"check_input\", data);\n $(\"#save_check\").click(function() { saveCheckSettings(editor); });\n $(\"#disable_check\").click(function() { disableCheckSettings(editor); });\n }, function() {\n $(\"#checks_description\").html(\"An error occurred.\");\n $(\".right\").html(\"\");\n });\n}",
"function showFile(confName){\n\tvar ext = confName.split(\".\")[1];\n\twindow.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSRead, failRead);\n\tfunction gotFSRead(fileSystem) {\n\t\t//alert(\"Pasok sa gotFSRead?\"+fileSystem);\n\t\tfileSystem.root.getFile(confName, null, gotFileEntryRead, failRead);\n\t}\n\n\tfunction gotFileEntryRead(fileEntry) {\n\t\t//alert(\"Pasok sa gotFileEntryRead?\"+fileEntry);\n\t\tfileEntry.file(gotFileRead, failRead);\n\t}\n\n\tfunction gotFileRead(file){\n\t\t//alert(\"Pasok sa gotFileRead?\"+file);\n\t\treadAsText(file);\n\t}\n\n\tfunction readAsText(file) {\n\t\t//alert(\"Pasok sa readAsText?\"+file);\n\t\tvar reader = new FileReader();\n\t\treader.onload = function(e) {\n\t\t\tif(ext == \"xml\"){\n\t\t\t\tgetDataFromXML(reader.result);\n\t\t\t}else if(ext ==\"topo\"){\n\t\t\t\tconvertTopoToXml(confName);\n\t\t\t}else if(ext == \"titan\"){\n\t\t\t\tsaveTitanToHome(confName,\"load\");\n\t\t\t\ttitanVar = reader.result;\n\t\t\t}\n\t\t\t//loading('hide');\n\t\t\t$(\"#loadConfig\").dialog('destroy');\n\t\t}\n\t\treader.readAsText(file);\n\t}\n\n\tfunction failRead(evt) {\n\t\talert(evt.target.error.code);\n\t}\n}",
"function fileChanged() {\n \"use strict\";\n if (bTrackChanges) {\n if (!bFileChanged) {\n bFileChanged = true;\n highlightChanged();\n }\n }\n}",
"function runProgram() {\n render();\n\n let input = document.getElementById(\"fileSelector\");\n input.addEventListener('change', function () {\n readFile(input);\n });\n\n window.onkeydown = function (event) {\n handleKeyPress(event.key);\n };\n}",
"function setCurrentFile(file) {\n data.currentFile = file;\n }",
"function fileHandler(event) {\n const input = event.target;//div that triggered the event. \n if ('files' in input && input.files.length > 0) {\n let outputTarget = masonsGainPage.inputTarget;//global object, add.\n let file = input.files[0];\n const reader = new FileReader();\n let readContent = new Promise((resolve, reject) => {\n reader.onload = event => resolve(event.target.result);\n reader.onerror = error => reject(error);\n reader.readAsText(file);\n });\n readContent.then(content => {\n outputTarget.value = content\n }).catch(error => { throw new Error(error) } );\n }\n}",
"function handleFileSelect(evt) {\n console.log(\"Handling file selection\");\n files = evt.target.files;\n fileCount = files.length;\n fileIndex = 0;\n handleFile(files[0]);\n}",
"function on_change_key_config()\n{\n\tkey_config = key_config_presets[key_config_menu.selectedIndex];\n}",
"function displayFile() {\n if (changed) {\n let fileName = $(this).val().split(\"\\\\\").pop();\n $(this).siblings(\".custom-file-label\").addClass(\"selected\").html(fileName);\n }\n}",
"function uploadFile(event){\n var input = event.target;\n var reader = new FileReader();\n reader.onload = function (){\n cur_ns.descriptor = jsyaml.safeLoad(reader.result);\n editor.setValue(cur_ns.descriptor);\n };\n reader.readAsText(input.files[0]);\n}",
"function readDataFile(e) {\n var file = e.target.files[0];\n if (!file) {\n return;\n }\n\n var reader = new FileReader();\n reader.onload = function(e) {\n var contents = e.target.result;\n displayContents(contents);\n parseInputData(contents);\n };\n reader.readAsText(file);\n }",
"function fileSelected(file) {\n\tif (file.type == \"text\" && file.subtype == \"plain\") {\n\t\tgetData(file.data);\n\t} else {\n\t\tcreateP(\"I need a text file.\");\n\t}\n}",
"function getFile(event) {\n\tconst input = event.target\n if ('files' in input && input.files.length > 0) {\n\t placeFileContent(\n document.getElementById('text-area-one'),\n input.files[0])\n }\n}",
"function optionChanged(newSample) {\n // Fetch new data each time a new sample is selected\n buildPlots(newSample);\n Demographics(newSample);\n }",
"function inputChanged(e) {\n var files = e.target.files;\n var attachments = [];\n for (var i = 0; i < files.length; i++) {\n pushAttachment(files.item(i));\n }\n bugChanged();\n}",
"function loadConfig() {\n\tconfig_file = fs.readFileSync(\"./config.json\");\n\tconfig = JSON.parse(config_file);\n}",
"function handleFiles(files) {\r\n\r\n\tvar file = files[0];\r\n\tif (file) {\r\n\t var reader = new FileReader();\r\n\t reader.readAsText(file, \"UTF-8\");\r\n\t reader.onload = function (evt) {\r\n\t document.getElementById(\"obj_file\").innerHTML = evt.target.result;\r\n\t main() ;\r\n\t }\r\n\t reader.onerror = function (evt) {\r\n\t document.getElementById(\"obj_file\").innerHTML = \"error reading file\";\r\n\t }\r\n\t}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
subprocess: only when it is not triggeredByEvent activity: only when it attach a compensation boundary event callActivity: no limitation | function canActivityBeCompensated(activity, boundaryEvents) {
return (is(activity, 'bpmn:SubProcess') && !activity.triggeredByEvent) ||
is(activity, 'bpmn:CallActivity') ||
isCompensationEventAttachedToActivity(activity, boundaryEvents);
} | [
"_spawnProcess (command, args, onstdout, onstderr) {\n return new Promise((resolve, reject) => {\n let shell = Spawn(command, args);\n shell.on('close', (code) => {\n resolve(code);\n });\n\n shell.stdout.on('data', (data) => {\n if (onstdout) {\n let d = data.toString();\n if (d.length > 1) onstdout(d);\n }\n });\n\n shell.stderr.on('data', (data) => {\n if (onstderr) {\n let d = data.toString();\n if (d.length > 1) onstderr(d);\n }\n });\n });\n }",
"handleBreakClipStarted(event) {\n let data = {};\n this.breakClipStarted = true;\n this.breakClipId = event.breakClipId;\n this.breakClipLength =\n this.breakManager.getBreakClipDurationSec();\n this.qt1 = this.breakClipLength / 4;\n this.qt2 = this.qt1 * 2;\n this.qt3 = this.qt1 * 3;\n\n data.id = this.breakClipId;\n data.action = event.type;\n\n // Adobe Agent specific values.\n data.position = event.index;\n data.length = this.breakClipLength;\n\n\n this.sendData(data);\n }",
"needsTaskBoundaryBetween(messageA, messageB) {\n return messageA.type !== 'event' || messageB.type !== 'event';\n }",
"async function onProcMsg(msg) {\n msg = msg.toString()\n\n // log the stdout line\n this.logLine(msg)\n\n /* \n * STREAMLINK EVENTS\n */\n\n // Handle Streamlink Events: No stream found, stream ended\n\n REGEX_NO_STREAM_FOUND.lastIndex = 0\n REGEX_NO_CHANNEL.lastIndex = 0\n REGEX_STREAM_ENDED.lastIndex = 0\n\n if (REGEX_NO_STREAM_FOUND.test(msg)) {\n ipcServer.ipcSend(\n 'streamlink-event',\n Result.newError(\n `${msg}`,\n '@ StreamlinkInstance stdout'\n )\n )\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n \n }\n\n if (REGEX_NO_CHANNEL.test(msg)) {\n ipcServer.ipcSend(\n 'streamlink-event',\n Result.newError(\n `${msg}`,\n '@ StreamlinkInstance stdout'\n )\n )\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n }\n\n if (REGEX_STREAM_ENDED.test(msg)) {\n // send streamlink event on stream end event.\n // disabled for now; don't want a toast notification every\n // time a player is closed.\n //\n // ipcServer.ipcSend(\n // 'streamlink-event',\n // Result.newOk(`Stream ${this.channelName} closed`)\n // )\n\n ipcServer.ipcSend('streamlink-stream-closed', this.channelName)\n\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n return\n }\n\n // Handle Streamlink Event: Invalid quality\n\n // match invalid quality option message.\n // use the available qualities list that is printed by streamlink to\n // decide on & launch the closest available stream quality to the user's preference.\n // eg. if available stream qualities are [480p, 720p, 1080p] and user's preference\n // is set to '900p', we'll look through the list, find that 720p is the\n // closest without going over, and attempt to launch at that quality instead of\n // failing to open anything.\n REGEX_STREAM_INVALID_QUALITY.lastIndex = 0\n if (REGEX_STREAM_INVALID_QUALITY.test(msg)) {\n // first, close the existing stream instance\n streamManager.closeStream(this.channelName)\n .catch(console.error)\n\n \n // match available qualities line\n // index 0 is the full match - contains both of the following groups\n // index 1 is group 1, always the string \"Available streams: \"\n // index 2 is group 2, string list of qualities. eg:\n // \"audio_only, 160p (worst), 360p, 480p, 720p60, etc...\"\n REGEX_AVAILABLE_QUALITIES.lastIndex = 0\n let availableQualMatch = REGEX_AVAILABLE_QUALITIES.exec(msg)\n\n // this shouldnt happen, but if it does, for now just fail\n if (availableQualMatch == null) {\n console.error('Err: availableQualMatch is null or undefined; no available quality options to choose from')\n return\n }\n\n // full match (string list of qualities) lives at index 2\n // turn it into an array of quality strings.\n // eg ['audio_only', '160p (worst)', '360p', '480p', '720p60', etc...]\n let availableStrs = availableQualMatch[2].split(', ')\n\n // build arrays of resolutions and framerates out of each quality string.\n // framerates default to 30 if not specified (eg a quality string of '480p'\n // will be represented in the arrays as [480] [30] - the indices will line up)\n let availableResolutions = []\n let availableFramerates = []\n\n availableStrs.forEach(qual => {\n // return the resolution string (match array index 0) if a match is found,\n // otherwise use the number 0 for the resolution and framerate if no match is found.\n\n // This is to turn things like 'audio_only' into an integer that we can easily ignore later,\n // but lets us keep the length and indicies of the availableResolutions array the\n // same as availableStrs so they line up as expected (as we'll need to access data\n // from availableStrs later).\n\n // match resolution string (and framerate string, if available) from quality string.\n // if match is null, no resolution or framerate were found.\n // match index 0 holds resolution string, index 1 holds framerate.\n // \n // example matches:\n // 'audio_only' -> null\n // '480p' -> ['480']\n // '1080p60' -> ['1080', '60']\n let m = qual.match(REGEX_NUMBERS_FROM_QUALITY_STR)\n\n // quality string contains no numbers, default resolution and framerate to 0.\n // we still store values for these unwanted qualities so the indices and\n // lengths of the arrays line up when we read from them later.\n if (m == null) {\n availableResolutions.push(0)\n availableFramerates.push(0)\n return\n }\n\n // match index 0: resolution string is a number\n // convert to int and store in resolutions array\n availableResolutions.push(parseInt(m[0]))\n\n // match index 1: framerate - if exists, convert to int and store; otherwise store 0.\n // unspecified framerate here can probably be assumed to be 30, but use 0 instead; same\n // effect when comparing.\n availableFramerates.push(m[1] ? parseInt(m[1]) : 0)\n })\n\n // get int versions of user's preferred resolution (retrieved from preferences or passed to instance open() call)\n let preferredResInt = parseInt(this.quality.match(REGEX_NUMBERS_FROM_QUALITY_STR)[0])\n let preferredFpsInt = parseInt(this.quality.match(REGEX_NUMBERS_FROM_QUALITY_STR)[1])\n\n // now that we've got an array of available qualities, we int compare our preferred quality\n // against each and determine the closest available option, which we then use when launching the stream.\n //\n // loop over in reverse order (highest to lowest quality) and compare each to preference.\n // Choose the first quality option that's lower than or equal to preferred.\n for (let i = availableResolutions.length - 1; i >= 0; i--) {\n // if target resolution is lower, open stream\n //\n // if target resolution is the same, make sure framerate is lower.\n // This is to avoid, for example, opening a 1080p60 stream if user's\n // preference is 1080p30, while still opening 1080p30 if the preference\n // is 1080p60 (and 1080p60 isnt available for the stream in question).\n // We will still open higher framerates at a lower fps; 720p60 will open when\n // the user preference is 1080p30 if it's the next lowest available quality.\n //\n // We're conservative to avoid poor performance or over-stressing\n // user's machine when they don't want to.\n \n // skip indices of resolution 0\n if (availableResolutions[i] === 0) continue\n if (\n // open this quality if resolution is lower than preference\n availableResolutions[i] < preferredResInt ||\n // open this quality if resolution is the same and fps is lower\n (availableResolutions[i] === preferredResInt &&\n availableFramerates[i] <= preferredFpsInt)\n ) {\n // the index of the current loop through availableResolutions will\n // correspond to the correct quality string in availableStrs\n let newQual = availableStrs[i].split(' ')[0]\n streamManager.launchStream(this.channelName, newQual)\n .catch(console.error)\n return\n }\n }\n\n // if we got here, no qualities could be used.\n // default to \"best\".\n //\n // this is in a timeout, as otherwise the newly opened process closes itself immediately. not sure why yet. \n setTimeout(() => {\n console.log('Could not find a suitable quality that is <= preferred. Defaulting to \"best\".')\n streamManager.launchStream(this.channelName, 'best')\n .catch(console.error)\n }, 1000) // 1 second\n }\n}",
"beforeCommand() { }",
"function should_call(event_def) {\n\t\tif (typeof event_def.should_call !== 'function') {\n\t\t\treturn true;\n\t\t}\n\t\treturn event_def.should_call();\n\t}",
"function callTMScript(cmd, handler, path, line, column, input, output, before_running) {\n\tconsole.log(\"cmd, path, line, column, input, output, before_running=\\n\"+cmd+\"\\n\"+path+\"\\n\"+line+\"\\n\"+column+\"\\n\"+input+\"\\n\"+output+\"\\n\"+before_running);\n command = '<dict>\\n\\\n<key>beforeRunningCommand</key>\\n\\\n<string>'+(before_running==null?\"nop\":before_running)+'</string>\\n\\\n<key>command</key>\\n\\\n<string>'+cmd+'</string>\\n\\\n<key>input</key>\\n\\\n<string>'+(input==null?\"none\":input)+'</string>\\n\\\n<key>output</key>\\n\\\n<string>'+(output==null?\"discard\":output)+'</string>\\n\\\n</dict>\\n\\\n';\n\n\tif (path) {\n\t\tcommand = 'open \"txmt://open?url=file://'+escape(path)+''+(line!=null?\"&line=\"+line:\"\")+(column!=null?\"&column=\"+column:\"\")+'\";\"' + ENV[\"TMTOOLS\"] + '\" call command \\'' + command + '\\'';\n\t}\n\telse {\n\t\tcommand = 'open \"txmt://open?\";\"$TMTOOLS\" call command \\'' + command + '\\'';\n\t}\n\tconsole.log(\"Final script\\n\" + command);\n\tif (handler) {\n\t\tprocess = TextMate.system(command, handler);\n\t\treturn process;\n\t}\n\telse {\n\t\tprocess = TextMate.system(command, null);\n\t\tconsole.log(\"Execution result status=\"+process.status+\" output=\\n\" +process.outputString+\"errors=\"+process.errorString);\n\t\treturn [process.status, process.outputString, command, process];\n\t}\n}",
"function verify_call_terminate(booking){\n xapi.status.get('Call').then((status) => {\n\n var callbacknumber = status[0].CallbackNumber ;\n callbacknumber = callbacknumber.split(\":\")[1];\n\n console.log(booking.DialInfo.Calls.Call[0].Number);\n\n if(callbacknumber == booking.DialInfo.Calls.Call[0].Number){\n xapi.command('Call Disconnect').catch(e => console.error('Could not end the call but we tried...'));\n }\n\n });\n}",
"onUseBaseRunClick () {\n if (!this.useBaseRun && !this.runOpts.csvDir && this.isUseCurrentAsBaseRun()) {\n this.$q.notify({ type: 'warning', message: this.$t('Input scenario should include all parameters otherwise model run may fail') })\n }\n }",
"function doesNotWantExternalActivity () {\n alert(\"Student does not want the external activity\") ;\n // send an InputResponse to the server with NO. callback fn should be processNextProblemResult\n sendNextProblemInputResponse(\"&answer=NO\");\n servletGet(\"InputResponseNextProblemIntervention\",\"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector,\n processNextProblemResult)\n}",
"async function parentProcessMessage (m) {\n if (m.type == \"config\") {\n main = m.config;\n for (i in children) children[i].send(m);\n } else if (m.type == \"CS\") {\n parseControl(m.data);\n } else if (m.type == \"activeLink\" && main != null && main.sock != null) {\n main.sock.activeLink = m.activeLink;\n } else if (m.type == \"QUIT\") {\n stop();\n process.exit(1);\n } else if (m.type == \"STOP\") {\n console.log(\"Transfer Stop Called\");\n stop();\n }\n}",
"_onDetachEnabled( event) {\n this.detached = true;\n if( event.cancellable) { event.stopPropagation(); }\n }",
"function syncActivityDataCB(data){\n var wasImmediateSync = data.isImmediate;\n var l_data = data.activityData;\n \n console.log(\"IsImmediate : \"+wasImmediateSync+\"||\"+l_data[0].activityId);\n \n if(wasImmediateSync){\n l_synAllData = {};\n //for(var i=0;i<l_data.length();i++){\n console.log(\"Upd after sync immediate : \"+l_data[0].activityId+\" \"+ l_data[0].syncImmediate+\" \"+l_data[0].syncImmediateStatus);\n updSyncDetailsInActivityWithActivityId(l_data[0].activityId, l_data[0].syncImmediate, l_data[0].syncImmediateStatus, 0);\n //}\n }\n else{\n l_synAllData = data.activityData;\n logSynActivity();\n }\n}",
"function ActivityStarted(){\n\n\tif (g_bFullScreen) {\n\t\tOnResize(g_ConWidth, g_ConHeight, 2);\n\t\tDVD.CursorType = 0;\n\t}\n\n\tg_bActivityDeclined = false;\n\tUpdateDVDTitle();\n\t//MFBar.MessageBox(\"Activity Started\", \"Status\");\n}",
"function startViz(){ \r\n\tmyProcess.setCallback(updateViz);\r\n}",
"handleCutVideo() {\n let self = this;\n\n // send event to parent that our task is starting\n self.props.onTaskStart( { taskName : 'Cut Video' } );\n\n let msg = { edl : this.edl.rawData() };\n\n cutVideo( msg,function(progress) {\n // send event to parent that our progress has updated\n self.props.onTaskProgress(progress);\n });\n }",
"function cmdUpdateReceived_ClickCase100() {\n console.log(\"cmdUpdateReceived_ClickCase100\");\n //fetch WO summary\n GenerateWOSummary();\n //fetch WO summary - scrap + unaccountable qty\n GenerateWOSummaryScrap();\n\n if (config.BypassExecutionStart) {\n //todo: line 5619\n }\n\n\n\n }",
"receivedCall(args, times) {\n const minRequired = times || 1;\n if (args.length === 0 && this.hasEmptyCalls(minRequired)) {\n return true;\n }\n const setupArgs = this.convertArgsToArguments(args);\n let matchCount = 0;\n for (const call of this.calls) {\n const isMatch = this.argumentsMatch(setupArgs, call);\n if (isMatch === true) {\n matchCount++;\n if (matchCount >= minRequired) {\n return true;\n }\n }\n }\n return false;\n }",
"function _callEvents(call){\n\t\tcall.on('stream', function(stream) {\n\t\t\t_addVideoDom(call, stream);\n\t\t});\n\n\t\tcall.on('close', function() {\n\t\t\t_call.close();\n\t\t\t_removeUserList(call);\n\t\t\t_removeVideoDom(call);\n\t\t});\n }",
"function wantsExternalActivity () {\n alert(\"Student wants the external activity\") ;\n // send an InputResponse to the server with YES. callback fn should be processNextProblemResult\n sendNextProblemInputResponse(\"&answer=YES\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
jvizTool navbar button icon class | function jvizToolNavbarBtnIcon(obj)
{
//Check for undefined object
if(typeof obj === 'undefined'){ var obj = {}; }
//Button ID
this.id = (typeof obj.id !== 'undefined')? obj.id : '';
//Button class
this.class = (typeof obj.class !== 'undefined')? obj.class : 'jvizFormBtnIconLight';
//Button title
this.title = (typeof obj.title === 'undefined') ? 'Button' : obj.title;
//Show button
this.show = true;
//Element type
this.type = 'button-icon';
//Return the button
return this;
} | [
"function jvizToolNavbarBtn(obj)\n{\n\t//Check for undefined object\n\tif(typeof obj === 'undefined'){ var obj = {}; }\n\n\t//Button ID\n\tthis.id = (typeof obj.id !== 'undefined')? obj.id : '';\n\n\t//Button class\n\tthis.class = (typeof obj.class !== 'undefined')? obj.class : 'jvizFormBtn';\n\n\t//Button title\n\tthis.title = (typeof obj.title === 'undefined') ? 'Button' : obj.title;\n\n\t//Show button\n\tthis.show = true;\n\n\t//Element type\n\tthis.type = 'button';\n\n\t//Return the button\n\treturn this;\n}",
"function buttonTemplate(icon) {\n return '<div class=\"vjs-topbar-button__icon\"><i class=\"fa ' + icon + '\" aria-hidden=\"true\"></i></div>';\n }",
"function ELEMENT_ARROW_BUTTON$static_(){FavoritesToolbar.ELEMENT_ARROW_BUTTON=( FavoritesToolbar.BLOCK.createElement(\"arrow-button\"));}",
"static set toolbarButton(value) {}",
"function setRobotIcon(icon, ok) {\n if(ok) {\n $(icon).removeClass(\"fa-download\").addClass(\"fa-check\");\n } else {\n $(icon).removeClass(\"fa-check\").addClass(\"fa-download\");\n }\n}",
"createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }",
"function megaMenuIcon() {\r\n\r\n var icons = document.querySelectorAll('.top-menu i');\r\n icons.forEach(element => {\r\n element.addEventListener('click', function (e) {\r\n if (e.target.classList.contains('fa-angle-down')) {\r\n e.target.classList.remove('fa-angle-down');\r\n e.target.classList.add('fa-angle-up');\r\n } else {\r\n e.target.classList.remove('fa-angle-up');\r\n e.target.classList.add('fa-angle-down');\r\n\r\n }\r\n });\r\n });\r\n}",
"function _iconClickEvent() {\n\n\t\t_toggleVisibility();\n\n\t\t// Turn of file watching when not using it\n\t\tif (false === visible) {\n\t\t\ttailDomain.exec(\"quitTail\")\n\t\t\t\t.done(function () {\n\t\t\t\t\tconsole.log(\"[brackets-tail-node] quitTail done event\");\n\t\t\t\t}).fail(function (err) {\n\t\t\t\t\tconsole.error(\"[brackets-tail-node] quitTail error event\", err);\n\t\t\t\t});\n\t\t}\n\t}",
"drawIcon() {\n return `<i class=\"fab fa-sketch\"></i>`\n }",
"changeCityIcon() {\n let cityIcon = document.getElementsByClassName('city-icon');\n cityIcon[0].setAttribute(\n 'src',\n `./assets/htmlcss/Icons for cities/${this.cityName.toLowerCase()}.svg`\n );\n }",
"function toggleToolbar() {\n var options = [\n '#circleDrawType',\n '#triangleDrawType',\n '#rectDrawType',\n '#lineDrawType',\n '#freeDrawType',\n '#eraserDrawType',\n ]; \n options.map(function(option){ \n if($(option)[0].className.includes('active')){\n $(option).button('toggle');\n }\n });\n \n }",
"function setProductIcons() {\n\tjQuery('.edit_button').button({\n\t\ticons: {\n primary: \"ui-icon-wrench\"\n\t\t}\n\t});\n\tjQuery('.save_button').button({\n\t\ticons: {\n primary: \"ui-icon-check\"\n\t\t}\n\t}).click(function() {\n\t\tjQuery.cookie('redirect','');\n\t\treturn true;\n\t});\n\tjQuery('.remove_button').button({\n\t\t\ticons: {\n\t primary: \"ui-icon-closethick\"\n\t }\n\t});\n\tjQuery('.add_button').button({\n\t\t\ticons: {\n\t primary: \"ui-icon-plusthick\"\n\t }\n\t});\n\tjQuery('.back').button({\n\t\t\ticons: {\n\t primary: \"ui-icon-arrowreturnthick-1-s\"\n\t }\n\t});\n}",
"function setIcons() {\n var node = $('#mytreeview').treeview('getNode', 0);\n // set root icon\n node.icon = 'fa fa-home';\n // set folder and group icons\n var folders = node.nodes;\n var groups;\n for (var i = 0; i < folders.length; i++) {\n $('#mytreeview').treeview('getNode', folders[i].nodeId).icon = 'fa fa-folder';\n groups = folders[i].nodes;\n if (typeof groups !== 'undefined') {\n for (var j = 0; j < groups.length; j++) {\n $('#mytreeview').treeview('getNode', groups[j].nodeId).icon = 'fa fa-users';\n }\n }\n }\n}",
"function jvizToolNavbarLabel(obj)\n{\n\t//Check for undefined object\n\tif(typeof obj === 'undefined'){ var obj = {}; }\n\n\t//Label ID\n\tthis.id = (typeof obj.id !== 'undefined')? obj.id : '';\n\n\t//Label class\n\tthis.class = (typeof obj.class !== 'undefined')? obj.class : 'jvizFormLabel';\n\n\t//Label text\n\tthis.text = (typeof obj.text === 'undefined') ? '' : obj.text;\n\n\t//Show label\n\tthis.show = true;\n\n\t//Element type\n\tthis.type = 'label';\n\n\t//Return the label\n\treturn this;\n}",
"function selecionaBtSidebar(i){\n $('#sidebar-app .ativo').removeClass('ativo');\n $('#sidebar-app ul li').eq(i).addClass('ativo').find('a > span.sprite-1').addClass('ativo');\n }",
"defaultNavStyles() {\n const btnElements = document.getElementsByClassName(\"actionNavs\");\n Array.prototype.forEach.call(btnElements, function (element) {\n element.style.backgroundColor = \"slategray\";\n element.style.color = \"white\";\n });\n const actionElements = document.getElementsByClassName(\"methods\");\n Array.prototype.forEach.call(actionElements, function (action) {\n action.style.display = \"none\";\n });\n }",
"function changeNavClass(nav_element) {\n document.getElementById(\"nav-about\").className = \"nav-icons\";\n document.getElementById(\"nav-research\").className = \"nav-icons\";\n document.getElementById(\"nav-publication\").className = \"nav-icons\";\n document.getElementById(\"nav-conference\").className = \"nav-icons\";\n document.getElementById(\"nav-teaching\").className = \"nav-icons\";\n\n document.getElementById(nav_element).className += \" active\";\n\n document.getElementById(\"location_icon\").className = \"fas fa-map-marker-alt\";\n document.getElementById(\"research_icon\").className = \"fa fa-flask fa-fw\";\n document.getElementById('book_icon').src=\"assets/images/icons/book-1.png\"\n document.getElementById(\"gear1\").style.display = \"none\";\n document.getElementById(\"gear2\").style.display = \"none\";\n\n }",
"function showToolBar(route){\n if(route.includes('pca')){\n document.querySelector('#pca-toolbar').classList.remove('hidden');\n document.querySelector('#hca-toolbar').classList.add('hidden');\n }else if(route.includes('hca')){\n document.querySelector('#hca-toolbar').classList.remove('hidden');\n document.querySelector('#pca-toolbar').classList.add('hidden');\n }\n}",
"static createIcon(options, enableTooltips, shortcuts) {\n options = options || {};\n let el = document.createElement(\"button\");\n let self = this;\n\n enableTooltips = (enableTooltips === undefined) ? true : enableTooltips;\n\n if (options.title && enableTooltips) {\n el.title = self.createTootlip(options.title, options.action, shortcuts);\n\n if (self.isMac) {\n el.title = el.title.replace(\"Ctrl\", \"⌘\");\n el.title = el.title.replace(\"Alt\", \"⌥\");\n }\n }\n\n el.tabIndex = -1;\n el.className = 'md-icon-button md-button';//options.className;\n // el.innerHTML = options.icon;\n\n let icon = document.createElement('i');\n icon.className = options.className;\n icon.innerHTML = options.icon;\n el.appendChild(icon);\n\n return el;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the start of Hijri Month. `hMonth` is 0 for Muharram, 1 for Safar, etc. `hYear` is any Hijri hYear. | function getIslamicMonthStart(hYear, hMonth) {
return Math.ceil(29.5 * hMonth) + (hYear - 1) * 354 + Math.floor((3 + 11 * hYear) / 30.0);
} | [
"getMonthOfYear() {\n switch (this.getJMonth()) {\n case '1':\n return 'فروردین';\n case '2':\n return 'اردیبهشت';\n case '3':\n return 'خرداد';\n case '4':\n return 'تیر';\n case '5':\n return 'مرداد';\n case '6':\n return 'شهریور';\n case '7':\n return 'مهر';\n case '8':\n return 'آبان';\n case '9':\n return 'آذر';\n case '10':\n return 'دی';\n case '11':\n return 'بهمن';\n case '12':\n return 'اسفند';\n }\n }",
"function getMonthPickerStart(selector) {\n jQuery(selector).monthpicker({\n showOn: \"both\",\n dateFormat: 'M yy',\n yearRange: 'c-5:c+10'\n });\n}",
"function nextStartMonth() {\n var thisMonth = new Date().getMonth();\n var nextMonth = 'Jan';\n\n if (0 <= thisMonth && thisMonth < 4) {\n nextMonth = 'May';\n } else if (4 <= thisMonth && thisMonth < 8) {\n nextMonth = 'Sep';\n }\n\n return nextMonth;\n }",
"getMonthNum() {\n\t\treturn this.props.month.substr(5,6);\n\t}",
"function getMonthList() {\n var today = new Date();\n var aMonth = today.getMonth();\n var i;\n var matrixMnthList = $(\".div-lpc-wrapper #matrixMonthList\");\n for (i = 0; i < 12; i++) {\n var monthRow = '<th class=\"label-month-lpc-wrapper\" id=\\\"' + i + '\\\">' + monthArray[aMonth] + '</th>';\n if ($(matrixMnthList)) {\n $(matrixMnthList).append(monthRow);\n }\n aMonth++;\n if (aMonth > 11) {\n aMonth = 0;\n }\n }\n}",
"getYearNum() {\n\t\treturn this.props.month.substr(0,4);\n\t}",
"function CreateMonthYearTitle(month, year) {\n var month_array = ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n \n for (var i = 0; i < month_array.length; i++) {\n if (month === i) {\n monthYearHeader.innerHTML = month_array[i];\n }\n }\n monthYearHeader.innerHTML = monthYearHeader.innerHTML + ' ' + year; // check\n}",
"function semesterStart(year,sem) {\n var test;\n switch(year) {\n case \"2014-2015\": {\n //11-8-2014 & 12-1-2015\n if(sem==\"1\")\n test = moment(\"11082014\",\"DDMMYYYY\");\n else if(sem==\"2\")\n test = moment(\"12012015\",\"DDMMYYYY\");\n else if(sem==\"3\")\n test = moment(\"11052015\",\"DDMMYYYY\");\n else \n test = moment(\"22062015\",\"DDMMYYYY\");\n } break; \n case \"2013-2014\": {\n //13-01-2014 & 12-08-2013\n if(sem==\"1\")\n test = moment(\"12082013\",\"DDMMYYYY\");\n else if(sem==\"2\")\n test = moment(\"11012014\",\"DDMMYYYY\");\n else if(sem==\"3\")\n test = moment(\"12052014\",\"DDMMYYYY\");\n else\n test = moment(\"23062014\",\"DDMMYYYY\");\n } break; \n }\n return test.toDate();\n}",
"function _getMonth(m) {\n\t\tif(mc.os.config.translations) {\n\t\t\treturn mc.os.config.translations.pc.settings.nodes['_constants'].months[m];\n\t\t} else {\n\t\t\treturn $MONTHS[m];\n\t\t}\n\t}",
"function DateTimeDayMonth() { }",
"function setDateContent(MONTH, YEAR) {\n\tdocument.getElementById(\"id_month\").innerHTML = setMonthList();\n\tdocument.getElementById(\"id_year\").innerHTML = setYearList();\n\n\tvar first_date = new Date(YEAR, MONTH, 1);\n\tvar of_day = first_date.getDay();\n\tvar mon_length = months_length[MONTH];\n\tvar check = false;\n\tvar start = 1;\n\n\tvar today = new Date();\n\tvar currentDay = today.getDate();\n\tvar currentYear = today.getYear() + 1900;\n\tvar currentMonth = today.getMonth();\n\n\tfor (i = 0; i < 42; i++) {\n\t\tif (i == of_day) {\n\t\t\tcheck = true;\n\t\t}\n\t\tif (check == true && start <= mon_length) {\n\t\t\tif (currentDay == start && currentMonth == MONTH && currentYear == YEAR) {\n\t\t\t\tdocument.getElementById(\"cell\" + i).innerHTML = start;\n\t\t\t\tdocument.getElementById(\"cell\" + i).style.color = \"red\";\n\t\t\t}else {\n\t\t\t\tdocument.getElementById(\"cell\" + i).innerHTML = start;\n\t\t\t\tdocument.getElementById(\"cell\" + i).style.color = \"#2582BE\";\n\t\t\t}\n\t\t\tstart++;\n\t\t}else {\n\t\t\tdocument.getElementById(\"cell\" + i).innerHTML = \"\";\n\t\t}\n\t}\n}",
"function printMonthTitle(month, year) {\n output = monthsName[month] + ' ' + year + '.';\n document.getElementsByClassName(\"date-info\")[0].innerText = output;\n }",
"function putMask_YearMonthDate(oElement)\n{\n var lstrValue = oElement.value;\n if(lstrValue == \"\" || !isInteger(lstrValue))\n return;\n\n re = new RegExp(\"/\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n if (lstrValue.length == 6) {\n partOne = lstrValue.substring(0,4);\n partTwo = lstrValue.substring(4);\n oElement.value = partOne + \"/\" +partTwo;\n }\n}",
"getPreviousMonth(){\n return new Month(this.year + Math.floor((this.month.index-1)/12), (this.month.index+11) % 12, this.setting.getWeekStartDay());\n }",
"function renderMonth() {\r\n // Creo un oggetto moment con anno e mese scelti\r\n var momentObject = {\r\n \"year\": startYear,\r\n \"month\": startMonth\r\n };\r\n\r\n // Creo una data moment.js passando l'oggetto creato\r\n var momentDate = moment(momentObject);\r\n // Ottengo il numero di giorni nel mese selezionato\r\n var daysInMonth = momentDate.daysInMonth();\r\n\r\n // Modifico il titolo in base al mese scelto\r\n $(\"h1\").text(momentDate.format(\"MMMM YYYY\"));\r\n\r\n // Per ognuno dei giorni nel mese, modifico il context e compilo il template\r\n for (var i = 1; i <= daysInMonth; i++) {\r\n var context = {\r\n \"day\": i,\r\n \"month\": momentDate.format(\"MMMM\")\r\n }\r\n\r\n // Compilo il template e lo aggiungo alla lista sulla pagina\r\n var html = template(context);\r\n $(\"ul.month-display\").append(html);\r\n }\r\n }",
"function month_links(start) { \n var startAr = start.split('-');\n var start_year = startAr[0];\n var start_month = startAr[1];\n var monthAr = [];\n var month,this_month,month_date, month_name, m, year;\n var this_m = parseInt(start_month, 10);\n var start_m = (12 + (this_m - 3)) % 12;\n var year = start_year;\n if(this_m - 3 < 0) year--;\n \n for(var i=start_m;i<12+start_m;i++) {\n if(i==12) year++; \n m = i%12;\n if(this_m == m+1) {\n month_name = g_months[m];\n month = '<b>' + month_name + '</b>';\n } else {\n month_name = g_monthsShort[m]; \n month_date = year + \"-\" + zero_pad(m+1) + \"-01\";\n month = '<a href=\"?start=' + month_date +'\" class=\"cal_nav start\" data-value=\"' + month_date + '\">' + month_name + '</a>';\n }\n monthAr.push(month);\n }\n return monthAr.join(' ');\n}",
"function Jan2014()\n{ \n var date = new Date();\n var day = date.getDate();\n var month = date.getMonth();\n var year = date.getFullYear()+1;\n \n var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');\n var mnth = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec');\n var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);\n var weekDay = new Array('Mo','Tu','We','Th','Fr','Sa','Su');\n var days_in_this_month = monthDays[0];\n\n // Create the basic Calendar structure.\n var next_month = '<table class=\"calendarTable\" onmouseover=ShowContent(\"div_event\"); onmouseout=HideContent(\"div_event\");>';\n next_month += '<tr><td class=\"monthHead\" colspan=\"7\">' + months[0] + ' ' + year + '</td></tr>';\n next_month += '<tr>';\n var first_week_day = new Date(year, 0, 0).getDay();\n for(week_day= 0; week_day < 7; week_day++) {\n next_month += '<td class=\"weekDay\">' + weekDay[week_day] + '</td>';\n }\n next_month += '</tr><tr>';\n\n // Fill the first week of the month with the appropriate number of blanks.\n for(week_day = 0; week_day < first_week_day; week_day++) {\n next_month += '<td> </td>';\n }\n week_day = first_week_day;\n for(day_counter = 1; day_counter <= days_in_this_month; day_counter++) {\n week_day %= 7;\n if(week_day == 0)\n next_month += '</tr><tr>';\n\n\t if(week_day == 5 || week_day ==6)\n\t {\n\t next_month += '<td class=\"weekEnd\" onclick=createEvents(\"'+day_counter+'\",\"'+01+'\",\"'+year+'\"); onmouseover=this.style.color=\"#FF0000\"; onmouseout=this.style.color=\"#444\";> ' + day_counter + ' </td>';\n\t }\n\n // Do something different for the current day.\n else if(day == day_counter && month == next_month) {\n next_month += '<td class=\"currentDay\" onclick=createEvents(\"'+day_counter+'\",\"'+01+'\",\"'+year+'\"); onmouseover=this.style.color=\"#FF0000\"; onmouseout=this.style.color=\"#444\";>' + day_counter + '</td>';\n }\n \t else {\n next_month += '<td class=\"monthDay\" onclick=createEvents(\"'+day_counter+'\",\"'+01+'\",\"'+year+'\"); onmouseover=this.style.color=\"#FF0000\"; onmouseout=this.style.color=\"#444\";> ' + day_counter + ' </td>';\n }\n week_day++;\n }\n next_month += '</tr>';\n next_month += '</table>';\n // Display the calendar.\n document.write(next_month); \n}",
"setMonthTh(newTh){\n _monthTh.set(this, newTh);\n }",
"function generateStartYears(selectedDatabaseMask) {\n var stringYear = $(\"input[name='stringYear']\");\n if (typeof stringYear == 'undefined') {\n console.warn(\"stringYear value could not be set!\");\n return;\n }\n\n var sy = calStartYear(selectedDatabaseMask, stringYear.val());\n var ey = calEndYear(selectedDatabaseMask);\n var dy = calDisplayYear(selectedDatabaseMask, stringYear.val());\n\n var years = new Array();\n var idx = 0;\n for (var j = sy; j <= ey; j++) {\n if (j == dy) years[idx++] = {\"label\": j, \"value\": j, \"selected\": true};\n else years[idx++] = {\"label\": j, \"value\": j};\n }\n return years\n }",
"function setMonth() {\n\tvar element = document.getElementById(\"selected_month\");\n\tMONTH = element.options[element.selectedIndex].value;\n\tsetDateContent(MONTH, YEAR);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
new ArgumentParser(options) Create a new ArgumentParser object. Options: `prog` The name of the program (default: Path.basename(process.argv[1])) `usage` A usage message (default: autogenerated from arguments) `description` A description of what the program does `epilog` Text following the argument descriptions `parents` Parsers whose arguments should be copied into this one `formatterClass` HelpFormatter class for printing help messages `prefixChars` Characters that prefix optional arguments `fromfilePrefixChars` Characters that prefix files containing additional arguments `argumentDefault` The default value for all arguments `addHelp` Add a h/help option `conflictHandler` Specifies how to handle conflicting argument names `debug` Enable debug mode. Argument errors throw exception in debug mode and process.exit in normal. Used for development and testing (default: false) See also [original guide][1] [1]: | function ArgumentParser(options) {
if (!(this instanceof ArgumentParser)) {
return new ArgumentParser(options);
}
var self = this;
options = options || {};
options.description = (options.description || null);
options.argumentDefault = (options.argumentDefault || null);
options.prefixChars = (options.prefixChars || '-');
options.conflictHandler = (options.conflictHandler || 'error');
ActionContainer.call(this, options);
options.addHelp = typeof options.addHelp === 'undefined' || !!options.addHelp;
options.parents = options.parents || [];
// default program name
options.prog = (options.prog || Path.basename(process.argv[1]));
this.prog = options.prog;
this.usage = options.usage;
this.epilog = options.epilog;
this.version = options.version;
this.debug = (options.debug === true);
this.formatterClass = (options.formatterClass || HelpFormatter);
this.fromfilePrefixChars = options.fromfilePrefixChars || null;
this._positionals = this.addArgumentGroup({ title: 'Positional arguments' });
this._optionals = this.addArgumentGroup({ title: 'Optional arguments' });
this._subparsers = null;
// register types
function FUNCTION_IDENTITY(o) {
return o;
}
this.register('type', 'auto', FUNCTION_IDENTITY);
this.register('type', null, FUNCTION_IDENTITY);
this.register('type', 'int', function (x) {
var result = parseInt(x, 10);
if (isNaN(result)) {
throw new Error(x + ' is not a valid integer.');
}
return result;
});
this.register('type', 'float', function (x) {
var result = parseFloat(x);
if (isNaN(result)) {
throw new Error(x + ' is not a valid float.');
}
return result;
});
this.register('type', 'string', function (x) {
return '' + x;
});
// add help and version arguments if necessary
var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0];
if (options.addHelp) {
this.addArgument(
[ defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help' ],
{
action: 'help',
defaultValue: c.SUPPRESS,
help: 'Show this help message and exit.'
}
);
}
if (typeof this.version !== 'undefined') {
this.addArgument(
[ defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version' ],
{
action: 'version',
version: this.version,
defaultValue: c.SUPPRESS,
help: "Show program's version number and exit."
}
);
}
// add parent arguments and defaults
options.parents.forEach(function (parent) {
self._addContainerActions(parent);
if (typeof parent._defaults !== 'undefined') {
for (var defaultKey in parent._defaults) {
if (parent._defaults.hasOwnProperty(defaultKey)) {
self._defaults[defaultKey] = parent._defaults[defaultKey];
}
}
}
});
} | [
"function handle_options(optionsArray) {\n var programName = [];\n var currentItem = optionsArray.shift();\n var defaults = amberc.createDefaultConfiguration();\n\n while (currentItem != null) {\n switch (currentItem) {\n case '-C':\n defaults.configFile = optionsArray.shift();\n break;\n case '-p':\n optionsArray.shift.split(',').forEach(function (pairString) {\n var mapping = pairString.split(':');\n defaults.paths[mapping[0]] = mapping[1];\n });\n break;\n case '-l':\n defaults.load.push.apply(defaults.load, optionsArray.shift().split(','));\n break;\n case '-g':\n defaults.jsGlobals.push.apply(defaults.jsGlobals, optionsArray.shift().split(','));\n break;\n case '-n':\n defaults.amdNamespace = optionsArray.shift();\n break;\n case '-D':\n defaults.outputDir = optionsArray.shift();\n break;\n case '-d':\n amber_dir = path.normalize(optionsArray.shift());\n break;\n case '-v':\n defaults.verbose = true;\n break;\n case '-h':\n case '--help':\n case '?':\n case '-?':\n print_usage_and_exit();\n break;\n default:\n defaults.stFiles.push(currentItem);\n break;\n }\n currentItem = optionsArray.shift();\n }\n\n if (1 < programName.length) {\n throw new Error('More than one name for ProgramName given: ' + programName);\n } else {\n defaults.program = programName[0];\n }\n return defaults;\n}",
"function parseArgs() {\n const pkg = require('../../package.json');\n\n config\n .usage('[options] <file ...>')\n .description('Send a file to all devices on a serial bus.')\n .version(pkg.version)\n .option('-l, --list', 'List all serial devices')\n .option('-b, --baud <number>', 'Baud rate to the serial device', parseInt)\n .option('-c, --command <number>', 'The Disco Bus message command that puts the devices into the bootloader.')\n .option('-d, --device <name>', 'The serial device to connect to')\n .option('-s, --page-size <number>', 'The programming page size for your device.', parseInt)\n .option('-p, --prog-version <maj.min>', 'The major.minor version of your program (for example 1.5)')\n .option('-t, --timeout <number>', 'How long to wait for devices to be ready for programming')\n .option('<file ...>', 'The file to program to your devices')\n .parse(process.argv);\n}",
"function Option() {\n Argument.apply(this, arguments);\n this.type = Argument.OPTION;\n this.extra = undefined;\n this.required = undefined;\n this.multiple = undefined;\n\n // a type specified in the literal, eg: {Number}\n this.kind = undefined\n\n // default value for the option, eg: {=stdout}\n this.value = undefined;\n}",
"function getopt (pat, opts, argv) {\n var arg, i = 0, $, arg, opt, l, alts, given = {};\n pat.replace(/--([^-]+)@/, function ($1, verbose) { opts[verbose] = [] });\n while (!(i >= argv.length || (argv[i] == \"--\" && argv.shift()) || !/^--?[^-]/.test(argv[i]))) {\n arg = argv.shift();\n arg = /^(--[^=]+)=(.*)$/.exec(arg) || /^(-[^-])(.+)$/.exec(arg) || [false, arg, true];\n alts = pat.replace(new RegExp(regular(arg[1]), 'g'), '').replace(/-[^,],--[^|]+\\|/g, '').split(\"|\");\n if ((l = alts.length - 1) != 1) abend(l ? \"ambiguous argument\" : \"unknown argument\", arg[1]);\n opt = (arg[1] + /,([^:@]*)/.exec(alts[0])[1]).replace(/^(-[^-]+)?--/, '').replace(/-/g, '');\n $ = /([:@])(.)$/.exec(alts[0]);\n if ($[2] != '!') {\n if ($[1].length == 1 || (argv.length && argv[0][0] != \"-\")) {\n if (!arg[0]) {\n if (!argv.length) abend(\"missing argument\", arg[1][1] != \"-\" ? arg[1] : \"--\" + opt);\n arg[2] = argv.shift();\n }\n if ($[2] == '#' && isNaN(arg[2] = parseFloat(arg[2]))) abend(\"numeric argument\", \"--\" + opt);\n }\n } else if (arg[0]) {\n if (arg[1][1] != \"-\") {\n argv.unshift(\"-\" + arg[2]);\n } else {\n abend(\"toggle argument\", arg[1][1] != \"-\" ? arg[1] : \"--\" + opt);\n }\n }\n given[opt] = true;\n if ($[1] == '@') opts[opt].push(arg[2]);\n else if (opts[opt] != null) abend(\"scalar argument\", arg[1]);\n else opts[opt] = arg[2];\n }\n return Object.keys(given);\n}",
"_parse(args) {\n const parsed = args.map(arg => {\n if (arg.includes('=')) {\n const [flag, value] = arg.split('=');\n const command = this._commandParser.getCommand(flag);\n return new Argument(command, value);\n } else {\n const command = this._commandParser.getCommand(arg);\n return new Argument(command, null);\n }\n });\n\n return parsed;\n }",
"function helpPlugin() {\n return function(app) {\n\n // style to turn `[ ]` strings into\n // colored strings with backticks\n app.style('codify', function(msg) {\n var re = /\\[([^\\]]*\\[?[^\\]]*\\]?[^[]*)\\]/g;\n return msg.replace(re, function(str, code) {\n return this.red('`' + code + '`');\n }.bind(this));\n });\n\n // style and format a single help command\n app.style('helpCommand', function(command) {\n var msg = '';\n msg += this.bold(command.name.substr(0, 1).toUpperCase() +\n command.name.substr(1) + ': ');\n msg += this.bold(command.description);\n return msg;\n });\n\n // style and format an array of help commands\n app.style('helpCommands', function(commands) {\n return commands\n .map(this.helpCommand)\n .join('\\n\\n');\n });\n\n // style and format a single example\n app.style('helpExample', function(example) {\n var msg = '';\n msg += ' ' + this.gray('# ' + example.description) + '\\n';\n msg += ' ' + this.white('$ ' + example.command);\n return msg;\n });\n\n // style and format an array of examples\n app.style('helpExamples', function(examples) {\n return examples\n .map(this.helpExample)\n .join('\\n\\n');\n });\n\n // style and format a single option\n app.style('helpOption', function(option) {\n var msg = '';\n msg += ' ' + (option.flag ? this.bold(option.flag) : ' ');\n msg += ' ' + this.bold(option.name);\n msg += ' ' + this.bold(this.codify(option.description));\n return msg;\n });\n\n // style and format an array of options\n app.style('helpOptions', function(options) {\n return options\n .map(this.helpOption)\n .join('\\n');\n });\n\n // style and formation a help text object using\n // other styles to break up responibilities\n app.emitter('help', function(help) {\n var msg = '\\n';\n msg += this.bold('Usage: ') + this.cyan(help.usage) + '\\n\\n';\n msg += this.helpCommands(help.commands);\n\n if (help.examples && help.examples.length) {\n msg += this.bold('Examples:\\n\\n');\n msg += this.helpExamples(help.examples);\n }\n\n if (help.options && help.options.length) {\n msg += this.bold('Options:\\n\\n');\n msg += this.helpOptions(help.options);\n }\n return msg + '\\n';\n });\n };\n}",
"static getParser (name) {\n return require(`./parsers/${name}.js`);\n }",
"function CommandLoader(obj) {\n if (!(this instanceof CommandLoader)) {\n return new CommandLoader(obj);\n }\n\n obj = obj || {};\n\n this.root = obj.root || path.resolve(__dirname, 'commands');\n this.strict = true;\n this.usage = obj.usage || 'help';\n this.fallback = obj.fallback || this.usage;\n this.default = obj.default || this.usage;\n this.manuals = obj.manuals || null;\n\n this.log = logger.log;\n\n this.commands = needs(__dirname, './commands');\n}",
"static newBuilder() {\n return new ProgramBuilder({\n booleanFlags: [],\n valuedFlags: [],\n positionalArguments: new PositionalArguments_1.default(),\n programMetadata: {}\n });\n }",
"function Workman_Options() {\n this.initialize.apply(this, arguments);\n}",
"function createYargsTemplate(yargs) {\n return yargs\n .help()\n .option('number', {\n alias: 'n',\n type: 'number',\n default: 1,\n description: 'The number of generated data'\n }).option('model', {\n alias: 'm',\n type: 'string',\n coerce: it => it ? path.resolve(it) : undefined,\n describe: 'The file to input the data model'\n }).option('output', {\n alias: 'o',\n type: 'string',\n coerce: it => it ? path.resolve(it) : undefined,\n describe: 'The file to write the output'\n })\n}",
"function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction 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}\n\t}",
"function getBumperOptions() {\n return __awaiter(this, void 0, void 0, function* () {\n const optionsFile = core.getInput('options-file');\n const scheme = core.getInput('scheme');\n const skip = core.getInput('skip');\n const customScheme = core.getInput('custom-scheme');\n const versionFile = core.getInput('version-file');\n const files = core.getInput('files');\n const rules = core.getInput('rules');\n const username = core.getInput('username');\n const email = core.getInput('email');\n let error = \"\"; // error message\n let bumperOptions = {};\n let err = (message) => {\n console.error(message);\n error += message + '\\n';\n };\n if (optionsFile && !fs.existsSync(optionsFile)) {\n console.warn(`Options file with path ${optionsFile} does not exist`);\n // error += `Options file with path ${optionsFile} does not exist\\n`;\n }\n else if (optionsFile && fs.existsSync(optionsFile)) {\n try {\n bumperOptions = JSON.parse(yield fs.readFileSync(optionsFile, { encoding: 'utf8', flag: 'r' }));\n }\n catch (e) {\n console.warn(`Error reading or parsing bumper options file with path ${optionsFile}\\n${e}`);\n }\n }\n if (scheme)\n bumperOptions.scheme = scheme;\n else if (!scheme && (!bumperOptions.hasOwnProperty('scheme')\n || !bumperOptions.scheme\n || bumperOptions.scheme.trim() === \"\")) {\n err(\"Scheme is not defined in option file or workflow input.\");\n }\n if (customScheme && customScheme.trim() !== \"\") {\n bumperOptions.scheme = \"custom\";\n bumperOptions.schemeDefinition = customScheme;\n }\n try {\n bumperOptions.schemeDefinition = getSchemeDefinition(bumperOptions);\n }\n catch (e) {\n err(e);\n }\n if (versionFile && versionFile.trim() !== '') {\n try {\n bumperOptions.versionFile = JSON.parse(versionFile);\n }\n catch (e) {\n // console.log(e.message);\n bumperOptions.versionFile = { path: versionFile };\n }\n }\n else if (!bumperOptions.hasOwnProperty('versionFile')\n || !bumperOptions.versionFile\n || (bumperOptions.versionFile instanceof String && bumperOptions.versionFile.trim() === \"\")) {\n err(\"Version file is not defined in option file or workflow input.\");\n }\n else {\n bumperOptions.versionFile = normalizeFiles([bumperOptions.versionFile])[0];\n }\n if (files && files.trim() !== '') {\n try {\n const filesArray = JSON.parse(files);\n if (!Array.isArray(filesArray)) {\n err(\"Files should be in array stringified JSON format\");\n }\n else\n bumperOptions.files = normalizeFiles([bumperOptions.versionFile, ...filesArray]);\n }\n catch (e) {\n err(\"Files not in JSON format\");\n }\n }\n else if (!bumperOptions.hasOwnProperty('files')\n || !bumperOptions.files\n || !Array.isArray(bumperOptions.files)) {\n err(\"Files are not defined in option file or workflow input.\");\n }\n else\n bumperOptions.files = normalizeFiles([bumperOptions.versionFile, ...bumperOptions.files]);\n if (rules && rules.trim() !== '') {\n try {\n const rulesArray = JSON.parse(rules);\n if (!Array.isArray(rulesArray)) {\n err(\"Rules should be in array stringified JSON format\");\n }\n else\n bumperOptions.rules = rulesArray;\n }\n catch (e) {\n err(\"Rules not in JSON format\");\n }\n }\n else if (!bumperOptions.hasOwnProperty('rules')\n || !bumperOptions.rules\n || !Array.isArray(bumperOptions.rules)) {\n err(\"Rules are not defined in option file or workflow input.\");\n }\n if (skip)\n bumperOptions.skip = skip;\n if (username)\n bumperOptions.username = username;\n if (email)\n bumperOptions.email = email;\n if (error !== \"\")\n throw new Error(error);\n else {\n console.log(JSON.stringify(bumperOptions));\n return bumperOptions;\n }\n });\n}",
"function getUsage (cliSpec) {\n const usage =\n ' ' +\n cliSpec.commands\n .map(c => `dapple ${c.name} ${c.options.map(o => o.name).join(' ')}`)\n .join('\\n ');\n const options =\n ' ' +\n cliSpec.options\n .map(o => o.name)\n .join('\\n ');\n return `Usage:\\n${usage}\\n\\nOptions:\\n${options}`;\n}",
"function getOptions(args) {\n var reportFilename = args.reportFilename,\n reportDir = args.reportDir,\n reportTitle = args.reportTitle,\n reportPageTitle = args.reportPageTitle,\n inlineAssets = args.inlineAssets,\n enableCharts = args.enableCharts,\n enableCode = args.enableCode,\n dev = args.dev;\n\n var filename = reportFilename.replace(fileExtRegex, '') + '.html';\n return {\n reportHtmlFile: path.join(reportDir, filename),\n reportTitle: reportTitle,\n reportPageTitle: reportPageTitle,\n inlineAssets: inlineAssets,\n enableCharts: enableCharts,\n enableCode: enableCode,\n dev: dev\n };\n}",
"function validateArgs() {\n //No arguments or any argument set including the help argument are both\n //automatically valid.\n //If -pre, -dest, -ign, -ext, -enc, or -cst were provided, -repo\n //must also have been provided.\n //The presence of -sets and -args is always optional.\n\n //Allow no arguments or any set with a -help argument.\n if (0 === aargsGiven.length || -1 !== aargsGiven.indexOf('-help')) {\n return;\n }\n\n //Otherwise, require the -repo command if -pre, -dest, -ign, -ext,\n //-enc, or -cst were provided.\n if ((-1 !== aargsGiven.indexOf('-pre') ||\n -1 !== aargsGiven.indexOf('-dest') ||\n -1 !== aargsGiven.indexOf('-ign') ||\n -1 !== aargsGiven.indexOf('-ext') ||\n -1 !== aargsGiven.indexOf('-enc') ||\n -1 !== aargsGiven.indexOf('-cst')) &&\n -1 === aargsGiven.indexOf('-repo')) {\n throw 'Invalid argument set. Must use -repo if using any other ' +\n 'command except -help, -sets, or -args.';\n }\n }",
"_initializePath() {\n let argPath = \"\";\n program\n .arguments('<path/to/components')\n .action((basePath) => {\n const validatedDirectory = validateDirectory(basePath);\n if (validatedDirectory.isValid ) {\n argPath = basePath;\n } else {\n die(validatedDirectory.error);\n }\n })\n .parse(process.argv);\n\n return argPath;\n }",
"function printHelp() {\n var spathToDocumentation = process.argv[1].split(PATH.sep), shelp;\n\n spathToDocumentation.pop();\n spathToDocumentation.push(PATH.sep + 'documentation.txt');\n shelp = FS.readFileSync(spathToDocumentation.join(PATH.sep),\n {'encoding': 'utf8'});\n console.log(shelp);\n }",
"function UIArgument(uiArgumentShorthand, localVars)\r\n{\r\n /**\r\n * @param uiArgumentShorthand\r\n * @returns true if validation passed\r\n */\r\n this.validate = function(uiArgumentShorthand)\r\n {\r\n var msg = \"UIArgument validation error:\\n\"\r\n + print_r(uiArgumentShorthand);\r\n \r\n // try really hard to throw an exception!\r\n if (!uiArgumentShorthand.name) {\r\n throw new UIArgumentException(msg + 'no name specified!');\r\n }\r\n if (!uiArgumentShorthand.description) {\r\n throw new UIArgumentException(msg + 'no description specified!');\r\n }\r\n if (!uiArgumentShorthand.defaultValues &&\r\n !uiArgumentShorthand.getDefaultValues) {\r\n throw new UIArgumentException(msg + 'no default values specified!');\r\n }\r\n \r\n return true;\r\n };\r\n \r\n \r\n \r\n /**\r\n * @param uiArgumentShorthand\r\n * @param localVars a list of local variables\r\n */\r\n this.init = function(uiArgumentShorthand, localVars)\r\n {\r\n this.validate(uiArgumentShorthand);\r\n this.name = uiArgumentShorthand.name;\r\n this.description = uiArgumentShorthand.description;\r\n if (uiArgumentShorthand.defaultValues) {\r\n var defaultValues = uiArgumentShorthand.defaultValues;\r\n this.getDefaultValues =\r\n function() { return defaultValues; }\r\n }\r\n else {\r\n this.getDefaultValues = uiArgumentShorthand.getDefaultValues;\r\n }\r\n \r\n for (var name in localVars) {\r\n this[name] = localVars[name];\r\n }\r\n }\r\n \r\n \r\n \r\n this.init(uiArgumentShorthand, localVars);\r\n}",
"function preParseOption(l, s, argv) {\n // look for the option in argv covering when it's `--opt=foobar`\n var i = argv.indexOf(l);\n if (i === -1) i = argv.indexOf(s);\n\n // maybe it's come in --argument=value style\n if (i === -1) {\n for (var ii = 0; ii < argv.length; ii++) {\n // --long=value\n i = argv[ii].indexOf(l + '=');\n if (i !== -1) return argv[ii].substr(argv[ii].indexOf(l + '='));\n // -s=value\n i = argv[ii].indexOf(s + '=');\n if (i !== -1) return argv[ii].substr(argv[ii].indexOf(s + '='));\n }\n }\n\n // no dice\n if (i === -1) return false;\n\n // return the argument if there is one\n if (argv[i + 1] && argv[i + 1][0] !== '-') return argv[i + 1];\n\n // otherwise true for finding it at all\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers the ts hook to compile typescript code within the memory | function registerTsHook(appRoot) {
try {
require(helpers_1.resolveFrom(appRoot, '@adonisjs/assembler/build/src/requireHook')).default(appRoot);
}
catch (error) {
if (isMissingModuleError(error)) {
throw new Error('AdonisJS requires "@adonisjs/assembler" in order to run typescript source directly');
}
throw error;
}
} | [
"function recompile() {\n if(compiling) {\n return;\n }\n\n compiling = true;\n\n console.log('Starting compile'.green);\n\n shell.exec('npm run tsc', {async: true}, (code, stdout, stderr) => {\n if(code === 0) {\n console.log(`Typescript compile completed`.green);\n\n lint();\n } else {\n console.error(`Typescript compile failed`.red);\n }\n\n compiling = false;\n });\n}",
"function compile(self) {\n\t\n\t // Load & clone RE patterns.\n\t var re = self.re = __webpack_require__(116)(self.__opts__);\n\t\n\t // Define dynamic patterns\n\t var tlds = self.__tlds__.slice();\n\t\n\t self.onCompile();\n\t\n\t if (!self.__tlds_replaced__) {\n\t tlds.push(tlds_2ch_src_re);\n\t }\n\t tlds.push(re.src_xn);\n\t\n\t re.src_tlds = tlds.join('|');\n\t\n\t function untpl(tpl) { return tpl.replace('%TLDS%', re.src_tlds); }\n\t\n\t re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i');\n\t re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i');\n\t re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i');\n\t re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i');\n\t\n\t //\n\t // Compile each schema\n\t //\n\t\n\t var aliases = [];\n\t\n\t self.__compiled__ = {}; // Reset compiled data\n\t\n\t function schemaError(name, val) {\n\t throw new Error('(LinkifyIt) Invalid schema \"' + name + '\": ' + val);\n\t }\n\t\n\t Object.keys(self.__schemas__).forEach(function (name) {\n\t var val = self.__schemas__[name];\n\t\n\t // skip disabled methods\n\t if (val === null) { return; }\n\t\n\t var compiled = { validate: null, link: null };\n\t\n\t self.__compiled__[name] = compiled;\n\t\n\t if (isObject(val)) {\n\t if (isRegExp(val.validate)) {\n\t compiled.validate = createValidator(val.validate);\n\t } else if (isFunction(val.validate)) {\n\t compiled.validate = val.validate;\n\t } else {\n\t schemaError(name, val);\n\t }\n\t\n\t if (isFunction(val.normalize)) {\n\t compiled.normalize = val.normalize;\n\t } else if (!val.normalize) {\n\t compiled.normalize = createNormalizer();\n\t } else {\n\t schemaError(name, val);\n\t }\n\t\n\t return;\n\t }\n\t\n\t if (isString(val)) {\n\t aliases.push(name);\n\t return;\n\t }\n\t\n\t schemaError(name, val);\n\t });\n\t\n\t //\n\t // Compile postponed aliases\n\t //\n\t\n\t aliases.forEach(function (alias) {\n\t if (!self.__compiled__[self.__schemas__[alias]]) {\n\t // Silently fail on missed schemas to avoid errons on disable.\n\t // schemaError(alias, self.__schemas__[alias]);\n\t return;\n\t }\n\t\n\t self.__compiled__[alias].validate =\n\t self.__compiled__[self.__schemas__[alias]].validate;\n\t self.__compiled__[alias].normalize =\n\t self.__compiled__[self.__schemas__[alias]].normalize;\n\t });\n\t\n\t //\n\t // Fake record for guessed links\n\t //\n\t self.__compiled__[''] = { validate: null, normalize: createNormalizer() };\n\t\n\t //\n\t // Build schema condition\n\t //\n\t var slist = Object.keys(self.__compiled__)\n\t .filter(function (name) {\n\t // Filter disabled & fake schemas\n\t return name.length > 0 && self.__compiled__[name];\n\t })\n\t .map(escapeRE)\n\t .join('|');\n\t // (?!_) cause 1.5x slowdown\n\t self.re.schema_test = RegExp('(^|(?!_)(?:[><\\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i');\n\t self.re.schema_search = RegExp('(^|(?!_)(?:[><\\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig');\n\t\n\t self.re.pretest = RegExp(\n\t '(' + self.re.schema_test.source + ')|' +\n\t '(' + self.re.host_fuzzy_test.source + ')|' +\n\t '@',\n\t 'i');\n\t\n\t //\n\t // Cleanup\n\t //\n\t\n\t resetScanCache(self);\n\t}",
"enterModularCompilation(ctx) {\n\t}",
"_compile(content, filename, filename2) {\n\n content = internalModule.stripShebang(content);\n\n // create wrapper function\n var wrapper = Module.wrap(content);\n\n var compiledWrapper = vm.runInThisContext(wrapper, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true\n });\n\n var inspectorWrapper = null;\n if (process._breakFirstLine && process._eval == null) {\n if (!resolvedArgv) {\n // we enter the repl if we're not given a filename argument.\n if (process.argv[1]) {\n resolvedArgv = Module._resolveFilename(process.argv[1], null, false);\n } else {\n resolvedArgv = 'repl';\n }\n }\n\n // Set breakpoint on module start\n if (filename2 === resolvedArgv) {\n delete process._breakFirstLine;\n inspectorWrapper = process.binding('inspector').callAndPauseOnStart;\n if (!inspectorWrapper) {\n const Debug = vm.runInDebugContext('Debug');\n Debug.setBreakPoint(compiledWrapper, 0, 0);\n }\n }\n }\n var dirname = path.dirname(filename);\n var require = internalModule.makeRequireFunction(this);\n var result;\n if (inspectorWrapper) {\n result = inspectorWrapper(compiledWrapper, this.exports, this.exports,\n require, this, filename, dirname, require.resolve);\n } else {\n result = compiledWrapper.call(this.exports, this.exports, require, this,\n filename, dirname, require.resolve);\n }\n return result;\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 }",
"function pushlex(type, info) {\n var result = function(){\n lexical = new CSharpLexical(indented, column, type, null, lexical, info)\n };\n result.lex = true;\n return result;\n }",
"function compile(code, output) {\n\tvar syntax = esprima.parse(code);\n\tvar compiler = new FirstPassCodeGen();\n\tvar module = compiler.compile(syntax);\n\tmodule.resolve();\n\tmodule.output(output);\n\treturn true;\n}",
"enterOrdinaryCompilation(ctx) {\n\t}",
"enterKotlinFile(ctx) {\n\t}",
"apply(compiler) {\n compiler.hooks.afterEmit.tap('MoveResourcesPlugin', (compilation)=>{\n let movePath = isProduction\n ? `${projectRootPath}/templates/_auto_generated/production/js_bundle.html`\n : `${projectRootPath}/templates/_auto_generated/development/js_bundle.html`;\n\n fs.rename(\n `${webAssetsDistDir}/js_bundle.html`,\n movePath,\n webpackUtils.moveResourcePluginErrorCallback);\n });\n }",
"function visitor(node) {\n if (!/^ts$/.test(node.lang)) {\n return;\n }\n node.value = \"// @ts-nocheck\\n\" + node.value.trim();\n }",
"replaceInnerSource(compiler) {\n compiler.hooks.compilation.tap('InjectInnerWebpackPlugin', (compilation) => {\n compilation.hooks.processAssets.tap('InjectInnerWebpackPlugin', () => {\n this.compilationAssets = compilation.assets;\n const hooks = this.htmlWebpackPlugin.getHooks(compilation);\n\n hooks.afterTemplateExecution.tap('InjectInnerWebpackPlugin', (data) => {\n const template = getRawTemplate(data.plugin.userOptions.template, compiler.context);\n\n const assetList = this.assetListMap[template];\n assetList && assetList.forEach((assetItem) => {\n const {\n chunk,\n innerJsUrl,\n rawScript,\n } = assetItem;\n\n const jsBundle = getBundleByChunk(compilation.chunks, chunk);\n\n if (jsBundle) {\n const content = compilation.assets[jsBundle].source();\n\n data.html = this.getReplacedContent({\n rawScript,\n innerJsUrl,\n content,\n originContent: data.html,\n });\n }\n });\n\n const rawAssetList = this.rawAssetListMap[template];\n rawAssetList && rawAssetList.forEach((rawAssetItem) => {\n const {\n scriptEntryPath,\n innerJsUrl,\n rawScript,\n } = rawAssetItem;\n\n const content = fs.readFileSync(scriptEntryPath, {\n encoding: 'utf-8'\n });\n\n data.html = this.getReplacedContent({\n rawScript,\n innerJsUrl,\n content,\n originContent: data.html,\n });\n });\n });\n });\n });\n }",
"function collectTypes (path: NodePath): void {\n path.traverse({\n InterfaceDeclaration (path: NodePath) {\n path.scope.setData(`typechecker:${path.node.id.name}`, path);\n },\n TypeAlias (path: NodePath) {\n path.scope.setData(`typechecker:${path.node.id.name}`, path);\n },\n ImportDeclaration (path: NodePath) {\n if (path.node.importKind !== 'type') {\n return;\n }\n path.get('specifiers')\n .forEach(specifier => {\n const local = specifier.get('local');\n if (local.isIdentifier()) {\n path.scope.setData(`typechecker:${local.node.name}`, specifier);\n }\n else {\n path.scope.setData(`typechecker:${local.node.id.name}`, specifier);\n }\n });\n },\n \"Function|Class\" (path: NodePath) {\n const node = path.node;\n if (node.typeParameters && node.typeParameters.params) {\n path.get('typeParameters').get('params').forEach(typeParam => {\n path.get('body').scope.setData(`typeparam:${typeParam.node.name}`, typeParam);\n });\n }\n }\n });\n }",
"function register(loader) {\n if (typeof indexOf == 'undefined')\n indexOf = Array.prototype.indexOf;\n if (typeof __eval == 'undefined')\n __eval = eval;\n\n // define exec for easy evaluation of a load record (load.name, load.source, load.address)\n // main feature is source maps support handling\n var curSystem, curModule;\n function exec(load) {\n var loader = this;\n if (load.name == '@traceur') {\n curSystem = System;\n curModule = Module;\n }\n // support sourceMappingURL (efficiently)\n var sourceMappingURL;\n var lastLineIndex = load.source.lastIndexOf('\\n');\n if (lastLineIndex != -1) {\n if (load.source.substr(lastLineIndex + 1, 21) == '//# sourceMappingURL=')\n sourceMappingURL = toAbsoluteURL(load.address, load.source.substr(lastLineIndex + 22, load.source.length - lastLineIndex - 23));\n }\n\n __eval(load.source, loader.global, load.address, sourceMappingURL);\n\n // traceur overwrites System and Module - write them back\n if (load.name == '@traceur') {\n loader.global.traceurSystem = loader.global.System;\n loader.global.System = curSystem;\n //loader.global.Module = curModule;\n }\n }\n loader.__exec = exec;\n\n function dedupe(deps) {\n var newDeps = [];\n for (var i = 0; i < deps.length; i++)\n if (indexOf.call(newDeps, deps[i]) == -1)\n newDeps.push(deps[i])\n return newDeps;\n }\n\n // Registry side table\n // Registry Entry Contains:\n // - deps \n // - declare for register modules\n // - execute for dynamic modules, also after declare for register modules\n // - declarative boolean indicating which of the above\n // - normalizedDeps derived from deps, created in instantiate\n // - depMap array derived from deps, populated gradually in link\n // - groupIndex used by group linking algorithm\n // - module a raw module exports object with no wrapper\n // - evaluated indiciating whether evaluation has happend for declarative modules\n // After linked and evaluated, entries are removed\n var lastRegister;\n function register(name, deps, declare) {\n if (typeof name != 'string') {\n declare = deps;\n deps = name;\n name = null;\n }\n if (declare.length == 0)\n throw 'Invalid System.register form. Ensure setting --modules=instantiate if using Traceur.';\n\n if (!loader.defined)\n loader.defined = {};\n\n lastRegister = {\n deps: deps,\n declare: declare,\n declarative: true,\n };\n\n if (name)\n loader.defined[name] = lastRegister;\n }\n loader.defined = loader.defined || {};\n loader.register = register;\n\n function buildGroups(entry, loader, groups) {\n groups[entry.groupIndex] = groups[entry.groupIndex] || [];\n\n if (indexOf.call(groups[entry.groupIndex], entry) != -1)\n return;\n\n groups[entry.groupIndex].push(entry);\n\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n \n // not in the registry means already linked / ES6\n if (!depEntry)\n continue;\n \n // now we know the entry is in our unlinked linkage group\n var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative);\n\n // the group index of an entry is always the maximum\n if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) {\n \n // if already in a group, remove from the old group\n if (depEntry.groupIndex) {\n groups[depEntry.groupIndex].splice(groups[depEntry.groupIndex].indexOf(depEntry), 1);\n\n // if the old group is empty, then we have a mixed depndency cycle\n if (groups[depEntry.groupIndex].length == 0)\n throw new TypeError(\"Mixed dependency cycle detected\");\n }\n\n depEntry.groupIndex = depGroupIndex;\n }\n\n buildGroups(depEntry, loader, groups);\n }\n }\n\n function link(name, loader) {\n var startEntry = loader.defined[name];\n\n startEntry.groupIndex = 0;\n\n var groups = [];\n\n buildGroups(startEntry, loader, groups);\n\n var curGroupDeclarative = !!startEntry.declarative == groups.length % 2;\n for (var i = groups.length - 1; i >= 0; i--) {\n var group = groups[i];\n for (var j = 0; j < group.length; j++) {\n var entry = group[j];\n\n // link each group\n if (curGroupDeclarative)\n linkDeclarativeModule(entry, loader);\n else\n linkDynamicModule(entry, loader);\n }\n curGroupDeclarative = !curGroupDeclarative; \n }\n }\n\n function linkDeclarativeModule(entry, loader) {\n // only link if already not already started linking (stops at circular)\n if (entry.module)\n return;\n\n // declare the module with an empty depMap\n var depMap = [];\n\n var declaration = entry.declare.call(loader.global, depMap);\n \n entry.module = declaration.exports;\n entry.exportStar = declaration.exportStar;\n entry.execute = declaration.execute;\n\n var module = entry.module;\n\n // now link all the module dependencies\n // amending the depMap as we go\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n \n // part of another linking group - use loader.get\n if (!depEntry) {\n depModule = loader.get(depName);\n }\n // if dependency already linked, use that\n else if (depEntry.module) {\n depModule = depEntry.module;\n }\n // otherwise we need to link the dependency\n else {\n linkDeclarativeModule(depEntry, loader);\n depModule = depEntry.module;\n }\n\n if (entry.exportStar && indexOf.call(entry.exportStar, entry.normalizedDeps[i]) != -1) {\n // we are exporting * from this dependency\n (function(depModule) {\n for (var p in depModule) (function(p) {\n // if the property is already defined throw?\n Object.defineProperty(module, p, {\n enumerable: true,\n get: function() {\n return depModule[p];\n },\n set: function(value) {\n depModule[p] = value;\n }\n });\n })(p);\n })(depModule);\n }\n\n depMap[i] = depModule;\n }\n }\n\n // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic)\n function getModule(name, loader) {\n var module;\n var entry = loader.defined[name];\n\n if (!entry)\n module = loader.get(name);\n\n else {\n if (entry.declarative)\n ensureEvaluated(name, [], loader);\n \n else if (!entry.evaluated)\n linkDynamicModule(entry, loader);\n module = entry.module;\n }\n\n return module.__useDefault ? module['default'] : module;\n }\n\n function linkDynamicModule(entry, loader) {\n if (entry.module)\n return;\n\n entry.module = {};\n\n // AMD requires execute the tree first\n if (!entry.executingRequire) {\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n if (depEntry)\n linkDynamicModule(depEntry, loader);\n }\n }\n\n // lookup the module name if it is in the registry\n var moduleName;\n for (var d in loader.defined) {\n if (loader.defined[d] != entry)\n continue;\n moduleName = d;\n break;\n }\n\n // now execute\n try {\n entry.evaluated = true;\n var output = entry.execute(function(name) {\n for (var i = 0; i < entry.deps.length; i++) {\n if (entry.deps[i] != name)\n continue;\n return getModule(entry.normalizedDeps[i], loader);\n }\n }, entry.module, moduleName);\n }\n catch(e) {\n throw e;\n }\n \n if (output)\n entry.module = output;\n }\n\n // given a module, and the list of modules for this current branch,\n // ensure that each of the dependencies of this module is evaluated\n // (unless one is a circular dependency already in the list of seen\n // modules, in which case we execute it)\n // then evaluate the module itself\n // depth-first left to right execution to match ES6 modules\n function ensureEvaluated(moduleName, seen, loader) {\n var entry = loader.defined[moduleName];\n\n // if already seen, that means it's an already-evaluated non circular dependency\n if (entry.evaluated || !entry.declarative)\n return;\n\n seen.push(moduleName);\n\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n if (indexOf.call(seen, depName) == -1) {\n if (!loader.defined[depName])\n loader.get(depName);\n else\n ensureEvaluated(depName, seen, loader);\n }\n }\n\n if (entry.evaluated)\n return;\n\n entry.evaluated = true;\n entry.execute.call(loader.global);\n delete entry.execute;\n }\n\n var registerRegEx = /System\\.register/;\n\n var loaderFetch = loader.fetch;\n loader.fetch = function(load) {\n var loader = this;\n if (loader.defined && loader.defined[load.name]) {\n load.metadata.format = 'defined';\n return '';\n }\n return loaderFetch(load);\n }\n\n var loaderTranslate = loader.translate;\n loader.translate = function(load) {\n this.register = register;\n\n this.__exec = exec;\n\n load.metadata.deps = load.metadata.deps || [];\n\n // we run the meta detection here (register is after meta)\n return Promise.resolve(loaderTranslate.call(this, load)).then(function(source) {\n \n // dont run format detection for globals shimmed\n // ideally this should be in the global extension, but there is\n // currently no neat way to separate it\n if (load.metadata.init || load.metadata.exports)\n load.metadata.format = load.metadata.format || 'global';\n\n // run detection for register format\n if (load.metadata.format == 'register' || !load.metadata.format && load.source.match(registerRegEx))\n load.metadata.format = 'register';\n return source;\n });\n }\n\n\n var loaderInstantiate = loader.instantiate;\n loader.instantiate = function(load) {\n var loader = this;\n\n var entry;\n \n if (loader.defined[load.name])\n loader.defined[load.name] = entry = loader.defined[load.name];\n\n else if (load.metadata.execute) {\n loader.defined[load.name] = entry = {\n deps: load.metadata.deps || [],\n execute: load.metadata.execute,\n executingRequire: load.metadata.executingRequire // NodeJS-style requires or not\n };\n }\n else if (load.metadata.format == 'register') {\n lastRegister = null;\n \n loader.__exec(load);\n\n // for a bundle, take the last defined module\n // in the bundle to be the bundle itself\n if (lastRegister)\n loader.defined[load.name] = entry = lastRegister;\n }\n\n if (!entry)\n return loaderInstantiate.call(this, load);\n\n entry.deps = dedupe(entry.deps);\n\n // first, normalize all dependencies\n var normalizePromises = [];\n for (var i = 0; i < entry.deps.length; i++)\n normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name)));\n \n return Promise.all(normalizePromises).then(function(normalizedDeps) {\n\n entry.normalizedDeps = normalizedDeps;\n\n // create the empty dep map - this is our key deferred dependency binding object passed into declare\n entry.depMap = [];\n\n return {\n deps: entry.deps,\n execute: function() {\n // this avoids double duplication allowing a bundle to equal its last defined module\n if (entry.esmodule) {\n delete loader.defined[load.name];\n return entry.esmodule;\n }\n\n // recursively ensure that the module and all its \n // dependencies are linked (with dependency group handling)\n link(load.name, loader);\n\n // now handle dependency execution in correct order\n ensureEvaluated(load.name, [], loader);\n\n // remove from the registry\n delete loader.defined[load.name];\n\n var module = Module(entry.module);\n\n // if the entry is an alias, set the alias too\n for (var name in loader.defined) {\n if (loader.defined[name].execute != entry.execute)\n continue;\n loader.defined[name].esmodule = module;\n }\n // return the defined module object\n return module;\n }\n };\n });\n }\n}",
"function InferTypes () {\n ASTTransform.call(this);\n this.varDefs = {};\n this.fnSignatures = {};\n this.fnTypeHints = {};\n this.fnRenaming = {};\n this.runAgain = false;\n}",
"function TamperLang() {\n this.init();\n}",
"function runPostWalkPlugins(options){\n\tvar cntxt = options.context || {};\n\tmergeContexts(cntxt);\n}",
"enterPreprocessorBinary(ctx) {\n\t}",
"generate() {\n var ast = this.ast;\n\n this.print(ast);\n this.catchUp();\n\n return {\n code: this.buffer.get(this.opts),\n tokens: this.buffer.tokens,\n directives: this.directives\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the element and Removes the entire Lesson Also deletes it from the page when it deletes it from the database | function removeLesson(element, lux){
console.log("=======Removing a Lesson=========");
var fullLesson = element.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
var id = fullLesson.getElementsByClassName("lesson-name")[0].id;
fullLesson.parentNode.removeChild(fullLesson);
if(lux){
Ajax("../Lux/Assets/upsert.php", {"id":id},
function(data){
// lesson has been remove from db
});
Ajax("../Lux/Assets/upsert.php", {query:{"lesson_id":id}},
function(data){
// lesson has been remove from db
});
}
} | [
"function delSkill(eleId)\n{\n var skldata = document.getElementById('skillarray').textContent;\n var arrSkill = skldata.split(\",\");\n d = document;\n var childEle = d.getElementById(eleId);\n var parentEle = d.getElementById('SkillsObj');\n \n parentEle.removeChild(childEle);\n \n //delete arrSkill[eleId];\n var delIndex = eleId - 100;\n var delIndex = arrSkill.indexOf(arrSkill[delIndex]);\n //arrSkill.splice(delIndex, 1);\n delete arrSkill[delIndex];\n var hdnskills = document.getElementById('skillarray');\n hdnskills.innerHTML = arrSkill.join();\n\n}",
"remove(element) {\n this.set.splice(this.set.indexOf(element), 1);\n console.log(\"element removed successfully\");\n }",
"destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }",
"remove() {\n // remove this element from appering \n document.getElementById(this.mainEl.id).remove();\n // send a request to remove this node \n axios.delete('post', {\n id: this.post.id\n })\n }",
"function delFeed(myURL){\n var element = document.getElementById(myURL);\n element.parentNode.removeChild(element);\n\tdeleteFromOnScreen(myURL);\n}",
"removeBlogPosts() {\n let blogPost = document.getElementById('blogPosts');\n if (blogPost) {\n blogPost.remove();\n }\n }",
"function removeMovies() {\n var myNode = document.getElementById(\"movies-list\");\n while (myNode.firstChild) {\n myNode.removeChild(myNode.firstChild);\n }\n}",
"function remove_note(e, i){\n \n e.parentNode.parentNode.removeChild(e.parentNode);\n const task=localStorage.getItem(\"array\");\n const note=JSON.parse(task);\n note.splice(i, 1);\n localStorage.setItem('array',JSON.stringify(note));\n location.reload();\n }",
"function deleteVassalOnClick(e){\r\n // Remove the element\r\n g_vassals.splice(parseInt(e.currentTarget.parentNode.id.split('vassal_')[1]), 1);\r\n\r\n setVassals();\r\n setVassalTable();\r\n}",
"function removeScore() {\n localStorage.removeItem(\"user\");\n var removeBtn = document.querySelector(\"#removeBtn\");\n var userList = document.querySelector(\"#userList\");\n removeBtn.parentNode.removeChild(removeBtn);\n userList.parentNode.removeChild(userList);\n liMax = 0;\n}",
"function view_deleteStudentFromView(id) {\n $(`#${id}`).remove();\n}",
"function deleteMovie() {\n\n let movieList = JSON.parse(sessionStorage.getItem(\"movieList\"));\n for (let i = 0; i < movieList.length; i++) {\n if (movieList[i].title == this.parentNode.id) {\n movieList.splice(i, 1);\n }\n }\n sessionStorage.setItem(\"movieList\", JSON.stringify(movieList));\n addMovies();\n}",
"function removeWord () {\n firstWord.remove();\n}",
"function deleteListItem(){\n\tthis.parentNode.remove();\n}",
"function removeStat()\r\n{\r\n var selspan = document.getElementById('lang_span');\r\n if (selspan.childNodes[2])\r\n {\r\n selspan.removeChild(selspan.childNodes[2]);\r\n }\r\n}",
"function domDeleteTodo(dom_element) {\n \n}",
"async function removeStoryfromOwnStoryPage(evt){\n const $storyId = $(evt.target).closest('li').attr('id');\n await storyList.removeStory(currentUser, $storyId);\n putOwnStoriesOnPage(currentUser);\n}",
"function removeFromDB(r){\n var database = firebase.database();\n var booksRef = database.ref('books');\n\n var key = r.parentNode.parentNode.getAttribute(\"id\");\n booksRef.child(key).remove().then(function(){\n console.log(\"Remove success\");\n }).catch(function(error){\n console.log(\"Remove failed : \", error);\n });\n \n document.querySelector(\"tbody\").innerHTML = \"\";\n retrieveData();\n}",
"remove(id) {\n\t\t\tlet index = this.ids.indexOf(id);\n\t\t\tthis.ids.splice(index, 1);\n\t\t\tthis._loadPage();\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets first element in an array that matches given predicate. Throws an error if no match is found. | function first(array, predicate) {
for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
var x = array_3[_i];
if (predicate(x))
return x;
}
throw new Error("first:No element satisfies the condition.!");
} | [
"function firstVal(arr, func) {\n func(arr[0], index, arr);\n}",
"function find(arr, searchValue){\n\treturn arr.filter(i=>{\n\t\treturn i===searchValue;\n\t})[0];\n}",
"function firstMatch(array,regex) {\n return array.filter(RegExp.prototype.test.bind(regex))[0];\n}",
"function findOrCreate(arr, predicate, construct) {\n const index = arr.findIndex((entry) => predicate(entry));\n if (index >= 0) {\n return arr[index];\n }\n const newEntry = construct();\n arr.push(newEntry);\n return newEntry;\n}",
"function find(arr, callback){\n for (let i=0; i<arr.length; i++){\n if (callback(arr[i], i, arr)) return arr[i];\n }\n return undefined;\n}",
"function head(arr){\n return arr[0];\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 getFirstElement(iterable) {\n var iterator = iterable[Symbol.iterator]();\n var result = iterator.next();\n if (result.done)\n throw new Error('getFirstElement was passed an empty iterable.');\n\n return result.value;\n }",
"function arr_find(arr, prop, val) {\n\treturn arr.find(v => { return v && v[prop] === val })\n}",
"function zerothItem(arr) {\n\treturn arr[0];\n}",
"function first(array, n) {\r\n if (array == null) \r\n return 0;\r\n if (n == null) \r\n return array[0];\r\n if (n < 0)\r\n return [];\r\n return array.slice(0, n);\r\n }",
"function findKey(record, predicate) {\n for (const a in record) {\n if (predicate(record[a]))\n return a;\n }\n return undefined;\n}",
"function arr_findIndex(arr = [], prop = \"\", val) {\n\treturn arr.findIndex(v => { return v && v[prop] === val })\n}",
"function lookup(xs, pred) /* forall<a,b> (xs : list<(a, b)>, pred : (a) -> bool) -> maybe<b> */ {\n return foreach_while(xs, function(kv /* (21629, 21630) */ ) {\n var _x31 = pred(fst(kv));\n if (_x31) {\n return Just(snd(kv));\n }\n else {\n return Nothing;\n }\n });\n}",
"findWhere(array, keyName, val) {\n return array.find((item) => {\n return item[keyName] == val;\n });\n }",
"function zerothVal(arr) {\n\treturn arr[0];\n}",
"function querySingle(selector, el){\r\n\t\treturn queryMultiple(selector, el)[0];\r\n\t}",
"getFirstEntry(name, filter = () => true) {\n return this.getEntries(name)\n .filter(filter)\n .shift();\n }",
"dropWhile(array, predicate) {\n for (let i = 0; i < array.length; i++) {\n if (!(predicate(array[i], array.indexOf(array[i]), array))) { // if predicate-function returns false...\n return this.drop(array, i); // ... drop the current element from the array\n }\n }\n return array;\n }",
"function findTruthy(array, { start, step }) {\n for (let i = start; i > 0 && i < array.length; i += step) {\n const item = array[i];\n if (!!item) return item;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Swaps a preexisting report with an updated version | function swapReports(newReport) {
var index = reportCompare(newReport);
// Report exists, swap it
if(index > -1)
reports[index] = newReport;
else // Report doesn't exist, add it
reports.push(newReport);
return true;
} | [
"static discardOldVersions (records) {\n for (let i=0; i < records.length-1; i++) {\n for (let j=i+1; j < records.length; j++) {\n if (records[i].spell_name === records[j].spell_name) {\n let dateA = new Date(records[i].published);\n let dateB = new Date(records[j].published);\n if (dateA < dateB || dateA === null || dateA === '') {\n records[j].rulebook.push(records[i].rulebook[0]);\n records[i] = records[j];\n } else {\n records[i].rulebook.push(records[j].rulebook[0]);\n }\n records.splice(j--, 1);\n }\n }\n }\n return records;\n }",
"function getPatchedSettings(oldSettings, newSettings) {\n if (!oldSettings //undefined\n || !oldSettings.view.report.performance[reportType] //undefined\n || !newSettings //undefined\n || !newSettings.view.report.performance[reportType] //undefined\n || oldSettings.view.report.performance[reportType].length !== newSettings.view.report.performance[reportType].length //not same size\n || angular.toJson(oldSettings) === angular.toJson(newSettings) //no changes\n || angular.toJson(oldSettings) === angular.toJson(REPORT_SETTINGS.default) //it's the first time, publisher has not had settings before\n ) {\n return newSettings;\n }\n\n var changedItems = [];\n for (var idx = 0; idx < oldSettings.view.report.performance[reportType].length; idx++) {\n if (oldSettings.view.report.performance[reportType][idx].key === newSettings.view.report.performance[reportType][idx].key\n && oldSettings.view.report.performance[reportType][idx].show !== newSettings.view.report.performance[reportType][idx].show\n ) {\n changedItems.push(newSettings.view.report.performance[reportType][idx]);\n }\n }\n\n var patchedSettings = angular.copy(newSettings);\n patchedSettings.view.report.performance[reportType] = changedItems;\n\n return patchedSettings;\n }",
"function updateORP(ssheet,issues,lastORPDetails,recentReleases) {\n var sprSheet=SpreadsheetApp.open(DriveApp.getFileById(ssheet))\n var genSheet=makeGeneralPage(sprSheet,recentReleases,lastORPDetails) \n var releases=releaseList()\n for ( r in releases ) {\n var release=releases[r]\n var mileSheet=updateMilestonePage(sprSheet,release,issues[release])\n } \n}",
"function swap (a, b) {\n var c = rep_data.data [a];\n rep_data.data [a] = rep_data.data [b];\n rep_data.data [b] = c;\n}",
"function updateBoardReport(model, reportId) {\n console.assert(model && model.board);\n\n if (reportId === sp.result(model.board, 'boardReport.idP')) {\n return $q.when(model);\n }\n\n model.board.boardReport = reportId;\n return saveBoard(model).then(requestModel);\n }",
"function refreshReport(event) {\n const refresher = event.target\n actions.loadReport(selectedTripId, true).finally(() => refresher.complete())\n }",
"swapRows() {\n Performance.start('swapRows');\n if (this.rows.length > 998) {\n let temp = this.rows[1];\n this.rows[1] = this.rows[998];\n this.rows[998] = temp;\n }\n Performance.stop();\n }",
"function processVersionUpgrade(oldVersion)\n{\n console.log('processVersionUpgrade:', oldVersion);\n\n // Make backup of synced data before proceeding\n makeEmergencyBackup(function()\n {\n var upgradeNotes = []; // Upgrade version notes\n switch (oldVersion)\n {\n /*\n case '1.1.6':\n case '1.1.5':\n case '1.1.4':\n case '1.1.3':\n case '1.1.2':\n case '1.1.1':\n case '1.1.0':\n case '1.0.9':\n case '1.0.8':\n case '1.0.6':\n case '1.0.5':\n case '1.0.3':\n case '1.0.0':\n upgradeNotes.push({ title:'-', message:'New database storage format' });\n case '1.6.1':\n case '1.6.0':\n case '1.5.1':\n case '1.5.0':\n case '1.4.0':\n case '1.3.5':\n case '1.3.2':\n case '1.3.1':\n case '1.3.0':\n case '1.2.6':\n case '1.2.5':\n case '1.2.2':\n case '1.2.0':\n upgradeNotes.push({title:'-', message:'New database storage format'});\n case '1.7.0':\n upgradeNotes.push({title:'-', message:'New database storage format'});\n case '1.8.0':\n upgradeNotes.push({title:'-', message:'Added support for Google Inbox'});\n upgradeNotes.push({title:'-', message:'Added support for Google Translate'});\n upgradeNotes.push({title:'-', message:'Added support for MailChimp'});\n upgradeNotes.push({title:'-', message:'Added support for Confluence'});\n case '1.8.1':\n upgradeNotes.push({title:'-', message:'Fix for Salesforce support'});\n upgradeNotes.push({title:'-', message:'Add new Textarea for demoing'});\n upgradeNotes.push({title:'-', message:'Slight optimizations'});\n case '1.8.2':\n case '1.8.3':\n upgradeNotes.push({title:'-', message:'Change sync error popups to banners'});\n upgradeNotes.push({title:'-', message:'Fix handling of trailing spaces'});\n upgradeNotes.push({title:'-', message:'Add auto-capitalization/-all-caps'});\n upgradeNotes.push({title:'-', message:'Updating banners to be dismissable'});\n case '1.8.4':\n upgradeNotes.push({title:'-', message:'Fix Inbox support'});\n upgradeNotes.push({title:'-', message:'Raise shortcut detection limit to 10s'});\n upgradeNotes.push({title:'-', message:'Fix for @ shortcut prefix issue'});\n case '1.8.5':\n upgradeNotes.push({title:'-', message:'Add omnibox (url bar!) support'});\n upgradeNotes.push({title:'-', message:'Allow consecutive shortcuts to fire'});\n upgradeNotes.push({title:'-', message:'Add support for O365 OWA'});\n upgradeNotes.push({title:'-', message:'Add support for G+ communities'});\n case '1.9.0':\n upgradeNotes.push({title:'-', message:'Fix for O365 OWA'});\n case '1.9.1':\n upgradeNotes.push({title:'-', message:'Fix for Zendesk Inbox'});\n case '1.9.2':\n upgradeNotes.push({title:'-', message:'Fix for Zendesk.com'});\n case '1.9.3':\n upgradeNotes.push({title:'-', message:'Support for Salesforce.com CKEditor'});\n case '1.9.5':\n upgradeNotes.push({title:'-', message:'Support for Hangouts, Facebook'});\n upgradeNotes.push({title:'-', message:'Toggle on/off from icon'});\n\n // Upgrade database to latest version and supply version notes\n upgradeShortcutsToLatest(upgradeNotes);\n break;\n*/\n default:\n console.log('unexpected version number:', oldVersion);\n break;\n }\n });\n}",
"function replaceValuesInExpectedReport(expectedReport, executorUuid) {\n if (expectedReport.report.body !== undefined) {\n if (expectedReport.report.body.nextResponseURL !== undefined) {\n expectedReport.report.body.nextResponseURL = replaceFromRegexOrString(\n expectedReport.report.body.nextResponseURL, \"EXECUTOR_UUID\",\n executorUuid);\n }\n if (expectedReport.report.body.previousResponseURL !== undefined) {\n expectedReport.report.body.previousResponseURL = replaceFromRegexOrString(\n expectedReport.report.body.previousResponseURL, \"EXECUTOR_UUID\",\n executorUuid);\n }\n if (expectedReport.report.body.referrer !== undefined) {\n expectedReport.report.body.referrer = replaceFromRegexOrString(\n expectedReport.report.body.referrer, \"EXECUTOR_UUID\",\n executorUuid);\n }\n }\n if (expectedReport.report.url !== undefined) {\n expectedReport.report.url = replaceFromRegexOrString(\n expectedReport.report.url, \"EXECUTOR_UUID\", executorUuid);\n }\n return expectedReport;\n}",
"function updateMilestonePage(sprSheet,milestone,issues) {\n\n var mileSheet=sprSheet.getSheetByName(milestone)\n if ( mileSheet == null ) return\n if ( mileSheet.getMaxRows() == 1 ) return // no PRs, nothing to do\n \n //get the existing sheet information\n var range=mileSheet.getRange(2,1,mileSheet.getMaxRows()-1,6)\n var data=range.getValues()\n // \n \n // otherwise, loop over the data and look for updates\n var foundPRs={}\n for ( var i in issues) { //issues is the new updated information\n var iss = issues[i]\n var pr = iss['prNum']\n var sigInfo=parseSigInfo(iss['labels'])\n var approvedSigs=sigInfo[0]\n var pendingSigs=sigInfo[1]\n var testsPassed=sigInfo[2]\n \n //check this against the info we have from before\n for ( var row in data ) {\n if ( data[row][0] != pr ) {\n continue;\n }\n foundPRs[data[row][0]]=1\n\n //now just update information as needed to match current github state\n if ( data[row][3] != approvedSigs ) {\n mileSheet.getRange(parseInt(row)+2,4).setValue(approvedSigs) //add one for 0->1 and one for the header row\n }\n if ( data[row][4] != pendingSigs ) {\n mileSheet.getRange(parseInt(row)+2,5).setValue(pendingSigs) \n }\n if ( data[row][5] != testsPassed ) {\n mileSheet.getRange(parseInt(row)+2,6).setValue(testsPassed)\n }\n break // no need to keep going\n } \n }\n // done updating old information\n \n // hide rows for PRs that are closed already\n for ( var row in data) {\n if ( foundPRs[data[row][0]] != 1 ) {\n mileSheet.hideRows(parseInt(row)+2)\n }\n }\n \n // now add new rows for new PRs\n var data=[]\n var formulas=[]\n for ( var i in issues ) { //this code must be repeated elsewhere - could be consolidated\n var iss=issues[i]\n var pr=iss['prNum']\n if ( foundPRs[pr] == 1 ) {\n continue\n }\n\n var sigInfo=parseSigInfo(iss['labels'])\n var approvedSigs=sigInfo[0]\n var pendingSigs=sigInfo[1]\n var testsPassed=sigInfo[2]\n var comments=''\n data.push( [ extractDate(iss['date']),iss['title'],approvedSigs,pendingSigs,testsPassed,comments] )\n formulas.push( ['=HYPERLINK(\"http://www.github.com/cms-sw/cmssw/pull/'+pr+'\",\"'+pr+'\")'] )\n }\n \n //in one set of commands, add all the new rows\n var nCols=7\n var nNewRows=data.length\n if ( nNewRows > 0 ) {\n mileSheet.insertRowsAfter(1,nNewRows)\n var rangeD=mileSheet.getRange(2,2,nNewRows,nCols-1)\n var rangeF=mileSheet.getRange(2,1,nNewRows,1)\n rangeD.setValues(data)\n rangeF.setFormulas(formulas)\n }\n \n \n // Protect the active sheet, then remove all other users from the list of editors.\n var protection = mileSheet.protect().setDescription('Protected sheet');\n \n // Ensure the current user is an editor before removing others. Otherwise, if the user's edit\n // permission comes from a group, the script will throw an exception upon removing the group.\n var me = Session.getEffectiveUser();\n protection.addEditor(me);\n protection.removeEditors(protection.getEditors());\n if (protection.canDomainEdit()) {\n protection.setDomainEdit(false);\n }\n\n //redo the formatting with the new rows\n var nRows=mileSheet.getLastRow()\n if ( nRows>1 ) {\n var range=mileSheet.getRange(2,nCols,nRows-1,1)\n protection.setUnprotectedRanges([range])\n }\n mileSheet.getRange(1,1,nRows,nCols).setWrap(true)\n \n}",
"function updateVersion() {\r\n\r\n\t\t\t\t\t\tconsole.log(\"updateVersion\");\r\n\r\n\t\t\t\t\t\tinekonApi\r\n\t\t\t\t\t\t\t\t.getVersion($scope.cartId, $scope.versionId)\r\n\t\t\t\t\t\t\t\t.then(\r\n\t\t\t\t\t\t\t\t\t\tfunction(result) {\r\n\t\t\t\t\t\t\t\t\t\t\tchartPromise\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.then(function(chart) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// data row\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar row = result.data.data.result, len = row.length, i;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar dataTable = new google.visualization.DataTable();\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdataTable.addColumn(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'number',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'index');\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdataTable.addColumn(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'number',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'Resultat');\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor (i = 0; i < len; ++i) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdataTable\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.addRow([\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trow[i] ]);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tchart.draw(dataTable);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t}",
"function deleteReportAtIndex(index) {\n let reportCache = findOrCreateReportCache();\n reportCache.splice(index, 1);\n\n return saveReportCache(reportCache);\n }",
"setupReportFinder(html, cell, i) {\n const graphicRow = cell.closest('tr');\n const newRow = document.createElement('tr');\n newRow.dataset.forRow = graphicRow.dataset.graphicsRow;\n newRow.innerHTML = `<td colspan=\"4\" class=\"report-choices\"><div id=\"report-choices-${i}\">${html}</div></td>`;\n graphicRow.after(newRow);\n newRow.querySelector('button.report').addEventListener('click', function (event) {\n event.preventDefault();\n const reportFilename = event.target.innerText.trim();\n cell.querySelector('input').value = `/reports/${reportFilename}`;\n newRow.remove();\n });\n newRow.querySelector('button.reports-cancel').addEventListener('click', function (event) {\n event.preventDefault();\n newRow.remove();\n });\n const self = this;\n newRow.querySelector('button.refresh').addEventListener('click', function (event) {\n event.preventDefault();\n const loading = event.target.querySelector('.loading');\n loading.style.display = 'inline';\n fetch('/releases/list-reports')\n .then(response => response.text())\n .then(function (html) {\n newRow.remove();\n self.setupReportFinder(html, cell, i);\n })\n .catch(function (error) {\n alert('Sorry, there was a problem reloading the list of reports.');\n loading.style.display = 'none';\n console.log(error);\n });\n });\n newRow.querySelector('.sorting-options button').addEventListener('click', function (event) {\n event.preventDefault();\n const link = event.target;\n link.classList.add('selected');\n const newest = newRow.querySelector('ul.newest');\n const alphabetic = newRow.querySelector('ul.alphabetic');\n if (link.classList.contains('newest')) {\n newRow.querySelector('.sorting-options button.alphabetic').classList.remove('selected');\n newest.style.display = 'block';\n alphabetic.style.display = 'none';\n } else if (link.classList.contains('alphabetic')) {\n newRow.querySelector('.sorting-options button.newest').classList.remove('selected');\n newest.style.display = 'none';\n alphabetic.style.display = 'block';\n }\n });\n }",
"function push_version() {\n if (versions.length == 30) { // 30 = Max undo\n versions.pop(); // Removes last element in Versions\n }\n var v_artwork = artwork.cloneNode(true);\n versions.unshift(v_artwork); // Adds current artwork to beginning of Versions\n}",
"function reportCompare(report) {\n\n if (reports.length > 0) {\n for (var i = 0; i < reports.length; i++) {\n if (reports[i].processId == report.processId && reports[i].host == report.host && reports[i].processStateChange == report.processStateChange && reports[i].mainClass == report.mainClass)\n return i;\n }\n return -1;\n }\n return -1;\n }",
"function updateExportStableResultsInOfflineMode() {\n\tlistOfStableResultsForCreatedFileExportModules = [];\n\tfor( var i = 0; i < configsCreatedFileExportModules.length; i++ ) {\n\t\t\n\t\tvar connectedOutputPinID = listConfigsCurrentInfo[i].config.chain[0].connections[0].outputPinID;\n\t\tfor (var j = 0; j < listConfigsCurrentInfo[i].status.chain[0].stableResults.length; j++ ) {\n\t\t\tif (listConfigsCurrentInfo[i].status.chain[0].stableResults[j].pinID == connectedOutputPinID) {\n\t\t\t\t//alert(JSON.stringify(listConfigsCurrentInfo[i].status.chain[0].stableResults[j]));\n\t\t\t\tlistOfStableResultsForCreatedFileExportModules[i] = listConfigsCurrentInfo[i].status.chain[0].stableResults[j]; // get stable results for selected [i] connected output pin [j]\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (listConfigsRecordingInfo[i].listOutputpinsExportStableResults == undefined) // first stable results query\n\t\t{\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults = {};\n\t\t\t\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.timestampStart = listOfStableResultsForCreatedFileExportModules[i].timestampStart;\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.timestampEnd = listOfStableResultsForCreatedFileExportModules[i].timestampEnd;\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.timestampNextPending = listConfigsRecordingInfo[i].listOutputpinsExportStableResults.timestampStart;\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.indexStart = listOfStableResultsForCreatedFileExportModules[i].indexStart;\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.indexEnd = listOfStableResultsForCreatedFileExportModules[i].indexEnd;\n\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.indexNextPending = listConfigsRecordingInfo[i].listOutputpinsExportStableResults.indexStart;\n\t\t}\n\t\telse // update stable results\n\t\t{\n\t\t\tif (listOfStableResultsForCreatedFileExportModules[i].timestampEnd>listConfigsRecordingInfo[i].listOutputpinsExportStableResults.timestampEnd)\n\t\t\t{\n\t\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.timestampEnd = listOfStableResultsForCreatedFileExportModules[i].timestampEnd;\n\t\t\t}\n\n\t\t\tif (listOfStableResultsForCreatedFileExportModules[i].indexEnd>listConfigsRecordingInfo[i].listOutputpinsExportStableResults.indexEnd)\n\t\t\t{\n\t\t\t\tlistConfigsRecordingInfo[i].listOutputpinsExportStableResults.indexEnd = listOfStableResultsForCreatedFileExportModules[i].indexEnd;\n\t\t\t}\n\t\t}\n\t}\n}",
"processControllerReport (report) {\n const { data } = report\n this.lastReport = data.buffer\n\n // Interface is unknown\n if (this.state.interface === 'none') {\n if (data.byteLength === 63) {\n this.state.interface = 'usb'\n } else {\n this.state.interface = 'bt'\n this.device.receiveFeatureReport(0x02)\n return\n }\n }\n\n this.state.timestamp = report.timeStamp\n\n // USB Reports\n if (this.state.interface === 'usb' && report.reportId === 0x01) {\n this.updateState(data)\n }\n // Bluetooth Reports\n if (this.state.interface === 'bt' && report.reportId === 0x11) {\n this.updateState(new DataView(data.buffer, 2))\n this.device.receiveFeatureReport(0x02)\n }\n }",
"function rollback(version) {\n // TODO\n internals.assertCurrentWorkingAlias();\n\n const config = internals.config;\n const versions = internals.versions;\n\n if (versions[version]) {\n // get the file from the requested version object\n const { file_hash } = versions[version];\n\n // get the compressed buffer from version_files using the hash (the saved compressed file of the version)\n // this can be turned into seperate functions\n const compressedBuffer = fse.readFileSync(\n path.join(internals.PROJECT_PATH, \"version_files\", file_hash)\n );\n\n // decompress the buffer\n const decompressedBuffer = zlib.brotliDecompressSync(compressedBuffer);\n\n fse.writeFileSync(internals.config.documentPath, decompressedBuffer);\n\n config.currentVersion = version;\n\n internals.saveConfigFile(config);\n\n // spinner.succeed(\n // chalk.bold(`Successfully rolled back to version ${version}`)\n // );\n // console.log(`Successfully rolled back to version ${version}`);\n } else {\n // spinner.fail(chalk.bold(\"Docit: given version does not exist\"));\n throw new Error(\"Docit: given version does not exist\");\n }\n}",
"upgradePromise({json = undefined, nRowsBetweenProgressEvents = 1000, onProgress = undefined} = {}) {\n\n this.reset();\n this.nRowsBetweenProgressEvents = nRowsBetweenProgressEvents;\n this.onProgress = onProgress;\n\n // Retrieve the data model version used in the json.\n let { version, isGuessed } = this.validator.getVersion(json);\n this.json = json;\n this.version = version;\n\n // If the data model version could not be found or guessed, stop here.\n if (!this.version)\n return Promise.resolve();\n\n this.jsonOld = json;\n this.versionOld = version;\n return this._mapPromise().then(this._mergePromise.bind(this));\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an approver for an ERC721 Token | async function getApproved(tokenID) {
console.log('Getting Approver for an NF Token', tokenID);
const nfToken = await NFTokenMetadata.at(await getContractAddress('NFTokenMetadata'));
return nfToken.getApproved.call(tokenID);
} | [
"async getContract() {\n let res = await axios(`${rahatServer}/api/v1/app/contracts/Rahat`);\n const { abi } = res.data;\n res = await axios(`${rahatServer}/api/v1/app/settings`);\n const contractAddress = res.data.agency.contracts.rahat;\n return new ethers.Contract(contractAddress, abi, wallet);\n }",
"static get_token({ organizationId, tokenId }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"getByToken(){\n return http.get(\"/Employee/token/\" + localStorage.getItem('login').toString().split(\"Bearer \")[1]);\n }",
"static getRequestorOrg(ctx) {\n\t\t//Return requestor MSP value\n\t\treturn ctx.clientIdentity.getMSPID();\n\t}",
"function getBearerToken() {\n // These are your credentials. Copied from Slack\n var clientId = \"vb5V9lDO52aGeCa72ne1m62jbeBVnpsmo0zNWB6WXNlaHsxHwX\"\n var clientSecret = \"lSZxDywC45exeleR65WjlWjkIIIPl8F4BTB9GexH\"\n // Has to be a POST request because you are sending data\n fetch(\"https://api.petfinder.com/v2/oauth2/token\", {\n method: 'POST',\n // They expect you to send this info in the \"body\"\n body: \"grant_type=client_credentials&client_id=\" + clientId + \"&client_secret=\" + clientSecret,\n // Needed to prevent errors \n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n }).then(function (apiResponse) {\n return apiResponse.json()\n }).then(function (bearerToken) {\n // This provides you an access token. \n // It is good for 3600 seconds, or 1 hour.\n getPetData(bearerToken.access_token)\n })\n}",
"ListOfContractsSignedBetweenYouAndOVH(agreed, contractId) {\n let url = `/me/agreements?`;\n const queryParams = new query_params_1.default();\n if (agreed) {\n queryParams.set('agreed', agreed.toString());\n }\n if (contractId) {\n queryParams.set('contractId', contractId.toString());\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"function getRequestToken(){\n console.log('Fetching request token from Twitter..');\n client.fetchRequestToken( 'oob', function( token, data, status ){\n if( ! token ){\n console.error('Twitter failure: status '+status+', failed to fetch request token');\n process.exit( EXIT_AUTHFAIL );\n }\n client.setAuth( consumerKey, consumerSec, token.key, token.secret );\n prompt('Enter verifier from '+token.getAuthorizationUrl(), getAccessToken );\n } );\n }",
"async getTokenRegistryContract(block, ads, chain) {\n return (\n await sdk.api.abi.call({\n block,\n target: ads,\n params: [],\n abi: abi[\"tokenRegistry:getTokens\"],\n })\n ).output;\n }",
"async getGuestToken(){\n\t\t \n\t\tvar tokenModel = new TokenModel();\n\t\tvar tokenResponseData = {};\n\t\ttry {\n\t\t\tconst url = config.SFCC_ENV_URL+SFCCAPIPath.SFCC_CUSTOMER_AUTH+\"?\"+SFCCAPIPath.SFCC_CLIENT_ID;\n\t\t\t \n\t\t\tvar bodyData = { \"type\": \"guest\"};\n\t\t\tvar authHeaders = {\n\t\t\t\t\"Content-Type\":\"application/json\"\n\t\t\t} \n\t\t\tconst guestTokenResp = await fetch(url,{method:'post',headers:authHeaders,body:JSON.stringify(bodyData)});\n\t\t\tvar customerDetails = await guestTokenResp.json();\n\t\t\ttokenResponseData = tokenModel.getTokenAssoicatedData(customerDetails);\n\t\t\tif(tokenResponseData.success){\n\t\t\t\ttokenResponseData.token = guestTokenResp.headers.get('Authorization');\n\t\t\t}else{\n\t\t\t\ttokenResponseData.token = \"\";\n\t\t\t}\n\t\t}catch (error) {\n\t\t\tconsole.log(\"Token.getGuestToken:\"+error);\n\t\t\ttokenResponseData.success=false;\n\t\t\ttokenResponseData.error = {};\n\t\t\ttokenResponseData.error.errorDescription = \"Token.getGuestToken: Error is \"+error.toString();\n\t\t\ttokenResponseData.error.errorMSG = getSFCCErrorMSG(\"Token.101\");\n\t\t\ttokenResponseData.error.errorCode = \"Token.101\";\n\t\t}\n\t\treturn tokenResponseData;\n\t}",
"function search_oauth2_token(token_id) {\n\n\treturn models.oauth_access_token.findOne({\n\t\twhere: {access_token: token_id},\n\t\tinclude: [{\n\t\t\tmodel: models.user,\n\t\t\tattributes: ['id', 'username', 'email', 'gravatar']\n\t\t}]\n\t}).then(function (token_info) {\n\t\tif (token_info) {\n\t\t\tif ((new Date()).getTime() > token_info.expires.getTime()) {\n\t\t\t\treturn Promise.reject({ error: {message: 'Oauth token has expired', code: 401, title: 'Unauthorized'}})\t\n\t\t\t}\n\n\t\t\tvar oauth2_token_owner = { oauth_client_id: token_info.oauth_client_id }\n\n\t\t\tif (token_info.user_id) {\n\t\t\t\toauth2_token_owner['user'] = token_info.User\n\t\t\t}\n\n\t\t\tif (token_info.iot_id) {\n\t\t\t\toauth2_token_owner['iot'] = token_info.iot_id\n\t\t\t}\n\t\t\t \n\t\t\treturn Promise.resolve(oauth2_token_owner)\n\t\t} else {\n\t\t\treturn Promise.reject({ error: {message: 'Oauth token not found', code: 404, title: 'Not Found'}})\n\t\t}\n })\n}",
"async function verify( token ) {\n const ticket = await client.verifyIdToken({\n idToken: token,\n audience: CLIENT_ID, \n });\n //En el payload vamos a tener toda la informacion del usuario\n const payload = ticket.getPayload();\n // const userid = payload['sub'];\n // If request specified a G Suite domain:\n //const domain = payload['hd'];\n return {\n nombre: payload.name,\n email:payload.email,\n img: payload.picture,\n google: true \n }\n}",
"function getDelegateApprover(recId)\n{\n\tvar ret = null;\n\tif(recId)\n\t{\n\t\tvar empRec = nlapiLoadRecord('employee',recId);\n\t\tvar delegateApp = empRec.getFieldValue('custentity_spk_emp_delgt_apv');\n\t\tvar isEligible = empRec.getFieldValue('custentity_spk_isdelegatereq');\n\t\tif(isEligible == 'T')\n\t\t{\n\t\t\tvar currDate = new Date();\n\t\t\tvar cDate = nlapiDateToString(currDate,'dd/mm/yyyy');\n\t\t\tvar currentDate = nlapiStringToDate(cDate);\n\t\t\tvar startDate = empRec.getFieldValue('custentity_spk_emp_delgt_stdate');\n\t\t\tvar endDate = empRec.getFieldValue('custentity_spk_emp_delgt_enddate');\t\t\t\n\t\t\tstartDate = new Date(startDate);\n\t\t\tendDate = new Date(endDate);\t\t\n\t\t\tif(delegateApp)\n\t\t\t{\t\t\t\t\t\t\n\t\t\t\tif(startDate && endDate && (currentDate >= startDate && currentDate <= endDate))\n\t\t\t\t{\n\t\t\t\t\tret = delegateApp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n }\n\treturn ret;\n}",
"async getContract() {\n if (!this.contract) {\n this.contractAddress = await this.getTokenAddress()\n const web3 = this.contractService.web3\n this.contract = new web3.eth.Contract(\n OriginTokenContract.abi,\n this.contractAddress\n )\n this.decimals = await this.contract.methods.decimals().call()\n }\n }",
"async function checkOreAccessToken(oreAccessToken, req) {\n let errHead = `invalid ore-access-token `\n let errMsg = ''\n try {\n let requestParams = {}\n if (!process.env.VERIFIER_PUBLIC_KEY) {\n errMsg = `verifier public key is missing. Provide a valid verifier public key as environment variable`;\n throw new Error(`${errMsg}`);\n }\n\n const verifierPublicKey = process.env.VERIFIER_PUBLIC_KEY.replace(/\\\\n/g, '\\n')\n\n const payload = await jwt.verify(oreAccessToken, verifierPublicKey, {\n algorithms: [\"ES256\"]\n })\n if (req.query && req.body && Object.keys(req.query).length > 0 && Object.keys(req.body).length > 0) {\n requestParams[\"http-url-params\"] = req.query\n requestParams[\"http-body-params\"] = req.body\n } else if (Object.keys(req.query).length > 0) {\n requestParams = req.query\n } else {\n requestParams = req.body\n }\n\n const isValid = await checkRequestParams(payload.reqParamHash, requestParams)\n return isValid\n } catch (error) {\n if (error.message == 'jwt expired') {\n errMsg = ` Expired ore-access-token. Provide a valid token.`\n }\n\n if (error.message == 'invalid signature') {\n errMsg = ` Invalid signature for ore-access-token. Make sure ore-access-token is signed with a valid key`\n }\n\n if (error.message == 'jwt malformed') {\n errMsg = ` Malformed ore-access-token. Make sure the ore-access-token has the valid right name and voucher.`\n }\n\n logError(\"Error\", `${errHead}:${errMsg}:${error.message}`)\n throw new Error(`${errHead}:${errMsg}:${error.message}`)\n }\n}",
"function getGuestToken(callback) {\n requests.getGuestToken(function (response) {\n if (response.success) {\n guestToken = response.token;\n callback && callback();\n }\n });\n}",
"getPastMeeting(uuid) {\n const response = jwtHelper.getApi('past_meetings/' + uuid);\n return response;\n }",
"getAccessToken() {\n return new Promise((resolve, reject) => {\n if (this.isAccessTokenValid()) {\n resolve(this.accessToken);\n } else {\n this.renewTokens().then(authResult => {\n resolve(authResult.accessToken);\n }, reject);\n }\n });\n }",
"function isActiveToken () {\n const url = `${baseURl}/api/user/verifyToken`\n return localforage.getItem('token').then((jwt) => {\n return axios.post(url, { params: jwt })\n })\n}",
"function getCreateAccountToken() {\n var params_0 = {\n action: \"query\",\n meta: \"tokens\",\n type: \"createaccount\",\n format: \"json\"\n };\n\n request.get({ url: endPoint, qs: params_0 }, function (error, res, body) {\n if (error) {\n return;\n }\n var data = JSON.parse(body);\n createaccount(data.query.tokens.createaccounttoken);\n });\n}",
"async function approveHash(uri, contractAddress, wallet, pass, ledgerCon) {\n if (web3 === undefined) {\n await connect(ledgerCon, contractAddress);\n }\n const contract = new web3.eth.Contract(CONTRACT_ABI, contractAddress);\n return web3.eth.personal\n .unlockAccount(wallet, pass, UNLOCK_DURATION)\n .then(() => console.log(\"Account unlocked! (\" + wallet + \")\"))\n .then(() => contract.methods.approve(uri).encodeABI())\n .then(txData => execTx(wallet, contractAddress, txData))\n .then(() => web3.eth.personal.lockAccount(wallet))\n .then(() => console.log(\"Account locked! (\" + wallet + \")\"));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine knockback, stagger, or neither. | applyKnockbackStagger(victim, attackEntity) {
// pre-extraction
let isKnockbackable = victim.has(Component.Knockbackable);
let isStaggerable = victim.has(Component.Staggerable);
let otherComps = this.ecs.getComponents(attackEntity);
let attack = otherComps.get(Component.Attack);
// compute what we want
let doStagger = isStaggerable && attack.info.damage > 0 && attack.info.attackType == Weapon.AttackType.Combo;
let doKnockback = isKnockbackable && attack.info.damage > 0 && (!doStagger);
// Handle extra knockback stuff.
if (doKnockback) {
this.applyKnockback(victim);
}
// Handle stagger stuff.
if (doStagger) {
this.applyStagger(victim, attackEntity);
}
// return whether we knockback'd or stagger'd
return [doKnockback, doStagger];
} | [
"function hungry(hunger){\n \nreturn hunger <= 5 ? 'Grab a snack': 'Sit down and eat a meal';\n}",
"function isSnowingv2() {\n if (weather === \"snowing\") {\n return \"it's snowing\";\n }\n else {\n return \"check back later for more details\";\n }\n}",
"function C006_Isolation_Yuki_CheckToEat() {\n\t\n\t// Yuki forces the player if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"LickEgg\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n\t// Yuki forces the player if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"LickSub\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n}",
"isStrongerThan(hand) {\n // ˅\n return this.judgeGame(hand) === 1;\n // ˄\n }",
"function massHysteria(c, d) {\n let c = cats;\n let d = dogs;\n\n if (d.raining === true && c.raining === true) {\n console.log ('DOGS AND CATS LIVING TOGETHER! MASS HYSTERIA!')\n }\n }",
"function C101_KinbakuClub_RopeGroup_HelplessKnot() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteKnot\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}",
"function applyTwoStrikeCountLogicToSwingChance(idDifference){\n\t\t\tvar positiveId = battingResults.positiveId;\n\t\t\tvar pitchInStrikeZone = __.isPitchInStrikeZone(pitch.location);\n\t\t\tvar negativeCloseOnZone = (!positiveId && pitchInStrikeZone && (idDifference <= battingConstants.BATTER_CLOSE_NEG_ID_MAX));\n\t\t\tvar likelySwingAndMissThreshold = (pitchInStrikeZone ? battingConstants.IN_ZONE_LIKELY_SWING_MISS_THRESHHOLD : battingConstants.OUT_OF_ZONE_LIKELY_SWING_MISS_THRESHHOLD);\n\t\t\tvar negativeNotClose = (!positiveId && (idDifference > likelySwingAndMissThreshold));\n\t\t\tvar positiveOnZone = (positiveId && pitchInStrikeZone);\n\t\t\tbattingResults.likelySwingAndMiss = negativeNotClose;\n\n\t\t\t//if in-zone pitch seen well enough, batter is more lkely to swing to avoid a strikeout looking OR\n\t\t\t//pitch thrown well enough to increase chance that batter chases\n\t\t\tif(positiveOnZone || negativeCloseOnZone || negativeNotClose){\n\t\t\t\tvar oneHundredMinusFinalChance = __.get100minusAttribute(battingResults.chanceOfSwinging);\n\t\t\t\tvar chanceOfSwingingPostIncrease = (battingResults.chanceOfSwinging + __.getRandomDecimalInclusive(oneHundredMinusFinalChance - battingConstants.SWING_INCREASE_MIN_SUBTRACTER, oneHundredMinusFinalChance, 1));\n\n\t\t\t\tbattingResults.chanceOfSwinging = chanceOfSwingingPostIncrease;\n\t\t\t}\n\t\t}",
"function decideWhetherOrNotToTrade(tweet){\n \n var buy = false\n var game = _.includes(tweet,'game') //bad\n var news = _.includes(tweet,'news') // good\n var money = _.includes(tweet,'money') //bad\n var fun = _.includes(tweet,'fun') //good\n var good = _.includes(tweet,'good') //bad \n var actor = _.includes(tweet,'actor') //good\n var movies = _.includes(tweet,'movies') //\n var tech = _.includes(tweet,'tech') //does nothing\n var music = _.includes(tweet,'music') //bad\n var people = _.includes(tweet,'people')//good\n var apple = _.includes(tweet,'apple')//good\n var google = _.includes(tweet,'google')//good\n if(bank.currency == 'USD'){\n \tif ( news || fun || actor || movies || people || apple || google){\n \t\tbuy = true\n \t}\n \telse{\n \t\tbuy = false\n \t}\n }\n return buy\n}",
"function betHorses(){ \r\n if(bet == 1) bet = 'horse1'; \r\n if(bet == 2) bet = 'horse2';\r\n if(bet == 3) bet = 'horse3';\r\n if(bet == 4) bet = 'horse4';\r\n}",
"function applyPitchTypeLogicToSwingChance(chanceOfSwinging){\n\t\t\tvar countPosition = __.batterCountPosition(gamePlayService.balls(), gamePlayService.strikes());//ahead, behind or even\n\t\t\tvar pitchType = (pitch.pitchSubType ? pitch.pitchSubType : pitch.pitchType);\n\t\t\tvar pitchTypeSwingPercentages = pitch.pitchTypeSwingPercentages[pitchType];\n\t\t\tvar pitchTypeSwingChance = pitchTypeSwingPercentages[countPosition];\n\t\t\tvar difference = (Math.abs(chanceOfSwinging - pitchTypeSwingChance) / battingConstants.LOGIC_SWING_CHANCE_DIVIDER);//bring the chance of swinging LOGIC_SWING_CHANCE_DIVIDER to the avg swing perc for this pitch type/count position\n\t\t\tdifference = ((chanceOfSwinging > pitchTypeSwingChance) ? difference : (difference * -1));\n\n\t\t\treturn (chanceOfSwinging + difference);\n\t\t}",
"function C006_Isolation_Yuki_CheckToStop() {\n\n\t// Yuki doesn't allow the player to stop if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"NoPullEgg\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t\tC006_Isolation_Yuki_AllowPullBack = false;\n\t}\n\n\t// Yuki doesn't allow the player to stop if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"NoPullSub\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t\tC006_Isolation_Yuki_AllowPullBack = false;\n\t}\n\t\n}",
"function check(smuggler,sheriff,players,decks){\n\tvar smugglerStats = players[smuggler].game;\n\tvar declared = smugglerStats.declared;\n\tvar sheriffStats = players[sheriff].game;\n\tvar lying=false;\n\tvar penalty=0;\n\t//forfeit any bribes\n\tfor(var bribe in player.bribe){\n\t\taddGood(sheriff,bribe);\n\t}\n\tfor(var good in smugglerStats.bag){\n\t\tif(good.name!=declared){\n\t\t\t//reset penalty to start being incurred to smuggler\n\t\t\tif(!lying){\n\t\t\t\tpenalty=0;\n\t\t\t}\n\t\t\tlying=true;\n\t\t\t//discard the good\n\t\t\tif(decks.leftHeap>decks.rightHeap){\n\t\t\t\tdecks.rightHeap.push(good);\n\t\t\t}else{\n\t\t\t\tdecks.leftHeap.push(good);\n\t\t\t}\n\t\t\tpenalty+=good.penalty;\n\t\t}else{\n\t\t\t//if player has been consistently truthful add more penalty\n\t\t\tif(!lying){\n\t\t\t\tpenalty+=good.penalty;\n\t\t\t}\n\t\t}\n\t\tpassThrough(smuggler);\n\t\tvar result;\n\t\tif(!lying){\n\t\t\tsheriffStats.money-=penalty;\n\t\t\tsmugglerStats.money+=penalty;\n\t\t\tresult = 'Tricked again! You lost {penalty} coins for incorrect inspection';\n\t\t}else{\n\t\t\tsheriffStats.money+=penalty;\n\t\t\tsmugglerStats.money-=penalty;\n\t\t\tresult = 'Gotcha! You caught them red handed. Nothing like a good profit';\n\t\t}\n\t\treturn{\"result\":result};\n\t}\n}",
"get isSwitchable() {\r\n return true; // we know no lightbulbs that aren't switchable\r\n }",
"handleAbsorption(predator) {\n // Calculate distance from boost to predator\n let d = dist(this.x, this.y, predator.x, predator.y);\n // Check if the distance is less than their two radii (an overlap)\n if (d < this.radius + predator.radius) {\n // Blue flashing effect indicating collision\n background(this.fillColor);\n // Increase predator speed once caught\n // No limit to its speed\n predator.speed = predator.speed * predator.boostSpeed;\n // Sound effect (ambient beep) when the predator boosts\n ambientBeep.play();\n // Setting the beep volume so it matches the background game music volume\n ambientBeep.setVolume(0.15);\n // Reset the boost once caught\n this.reset();\n }\n }",
"function C101_KinbakuClub_RopeGroup_HelplessStruggle() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteStruggle\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}",
"function poopMike(message) {\n\n\tconst addChance = 2;\n\tconst randomNum = (Math.random() * 100);\n\n\t// Determine whether to poop Mike or not\n\tif (randomNum >= addChance) {\n\t\t// If result is greater than likelihood, end.\n\t\tconsole.info('Mike has narrowly escaped pooping');\n\t\treturn;\n\t}\n\t// poop on Mike\n\tmessage.react('💩');\n\tconsole.info(\"Mike's been pooped\");\n\t\n}",
"humanHitOrStay() {\n while (this.human.HitOrStay()) {\n\n console.clear();\n this.showMoney();\n this.dealer.nextCard.call(this);\n this.displayHandsWhileHitting();\n\n if (this.human.isBusted()) {\n console.clear();\n break;\n }\n\n }\n }",
"get isWeighted() {\n return this._config.isWeighted;\n }",
"function adjustWill (luckySign, luckModifier) {\n var adjust = 0;\n if (luckySign.luckySign != undefined && (luckySign.luckySign === \"Luck sign\" || luckySign.luckySign === \"Resisted temptation\")){\n adjust = luckModifier;\n }\n\treturn adjust;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add this object to the list of drawable entities of this Canvas. | attach(obj)
{
if (obj.draw) {
this.entities.add(obj);
return true;
}
throw new Error("The object passsed is not drawable.");
} | [
"draw() {\r\n this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height);\r\n this._ctx.save();\r\n for (let i = 0; i < this._entities.length; i++) {\r\n this._entities[i].draw(this._ctx);\r\n }\r\n this._ctx.restore();\r\n }",
"add_element(obj) {\n if (!(obj instanceof GameObject)) throw new TypeError(\"#Animation: Can only add gameobjects to the scene\");\n this.actors.push(obj);\n this.scene.add(obj.mesh);\n }",
"constructor(canvasElementId, canvasWidth = '', imageSrc = '',\n lineWidth = '2', lineColor = '#000000', lineHead = false, fontFamily = 'Arial',\n fontSize = '20', fontColor = '#000000', fontStyle = 'regular', fontAlign = 'center',\n fontBaseline = 'middle', mark = 'X', orderType = ORDER_TYPE_NUM,\n // Below are specific class parameters\n listObjectsCoords = [], strokeRectObject = true,) {\n\n super(canvasElementId, canvasWidth, imageSrc, lineWidth, lineColor, lineHead, fontFamily,\n fontSize, fontColor, fontStyle, fontAlign, fontBaseline, mark, orderType);\n\n // own properties of the class\n this.listObjectsCoords = listObjectsCoords; // array of objects coordinates in the image\n this._listObjectsAssociated = []; // array to store the array of objects coordinates positioned by user\n this.strokeRectObject = strokeRectObject; // define if object will be put into a rectangle\n this._numberAssociationsConnected = 0;\n\n // binding click event to canvas element to allow the position object exercise execution\n this._canvasElement.addEventListener(\"click\", this.clickAction.bind(this), false);\n }",
"draw() {\n this.ghosts.forEach((ghost) => ghost.draw());\n }",
"function drawEntities() {\n for (let i = 0; i < entities.length; i++) {\n push();\n const entity = entities[i];\n if(entity.position) {\n translate(entity.position.x - camera.x, entity.position.y - camera.y);\n }\n\n if(entity.rotate) {\n rotate(entity.rotate);\n }\n\n if(entity.size && entity.img) {\n image(entity.img, 0, 0);\n } else if (entity.size && entity.color) {\n fill(entity.color);\n rect(\n 0,\n 0,\n entity.size.w,\n entity.size.h,\n );\n } \n pop();\n }\n}",
"#runDrawCallbacks() {\n let dont_clear = false;\n if (this.#clear) { this.#context.clearRect(0, 0, this.#canvas.width, this.#canvas.height); }\n this.#context.translate(0.5, 0.5);\n this.#drawables.forEach(drawable => {\n dont_clear = drawable.draw(this.#context, this.#canvas.width, this.#canvas.height, this.#canvas, this.#clear) || dont_clear;\n });\n this.#context.translate(-0.5, -0.5);\n this.#clear = !dont_clear;\n }",
"draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }",
"constructor()\n {\n // using arrays rather than sets, because draw order is important.\n this.spriteList = [];\n }",
"addLineToLinesDrawn() {\n if (!Array.isArray(this._currentLineCoordinates)) throw Error('Line coordinates must be an array')\n this._linesDrawn.push(this._currentLineCoordinates)\n }",
"function AddShapeToCanvas(shape){\n self.canvas.add(shape);\n self.DropDefault_X +=10;\n self.DropDefault_Y +=10; \n self.canvas.isDrawingMode = false; \n }",
"add(o){\n\t\t\twhile(this.cases[o.getY()][o.getX()][\"TILE\"].getCollide()){\n\t\t\t\t\tvar r = rand(0 ,1);\n\t\t\t\t\tif(r == 0){\n\t\t\t\t\t\to.x++;\n\t\t\t\t\t}else{\n\t\t\t\t\t\to.y++;\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tvar t = this.cases[o.getY()][o.getX()];\n\t\t\tif(o instanceof Objet){\n\t\t\t\tt[\"OBJET\"] = o;\n\t\t\t\tthis.stage.appendChild(o.sprite);\n\t\t\t\to.afficher();\n\t\t\t}\n\t\t\tif(o instanceof Entite){\n\t\t\t\tt[\"ENTITE\"] = o;\n\t\t\t\tthis.stage.appendChild(o.div);\n\t\t\t\to.currentStage = this;\n\t\t\t}\n\t\t\t\n\n\t}",
"pushShapes(e) {\r\n const pointer = this.pointer;\r\n\r\n this.pointer.updateCoords(e);\r\n let nearbyShapes = this.pointer.nearbyShapes(this);\r\n nearbyShapes.forEach((shape) => {\r\n // Set new shape direction to opposite of pointer\r\n shape.direction = Math.atan2(shape.y - this.pointer.y, shape.x - this.pointer.x) * 180 / Math.PI;\r\n shape.step = 6;\r\n shape.draw();\r\n });\r\n }",
"add(shape) {\n // store shape offset\n var offset = shape.__position;\n\n // reset shapes list cache\n this.__shapes_list_c = void 0;\n\n // add shape to list of shapes and fix position\n this.__shapes.push({\n shape: shape,\n offset: offset.clone()\n });\n shape.set_position(this.__position.add(offset));\n\n // reset bounding-box\n this.reset_aabb();\n\n // set shape tags to be the composite shape tags\n shape.__collision_tags_val = this.__collision_tags_val;\n shape.__collision_tags = this.__collision_tags;\n\n // set shape debug colors\n shape.__override_fill_color = this.__override_fill_color;\n shape.__override_stroke_color = this.__override_stroke_color;\n\n // return the newly added shape\n return shape;\n }",
"draw() {\n\t\tthis.components.forEach( component => component.draw() );\n\t}",
"function fabricAddObjectIDs() {\n fabric.Canvas.prototype.id = 0;\n\n\n fabric.Canvas.prototype.add = (function(originalFn) {\n return function(...args) {\n args.forEach(obj => {\n if (null == obj.id) {\n obj.id = this.id++;\n }\n });\n originalFn.call(this, ...args)\n \n return this\n };\n })(fabric.Canvas.prototype.add);\n\n \n fabric.Object.prototype.toObject = (function(originalFn) {\n return function(properties) {\n return fabric.util.object.extend(originalFn.call(this, properties), {\n id: this.id\n });\n };\n })(fabric.Object.prototype.toObject);\n\n\n /** \n * Function of every new fabric.Canvas. \n * Returns the fabric object with a given id, return null if no object matching the id is found\n *\n * @function getObjectById\n * @param {int} id \n * id to look for\n */\n fabric.Canvas.prototype.getObjectById = function(id) {\n var object = null,\n objects = this.getObjects();\n for (var i = 0, len = this.size(); i < len; i++) {\n if (id === objects[i].id) {\n object = objects[i];\n break;\n }\n }\n\n return object;\n };\n\n fabric.Canvas.prototype.toJSON = (function(toJSON) {\n return function(propertiesToInclude) {\n return fabric.util.object.extend(toJSON.call(this, propertiesToInclude), {\n id: this.id,\n });\n }\n })(fabric.Canvas.prototype.toJSON);\n}",
"function render() {\n\t//clear all canvases for a fresh render\n\tclearScreen();\n\t\n\t//draw objects centered in order\n\tfor (let i = 0; i < objects.length; ++i) {\n\t\tdrawCentered(objects[i].imgName,ctx, objects[i].x, objects[i].y,objects[i].dir);\n\t}\n\t\n\t//finally draw the HUD\n\tdrawHUD();\n}",
"function drawObjects(ctx) {\n ctx.fillStyle = \"000000\";\n for (i = 0; i < objects.length; i++) {\n ctx.beginPath();\n //Move to first Vertex\n ctx.moveTo(objects[i].vertices[0].x, objects[i].vertices[0].y);\n //This starts at index 1 becuase the first line should be going to the second vertex\n for (v = 1; v < objects[i].vertices.length; v++) {\n ctx.lineTo(objects[i].vertices[v].x, objects[i].vertices[v].y);\n }\n //Draw line back to the first\n ctx.lineTo(objects[i].vertices[0].x, objects[i].vertices[0].y);\n //Fill in the shape with color\n ctx.fill();\n }\n}",
"draw(gameObjects) {\r\n this.ctx.clearRect(0, 0, Helper.FieldSize.WIDTH, Helper.FieldSize.HEIGHT);\r\n for (let i = 0; i < gameObjects.length; i++) {\r\n gameObjects[i].draw(this.ctx);\r\n }\r\n }",
"createCircle(){\n let circle = Circle.createCircle(this.activeColor);\n this.canvas.add(circle);\n this.notifyCanvasChange(circle.id, \"added\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function LMSGetStudentID() Inputs:none Return:Unique Identifier used by the LMS to identify student OR null if the call failed Description: Note: The student_id is a read only field in SCORM and there is no corresponding SetValue | function LMSGetStudentID()
{
return(LMSGetValue("cmi.core.student_id"))
} | [
"function LMSGetStudentName()\n{\n\treturn(LMSGetValue(\"cmi.core.student_name\"))\n}",
"getCourseIDs(studentID) {\n const courseInstanceDocs = CourseInstances.find({ studentID }).fetch();\n const courseIDs = courseInstanceDocs.map((doc) => doc.courseID);\n return _.uniq(courseIDs);\n }",
"getMSID() {\n const streamId = this.getStreamId();\n const trackId = this.getTrackId();\n\n return streamId && trackId ? `${streamId} ${trackId}` : null;\n }",
"student(){\n return Students.findOne({userId: this.state.id});\n }",
"get_selected_student_chat(student) {\n this.spinner = true;\n if (this.selected_student) {\n this.live_session_chat_service.leave({\n room_id: this.selected_student.student_id + this.selected_student.batch_id,\n });\n }\n this.selected_student = student;\n if (this.selected_student.sme_id === localStorage.getItem('uid')) {\n this.live_session_chat_service.join_room({\n room_id: this.selected_student.student_id + this.selected_student.batch_id,\n });\n }\n this.chat_service\n .get_selected_studentChat(this.selected_student._id)\n .subscribe((res) => {\n const response = res.data;\n this.selected_student_chat_message = response.message;\n this.scroll_chat_container();\n this.spinner = false;\n }, (error) => this.error_handler(error));\n }",
"function SBR_display_student() {\n //console.log(\"===== SBR_display_student =====\");\n t_MSSSS_display_in_sbr(\"student\", setting_dict.sel_student_pk);\n // hide itemcount\n //t_set_sbr_itemcount_txt(loc, 0)\n }",
"showStudentsById(id){\n\t\tconsole.log(\"Show student by Id\");\n\t\tvar data = fileSystem.readFileSync(studentData);\n\t\tvar jsonData = JSON.parse(data);\n\t\tvar i,student;\n\t\tfor (i = 0 ; i < jsonData.length ; i++ ){\n\t\t\t\n\t\t\tif (jsonData[i].id == id) {\n\t\t\t\tconsole.log(\"Found id: \" + jsonData[i].id + \"\\nName: \" + jsonData[i].name);\t\n\t\t\t\tstudent = jsonData[i];\n\t\t\t\treturn student;\n\t\t\t}\t\t\n\t\t}\n\t\t//If ID not not exist console will display + empty array in webPage\n\t\tconsole.log(\"student: \" + id + \", not exist\");\t\t\n\t}",
"function LMSIsInitialized()\n{\n // there is no direct method for determining if the LMS API is initialized\n // for example an LMSIsInitialized function defined on the API so we'll try\n // a simple LMSGetValue and trap for the LMS Not Initialized Error\n\n var api = getAPIHandle();\n if (api == null)\n {\n messageAlert(\"Unable to locate the LMS's API Implementation.\\nLMSIsInitialized() failed.\");\n return false;\n }\n else\n {\n var value = api.LMSGetValue(\"cmi.core.student_name\");\n var errCode = api.LMSGetLastError().toString();\n if (errCode == _NotInitialized)\n {\n return false;\n }\n else\n {\n return true;\n }\n }\n}",
"function readStudentById(id, callbacks) {\n return StudentModel.findById(id, function (err, student) {\n if (!err) {\n callbacks.success(student);\n } else {\n sendInfoMail('Student read with id failed: ' + id, err);\n callbacks.error(err);\n }\n });\n}",
"get patientId() {\n\t\t// subject.reference = 'Patient/{patientId}'\n\t\treturn (\n\t\t\tthis._subject\n\t\t\t&& this._subject.reference\n\t\t\t&& this._subject.reference.split('/')[1]\n\t\t);\n\t}",
"function Student(school) {\n var self = this;\n\n self.name = name;\n self.course = course;\n self.grade = grade;\n self.student_id = student_id;\n self.db_id = db_id;\n\n self.getFormInputs = function () {\n for (var x in school.inputIds) {\n var id_temp = school.inputIds[x];\n var value = $('#' + id_temp).val();\n self[id_temp] = value;\n }\n };\n}",
"function findPidByName(nameString, studentList, org) {\n if (!nameString)\n return false;\n\n const activeStudents = studentList.filter((doc) => doc.profile);\n\n for (let i = 0; i < activeStudents.length; i++) {\n const doc = activeStudents[i];\n // activeStudents.forEach((doc) => {\n if (doc.profile) {\n // first check \"Full Name\" field\n const foundLabels = doc.profile.org.filter((label) => label === (`${org}_Full Name_${nameString}`));\n if (foundLabels.length > 0)\n return doc.pid;\n if (doc.profile.name === `${nameString}~c`)\n return doc.pid;\n // else loop on\n }\n }\n // if not found and returned above, generate failure\n return `-- Unrecognized name: ${nameString} --`;\n}",
"function getSubjectId (subject) {\n if ('uri' in subject) {\n return subject.uri\n } else if ('_subject_id' in subject) {\n return subject._subject_id\n } else {\n const result = '' + subjectIdCounter\n subject._subject_id = result\n ++subjectIdCounter\n return result\n }\n }",
"function GIVEStudentContact(id, l_name, f_name, m_name, suf, w_phone, m_phone, mail) {\n\tvar scon = {\n\t\tid\t\t: id,\n\t\tl_name \t: l_name,\n\t\tf_name\t: f_name,\n\t\tm_name\t: m_name,\n\t\tsuf \t: suf,\n\t\t\n\t\t//some DB entries for phone numbers are 0 or -1 to denote\n\t\t//no phone number known, set to empty string for these\n\t\tw_phone\t: (w_phone <= 0) ? '' : w_phone, \n\t\tm_phone\t: (m_phone <= 0) ? '' : m_phone,\n\t\tmail\t: mail\n\t};\n\treturn scon;\n}",
"findUniqueIdentifier() {\n const metadataId = this.attributes[\"unique-identifier\"];\n if (metadataId) {\n const uidMetadata = this.metadata.findItemWithId(\n \"dc:identifier\",\n metadataId\n );\n if (uidMetadata) {\n return uidMetadata.value;\n }\n }\n }",
"function uidMismatch() {\n alert(\"The unique id that you've provided doesn't match the id that have been assigned to your school. Please make sure that you have entered the valid unique id that has been provided to your school by our team.\");\n}",
"function SBR_MSSSS_student_response(tblName, selected_dict, sel_student_pk) {\n console.log( \"===== SBR_MSSSS_student_response ========= \");\n console.log( \" tblName\", tblName);\n console.log( \" sel_student_pk\", sel_student_pk, typeof sel_student_pk);\n console.log( \" selected_dict\", selected_dict);\n // arguments of MSSSS_response are set in t_MSSSS_Save or t_MSSSS_Save_NEW\n // when changing student, only update settings, dont use DatalistDownload but filter on page\n\n // 'all clusters' has value -1\n if(sel_student_pk === -1) { sel_student_pk = null};\n\n setting_dict.sel_student_pk = sel_student_pk;\n setting_dict.sel_student_name = (selected_dict && selected_dict.fullname) ? selected_dict.fullname : null;\n\n console.log( \" setting_dict.sel_student_pk\", setting_dict.sel_student_pk);\n console.log( \" setting_dict.sel_student_name\", setting_dict.sel_student_name);\n\n// when selecting cluster: also set subject to the subject of this cluster\n setting_dict.sel_subject_pk = null;\n setting_dict.sel_subject_name = null;\n setting_dict.sel_cluster_pk = null;\n setting_dict.sel_cluster_name = null;\n\n// --- upload new setting\n const upload_dict = {selected_pk: {\n sel_student_pk: sel_student_pk,\n sel_subject_pk: null,\n sel_cluster_pk: null\n }};\n b_UploadSettings (upload_dict, urls.url_usersetting_upload);\n\n SBR_display_student();\n\n // hide itemcount\n t_set_sbr_itemcount_txt(loc, 0)\n\n FillTblRows();\n\n }",
"function getClinicalObjectUid(writebackContext, pjdsClinicalObjectUid, callback) {\n if (pjdsClinicalObjectUid) {\n return callback(null, writebackContext, pjdsClinicalObjectUid);\n } else {\n var clinicalObject = {};\n clinicalObject.patientUid = writebackContext.model.patientUid;\n clinicalObject.authorUid = writebackContext.model.authorUid;\n clinicalObject.domain = 'ehmp-observation';\n clinicalObject.subDomain = 'labResult';\n clinicalObject.visit = writebackContext.model.visit;\n clinicalObject.ehmpState = 'active';\n clinicalObject.referenceId = writebackContext.model.referenceId;\n pjds.create(writebackContext.logger, writebackContext.appConfig, clinicalObject, function(err, response) {\n if (err) {\n return callback(err);\n }\n writebackContext.logger.debug({\n clinicalObject: response\n }, 'new clinical object');\n var location = response.headers.location;\n var clinicalObjectUid = location.substring(location.indexOf('urn:va'), location.length);\n return callback(null, writebackContext, clinicalObjectUid);\n });\n }\n}",
"function getStationId(stationName, bound) {\n\tvar stationIdCursor = Stops.find({\n\t\t\"stop_name\": stationName,\n\t\t\"platform_code\": bound\n\t},{\n\t\tfields: {\n\t\t\t\"stop_id\": 1\n\t\t}\n\t});\n\n\tvar stationIdFetched = stationIdCursor.fetch()\n\n\tif (stationIdFetched.length !== 0) {\n\t\tvar stationId = stationIdCursor.fetch()[0][\"stop_id\"];\n\t}\n\n\treturn stationId;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check email input patten check phone number input pattern check zipcode pattern check whether password are the same or not | function checkValid() {
if(!document.getElementById("email").value.match(/\S+@\S+\.\S+/)){
if (document.getElementById("email").value != "") {
alert("Email Format is wrong!")
return false;
}
}
if (!document.getElementById("phone_number").value.match("^\\d{3}-\\d{3}-\\d{4}$")) {
if (document.getElementById("phone_number").value != "") {
alert("Phone Format is wrong!")
return false;
}
}
if (!document.getElementById("zipcode").value.match("^\\d{5}$")) {
if (document.getElementById("zipcode").value != "") {
alert("Zipcode Format is wrong!")
return false;
}
}
var password = document.getElementById("password")
var password2 = document.getElementById("password2")
if (password.value == "" && password2.value != "") {
alert("Password is empty !")
return false;
} else if (password2.value == "" && password.value != ""){
alert("Confirmation Password is empty !")
return false;
}
return true;
} | [
"function validateSignupPassword(password1, password2)\n{\n var re = new RegExp(/^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^0-9a-zA-Z].*).{6,}$/);\n if(password1.value == \"\" || password2.value == \"\") {\n $('#caMsg').html(\"You must enter a password.<br> (atleast 6 characters containing one uppercase AND lowercase letter, number, and non-alphanumeric)<br>\");\n password1.value=\"\";\n password2.value=\"\";\n password1.focus();\n return false;\n }\n if(password1.value != \"\" && password1.value == password2.value) {\n if(!re.test(password1.value)) {\n $('#caMsg').html(\"You must enter a valid password!<br> (atleast 6 characters containing one uppercase AND lowercase letter, number, and non-alphanumeric)<br>\");\n password1.value=\"\";\n password2.value=\"\";\n password1.focus();\n return false;\n }\n } else {\n $('#caMsg').html(\"Error: Please check that you've entered and confirmed your password!<br>\");\n password1.value=\"\";\n password2.value=\"\";\n password1.focus();\n return false;\n }\n return true;\n}",
"function ccvAndZipEntered() {\n\tvar zipVal = /^\\d{5}$|^\\d{5}-\\d{4}$/;\n\tvar cvvVal = /^\\d{3}$/;\n\treturn zipVal.test($(\"#zip\").val()) && cvvVal.test($(\"#cvv\").val());\n}",
"validatePassword(password) {\n if (/^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/.test(password)) { return true }\n return false\n }",
"function email_check() {\r\n email_warn(email_validate());\r\n final_validate();\r\n}",
"function validateAddress() {\r\n var addressInput = $('#register-address');\r\n var addressInputValue = addressInput.val();\r\n var addressRegex = /^\\d+\\s([A-Z]?[a-z]+\\s){2}\\d{5}\\s[A-Z]?[a-z]+$/;\r\n\r\n if (addressInputValue.match(addressRegex)) {\r\n validInput(addressInput);\r\n } else {\r\n invalidInput(addressInput, $mustBeAnAddress)\r\n }\r\n}",
"function validation() {\nvar name = document.getElementById(\"name\").value;\nvar email = document.getElementById(\"email\").value;\nvar emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;\nif (name === '' || email === '') {\nalert(\"Please fill all fields...!!!!!!\");\nreturn false;\n} else if (!(email).match(emailReg)) {\nalert(\"Invalid Email...!!!!!!\");\nreturn false;\n} else {\nreturn true;\n}\n}",
"function checkFormatEmail(emailAddress) {\n var pattern = /^([a-z\\d!#$%&'*+\\-\\/=?^_`{|}~\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]+(\\.[a-z\\d!#$%&'*+\\-\\/=?^_`{|}~\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]+)*|\"((([ \\t]*\\r\\n)?[ \\t]+)?([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f\\x21\\x23-\\x5b\\x5d-\\x7e\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))*(([ \\t]*\\r\\n)?[ \\t]+)?\")@(([a-z\\d\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]|[a-z\\d\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF][a-z\\d\\-._~\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]*[a-z\\d\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])\\.)+([a-z\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]|[a-z\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF][a-z\\d\\-._~\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]*[a-z\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])\\.?$/i;\n return pattern.test($(emailAddress).val());\n}",
"function validate_email() {\n //console.log(\"CDAC EMAIL ID Validation function calling starts\");\n //document.getElementById(\"otp\").disabled = false;\n\n // var alt_email = document.getElementById(\"alt_email\").value.trim().toLowerCase();\n //console.log(\"Email ID entered is \" + hin_email);\n\n // if ((alt_email.length) == 0 || (alt_email.length) == undefined) {\n //console.log(\"Length of Email ID entered is \" + hin_email.length);\n //document.getElementById(\"otp_sent_msg_success\").innerHTML = \"\";\n // document.getElementById(\"error_alt_email\").innerHTML = \"Please Enter Email ID\";\n // return false\n\n // }\n\n // var domain = alt_email.substring(alt_email.length - 8, alt_email.length);\n //console.log(\"Email ID entered has domain \" + domain);\n\n//CDAC DOMAIN CHECK FOR EMAIL ID ENTERED Starts\n\n // if (domain != \"@cdac.in\") {\n\n //console.log(\"Email ID does not belog to CDAC\");\n // document.getElementById(\"otp_sent_msg_success\").innerHTML = \"\";\n // document.getElementById(\"error_alt_email\").innerHTML = \"Incorrect Email ID\";\n // return false;\n\n // }\n\n//CDAC DOMAIN CHECK FOR EMAIL ID ENTERED Ends\n // var username = alt_email.substring(0, alt_email.length - 8);\n //console.log(\"Email ID entered has username \" + username);\n\n\n // var regexp = /^[a-zA-Z]+$/;\n\n // if (username.match(regexp)) {\n //console.log(\"Email ID validation passed since it belongs to CDAC \" + username + \"@cdac.in\");\n // document.getElementById(\"error_alt_email\").innerHTML = \"\";\n // return true;\n // } else {\n //console.log(\"Email ID has invalid characters\");\n // document.getElementById(\"otp_sent_msg_success\").innerHTML = \"\";\n // document.getElementById(\"error_alt_email\").innerHTML = \"Invalid Characters in Email ID \";\n // return false;\n // }\n\n}",
"function validateAddress() {\n return checkPersonalInfo(\"address\", \"Address must have at least 3 characters\");\n}",
"_isValidInput() {\n if (!validate(this.email)) {\n return false;\n }\n const indexOfAt = this.email.indexOf(\"@\"); // index of @ symbol\n this.domain = this.email.substring(indexOfAt + 1);\n return true;\n }",
"function validateMail() {\n \n var mail = document.querySelector(\"#mail\").value;\n var regex = /^(([^<>()[\\]\\\\.,;:\\s@\\“]+(\\.[^<>()[\\]\\\\.,;:\\s@\\“]+)*)|(\\“.+\\“))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n\n return regex.test(mail);\n}",
"function checkEmail(email){\r\n\tif (!checkLength(email, 6)) {\r\n\t\treturn false;\r\n\t} else if (email.indexOf(\"@\") == -1) {\r\n\t\treturn false;\r\n\t} else if (email.indexOf(\".\") == -1) {\r\n\t\treturn false;\r\n\t} else if (email.lastIndexOf(\".\") < email.lastIndexOf(\"@\")) {\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}",
"function validateForgotPasswordEmail(email, id) {\n removeError(id);\n $.get(\"../../php/common/getData.php?table=user&column=email&value=\" + email, function (data, status) {\n if (data === 'false') {\n isForgotPasswordEmail = false;\n errorToggle(id, \"Email not exits!\", true);\n } else {\n isForgotPasswordEmail = true;\n errorToggle(id, \"Looks Good!\", false);\n }\n let regex = /^([a-zA-Z0-9_\\.\\-\\+])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\n\n if(!regex.test(email)) {\n errorToggle(id, \"Invalid Email!\", true);\n isForgotPasswordEmail = false;\n }else{\n isForgotPasswordEmail = true;\n }\n });\n}",
"function setupEmail() {\n var short = $attrs['checkEmail'];\n var shorts = short ? short.split('|') : [];\n var message = nls._(shorts[0] || $attrs['checkEmailMessage'] || 'message_email');\n field.checks.regexp = {\n message: message,\n regexp: /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i,\n forbid: false,\n active: true\n };\n var condition = shorts[1] || $attrs['checkEmailIf'];\n if (condition) {\n $scope.$parent.$watch(condition, function(value){\n field.checks.regexp.active = value;\n });\n }\n }",
"function validateEmailAndPassword() {\n if(!$scope.email || !$scope.password) {\n $timeout(function() {\n $scope.authenticateResponse = \"Please enter an email and password\";\n $scope.authenticateResponseClass = \"alert-info\";\n resetResponse();\n });\n return false;\n }\n\n return true;\n }",
"function formVerify() {\n if (formInfo.contactMsg.value !== \"\") {\n if (emailRegex.test(formInfo.contactEmail.value)) {\n if (formInfo.contactName.value !== \"\") {\n return \"allGood\";\n }\n return \"nameInvalid\";\n }\n return \"emailInvalid\";\n }\n\n return \"msgInvalid\";\n}",
"function validateEnquiryEmailsForm()\n{\n var regEmail = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n if(document.frmAddEditEmail.frmEnquiryEmail.value == \"\")\n {\n alert(ENTER_EMAIL);\n document.frmAddEditEmail.frmEnquiryEmail.focus() ;\n return false;\n }\n if(document.frmAddEditEmail.frmEnquiryEmail.value != \"\")\n {\n var result = document.frmAddEditEmail.frmEnquiryEmail.value.split(\",\");\n // alert(result);\n for(var i = 0;i < result.length;i++)\n {\n if(!regEmail.test(result[i])) \n {\n alert(result[i]+EMAIL_SEEMS_WRONG); \t\t\n document.frmAddEditEmail.frmEnquiryEmail.focus();\n return false;\n }\n }\n }\n}",
"function checkRequirements() {\n if (firstPassword.length < 5) {\n firstInputIssuesTracker.add(\"كلمه المرور اقل من 5 حروف\");\n } else if (firstPassword.length > 15) {\n firstInputIssuesTracker.add(\"كلمه المرور اكبر من 5 حروف\");\n }\n\n \n\n if (!firstPassword.match(/[a-z | A-Z | ا-ي]/g)) {\n firstInputIssuesTracker.add(\"الرجاء استخدام الحروف والارقام\");\n }\n\n \n\n var illegalCharacterGroup = firstPassword.match(/[^A-z0-9أ-ي!\\@\\#\\$\\%\\^\\&\\*]/g)\n if (illegalCharacterGroup) {\n illegalCharacterGroup.forEach(function (illegalChar) {\n firstInputIssuesTracker.add(\"غير مسموح بهذه الرموز: \" + illegalChar);\n });\n }\n }",
"function validateEmail()\n{\n//variable email is set by element id contactEmail from the form\n\tvar email = document.getElementById(\"contactEmail\").value; \n\t\n\t//validation for email\n\tif(email.length == 0)\n\t{\n\t\tproducePrompt(\"Email is Required\", \"emailPrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!email.match(/^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/)){\n\t\tproducePrompt(\"Email Address is Invalid\", \"emailPrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Valid Email\", \"emailPrompt\", \"green\"); \n\t\treturn true; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the minimum zoom level (inclusive) at which the layer may be visible. | get minZoom() {
return this._minZoom;
} | [
"getZoomLevel() {\n return this.dynamics.zoom.current;\n }",
"set minZoom(value) {\n this._minZoom = value;\n //Update visibility if necessary\n this.updateVisibility();\n }",
"function currentZoomMap() {\n if(map)\n return map.getZoom();\n}",
"function onZoom()\r\n{\r\n\tevaluateLayerVisibility();\r\n\t$(\"#zoomlevel\").val(Math.floor(map.getView().getZoom()));\r\n}",
"function restrictZoom(zoom) {\n let newZoom = zoom;\n if (zoom <= 1) newZoom = 1;\n else if (zoom > 8) newZoom = 8;\n return newZoom;\n}",
"function setZoomLevel(value=0){\n map.setZoom(value);\n}",
"function getUserZoomUI() {\n return parseInt($(\"#mapZoom\").prop('value'));\n }",
"function min(){return colorScale.domain()[0];}",
"function setZoomLevel(value) {\n if (value && (zoomLevel !== value)) {\n var centerPosition = getCenterPosition();\n \n zoomLevel = value;\n \n // update the rads per pixel to reflect the zoom level change\n radsPerPixel = T5.Geo.radsPerPixel(zoomLevel);\n \n // pan to the new position\n panToPosition(centerPosition);\n\n // trigger the zoom level change\n self.trigger('zoomLevelChange', zoomLevel);\n self.triggerAll('resync', self);\n } // if\n }",
"getZoomMult(){\n return this.state.distance * this.scale_zoom;\n }",
"getClosestScaleToFitMap() {\n const mapView = this.map.getView();\n const mapExtent = mapView.calculateExtent();\n const scales = this.getScales();\n let fitScale = scales[0];\n\n scales.forEach(scale => {\n const scaleVal = scale.value ? scale.value : scale;\n const printExtent = this.calculatePrintExtent(scaleVal);\n const contains = containsExtent(mapExtent, printExtent);\n\n if (contains) {\n fitScale = scale;\n }\n });\n\n return fitScale;\n }",
"isVisibleAtZoomLevel(zoomLevel) {\n //Check display intention and zoom range\n return (zoomLevel >= this.minZoom)\n && (zoomLevel < this.maxZoom)\n && this._displayIntention;\n }",
"fovToZoomLevel(fov) {\n const temp = Math.round((fov - this.config.minFov) / (this.config.maxFov - this.config.minFov) * 100);\n return temp - 2 * (temp - 50);\n }",
"function setMapLevel(data) {\n\tvar lat_max = 0, lat_min = 1000, lng_max = 0, lng_min = 1000;\n\tvar lat_range = 0, lng_range = 0, level;\n\n\t$.each( data.restaurants, function( i, restaurant ) {\n\t\tlat_max = Math.max(lat_max, restaurant.lat);\n\t\tlat_min = Math.min(lat_min, restaurant.lat);\n\t\tlng_max = Math.max(lng_max, restaurant.lng);\n\t\tlng_min = Math.min(lng_min, restaurant.lng);\n\t});\n\n\tlat_range = lat_max - lat_min;\n\tlng_range = lng_max - lng_min;\n\n\tif ( lat_range > 0.28 || lng_range > 0.18 ) {\n\t\tlevel = 5;\n\t} else if ( lat_range > 0.15 || lng_range > 0.09 ) {\n\t level = 6;\n\t} else if ( lat_range > 0.075 || lng_range > 0.04 ) {\n\t level = 7;\n\t} else if ( lat_range > 0.035 || lng_range > 0.02 ) {\n\t level = 8;\n\t} else if ( lat_range > 0.02 || lng_range > 0.013 ) {\n\t level = 9;\n\t} else if ( lat_range > 0.01 || lng_range > 0.005 ) {\n\t level = 10;\n\t} else {\n\t level = 11;\n\t};\n\t\n\toMap.setLevel(level);\n}",
"low() {\n let mark = Object.values(marks[0]).map(element => {\n return parseInt(element);\n });\n return Math.min(...mark);\n }",
"function getStoredZoom() {\n if(parseInt(localStorage.getItem(\"userZoom\")) > 0) {\n $(\"#mapZoom\").prop('value', localStorage.getItem(\"userZoom\"));\n return (parseInt(localStorage.getItem(\"userZoom\")));\n }\n }",
"function BAGetZoomRatio() {\n\tvar per = 1;\n\tif (BA.ua.isIE70) {\n\t\tif (!document.compatMode || document.compatMode == 'BackCompat') {\n\t\t\tper = document.documentElement.offsetWidth / document.body.offsetWidth;\n\t\t} else {\n\t\t\tBAGetGeometry();\n\t\t\tvar ins = document.createElementBA('ins');\n\t\t\tins.style.display = 'block';\n\t\t\tins.style.position = 'absolute';\n\t\t\tins.style.top = '-100px';\n\t\t\tins.style.left = '0px';\n\t\t\tins.style.width = (BA.geom.pageW * 10) + 'px';\n\t\t\tdocument.body.appendChildBA(ins);\n\t\t\tBAGetGeometry();\n\t\t\tper = BA.geom.pageW / ins.offsetWidth;\n\t\t\tdocument.body.removeChildBA(ins);\n\t\t}\n\t}\n\treturn per;\n}",
"set zoom(delta) {\n // TODO: limit zoom\n\n if (delta < 0 && this.zoom < 0.05) {\n return null;\n }\n if (delta > 0 && this.zoom > 200) {\n return null;\n }\n\n if (!this.dragEnabled) {\n const oldZoom = this.zoomLevel;\n if (delta !== undefined) {\n this.zoomLevel += this.zoomLevel / (25 / delta);\n }\n\n let currentMousePos = createVector(\n mouseX / oldZoom - this.pos.x,\n mouseY / oldZoom - this.pos.y\n );\n\n let newMousePos = createVector(\n mouseX / this.zoom - this.pos.x,\n mouseY / this.zoom - this.pos.y\n );\n\n this.mouseDelta = currentMousePos.sub(newMousePos);\n\n this.pos = this.pos.sub(this.mouseDelta);\n }\n }",
"function setZoomExtent(k) {\n var numOfPoints = currSeries[0].data.length;\n //choose the max among all the series\n for (var i = 1; i < currSeries.length; i++) {\n if (numOfPoints < currSeries[i].data.length) {\n numOfPoints = currSeries[i].data.length;\n }\n }\n if (!k || k > numOfPoints) k = 3;\n zoom.scaleExtent([1, numOfPoints / k]);\n maxScaleExtent = parseInt(numOfPoints / k);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Generic Distribution Provider Action by id. | static get(id){
let kparams = {};
kparams.id = id;
return new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'get', kparams);
} | [
"static getByProviderId(genericDistributionProviderId, actionType){\n\t\tlet kparams = {};\n\t\tkparams.genericDistributionProviderId = genericDistributionProviderId;\n\t\tkparams.actionType = actionType;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'getByProviderId', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'delete', kparams);\n\t}",
"static update(id, genericDistributionProviderAction){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.genericDistributionProviderAction = genericDistributionProviderAction;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'update', kparams);\n\t}",
"static deleteByProviderId(genericDistributionProviderId, actionType){\n\t\tlet kparams = {};\n\t\tkparams.genericDistributionProviderId = genericDistributionProviderId;\n\t\tkparams.actionType = actionType;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'deleteByProviderId', kparams);\n\t}",
"async function getAction(id) {\n const actions = await db.select('*')\n .from('actions as a')\n .where('a.id', Number(id));\n const contexts = await db.select('c.id', 'c.name')\n .from('actions_contexts as ac')\n .join('contexts as c', 'c.id', 'ac.context_id')\n .where('ac.action_id', Number(id));\n if(actions.length !== 0) {\n const result = {...actions[0], contexts: contexts};\n return result;\n } else {\n return actions[0];\n }\n}",
"static updateByProviderId(genericDistributionProviderId, actionType, genericDistributionProviderAction){\n\t\tlet kparams = {};\n\t\tkparams.genericDistributionProviderId = genericDistributionProviderId;\n\t\tkparams.actionType = actionType;\n\t\tkparams.genericDistributionProviderAction = genericDistributionProviderAction;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'updateByProviderId', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'delete', kparams);\n\t}",
"static add(genericDistributionProviderAction){\n\t\tlet kparams = {};\n\t\tkparams.genericDistributionProviderAction = genericDistributionProviderAction;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'add', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_entrydistribution', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'delete', kparams);\n\t}",
"function getAction() {\r\n\r\n return( action );\r\n\r\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'delete', kparams);\n\t}",
"static update(id, genericDistributionProvider){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.genericDistributionProvider = genericDistributionProvider;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovider', 'update', kparams);\n\t}",
"static submitFetchReport(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_entrydistribution', 'submitFetchReport', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('thumbparams', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'delete', kparams);\n\t}",
"getActionIdentifier() {\n return this._actionIdentifier;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an AI player to the game | function addAI() {
if (!availableIDs.length) {
// No more room
return;
}
logger.info("Adding AI");
clientCount++;
var playerID = availableIDs.pop();
var newHand = new Hand(0);
var ai = new Player(playerID, null, "Agent " + playerID, newHand);
// Give hand to new player
dealHand(ai, FACEDOWN);
ai.hand.faceDown.sort(function(a,b) {return a.value()-b.value()});
ai.hand.showing.sort(function(a,b) {return a.value()-b.value()});
var aiClient = {
"id": ai.id
};
// Map this player ID to the AI object
AIs[ai.id] = aiClient;
// Map the new player and connection handle to this client uid
clients[aiClient.id] = {
"player": ai,
"playTurn": function() {
setTimeout(AITurn, AI_TURN_TIME);
},
"connection": null
};
addAICommon(ai);
} | [
"function addPlayer(username)\n{\n // Check that this player isn't in a lobby already\n if (lobbies.some(lobby =>\n lobby.players.some(player =>\n player.username == username\n )\n ))\n {\n throw 'This player is already in a lobby.';\n }\n\n // Create the new player\n var player = \n {\n username: username,\n host: false,\n connected: false,\n spectator: false,\n ready: false,\n points: 0,\n answer: '',\n answered: false\n // TODO: Additional metadata\n };\n\n // Set first player added as host\n if (this.players.length == 0)\n {\n player.host = true;\n }\n else if (this.cur_state.name != 'queueing')\n { // Set spectator if game is ongoing\n player.spectator = true;\n }\n\n // Add the player to the lobby\n this.players.push(player);\n}",
"addAiOpponent() {\n\t\tif ( this.status != 'available' ) {\n\t\t\tthrow new Error( 'Not available.' );\n\t\t}\n\n\t\tthis[ _connection ].request( 'join', this.gameId, { ai: true } )\n\t\t\t.then( gameData => {\n\t\t\t\tthis.opponent.id = gameData.opponentId;\n\t\t\t\tthis.opponent.isInGame = true;\n\t\t\t\tthis.status = 'full';\n\t\t\t} )\n\t\t\t.catch( error => this._handleServerError( error ) );\n\t}",
"addPlayer(firstName, lastName, age) {\n const player = {\n firstName,\n lastName,\n age\n }\n //pushes to an array\n this._players.push(player);\n }",
"function addPlayer() \n{\n\tgbox.addObject({\n\t\tid: 'player_id',\t\t\t// Reference ID\n\t\tgroup: 'player',\t\t\t// Rendering group player belongs to\n\t\ttileset: 'player_tiles',\t// Image set for sprite animation\n\t\t\t\n\t\t// Set collision box for player\n\t\t// TODO: Test, may not need this for toys.platformer.\n\t\t// toys.topview object's default colh value is bottom half of tile,\n\t\t// so character can overlap map features.\n\t\tcolh: gbox.getTiles('player_tiles').tileh,\n\t\t\n\t\t// Run once upon creation, initialize player object\n\t\tinitialize: function() {\n\t\t\t// Initialize the player as a platformer object\n\t\t\t// to access helper methods\n\t\t\ttoys.platformer.initialize(this, {});\n\t\t\t\n\t\t\t// Set default player position\n\t\t\t// TODO: Make default location a constant point\n\t\t\tthis.x = 20;\n\t\t\tthis.y = 20;\n\t\t},\n\t\t\n\t\t// Step function performed during each cycle (*before* rendering)\n\t\tfirst: function() {\n\t\t\t// \"Keys\" methods apply acceleration based on direction pressed.\n\t\t\ttoys.platformer.horizontalKeys(this, { left: 'left', right: 'right' });\n\t\t\t\n\t\t\t// Apply friction to acceleration to prevent crazy physics\n\t\t\ttoys.platformer.handleAccellerations(this);\n\t\t\t\n\t\t\t// Apply forces through physics engine\n\t\t\ttoys.platformer.applyGravity(this);\n\t\t\t\n\t\t\t/*\n\t\t\t * Collision detection\n\t\t\t * Tolerance value creates more organic collision box.\n\t\t\t * TODO: Only check for vertical collision if this.y has changed.\n\t\t\t */\n\t\t\ttoys.platformer.verticalTileCollision(this, map, 'map');\n\t\t\t//toys.platformer.horizontalTileCollision(this, map, 'map', 1);\n\t\t},\n\t\t\n\t\t// Draw the player tile with updated position/properties\n\t\tblit: function() {\n\t\t\tvar blitData = {\n\t\t\t\t\ttileset: this.tileset,\n\t\t\t\t\ttile:\t 0, //this.frame,\n\t\t\t\t\tdx:\t\t this.x,\n\t\t\t\t\tdy:\t\t this.y,\n\t\t\t\t\tfliph:\t this.fliph,\n\t\t\t\t\tflipv:\t this.flipv,\n\t\t\t\t\tcamera:\t this.camera,\n\t\t\t\t\talpha:\t 1.0\n\t\t\t};\n\t\t\tgbox.blitTile(gbox.getBufferContext(), blitData);\n\t\t}\n\t});\n}",
"giveAI() {\n\n this.isAI = true;\n\n this.AIcontroller = new AIController(this);\n\n\n }",
"function addPlayer(team) {\n\tvar container = $('#players-team-'+team);\n\n\t//max. 20 players to prevent database flooding\n\tif(container.children().length >= 20) return;\n\n\tvar last_id = 0;\n\n\tvar spl = container.children().last().attr('id').split(\"-\");\n\n\tlast_id = Number(spl[spl.length-1]);\n\tif(!$.isNumeric(last_id)) {\n\t\tlast_id = 0;\n\t}\n\n\tvar id = last_id+1;\n\n\tvar div = $(document.createElement('div')).addClass('player').addClass('overlay-container').addClass('player-'+team).attr('id', 'player-'+team+'-'+id);\n\n\t//TODO: Set default value to next free number\n\tvar number_html = '<input type=\"number\" class=\"player-number border\">'\n\t$(number_html).appendTo(div);\n\n\tvar name_html = '<input type=\"text\" class=\"player-name border\" placeholder=\"Player Name\" maxlength=\"30\">';\n\t$(name_html).appendTo(div);\n\n\tvar remove_html = '<div class=\"overlay-right border\" onclick=\"removePlayer(\\''+team+'\\', '+id+')\"><i class=\"fa fa-times\"></i></div>'\n\t$(remove_html).appendTo(div);\n\n\tdiv.appendTo(container);\n\n\tresize();\n\tapplyRangeChecks();\n}",
"function playPlayerVsComputer(){\n setPlayerVsPlayer({\n AI:true,\n AImove:false\n });\n }",
"addGame(opponentName, teamPoints, opponentPoints) {\n let game = {\n opponent: opponentName,\n teamPoints: teamPoints,\n opponentPoints: opponentPoints\n }\n // adds the new game to the _games array\n this._games.push(game);\n }",
"function createPlayer() {\n\n entityManager.generatePlayer({\n cx : 240,\n cy : 266,\n });\n\n}",
"function addPlayer(name, callback) {\n\tvar query = 'INSERT INTO \"Players\" (\"PlayerName\") VALUES (\\'' + name + '\\');';\n\t//console.log(query);\n\tclient.query(query, (errQ, resQ) => {\n\t\tif(errQ) {\n\t\t\tconsole.log(\"addPlayer() - SQL error - \" + errQ);\n\t\t\tcallback(errQ);\n\t\t} else {\n\t\t\tif(resQ.rowCount > 0) {\n\t\t\t\tcallback(resQ);\n\t\t\t} else\n\t\t\t{\n\t\t\t\tconsole.log(\"addPlayer() - Error - \" + errQ);\n\t\t\t\tcallback(errQ);\n\t\t\t}\n\t\t}\n\t})\n}",
"function playerSetUp(p) {\n GeometrySplit.game.physics.arcade.enable(p);\n p.animations.add('current', [0, 1, 2, 1], 8);\n p.body.collideWorldBounds = true;\n p.body.gravity.y = 1000;\n p.body.maxVelocity.y = 850;\n p.body.bounce = {x: 0, y: 0};\n p.tint = 0x98FB98;\n players.add(p);\n}",
"createPlayer() {\n this.player = new Player(this.level);\n }",
"addGame(opponent, teamPoints, opponentPoints) {\n const game = {\n opponent,\n teamPoints,\n opponentPoints\n }\n //pushes to an array\n this._games.push(game)\n }",
"initPlayers() {\n\n for( var i = 0; i < this.gameConfig.numPlayers; i++ ) {\n this.gameConfig.players.push({\n name : '',\n imgPath : 'img/ninja-odd.png',\n killed : false,\n nameToKill: '',\n word : ''\n })\n }\n\n this.saveGameConfig();\n }",
"function player (name, age, team, pointsScored) {\n this.name = name;\n this.age = age;\n this.team = team;\n this.pointsScored = pointsScored;\n \n this.addPoints = function(num){\nthis.pointsScored += num;\nreturn this.pointsScored;\n }\n}",
"makeAIMove() {\n this.thinking = true\n\n const aiMove = this.gameManager.minimax().move\n\n if (aiMove) {\n this.makeMove(aiMove)\n }\n\n setTimeout(() => {\n this.thinking = false\n }, 0)\n }",
"function createPlayer() {\n player = new PIXI.AnimatedSprite(playerSheet.walkSouth);\n player.anchor.set(0.5);\n player.animationSpeed = 0.18;\n player.loop = false;\n player.x = app.view.width / 2;\n player.y = app.view.height / 2;\n app.stage.addChild(player);\n player.play();\n}",
"function createNewPlayer(){\n let newPlayerButton = document.querySelector('#playername-submit');\n newPlayerButton.addEventListener(\"click\", getNewPlayer);\n}",
"function updatePlayer() {\n initializePlayer();\n newPlayer.setYearsInLeague(\"16\");\n newPlayer.display();\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates template with the given node and question | updateTemplateForNode(node) {
console.log('Updating for node: ' + node.node_id);
// Lookup related question for given node
var matchingQuestion = this.findQuestionForQuestionId(node.question_id);
// Reset
document.getElementById("sp-text").value = null;
document.getElementById("sp-radio-1").checked = false;
document.getElementById("sp-radio-2").checked = false;
if (matchingQuestion.type == "text") {
var textGroup = document.getElementById("sp-text-group");
textGroup.style.display = "block";
var radioGroup = document.getElementById("sp-radio-group");
radioGroup.style.display = "none";
var textQuestionLabel = document.getElementById("sp-text-label");
textQuestionLabel.innerHTML = matchingQuestion.label;
} else {
var textGroup = document.getElementById("sp-text-group");
textGroup.style.display = "none";
var radioGroup = document.getElementById("sp-radio-group");
radioGroup.style.display = "block";
var radioQuestionLabel = document.getElementById("sp-radio-label");
var radioAnswer1Label = document.getElementById("sp-radio1-label");
var radioAnswer2Label = document.getElementById("sp-radio2-label");
radioQuestionLabel.innerHTML = matchingQuestion.label;
radioAnswer1Label.innerHTML = matchingQuestion.options[0];
radioAnswer2Label.innerHTML = matchingQuestion.options[1];
}
// Reset and hide any error message
var errorSummary = document.getElementById("sp-error-summary");
errorSummary.style.display = "none";
} | [
"function generateQuestionElement(currentQuestion) {\n let tempQuestion = STORE.questions[currentQuestion];\n let tempPageNum = STORE.questionNumber + 1;\n return `<section id=\"question set\">\n <div class=\"page\">\n <form id=\"js-form\" name=\"form\">\n <h2>${tempQuestion.question}</h2>\n <input id = 'a' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[0]}\" required>\n <label for=\"${tempQuestion.answers[0]}\">${tempQuestion.answers[0]}</label><br>\n <input id = 'b' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[1]}\" >\n <label for=\"${tempQuestion.answers[1]}\">${tempQuestion.answers[1]}</label><br>\n <input id = 'c' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[2]}\" >\n <label for=\"${tempQuestion.answers[2]}\">${tempQuestion.answers[2]}</label><br>\n <input id = 'd' name=\"answer\" type=\"radio\" onclick=\"handleRadioClicked()\" value=\"${tempQuestion.answers[3]}\" >\n <label for=\"${tempQuestion.answers[3]}\">${tempQuestion.answers[3]}</label><br>\n <button type=\"submit\" id=\"js-submit\" hide>Submit</button>\n </form>\n <h3></h3>\n <p>Question ${tempPageNum} of 5 <br>\n Score: ${STORE.score}</p>\n </div>\n </section>`;\n}",
"function questionWrite() {\n questionEl.textContent = questionText;\n}",
"function renderQuestions(questions){\n\tvar source = $(\"#questions-template\").html(); \n\tvar template = Handlebars.compile(source); \n\t$('#questions').append(template(questions));\n\tvar source2 = $(\"#questions-no-template\").html(); \n\tvar template2 = Handlebars.compile(source2); \n\t$('.select-class').append(template2(questions));\n\tcurrentQuestion = $( \"#select-question\" ).val();\n\t$( \"#select-question\" ).on('change', showQuestion);\n}",
"function generateQuestionReviewView() {\r\n let question = store.questions[store.questionNumber];\r\n let html = `\r\n <div id=\"question-page\">\r\n <div id=\"question-count\">Question ${store.questionNumber + 1} of ${store.questions.length}</div>\r\n <h2 id=\"question\">${question.question}</h2>\r\n <h3> You got the question ${(question.correctAnswer === store.submittedAnswer) ? 'correct!' : 'wrong!'}</h3>\r\n <ul id=\"answers-results\">`;\r\n //For each answer, check if it's right or wrong and highlight it appriorately\r\n question.answers.forEach(answer => {\r\n //answer right\r\n if(answer === question.correctAnswer) {\r\n html += `<li class=\"correct-answer\">${answer}</li>`;\r\n }\r\n //answer wrong and user selected\r\n else if(answer !== question.correctAnswer && answer === store.submittedAnswer) {\r\n html += `<li class=\"wrong-answer\">${answer}</li>`;\r\n }\r\n //answer wrong\r\n else {\r\n html += `<li>${answer}</li>`;\r\n }\r\n });\r\n html += `\r\n </ul>\r\n <div>\r\n <p id=\"count\">Score: ${store.score} out of ${store.questions.length}</p>\r\n <button id=\"next\">${(store.questionNumber < store.questions.length - 1) ? 'NEXT' : 'FINISH'}</button>\r\n </div>\r\n </div>`;\r\n return html;\r\n}",
"function updatePage() {\n $(\"#question\").text(questionArray[questionNumber].question);\n $(\"#answer1\").text(questionArray[questionNumber].answers[0]);\n $(\"#answer2\").text(questionArray[questionNumber].answers[1]);\n $(\"#answer3\").text(questionArray[questionNumber].answers[2]);\n $(\"#answer4\").text(questionArray[questionNumber].answers[3]);\n}",
"function wrapNode(node, template){\n return function() {\n return {\n name: template,\n data: node\n };\n };\n }",
"function renderQuestion () {\n $('main').html(generateQuestion());\n}",
"function handleQuestion() {\n $('.js-quiz-next-button').attr('value', 'Check Answer'); // Sets the value of the next button to 'check answer'\n $('.js-quiz-next-button').attr('aria-label', 'Check Answer'); // Set the aria label for the button\n $('.js-quiz-restart-button').prop('disabled', false); // Makes sure the Restart button is enabled\n let position = handleUserPosition(STORE.restart); // Increment user position \n let score = handleUserScore(STORE.answer); // Increment user score\n $('.js-quiz-form').data('form-state', 'factoid'); // Set form state to factoid\n renderPlanetProfile(); // Generate the planet profile\n renderUserInformation(position, score); // Display the new user score information\n renderQuestion(STORE.currentPlanet); // Display the next question\n renderOptions(STORE.currentPlanet); // Display the options for that question\n}",
"function renderQuestion() {\n $(\"#quiz\").html(`\n <p>${myQuestions[questCounter].question}</p>\n <p><button class=\"answers\">${myQuestions[questCounter].answers.a}</button></p>\n <p><button class=\"answers\">${myQuestions[questCounter].answers.b}</button></p>\n <p><button class=\"answers\">${myQuestions[questCounter].answers.c}</button></p>\n `)\n }",
"function template_edit()\n{\n}",
"function updateQuestionName (evt)\n{\n evt.preventDefault();\n\n var matches = this.id.match(/question_([0-9]+)_name/);\n if (!matches.length) {\n return;\n }\n \n var qid = matches[1];\n\n var newName = $F('question_' + qid + '_name');\n setTextById('question_' + qid + '_title', newName);\n\n questions[qid]['name'] = newName;\n}",
"function loadQuestion(questId) {\n let questionare = document.getElementById('questionare');\n let url = `http://localhost:3001/questions/${questId}`;\n // compile template\n let source = document.getElementById('questionare-template').innerHTML;\n let template = Handlebars.compile(source);\n\n fetch(url)\n .then(response => response.json())\n .then(json => {\n let question = json.question;\n let theAnswer = json.theAnswer;\n let answers = json.answers;\n let html = template({ question, theAnswer, answers });\n questionare.innerHTML = html;\n loader.fadeOut(100);\n n += 1;\n });\n}",
"function loadQuestion (questionIndex) {\n var q = questions[questionIndex];\n questionEl.textContent = (questionIndex + 1) + '.' + q.question;\n opt1.textContent = q.option1;\n opt2.textContent = q.option2;\n opt3.textContent = q.option3;\n opt4.textContent = q.option4;\n\n}",
"function answerQuestion(field, answerTemplate) {\n return function (session, results) {\n // Check to see if we have a hondaModel. The user can cancel picking a hondaModel so IPromptResult.response\n // can be null. \n if (results.response) {\n // Save hondaModel for multi-turn case and compose answer \n var hondaModel = session.dialogData.hondaModel = results.response;\n var answer = { hondaModel: hondaModel.entity, value: data[hondaModel.entity][field] };\n session.send(answerTemplate, answer);\n } else {\n session.send(prompts.cancel);\n }\n };\n}",
"function replace_template(path, context, container_id) {\n\tload_template(path, context, function(html){\n\t\t$(container_id).html(html);\n\t});\n}",
"function setContent(target, value, options) {\n if(!options || (!options.template && !options.templateSelector)) {\n __private.Log.error(\"No valid template is specified for 'content' access point. current node:\" + __private.HTMLAPHelper.getNodeDescription(target));\n return;\n }\n\n var raiseEvent = function(childNode, evt){\n if(options && options[evt]){\n var f = __private.Utility.getValueOnPath(value, options[evt]);\n try{\n f.apply(target, [childNode, __private.HTMLKnotBuilder.getOnNodeDataContext(value)]);\n }\n catch(err) {\n __private.Log.warning(\"Raise \" + evt + \" event failed.\", err);\n }\n }\n };\n\n var template = options.template;\n var isTemplateSelector = false;\n if(options.templateSelector){\n if(!(value === null || typeof(value) === \"undefined\")){\n template = getTemplateFromSelector(options.templateSelector, target, value, true);\n }\n isTemplateSelector = true;\n }\n\n var currentContent = target.children[0]\n if(!currentContent) {\n if(value === null || typeof(value) === \"undefined\" || template === null || typeof (template) === \"undefined\") {\n return;\n }\n var n = __private.HTMLKnotBuilder.createFromTemplate(template, value, target);\n if(n) {\n raiseEvent(currentContent, \"@adding\");\n target.appendChild(n);\n if(!__private.HTMLKnotBuilder.hasDataContext(n)) {\n __private.HTMLKnotBuilder.setDataContext(n, value);\n }\n raiseEvent(n, \"@added\");\n __private.Debugger.nodeAdded(n);\n }\n }\n else{\n if(currentContent.__knot && currentContent.__knot.dataContext === value) {\n return;\n }\n if(value === null || typeof(value) === \"undefined\" || template === null || typeof (template) === \"undefined\") {\n raiseEvent(currentContent, \"@removing\");\n removeNodeCreatedFromTemplate(currentContent);\n raiseEvent(currentContent, \"@removed\");\n }\n else{\n if(isTemplateSelector || __private.HTMLKnotBuilder.isDynamicTemplate(template)) {\n removeNodeCreatedFromTemplate(currentContent);\n currentContent = null;\n if(template){\n currentContent = __private.HTMLKnotBuilder.createFromTemplate(template, value, target);\n }\n if(currentContent) {\n raiseEvent(currentContent, \"@adding\");\n target.appendChild(currentContent);\n if(!__private.HTMLKnotBuilder.hasDataContext(currentContent)) {\n __private.HTMLKnotBuilder.setDataContext(currentContent, value);\n }\n __private.Debugger.nodeAdded(currentContent);\n raiseEvent(currentContent, \"@added\");\n }\n }\n else{\n __private.HTMLKnotBuilder.setDataContext(currentContent, value);\n }\n if(currentContent) {\n if(!currentContent.__knot) {\n currentContent.__knot = {};\n }\n currentContent.__knot.dataContext = value;\n }\n }\n }\n }",
"function populatePretestPage(qn) {\r\n\r\n var question = pretestData.questions[qn].question;\r\n var id = pretestData.questions[qn].id;\r\n var optionsStr = '';\r\n var options = pretestData.questions[qn].choices;\r\n var choiceLen = pretestData.questions[qn].correct.length;\r\n $.each(options, function(key, value) {\r\n if(pretestData.questions[qn].multi) {\r\n optionsStr += '<label class=\"radio\"><input value=\"' + key + '\" type=\"checkbox\" name=\"' + id + '\">' + value + '</label>';\r\n } else {\r\n optionsStr += '<label class=\"radio\"><input value=\"' + key + '\" type=\"radio\" name=\"' + id + '\">' + value + '</label>';\r\n }\r\n });\r\n\r\n var qnStr = '<label class=\"control-label\">' + question + '</label>';\r\n $('.pre-test').find('.qn-block').html(qnStr + optionsStr);\r\n $('.pre-test').find('.qn-block').attr('data-id', qn)\r\n $('.pre-test').find('.qn-block').attr('data-multi', pretestData.questions[qn].multi)\r\n\r\n if(pretestData.questions[qn].multi) {\r\n $('.pre-test').find('.qn-block').append('<span><strong>Note:</strong> Select atleast '+choiceLen+' choices</span>')\r\n }\r\n\r\n //Display question number against total questions in the bottom \r\n $(\".postTestNav\").css({ \"display\": \"block\" });\r\n $(\".postTestNav\").text(qn + 1 + \" of \" + pretestData.questions.length);\r\n }",
"function DocEdit_processPriorNodeEdit(index)\n{\n //only update if new text has been provided\n if (this.text != null)\n {\n //if nodeAttribute, only update the attribute (or tag section)\n if (this.weight.indexOf(\"nodeAttribute\") == 0)\n {\n var pos = extUtils.findAttributePosition(this.priorNode, this.weightInfo);\n if (pos)\n {\n this.insertPos = pos[0];\n this.replacePos = pos[1];\n\n //if positional attribute and removing text\n if (this.weight.indexOf(\",\") != -1 && !this.text)\n {\n //if attribute has space before and after, and removing attribute, strip a space\n if (docEdits.allSrc.charAt(this.insertPos-1) == \" \" &&\n docEdits.allSrc.charAt(this.replacePos) == \" \")\n {\n this.replacePos++;\n }\n }\n }\n }\n else //if not nodeAttribute, do a full replace of the tag\n {\n //if replacing a block tag and the new text\n // starts the same but has no end tag, preserve innerHTML\n if (extUtils.isBlockTag(this.priorNode) &&\n (this.text.search(RegExp(\"\\\\s*<\"+dwscripts.getTagName(this.priorNode),\"i\"))==0) &&\n (this.text.search(RegExp(\"</\"+dwscripts.getTagName(this.priorNode),\"i\"))==-1)\n )\n {\n // This logic is now performed in extPart.queueDocEdit()\n }\n else // if not a block tag\n {\n var priorNodeOffsets = dwscripts.getNodeOffsets(this.priorNode);\n var insertMergeDelims = this.mergeDelims;\n var existingMergeDelims = docEdits.canMergeBlock(dwscripts.getOuterHTML(this.priorNode));\n\n if (this.dontMerge || !existingMergeDelims)\n {\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n }\n else if (this.text == \"\")\n {\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n\n this.bDontMergeTop = true;\n this.bDontMergeBottom = true;\n\n this.mergeDelims = existingMergeDelims;\n }\n else if (insertMergeDelims\n && insertMergeDelims[0].toLowerCase() == existingMergeDelims[0].toLowerCase()\n && insertMergeDelims[1].toLowerCase() == existingMergeDelims[1].toLowerCase())\n {\n var escStartDelim = dwscripts.escRegExpChars(insertMergeDelims[0]);\n var escEndDelim = dwscripts.escRegExpChars(insertMergeDelims[1]);\n\n // Only strip the delimeters if we are not replacing the whole block\n if (this.matchRangeMin != 0 &&\n (priorNodeOffsets[0] + this.matchRangeMax) != priorNodeOffsets[1])\n {\n // Preserve spaces and tabs before the first newline before the end delimeter.\n var pattern = \"^\\\\s*\" + escStartDelim + \"\\\\s*([\\\\S\\\\s]*[^\\\\r\\\\n])\\\\s*\" + escEndDelim + \"\\\\s*$\";\n this.text = this.text.replace(new RegExp(pattern,\"i\"), \"$1\");\n }\n\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n this.bDontMergeTop = true;\n this.bDontMergeBottom = true;\n }\n else\n {\n //must split up existing node and insert in between\n var partBefore = docEdits.allSrc.substring(priorNodeOffsets[0], this.matchRangeMin + priorNodeOffsets[0]);\n var partAfter = docEdits.allSrc.substring(this.matchRangeMax + priorNodeOffsets[0], priorNodeOffsets[1]);\n\n var pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[0]) + \"\\\\s*$\";\n if (partBefore && partBefore.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = existingMergeDelims[1] + docEdits.strNewlinePref + this.text;\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.bDontMergeTop = true;\n }\n else\n {\n this.insertPos = priorNodeOffsets[0];\n }\n\n pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[1]) + \"\\\\s*$\";\n if (partAfter && partAfter.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = this.text + docEdits.strNewlinePref + existingMergeDelims[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n this.bDontMergeBottom = true;\n }\n else\n {\n this.replacePos = priorNodeOffsets[1];\n }\n }\n }\n }\n \n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.priorNode, true); // pss true for isUpdate\n } \n }\n}",
"function updateQuestion(req, res) {\n\n console.log(\"Inside question controllers -> updateQuestion()\");\n\n\n Question.findByIdAndUpdate(\n req.params.id,\n {\n $set: {\n question: req.body.question,\n quesDescription: req.body.quesDescription,\n userTags: req.body.userTags,\n repliesObject: req.body.repliesObject,\n viewCount: req.body.viewCount,\n // userId: req.body.userId,\n dateAdded: req.body.dateAdded\n }\n },\n {\n new: true\n }\n )\n .then(dbQuestionData => res.status(200).json(dbQuestionData))\n .catch(err => {\n console.log(err);\n res.status(500).json(err);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns `true` if the either is an instance of `Left`, `false` otherwise | function isLeft(ma) {
switch (ma._tag) {
case 'Left':
return true;
case 'Right':
return false;
}
} | [
"noMovesLeft () {\n if (this.movesLeft < 1) {\n return true\n } else {\n return false\n }\n }",
"isLeftClicking() {\r\n return this.activeClick === LEFT_CLICK_ID;\r\n }",
"function checkForOverlap(currentDropArea , leftPos,width) {\n\t\tvar children = currentDropArea.children;\n\t\tfor(var i = 0; i < children.length; i++) {\n\t\t\tvar currentChild = children[i].getBoundingClientRect();\n\t\t\tif((leftPos <= currentChild.right && leftPos >= currentChild.left) || (leftPos + width <= currentChild.right && leftPos + width >= currentChild.left)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"function checkBsktForLeft() {\n for (let good in bestOffer.left) {\n if (basket.hasOwnProperty(bestOffer.left[good])) {\n return true;\n }\n }\n}",
"function leftOrRight(currentPoint, otherPoint) {\n if (currentPoint[0] === otherPoint[0]) {\n return SAME;\n }\n else if (currentPoint[0] < otherPoint[0]) {\n return LEFT;\n }\n else {\n return RIGHT;\n }\n }",
"static subnodeHasPrecedence(node, subnode, right)\n {\n const\n nodeType = node.type,\n nodePrecedence = expressionTypePrecedence[nodeType] || -1,\n subnodePrecedence = expressionTypePrecedence[subnode.type] || -1;\n\n if (subnodePrecedence > nodePrecedence)\n return true;\n\n if (nodePrecedence === subnodePrecedence && isLogicalOrBinaryExpression.test(nodeType))\n {\n const\n subnodeOperatorPrecedence = operatorPrecedence[subnode.operator],\n nodeOperatorPrecedence = operatorPrecedence[node.operator];\n\n return (\n subnodeOperatorPrecedence > nodeOperatorPrecedence ||\n (right === true && nodeOperatorPrecedence === subnodeOperatorPrecedence)\n );\n }\n\n return false;\n }",
"function checkHitLeftRight(ball) {\n\t\tif (ball.offsetLeft <= 0 || ball.offsetLeft >= 975) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"function isEitherEven(num1, num2) {\n // your code here\n return ((num1 % 2) === 0 || (num2 % 2) === 0) ? true : false;\n}",
"function detectLeftButton(evt) {\n evt = evt || window.event;\n if (\"buttons\" in evt) {\n return evt.buttons == 1;\n }\n var button = evt.which || evt.button;\n return button == 1;\n}",
"function is_to_the_left_of_blank(tile) {\n var isLeft = false;\n if (tile.row === blank.row - 1)\n {\n isLeft = true;\n }\n return isLeft;\n}",
"isRightClicking() {\r\n return this.activeClick === RIGHT_CLICK_ID;\r\n }",
"isInside(modelSpacePoint) {\n\t\t// jshint unused:vars\n\t\treturn false;\n\t}",
"get isOwning() {\n return !!(this.isManyToOne ||\n (this.isManyToMany && this.joinTable) ||\n (this.isOneToOne && this.joinColumn));\n }",
"function isSelf(candidate) {\r\n\treturn (self == candidate);\r\n}",
"leftPanelComponentToRender(){\n //Switch statement to check which component should be rendered on the left\n switch(this.state.leftPanelComponent){\n case \"LoginComponent\":\n //If a token does not exist the user is not logged in, so will just show the player stats component\n if(this.state.token){\n this.setState({\n leftPanelComponent: \"PlayerStatsComponent\",\n })\n } else {\n return <LoginComponent informationMessage={this.state.leftPanelComponentInformationMessage} callbackToParent={this.leftPanelComponentChildCallback}/>\n }\n case \"RegisterComponent\":\n return <RegisterComponent callbackToParent={this.leftPanelComponentChildCallback}/>\n case \"PlayerStatsComponent\":\n if(this.state.token){\n return <PlayerStatsComponent token={this.state.token} callbackToParent={this.leftPanelComponentChildCallback}/> \n } else {\n this.setState({\n leftPanelComponent: \"LoginComponent\",\n })\n }\n case \"ShopComponent\":\n if(this.state.token){\n return <ShopComponent token={this.state.token} shouldForceUpdate={this.state.openedPackForceShopUpdate} callbackToParent={this.leftPanelComponentChildCallback}/> \n } else {\n this.setState({\n leftPanelComponent: \"LoginComponent\",\n })\n }\n }\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ServiceLinkedRole.__pulumiType;\n }",
"getOverlap(topLeft1, bottomRight1, topLeft2, bottomRight2) {\n\t\tif (topLeft1.x > bottomRight2.x || topLeft2.x > bottomRight1.x) {\n\t\t\t// rectangles are to the left/right of eachother \n\t\t\treturn false;\n\t\t}\n\t\telse if (topLeft1.y > bottomRight2.y || topLeft2.y > bottomRight1.y) {\n\t\t\t// rectangles are above/below each other\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}",
"function goLeft(rover) {\r\n\tswitch(rover.direction) {\r\n\t\tcase 'N': rover.position[1]--;\r\n\t\t\tbreak;\r\n\t\tcase 'E': rover.position[0]--;\r\n\t\t\tbreak;\r\n\t\tcase 'W': rover.position[0]++;\r\n\t\t\tbreak;\r\n\t\tcase 'S': rover.position[1]++;\r\n\t\t\tbreak;\r\n\t}\r\n}",
"function check(...types) {\n for (const type of types) {\n if (type === currentToken().type) {\n return true;\n }\n }\n return false;\n }",
"function isNearLeftEdge(element, event) {\n\tlet ret = false;\n\tlet offset = getElementOffset(element);\n\tlet rightEdge = element.getBoundingClientRect().right - offset.left;\n\tlet mouseClickPosition = event.pageX - offset.left;\n\n\tlet buttonWidth = element.getBoundingClientRect().width * .30;\n\n\tif (buttonWidth > 50){\n\t\tbuttonWidth = 50;\n\t}\n\n\tif (rightEdge - mouseClickPosition < buttonWidth) {\n\t\tret = true;\n\t}\n\n\treturn ret;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if box fits on bed | function isOnBed(bed, box) {
setOutline(bed);
return (insideHull(box, getOutline(bed)) >= 0);
} | [
"function collides(bed, box) {\n\tif (isEmpty(bed)) {\n\t\treturn false;\n\t}\n\n\tfor (var i = 0; i < bed.boxes.length; i++) {\n\t\t//Check if boxes are the same (then outsideHull will return)\n\t\tif (equalBoxes(box, bed.boxes[i])) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!outsideHull(box, getHull(bed.boxes[i]))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"containsBox(planes, box) {\n\n const {min, max} = box\n\n const vertices = [\n new THREE.Vector3(min.x, min.y, min.z),\n new THREE.Vector3(min.x, min.y, max.z),\n new THREE.Vector3(min.x, max.y, max.z),\n new THREE.Vector3(max.x, max.y, max.z),\n new THREE.Vector3(max.x, max.y, min.z),\n new THREE.Vector3(max.x, min.y, min.z),\n new THREE.Vector3(min.x, max.y, min.z),\n new THREE.Vector3(max.x, min.y, max.z)\n ]\n\n for (let vertex of vertices) {\n\n for (let plane of planes) {\n\n if (plane.distanceToPoint(vertex) < 0) {\n\n return false\n }\n }\n }\n\n return true\n }",
"function canPlaceAt(bed, box, position) {\n\t//Box can be placed at position if it fits on the bed and doesnt collide with any other boxes\n\tvar newBox = moveTo(box, position);\n\treturn (isOnBed(bed, newBox) && !collides(bed, newBox));\n}",
"function checkInsideBoundingBox(bound, pt)\n{\n\tif (pt.x < bound.lower_bound.x || pt.x > bound.higher_bound.x) {\n\t\treturn false;\n\t}\n\tif (pt.y < bound.lower_bound.y || pt.y > bound.higher_bound.y) {\n\t\treturn false;\n\t}\n\tif (pt.z < bound.lower_bound.z || pt.z > bound.higher_bound.z) {\n\t\treturn false;\n\t} \n\treturn true;\n}",
"testBoxOverlaps() {\n // Overlapping tests.\n let box2 = new Box(1, 4, 4, 1);\n\n // Corner overlaps.\n assertTrue('NW overlap', boxOverlaps(new Box(0, 2, 2, 0), box2));\n assertTrue('NE overlap', boxOverlaps(new Box(0, 5, 2, 3), box2));\n assertTrue('SE overlap', boxOverlaps(new Box(3, 5, 5, 3), box2));\n assertTrue('SW overlap', boxOverlaps(new Box(3, 2, 5, 0), box2));\n\n // Inside.\n assertTrue('Inside overlap', boxOverlaps(new Box(2, 3, 3, 2), box2));\n\n // Around.\n assertTrue('Outside overlap', boxOverlaps(new Box(0, 5, 5, 0), box2));\n\n // Edge overlaps.\n assertTrue('N overlap', boxOverlaps(new Box(0, 3, 2, 2), box2));\n assertTrue('E overlap', boxOverlaps(new Box(2, 5, 3, 3), box2));\n assertTrue('S overlap', boxOverlaps(new Box(3, 3, 5, 2), box2));\n assertTrue('W overlap', boxOverlaps(new Box(2, 2, 3, 0), box2));\n\n assertTrue('N-in overlap', boxOverlaps(new Box(0, 5, 2, 0), box2));\n assertTrue('E-in overlap', boxOverlaps(new Box(0, 5, 5, 3), box2));\n assertTrue('S-in overlap', boxOverlaps(new Box(3, 5, 5, 0), box2));\n assertTrue('W-in overlap', boxOverlaps(new Box(0, 2, 5, 0), box2));\n\n // Does not overlap.\n box2 = new Box(3, 6, 6, 3);\n\n // Along the edge - shorter.\n assertFalse('N-in no overlap', boxOverlaps(new Box(1, 5, 2, 4), box2));\n assertFalse('E-in no overlap', boxOverlaps(new Box(4, 8, 5, 7), box2));\n assertFalse('S-in no overlap', boxOverlaps(new Box(7, 5, 8, 4), box2));\n assertFalse('N-in no overlap', boxOverlaps(new Box(4, 2, 5, 1), box2));\n\n // By the corner.\n assertFalse('NE no overlap', boxOverlaps(new Box(1, 8, 2, 7), box2));\n assertFalse('SE no overlap', boxOverlaps(new Box(7, 8, 8, 7), box2));\n assertFalse('SW no overlap', boxOverlaps(new Box(7, 2, 8, 1), box2));\n assertFalse('NW no overlap', boxOverlaps(new Box(1, 2, 2, 1), box2));\n\n // Perpendicular to an edge.\n assertFalse('NNE no overlap', boxOverlaps(new Box(1, 7, 2, 5), box2));\n assertFalse('NEE no overlap', boxOverlaps(new Box(2, 8, 4, 7), box2));\n assertFalse('SEE no overlap', boxOverlaps(new Box(5, 8, 7, 7), box2));\n assertFalse('SSE no overlap', boxOverlaps(new Box(7, 7, 8, 5), box2));\n assertFalse('SSW no overlap', boxOverlaps(new Box(7, 4, 8, 2), box2));\n assertFalse('SWW no overlap', boxOverlaps(new Box(5, 2, 7, 1), box2));\n assertFalse('NWW no overlap', boxOverlaps(new Box(2, 2, 4, 1), box2));\n assertFalse('NNW no overlap', boxOverlaps(new Box(1, 4, 2, 2), box2));\n\n // Along the edge - longer.\n assertFalse('N no overlap', boxOverlaps(new Box(0, 7, 1, 2), box2));\n assertFalse('E no overlap', boxOverlaps(new Box(2, 9, 7, 8), box2));\n assertFalse('S no overlap', boxOverlaps(new Box(8, 7, 9, 2), box2));\n assertFalse('W no overlap', boxOverlaps(new Box(2, 1, 7, 0), box2));\n }",
"function isEmpty(bed) {\n\tif (!bed.hasOwnProperty('boxes') || bed.boxes.length == 0) {\n\t\treturn true;\n\t}\n\treturn false;\n}",
"function levelFourGridBox5(j) {\n let box5 = 17;\n let across = 2;\n let nextLine = 12;\n if (\n (j > box5 && j < box5 + across) ||\n (j > box5 + nextLine && j < box5 + nextLine + across)\n ) {\n return true;\n } else {\n return false;\n }\n}",
"function checkCube() {\n//===============================\n var check = false;\n\n // Check each color\n for(face in colorMap) {\n // Check each sticker from that color\n $(\".color-\"+colorMap[face]).each(function() {\n\n // If the sticker isn't on the right face for its color\n // Then the cube hasn't been solved yet\n check = $(this).hasClass(\"pyramid-\"+face);\n return check;\n });\n\n if(!check) break;\n }\n\n return check;\n}",
"checkEat() {\n let x = convert(this.snake[0].style.left);\n let y = convert(this.snake[0].style.top);\n\n let check = false;\n if (x === this.bait.x && y === this.bait.y) check = true;\n\n return check;\n }",
"function isInside(x, y, card) {\n let w = card.image.width\n let h = card.image.height\n let cx = card.x\n let cy = card.y\n\n if ( x > cx && x < ( cx + w ) && y > cy && y < ( cy + h ) \n && card.state == 'table') {\n return {w: w, h: h, cx: cx, cy: cy}\n } else {\n return false\n }\n }",
"function GrabbedBox(){\n\t\tthis.boxGrabbed = false;\n\t\tthis.boxGrabbedIndex = -1;\n\t\tthis.overObstacleIndex = -1;\n\t\tthis.indexOnBoard = -1\n\t\tthis.xInitial = 0;\n\t\tthis.yInitial = 0;\n\t\tthis.xGrabOffset = 0;\n\t\tthis.yGrabOffset = 0;\n\t}",
"function equalBoxes(bb1, bb2){\n\treturn (bb1.min.x == bb2.min.x &&\n\t\tbb1.min.y == bb2.min.y && bb1.max.x == bb2.max.x &&\n\t\tbb1.max.y == bb2.max.y);\n}",
"function levelFourGridBox6(j) {\n let box6 = 18;\n let across = 2;\n let nextLine = 12;\n if (\n (j > box6 && j < box6 + across) ||\n (j > box6 + nextLine && j < box6 + nextLine + across)\n ) {\n return true;\n } else {\n return false;\n }\n}",
"function isThereEnoughChocolateBags(small, big, total){\n const maxBigBoxes = total / 5;\n const bigBoxesWeCanUse = maxBigBoxes < big ? maxBigBoxes : big;\n total -= bigBoxesWeCanUse * 5;\n\n if(small < total)return false;\n else return true;\n}",
"function inBounds(p) {\n // check bounds of display\n if((p[0]-2*bcr) <= width * 0.1 || //left\n (p[0]+2*bcr) >= width - (width * 0.1) || //right\n (p[1]-2*bcr) <= height * 0.1 ||\n (p[1]+2*bcr) >= height - (height * 0.1)) {\n return false;\n }\n return true;\n}",
"function isInField(x, y)\n{\n if (g_field.x > x || x >= g_field.x + g_field.width )\n {\n return false;\n }\n if (g_field.y > y || y >= g_field.y + g_field.height )\n {\n return false;\n }\n return true;\n}",
"function isInside(rw, rh, rx, ry, x, y)\n{\n return x <= rx+rw && x >= rx && y <= ry+rh && y >= ry // Get Click Inside a Bush\n}",
"isGameFieldValid() {\n\t\tlet self = this;\n\t\tlet isValid = true;\n\t\tthis.birds.forEach(function(bird) {\n\t\t\tlet h = bird.getHeight();\n\t\t\tlet location = bird.getLocation();\n\t\t\tlet x = location.x;\n\t\t\tlet y = location.y;\n\t\t\tisValid = self.fieldSize.isWithinField(h, x, y);\n\t\t\tif (!isValid) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\treturn isValid;\n\t}",
"function levelFourGridBox4(j) {\n let box4 = 16;\n let across = 2;\n let nextLine = 12;\n if (\n (j > box4 && j < box4 + across) ||\n (j > box4 + nextLine && j < box4 + nextLine + across)\n ) {\n return true;\n } else {\n return false;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge two text nodes: `node` into `prev`. | function mergeText(prev, node) {
prev.value += node.value;
return prev;
} | [
"function merge(n) {\n if (n.nodeType === Node.TEXT_NODE) {\n if (n.nextSibling && n.nextSibling.nodeType === Node.TEXT_NODE) {\n n.textContent += n.nextSibling.textContent;\n n.nextSibling.parentNode.removeChild(n.nextSibling);\n }\n\n if (n.previousSibling && n.previousSibling.nodeType === Node.TEXT_NODE) {\n n.previousSibling.textContent += n.textContent;\n n.parentNode.removeChild(n);\n }\n }\n}",
"function emitTagAndPreviousTextNode() {\n var textBeforeTag = html.slice(currentDataIdx, currentTag.idx);\n if (textBeforeTag) {\n // the html tag was the first element in the html string, or two\n // tags next to each other, in which case we should not emit a text\n // node\n onText(textBeforeTag, currentDataIdx);\n }\n if (currentTag.type === 'comment') {\n onComment(currentTag.idx);\n }\n else if (currentTag.type === 'doctype') {\n onDoctype(currentTag.idx);\n }\n else {\n if (currentTag.isOpening) {\n onOpenTag(currentTag.name, currentTag.idx);\n }\n if (currentTag.isClosing) {\n // note: self-closing tags will emit both opening and closing\n onCloseTag(currentTag.name, currentTag.idx);\n }\n }\n // Since we just emitted a tag, reset to the data state for the next char\n resetToDataState();\n currentDataIdx = charIdx + 1;\n }",
"function prevParentTextNode(e) {\n\t\tconst elem = e.first()[0],\n\t\t\tparent = e.parent();\n\t\t/*\n\t\t\tQuit early if there's no parent.\n\t\t*/\n\t\tif (!parent.length) {\n\t\t\treturn null;\n\t\t}\n\t\t/*\n\t\t\tGet the parent's text nodes, and obtain only the last one which is\n\t\t\tearlier (or later, depending on positionBitmask) than this element.\n\t\t*/\n\t\tlet textNodes = parent.textNodes().filter((e) => {\n\t\t\tconst pos = e.compareDocumentPosition(elem);\n\t\t\treturn pos & 4 && !(pos & 8);\n\t\t});\n\t\ttextNodes = textNodes[textNodes.length-1];\n\t\t/*\n\t\t\tIf no text nodes were found, look higher up the tree, to the grandparent.\n\t\t*/\n\t\treturn !textNodes ? prevParentTextNode(parent) : textNodes;\n\t}",
"function Edge(prev_node, character, next_node) {\n this.prev_node = prev_node;\n this.character = character; \n this.next_node = next_node; \n}",
"function insertAfter(sourceWord, newWord)\n{\n\tif(!newWord.word.match(regexp_is_space)) //if it's not just spaces, insert it\n\t{\n\t\t//insert into words list structure\n\t\tnewWord.nextWord = sourceWord.nextWord;\n\t\tsourceWord.nextWord = newWord;\n\t\t\n\t\tnewWord.previousWord = sourceWord;\n\t\tif(newWord.nextWord)\n\t\t{\n\t\t\tnewWord.nextWord.previousWord = newWord;\n\t\t}\n\t\t\n\t\t//determine the right sentence\n\t\tif(sourceWord.word.match(regexp_contains_eos)) //if the sourceWord is an end of sentence\n\t\t{\n\t\t\tnewWord.sentence = sourceWord.sentence.nextSentence;\n\t\t\tnewWord.sentence.firstWord = newWord;\n\t\t\tif(!newWord.sentence.lastWord) //if the sentence was empty, it's also the last word\n\t\t\t{\n\t\t\t\tnewWord.sentence.lastWord = newWord;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnewWord.sentence = sourceWord.sentence;\n\t\t\tif(sourceWord.sentence.lastWord == sourceWord) //if sourceWord was the last of its sentence\n\t\t\t{\n\t\t\t\tsourceWord.sentence.lastWord = newWord;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//edit the node start and end points if needed\n\t\tif(newWord.node != sourceWord.node) //if not the same node as the previous word, it's the first of its node\n\t\t{\n\t\t\tnewWord.node.firstWord = newWord;\n\t\t}\n\t\tif(!newWord.nextWord || newWord.node != newWord.nextWord.node) \n\t\t{\n\t\t\tnewWord.node.lastWord = newWord;\n\t\t}\n\t\t\n\t\t//update offsets of the following words\n\t\tupdateOffsets(newWord.node, newWord.nextWord, newWord.word.length);\n\t\t\n\t\t//if we just inserted end of sentence punctuation, what follows becomes a new sentence\n\t\tif(newWord.word.match(regexp_contains_eos)) \n\t\t{\n\t\t\tsplitSentenceFrom(newWord);\n\t\t}\n\t\t\n\t\tnewWord.node.parent_text.log.addWord(newWord);\n\t\t\n\t\treturn newWord;\n\t}\n\telse\t//just update the offsets\n\t{\n\t\tupdateOffsets(newWord.node, sourceWord.nextWord, newWord.word.length);\n\t\treturn null;\n\t}\n}",
"function DocEdit_processPriorNodeEdit(index)\n{\n //only update if new text has been provided\n if (this.text != null)\n {\n //if nodeAttribute, only update the attribute (or tag section)\n if (this.weight.indexOf(\"nodeAttribute\") == 0)\n {\n var pos = extUtils.findAttributePosition(this.priorNode, this.weightInfo);\n if (pos)\n {\n this.insertPos = pos[0];\n this.replacePos = pos[1];\n\n //if positional attribute and removing text\n if (this.weight.indexOf(\",\") != -1 && !this.text)\n {\n //if attribute has space before and after, and removing attribute, strip a space\n if (docEdits.allSrc.charAt(this.insertPos-1) == \" \" &&\n docEdits.allSrc.charAt(this.replacePos) == \" \")\n {\n this.replacePos++;\n }\n }\n }\n }\n else //if not nodeAttribute, do a full replace of the tag\n {\n //if replacing a block tag and the new text\n // starts the same but has no end tag, preserve innerHTML\n if (extUtils.isBlockTag(this.priorNode) &&\n (this.text.search(RegExp(\"\\\\s*<\"+dwscripts.getTagName(this.priorNode),\"i\"))==0) &&\n (this.text.search(RegExp(\"</\"+dwscripts.getTagName(this.priorNode),\"i\"))==-1)\n )\n {\n // This logic is now performed in extPart.queueDocEdit()\n }\n else // if not a block tag\n {\n var priorNodeOffsets = dwscripts.getNodeOffsets(this.priorNode);\n var insertMergeDelims = this.mergeDelims;\n var existingMergeDelims = docEdits.canMergeBlock(dwscripts.getOuterHTML(this.priorNode));\n\n if (this.dontMerge || !existingMergeDelims)\n {\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n }\n else if (this.text == \"\")\n {\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n\n this.bDontMergeTop = true;\n this.bDontMergeBottom = true;\n\n this.mergeDelims = existingMergeDelims;\n }\n else if (insertMergeDelims\n && insertMergeDelims[0].toLowerCase() == existingMergeDelims[0].toLowerCase()\n && insertMergeDelims[1].toLowerCase() == existingMergeDelims[1].toLowerCase())\n {\n var escStartDelim = dwscripts.escRegExpChars(insertMergeDelims[0]);\n var escEndDelim = dwscripts.escRegExpChars(insertMergeDelims[1]);\n\n // Only strip the delimeters if we are not replacing the whole block\n if (this.matchRangeMin != 0 &&\n (priorNodeOffsets[0] + this.matchRangeMax) != priorNodeOffsets[1])\n {\n // Preserve spaces and tabs before the first newline before the end delimeter.\n var pattern = \"^\\\\s*\" + escStartDelim + \"\\\\s*([\\\\S\\\\s]*[^\\\\r\\\\n])\\\\s*\" + escEndDelim + \"\\\\s*$\";\n this.text = this.text.replace(new RegExp(pattern,\"i\"), \"$1\");\n }\n\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n this.bDontMergeTop = true;\n this.bDontMergeBottom = true;\n }\n else\n {\n //must split up existing node and insert in between\n var partBefore = docEdits.allSrc.substring(priorNodeOffsets[0], this.matchRangeMin + priorNodeOffsets[0]);\n var partAfter = docEdits.allSrc.substring(this.matchRangeMax + priorNodeOffsets[0], priorNodeOffsets[1]);\n\n var pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[0]) + \"\\\\s*$\";\n if (partBefore && partBefore.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = existingMergeDelims[1] + docEdits.strNewlinePref + this.text;\n this.insertPos = this.matchRangeMin + priorNodeOffsets[0];\n this.bDontMergeTop = true;\n }\n else\n {\n this.insertPos = priorNodeOffsets[0];\n }\n\n pattern = \"^\\\\s*\" + dwscripts.escRegExpChars(existingMergeDelims[1]) + \"\\\\s*$\";\n if (partAfter && partAfter.search(new RegExp(pattern, \"i\")) == -1)\n {\n this.text = this.text + docEdits.strNewlinePref + existingMergeDelims[0];\n this.replacePos = this.matchRangeMax + priorNodeOffsets[0];\n this.bDontMergeBottom = true;\n }\n else\n {\n this.replacePos = priorNodeOffsets[1];\n }\n }\n }\n }\n \n if (!this.dontPreprocessText)\n {\n this.text = dwscripts.preprocessDocEditInsertText(this.text, this.priorNode, true); // pss true for isUpdate\n } \n }\n}",
"function processText (node, div, queue) {\n const text = node.textContent;\n try {\n Expect(div).is.ok();\n Expect(div.noText).is.not.true();\n Expect(div.break).is.not.true();\n if (div.link) {\n if (!div.linkText) {\n Expect(_.startsWith(text, 'http')).is.true();\n div.linkText = true;\n } else {\n Expect(div.linkSuffix).is.not.true();\n Expect(text.charAt(0)).is.equal(',');\n div.linkSuffix = true;\n }\n }\n } catch(err) {\n console.log(`text: ${text}`);\n console.log(`node: ${Stringify(div)}`);\n let prev = queue.pop();\n console.log(`prevNode: ${prev && Stringify(prev)}`);\n throw err;\n }\n return text;\n}",
"previous() {\n let tmp = this.currentNode.previous();\n if (!tmp.done) {\n this.currentNode = tmp.value;\n this.currentNode.clearChildren();\n //this.currentNode.children.forEach((child) => child.clearChildren());\n console.log(\" ================ PREV ================ \");\n this.ptree();\n }\n return tmp;\n }",
"function previousElement(element)\r\n{\r\n\twhile (element = element.previousSibling)\r\n\t{\r\n\t\tif (element.nodeType == 1) return element;\r\n\t}\r\n\treturn null;\r\n}",
"prependData(target, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner === target){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }",
"function assert_previous_nodes(aNodeType, aStart, aNum) {\n let node = aStart;\n for (let i = 0; i < aNum; ++i) {\n node = node.previousSibling;\n if (node.localName != aNodeType)\n throw new Error(\"The node should be preceded by \" + aNum + \" nodes of \" +\n \"type \" + aNodeType);\n }\n return node;\n}",
"function insert_elt_after(new_elt, old_elt){\n old_elt.parentNode.insertBefore(new_elt, old_elt.nextSibling);\n}",
"function followingNonDescendantNode(node) {\n if (node.ownerElement) {\n if (node.ownerElement.firstChild) return node.ownerElement.firstChild;\n node = node.ownerElement;\n }\n do {\n if (node.nextSibling) return node.nextSibling;\n } while (node = node.parentNode);\n return null;\n }",
"static changeNode(node, selection, splits, dom) {\n\t\tif(node == null || node.parentNode == null)\n\t\t\treturn;\n\t\tif(dom == null)\n\t\t\tdom = document;\n\t\tvar master = node.parentNode;\n\t\tmaster.removeChild(node); //ich denke hier werden mehrere kinder möglch sein, deshalb reversing\n\t\tMarkMyWords._highlights[master] = node;\n\t\tfor(var item of splits) {\n\t\t\tmaster.appendChild(item === null ?\n\t\t\t\tMarkMyWords.makeMarkNode(selection, dom) :\n\t\t\t\tdom.createTextNode(item));\n\t\t}\n\t}",
"prependDataBeforeVal(val, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner.data === val){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }",
"prevSibling() {\n return this.sibling(-1)\n }",
"function WordNode(id, text) {\n this.id = id;\n this.text = text;\n this.connections = {};\n this.ltr = true;\n}",
"function setTextContent(node, value) {\n if (predicates_1.isCommentNode(node)) {\n node.data = value;\n }\n else if (predicates_1.isTextNode(node)) {\n node.value = value;\n }\n else {\n const tn = modification_1.constructors.text(value);\n tn.parentNode = node;\n node.childNodes = [tn];\n }\n}",
"onPreviousParagraphRequested() {}",
"function bringNodeToFront(p) {\n\tlet i, j;\n\tp.selection.bringToFront();\n\tfor (i = 0; i < p.channels.length; ++i) {\n\t\tfor (j = 1; j < p.channels[i].parts.length; ++j)\n\t\t\tp.channels[i].parts[j].bringToFront();\n\t\tp.channels[i].node1.bringToFront();\n\t\tp.channels[i].node2.bringToFront()\n\t}\n\tp.label.bringToFront();\n\tif (p.delete)\n\t\tp.delete.bringToFront();\n\tif (p.split)\n\t\tp.split.bringToFront()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selects and sets an existing stack matching the stack name, failing if none exists. | selectStack(stackName) {
return __awaiter(this, void 0, void 0, function* () {
// If this is a remote workspace, we don't want to actually select the stack (which would modify global state);
// but we will ensure the stack exists by calling `pulumi stack`.
const args = ["stack"];
if (!this.isRemote) {
args.push("select");
}
args.push("--stack", stackName);
yield this.runPulumiCmd(args);
});
} | [
"static selectStack(args, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const ws = yield createLocalWorkspace(args, opts);\n const stack = yield stack_1.Stack.select(args.stackName, ws);\n return remoteStack_1.RemoteStack.create(stack);\n });\n }",
"lookupStack(name) {\n const len = this.stack.length - 1;\n for (let i = len; i >= 0; i--) {\n const frame = this.stack[i];\n const node = this.resolveName(name, frame);\n if (node.type !== types.MISSING) {\n return node;\n }\n\n if (frame.stopResolution) {\n break;\n }\n }\n return MISSING_NODE;\n }",
"function Stack() {\n\tthis.layers = [];\n\tthis.layers.push({});\n\t\n\tthis.addLayer = function() {\n\t\tthis.layers.push({});\n\t}\n\tthis.removeLayer = function() {\n\t\tthis.layers.pop();\n\t}\n\tthis.addVar = function(name, value) {\n\t\tname = name.toLowerCase();\n\t\tthis.layers[this.layers.length-1][name] = value;\n\t}\n\tthis.existVar = function(name) {\n\t\tname = name.toLowerCase();\n\t\tvar result = false;\n\t\tfor(var i=this.layers.length-1; i>=0; i--) {\n\t\t\tif(this.layers[i].hasOwnProperty(name)) {\n\t\t\t\tresult = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tthis.existNow = function(name) {\n\t\tname = name.toLowerCase();\n\t\tvar result = false;\n\t\tif(this.layers[this.layers.length-1].hasOwnProperty(name)) {\n\t\t\tresult = true;\n\t\t}\n\t\treturn result;\n\t}\n\tthis.setVar = function(name, value) {\n\t\tname = name.toLowerCase();\n\t\tfor(var i=this.layers.length-1; i>=0; i--) {\n\t\t\tif(this.layers[i].hasOwnProperty(name)) {\n\t\t\t\tthis.layers[i][name] = value;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tthis.getVar = function(name) {\n\t\tname = name.toLowerCase();\n\t\tfor(var i=this.layers.length-1; i>=0; i--) {\n\t\t\tif(this.layers[i].hasOwnProperty(name)) {\n\t\t\t\treturn this.layers[i][name];\n\t\t\t}\n\t\t}\n\t}\n}",
"getStackByName(stackName) {\n const artifacts = this.artifacts.filter(a => a instanceof cloudformation_artifact_1.CloudFormationStackArtifact && a.stackName === stackName);\n if (!artifacts || artifacts.length === 0) {\n throw new Error(`Unable to find stack with stack name \"${stackName}\"`);\n }\n if (artifacts.length > 1) {\n // eslint-disable-next-line max-len\n throw new Error(`There are multiple stacks with the stack name \"${stackName}\" (${artifacts.map(a => a.id).join(',')}). Use \"getStackArtifact(id)\" instead`);\n }\n return artifacts[0];\n }",
"checkStackSize(stack, minSize, name) {\n const size = stack.size();\n if (size < minSize) throw new Error(`Expected stack '${name}' to be of size >= ${minSize}, size is ${size}`);\n }",
"set(name, value, global) {\n if (global === void 0) {\n global = false;\n }\n\n if (global) {\n // Global set is equivalent to setting in all groups. Simulate this\n // by destroying any undos currently scheduled for this name,\n // and adding an undo with the *new* value (in case it later gets\n // locally reset within this environment).\n for (let i = 0; i < this.undefStack.length; i++) {\n delete this.undefStack[i][name];\n }\n\n if (this.undefStack.length > 0) {\n this.undefStack[this.undefStack.length - 1][name] = value;\n }\n } else {\n // Undo this set at end of this group (possibly to `undefined`),\n // unless an undo is already in place, in which case that older\n // value is the correct one.\n const top = this.undefStack[this.undefStack.length - 1];\n\n if (top && !top.hasOwnProperty(name)) {\n top[name] = this.current[name];\n }\n }\n\n this.current[name] = value;\n }",
"setSelectedItemByName(name){\n\t\tvar item = this.getStyleByName(name);\n\t\tif(item==false) return;\n\t\tthis.setSelectedItem(item.ID);\n\t}",
"popActive() {\n\t\t\tif(!this._activeStack.length) throw new Error(\"Active stack for \"+this.name+\" is empty and requested pop.\");\n\t\t\tthis._activeStack.pop().becomeActive();\n\t\t}",
"find_stack_by_contents(num){\n for (let i = 0; i < this.board.length; i++){\n if (this.board[i].current_set.includes(num)){\n return this.board[i]\n }\n }\n }",
"function Stack(props) {\n return __assign({ Type: 'AWS::OpsWorks::Stack' }, props);\n }",
"function testGetStackById(done, stack) {\n chai.request(server)\n .get(BASEURL + 'id/' + stack._id)\n .end(function(err, res) {\n res.should.be.json;\n res.body.should.be.a('object');\n res.body.should.have.property('status');\n res.body.should.have.property('success');\n res.body.should.have.property('result');\n res.body.status.should.equal(200);\n res.body.result.should.be.a('object');\n done();\n });\n}",
"function setScene(sceneName) {\n scene = sceneName;\n switch (sceneName) {\n case \"main_menu\":\n mainMenuScreen();\n break;\n case \"game_level\":\n startGame(); // Sets up game variables\n break;\n case \"game_over\":\n gameOverScreen();\n break;\n default:\n console.error(\"Invalid scene name: \" + sceneName);\n break;\n }\n}",
"static async deleteStack(stackName) {\n await KelchCommon.exec('aws cloudformation delete-stack --stack-name ' + stackName);\n }",
"function displayStackSelectionBox(row,column)\n{\n\tvar tile = map[row][column];\n\tvar stack = tile.stack;\n\t\n\tvar addMoveButton = 0;\n\tvar index = 0;\n\t//check to see if there's a select square here\n\tfor(var i=0;i<movementSquares.length;i++)\n\t{\n\t\tif(movementSquares[i].row == row && movementSquares[i].column == column)\n\t\t{\n\t\t\taddMoveButton = 1;\n\t\t\t\n\t\t}\n\t}\n\t\n\t//background\n\tvar stackSelectionBox = new createjs.Shape();\n\tstackSelectionBox.graphics.beginFill(\"DarkSlateGray\").drawRect(0, 0, 44, 25*(stack.length+addMoveButton));\n\tstackSelectionBox.x = 24*(column+1);\n\tstackSelectionBox.y = 50+24*row;\n\tstackSelectionBox.name = \"stackSelectionBox\";\n\tstage.addChild(stackSelectionBox);\n\t\n\tfor(var i=0;i<stack.length;i++)\n\t{\n\t\t//add button\n\t\tvar SSBButton = new Button(\"SSBButton\",24*(column+1)+20,52+24*row+24*i,20,20);\n\t\tSSBButton.name = \"SSBButton\"+i;\n\t\tSSBButton.text = \"<\";\n\t\tSSBButton.row = row;\n\t\tSSBButton.column = column;\n\t\tSSBButton.target = stack[i];\n\t\tSSBButton.handleButtonEvent = handleSSBBEvent;\n\t\tSSBButton.onClick = function()\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tdeSelectAll();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar tile = map[this.row][this.column]\n\t\t\t\t\t\t\t\tselectedObject = this.target;\n\t\t\t\t\t\t\t\tdisplaySelectBox(this.row,this.column);\n\t\t\t\t\t\t\t\tselectedObject.displayInfo(stage, player);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(isUnit(this.target) == true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tselectedUnit = this.target;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(selectedUnit.movementPoints > 0 && selectedUnit.color == player.color && player.onTurn == true)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tdisplayMovementSquares(this.row,this.column);\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\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tselectedUnit = null;\n\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\tremoveStackSelectionBox();\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\tSSBButton.draw();\n\t\t\n\t\t//add image\n\t\tvar objectImage = new Image();\n\t\tobjectImage.src = stack[i].image.src;\n\t\tobjectImage.yOffset = i;\n\t\tobjectImage.onload = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar SSBImage = new createjs.Bitmap(this);\n\t\t\t\t\t\t\t\tSSBImage.x = 24*(column+1)+2;\n\t\t\t\t\t\t\t\tSSBImage.y = 54 + 24*row+24*this.yOffset;\n\t\t\t\t\t\t\t\tSSBImage.name = \"SSBImage\";\n\t\t\t\t\t\t\t\tstage.addChild(SSBImage);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\t\n\t\tindex++;\n\t}\n\t\n\tif(addMoveButton == 1)\n\t{\n\t\t//add move here button\n\t\tvar moveHereButton = new Button(\"moveHereButton\",24*(column+1)+20,52+24*row+24*index,20,20);\n\t\tmoveHereButton.name = \"moveHereButton\";\n\t\tmoveHereButton.text = \"<\";\n\t\tmoveHereButton.row = row;\n\t\tmoveHereButton.column = column;\n\t\t\n\t\tvar placeHolder = [];placeHolder.type = \"Move Here\";\n\t\t\n\t\tmoveHereButton.target = placeHolder;\n\t\tmoveHereButton.handleButtonEvent = handleSSBBEvent;\n\t\tmoveHereButton.onClick = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveSelectedUnit(this.row,this.column);\n\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(selectedUnit.movementPoints > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdisplayMovementSquares(selectedUnit.row,selectedUnit.column);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tremoveMovementSquares();\n\t\t\t\t\t\t\t\t\tstage.update();\n\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\tremoveStackSelectionBox();\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t\tmoveHereButton.draw();\n\t\t\n\t\t//add image\n\t\tvar moveHereImage = new Image();\n\t\tmoveHereImage.src = \"http://kev1shell.github.io/assets/sprites/other/moveHereSymbol.png\";\n\t\tmoveHereImage.yOffset = index;\n\t\tmoveHereImage.onload = function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar MHImage = new createjs.Bitmap(this);\n\t\t\t\t\t\t\t\tMHImage.x = 24*(column+1)+2;\n\t\t\t\t\t\t\t\tMHImage.y = 54 + 24*row+24*this.yOffset;\n\t\t\t\t\t\t\t\tMHImage.name = \"MHImage\";\n\t\t\t\t\t\t\t\tstage.addChild(MHImage);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstage.update();\n\t\t\t\t\t\t\t}\n\t}\n\t\n\tcacheStage();\n\tstage.update();\n\t\n}",
"static init(options = {}, elOrString = '.grid-stack') {\r\n let el = GridStack.getGridElement(elOrString);\r\n if (!el) {\r\n if (typeof elOrString === 'string') {\r\n console.error('GridStack.initAll() no grid was found with selector \"' + elOrString + '\" - element missing or wrong selector ?' +\r\n '\\nNote: \".grid-stack\" is required for proper CSS styling and drag/drop, and is the default selector.');\r\n }\r\n else {\r\n console.error('GridStack.init() no grid element was passed.');\r\n }\r\n return null;\r\n }\r\n if (!el.gridstack) {\r\n el.gridstack = new GridStack(el, utils_1.Utils.clone(options));\r\n }\r\n return el.gridstack;\r\n }",
"function selectStash() {\n var stash = ctrl.selectedStash;\n\n if (!stash.name) {\n return;\n }\n\n // reset selected file because it takes time to select stashes.\n setSelectedFile(null);\n\n if (stash.name === 'Local Changes') {\n // show local changes.\n if (gitfunctions.selectStash.canceler) {\n gitfunctions.selectStash.canceler.resolve();\n }\n if (ctrl.localStatus) {\n ctrl.selectedStash.diffDetails = ctrl.localStatus.map(function (f) {\n return {\n // fileName: f.name,\n name: f.name,\n commitType: f.tags.indexOf('added') > -1 ? 'new' : (f.tags.indexOf('deleted') > -1 ? 'deleted' : 'modified'),\n tags: f.tags\n };\n });\n setSelectedFile(ctrl.selectedStash.diffDetails[0]);\n }\n\n return;\n }\n\n return gitfunctions.selectStash(stash).then(function (op) {\n if(!op || !op.output || !op.output.length) {\n return;\n }\n ctrl.selectedStash.diffDetails = UtilsService.parseMultipleDiffs(op.output.join(''));\n setSelectedFile(ctrl.selectedStash.diffDetails[0]);\n });\n }",
"function findVariableInScopeStack(name) {\n for (const scope of scopeList) {\n if (name && scope && name in scope) {\n return scope[name];\n }\n }\n return null;\n}",
"function loadPreviousStack() {\n var storedNavigationStack = window.localStorage.getItem('navigationStack');\n\n if(storedNavigationStack !== null)\n _navigationStack = storedNavigationStack.split(',');\n }",
"function HomeStackScreen() {\n const HomeStack = createStackNavigator();\n return (\n <HomeStack.Navigator screenOptions={{ headerShown: false }}>\n <HomeStack.Screen name=\"HomeRoot\" component={HomeBottomTabNavigator} />\n {/* <Stack.Screen name=\"NotFound\" component={NotFoundScreen} options={{ title: 'Oops!' }} /> */}\n </HomeStack.Navigator>\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function declarations test function to check memory use | function checkMemory() {
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
} | [
"function test2() {\n const v8 = require('v8');\n console.log(v8.getHeapSpaceStatistics());\n}",
"function m_private_memory_size() {\n return 4224;\t\t// This is specific to descrypt8m\n}",
"function clearMemory(){ memory = [] }",
"check() {\n if (this.refCounts.size == 1) return 0; // purerc roots\n if (this.oninfo) {\n for (let [ptr, rc] of this.refCounts) {\n this.oninfo(\"LEAKING \" + ptr + \" @ \" + rc);\n }\n }\n return this.refCounts.size;\n }",
"function checkMemory(memoryType, page, pageToSave=null){\n\tvar memoryList;\n\tvar memorySize;\n\tvar memoryName;\n\t// Getting data from the current memory type\n\tswitch (memoryType){\n\t\tcase 0: // Primary\n\t\tmemoryList = primaryMemoryList;\n\t\tmemorySize = primaryMemorySize;\n\t\tmemoryName = \"na Memória Primária\";\n\t\tbreak;\n\t\tcase 1: // Swap\n\t\tmemoryList = virtualMemoryList;\n\t\tmemorySize = virtualMemorySize;\n\t\tmemoryName = \"no Espaço de Swap\";\n\t\tbreak;\n\t\tcase 2: // Secondary\n\t\t// Stopping condition: Page is always stored inside the disk\n\t\t// No indexes are considered for it\n\t\tinstructionLog[instructionIndex].push(`Procurando por Página ${page.pageId} do Processo ${page.processId} no Disco...`);\n\t\tinstructionLog[instructionIndex].push(\"Página Encontrada!\");\n\t\tif (pageToSave != null)\n\t\tinstructionLog[instructionIndex].push(`Salvando Página ${pageToSave.pageId} do Processo ${pageToSave.processId} enviada da Memória Principal no Disco.`);\n\t\treturn {\n\t\t\tmemoryType: 2,\n\t\t\tindex: 0\n\t\t}\n\t}\n\tinstructionLog[instructionIndex].push(`Procurando por Página ${page.pageId} do Processo ${page.processId} ${memoryName}...`);\n\t// Search for the page inside the current memory list\n\tvar index = memoryList.findIndex(function(element){\n\t\treturn element.processId == page.processId && element.pageId == page.pageId;\n\t});\n\t// If it's found, return it, and save any page (sent from an upper memory that's full)\n\t// There's no need to verify if it has space to save since it can swap the requested page with the sent page (worst case)\n\tif (index != -1){\n\t\tinstructionLog[instructionIndex].push(\"Página Encontrada!\");\n\t\tif (memoryType === 0){\n\t\t\tmemoryList[index].referenced = true;\n\t\t}\n\t\tif (pageToSave != null){\n\t\t\tinstructionLog[instructionIndex].push(`Salvando Página ${pageToSave.pageId} do Processo ${pageToSave.processId} enviada da Memória Principal ${memoryName}.`);\n\t\t\tmemoryList.push(pageToSave);\n\t\t}\n\t\treturn {\n\t\t\tmemoryType: memoryType,\n\t\t\tindex: index\n\t\t}\n\t}\n\t// If it isn't found, send a request for the next memory\n\telse {\n\t\t// PAGE FAULT: page isn't located in any memory, so it will be requested from disk.\n\t\tif (memoryType == 0){\n\t\t\tinstructionLog[instructionIndex].push(\"Page Fault! Página não se encontra na Memória Primária.\");\n\t\t\t// numberPageFaults++;\n\t\t}\n\t\telse\n\t\t\tinstructionLog[instructionIndex].push(`Página não se encontra ${memoryName}.`);\n\t\tif (memoryList.length == memorySize){\n\t\t\t// PAGE SWAP: Send a page (chosen with a substitution algorithm) to the next memory so it can have space for the requested page\n\t\t\tif (memoryType == 0){\n\t\t\t\t// Current Substitution Algorithm: CLOCK\n\t\t\t\tpageToSave = clockSubstitution(memoryList);\n\t\t\t\tinstructionLog[instructionIndex].push(`Memória Primária cheia. Abrindo espaço removendo a Página ${pageToSave.pageId} do Processo ${pageToSave.processId}.`);\n\t\t\t\t// Change presence bit to false since it will be removed from primary memory\n\t\t\t\tprocessList[pageToSave.processId][pageToSave.pageId].p = false;\n\t\t\t\treturn checkMemory(++memoryType, page, pageToSave);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// If the current memory received a page to save from a upper memory and it's full as well, send it to the next memory\n\t\t\t\treturn checkMemory(++memoryType, page, pageToSave);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// If the current memory received a page to save, save it\n\t\t\tif (pageToSave != null){\n\t\t\t\tinstructionLog[instructionIndex].push(`Salvando Página ${pageToSave.pageId} do Processo ${pageToSave.processId} enviada da Memória Principal ${memoryName}.`);\n\t\t\t\tmemoryList.push(pageToSave);\n\t\t\t}\n\t\t\t// There's no need to send the saved page for the next memory since it wasn't full\n\t\t\treturn checkMemory(++memoryType, page);\n\t\t}\n\t}\n}",
"verifyMemory(loc1, loc2) {\n if (!this.memory.isValidAddress(loc1) || !this.memory.isValidAddress(loc2)) {\n this.pushError(\"Invalid memory location [line \" + this.line + \"]: 0x\" + (loc1 >>> 0).toString(16) +\n ((loc2 === undefined) ? \"\" : \" to 0x\" + (loc2 >>> 0).toString(16)));\n }\n }",
"mmap(length)\n {\n var msg = `Memory::mmap(${length})`;\n // First page is reserved for JS allocation\n if ((this.m_JS_data_segment + this.m_C_allocated_bytes + length) > this.m_C_data_segment)\n {\n //TODO: this.m_memory.grow\n return -1;\n }\n this.m_C_allocated_bytes += length;\n console.log(msg + \" => \" + this.m_JS_data_segment);\n return this.m_JS_data_segment;\n }",
"function plus(){\n\tmemory[pointer]++;\n}",
"_clearMemory() {\n for (let i = 0; i < this._memory.length; i++) {\n this._memory[i] = 0;\n }\n }",
"testAssertResultLength() {\n \n }",
"function testSlice() {\n checkSlice();\n}",
"getFailSize(onGet){\r\n assert.equal(typeof onGet,'function','onGet must be a function');\r\n this.queueMgr.countQueue(FATUS_QUEUE_FAIL_NAME,onGet);\r\n }",
"static measure(name, executedFunction) { \n\t\tvar usedTicks = Game.cpu.getUsed();\n\t\texecutedFunction();\n\t\tusedTicks = Game.cpu.getUsed() - usedTicks;\n\t\t\n this._measurements.push( { \n \tname: name,\n \tusedTicks: usedTicks,\n });\n }",
"function parseMemory() {\n var id = t.identifier(getUniqueName(\"memory\"));\n var limits = t.limit(0);\n\n if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) {\n id = t.identifier(token.value);\n eatToken();\n } else {\n id = t.withRaw(id, \"\"); // preserve anonymous\n }\n /**\n * Maybe data\n */\n\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.data)) {\n eatToken(); // (\n\n eatToken(); // data\n // TODO(sven): do something with the data collected here\n\n var stringInitializer = token.value;\n eatTokenOfType(_tokenizer.tokens.string); // Update limits accordingly\n\n limits = t.limit(stringInitializer.length);\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n /**\n * Maybe export\n */\n\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) {\n eatToken(); // (\n\n eatToken(); // export\n\n if (token.type !== _tokenizer.tokens.string) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Expected string in export\" + \", given \" + tokenToString(token));\n }();\n }\n\n var _name = token.value;\n eatToken();\n state.registredExportedElements.push({\n exportType: \"Memory\",\n name: _name,\n id: id\n });\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n /**\n * Memory signature\n */\n\n\n if (token.type === _tokenizer.tokens.number) {\n limits = t.limit((0, _numberLiterals.parse32I)(token.value));\n eatToken();\n\n if (token.type === _tokenizer.tokens.number) {\n limits.max = (0, _numberLiterals.parse32I)(token.value);\n eatToken();\n }\n }\n\n return t.memory(limits, id);\n }",
"function abiSizeAndAllocate(dataType, userDefinedTypes, existingAllocations) {\n switch (dataType.typeClass) {\n case \"bool\":\n case \"address\":\n case \"contract\":\n case \"int\":\n case \"uint\":\n case \"fixed\":\n case \"ufixed\":\n case \"enum\":\n return {\n size: evm_1.EVM.WORD_SIZE,\n dynamic: false,\n allocations: existingAllocations\n };\n case \"string\":\n return {\n size: evm_1.EVM.WORD_SIZE,\n dynamic: true,\n allocations: existingAllocations\n };\n case \"bytes\":\n return {\n size: evm_1.EVM.WORD_SIZE,\n dynamic: dataType.kind === \"dynamic\",\n allocations: existingAllocations\n };\n case \"mapping\":\n return {\n allocations: existingAllocations\n };\n case \"function\":\n switch (dataType.visibility) {\n case \"external\":\n return {\n size: evm_1.EVM.WORD_SIZE,\n dynamic: false,\n allocations: existingAllocations\n };\n case \"internal\":\n return {\n allocations: existingAllocations\n };\n }\n case \"array\": {\n switch (dataType.kind) {\n case \"dynamic\":\n return {\n size: evm_1.EVM.WORD_SIZE,\n dynamic: true,\n allocations: existingAllocations\n };\n case \"static\":\n if (dataType.length.isZero()) {\n //arrays of length 0 are static regardless of base type\n return {\n size: 0,\n dynamic: false,\n allocations: existingAllocations\n };\n }\n const { size: baseSize, dynamic, allocations } = abiSizeAndAllocate(dataType.baseType, userDefinedTypes, existingAllocations);\n return {\n //WARNING! The use of toNumber() here may throw an exception!\n //I'm judging this OK since if you have arrays that large we have bigger problems :P\n size: dataType.length.toNumber() * baseSize,\n dynamic,\n allocations\n };\n }\n }\n case \"struct\": {\n let allocations = existingAllocations;\n let allocation = allocations[dataType.id];\n if (allocation === undefined) {\n //if we don't find an allocation, we'll have to do the allocation ourselves\n const storedType = userDefinedTypes[dataType.id];\n if (!storedType) {\n throw new errors_1.UnknownUserDefinedTypeError(dataType.id, datatype_1.TypeUtils.typeString(dataType));\n }\n debug(\"storedType: %O\", storedType);\n allocations = allocateStruct(storedType, userDefinedTypes, existingAllocations);\n allocation = allocations[storedType.id];\n }\n //having found our allocation, if it's not null, we can just look up its size and dynamicity\n if (allocation !== null) {\n return {\n size: allocation.length,\n dynamic: allocation.dynamic,\n allocations\n };\n }\n //if it is null, this type doesn't go in the abi\n else {\n return {\n allocations\n };\n }\n }\n case \"tuple\": {\n //Warning! Yucky wasteful recomputation here!\n let size = 0;\n let dynamic = false;\n //note that we don't just invoke allocateStruct here!\n //why not? because it has no ID to store the result in!\n //and we can't use a fake like -1 because there might be a recursive call to it,\n //and then the results would overwrite each other\n //I mean, we could do some hashing thing or something, but I think it's easier to just\n //copy the logic in this one case (sorry)\n for (let member of dataType.memberTypes) {\n let { size: memberSize, dynamic: memberDynamic } = abiSizeAndAllocate(member.type, userDefinedTypes, existingAllocations);\n size += memberSize;\n dynamic = dynamic || memberDynamic;\n }\n return { size, dynamic, allocations: existingAllocations };\n }\n }\n}",
"function TestContextAllocation() {\n function* g1(a, b, c) { yield 1; return [a, b, c]; }\n function* g2() { yield 1; return arguments; }\n function* g3() { yield 1; return this; }\n function* g4() { var x = 10; yield 1; return x; }\n // Temporary variable context allocation\n function* g5(l) { \"use strict\"; yield 1; for (let x in l) { yield x; } }\n\n g1();\n g2();\n g3();\n g4();\n g5([\"foo\"]);\n}",
"function dataTooBig() {\n switch (qwQueryService.outputTab) {\n case 1: return(qc.lastResult.resultSize / qc.maxAceSize) > 1.1;\n //case 2: return(qc.lastResult.resultSize / qc.maxTableSize) > 1.1;\n case 3: return(qc.lastResult.resultSize / qc.maxTreeSize) > 1.1;\n }\n\n }",
"function registerMeasure(fromNet , toNet ){\n var regID = uniqueRegID(fromNet , toNet);\n if (!__registered_measures__[regID]){\n __registered_measures__[regID]={\n fromNet: fromNet,\n toNet:toNet,\n numRetries : 0\n };\n return true;\n }else{\n if (__registered_measures__[regID].numRetries < configuration.smartAutoMeasure.numRetries){\n __registered_measures__[regID].numRetries++;\n return false;\n }else{\n // The registered measure is LOST!\n showTitle(\"MEASURE LOST! \"+fromNet+\" -> \"+toNet)\n unRegisterMeasure(fromNet , toNet);\n return true; // We can add a new measure\n }\n }\n}",
"function unit_list_size(unit_list)\n{\n return unit_list.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
methodsetHTML returns HTML for the methodset of the specified TypeInfoJSON value. | function methodsetHTML(info) {
var html = "";
if (info.Methods != null) {
for (var i = 0; i < info.Methods.length; i++) {
html += "<code>" + makeAnchor(info.Methods[i]) + "</code><br/>\n";
}
}
return html;
} | [
"function setupTypeInfo() {\n for (var i in document.ANALYSIS_DATA) {\n var data = document.ANALYSIS_DATA[i];\n\n var el = document.getElementById(\"implements-\" + i);\n if (el != null) {\n // el != null => data is TypeInfoJSON.\n if (data.ImplGroups != null) {\n el.innerHTML = implementsHTML(data);\n el.parentNode.parentNode.style.display = \"block\";\n }\n }\n\n var el = document.getElementById(\"methodset-\" + i);\n if (el != null) {\n // el != null => data is TypeInfoJSON.\n if (data.Methods != null) {\n el.innerHTML = methodsetHTML(data);\n el.parentNode.parentNode.style.display = \"block\";\n }\n }\n }\n}",
"function buildHTMLForSet(setName) {\n const setElem = document.createElement('div');\n setElem.classList.add('set-item');\n setElem.dataset.setName = setName;\n\n const setNameElem = document.createElement('span');\n setNameElem.innerText = setName;\n\n const editBtn = document.createElement('i');\n editBtn.classList.add('fas', 'fa-wrench');\n editBtn.title = 'Edit';\n\n const delBtn = document.createElement('i');\n delBtn.classList.add('fas', 'fa-trash-alt');\n delBtn.title = 'Delete';\n\n const btnContainer = document.createElement('span');\n btnContainer.classList.add('buttons');\n\n btnContainer.append(editBtn, delBtn);\n setElem.append(setNameElem, btnContainer);\n return setElem;\n }",
"setHtml(element, html){\n element.html(html);\n }",
"function getTypeSelectStr(ind, selected_index, htmlId) {\r\n\r\n str = \"<select onchange='changeType(this,\" + ind + \",\\\"\" + htmlId +\r\n \"\\\")'>\";\r\n for (var i = 0; i < TypesArr.length; i++) {\r\n str += \"<option value='\" + i + \"' \";\r\n if (i == selected_index)\r\n str += \"selected\";\r\n str += \">\" + TypesArr[i] + \"</option>\";\r\n }\r\n str += \"</select>\";\r\n\r\n return str;\r\n }",
"get fieldValuesAsHTML() {\n return SPInstance(this, \"FieldValuesAsHTML\");\n }",
"onRender()\n {\n /* var templateResourceType = _.template($('#template-resourcetype_collection_item').html());\n var resourceTypeCollection = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__GLOBAL_RESOURCETYPE_COLLECTION);\n// var html = templateResourceType({url: null, mimetype: 'Auto-detect', extension: 'Rodan will attempt to determine the file type based on the file itself'});\n // this.$el.find('#select-resourcetype').append(html);\n for (var i = 0; i < resourceTypeCollection.length; i++)\n {\n \tvar resourceType = resourceTypeCollection.at(i);\n var html = templateResourceType(resourceType.attributes);\n \tthis.$el.find('#select-resourcetype').append(html);\n }*/\n }",
"function implementsHTML(info) {\n var html = \"\";\n if (info.ImplGroups != null) {\n for (var i = 0; i < info.ImplGroups.length; i++) {\n var group = info.ImplGroups[i];\n var x = \"<code>\" + escapeHTML(group.Descr) + \"</code> \";\n for (var j = 0; j < group.Facts.length; j++) {\n var fact = group.Facts[j];\n var y = \"<code>\" + makeAnchor(fact.Other) + \"</code>\";\n if (fact.ByKind != null) {\n html += escapeHTML(fact.ByKind) + \" type \" + y + \" implements \" + x;\n } else {\n html += x + \" implements \" + y;\n }\n html += \"<br/>\\n\";\n }\n }\n }\n return html;\n}",
"set fieldValue(value){\n this.element.innerHTML = value;\n }",
"renderField() {}",
"set type(aValue) {\n this._logger.debug(\"type[set]\");\n this._type = aValue;\n }",
"function setMethodToCall(methodToCall) {\n jQuery(\"<input type='hidden' name='methodToCall' value='\" + methodToCall + \"'/>\").appendTo(jQuery(\"#formComplete\"));\n}",
"function $Html(id, value){\n\n if (typeof value != 'undefined'){\n $O(id).innerHTML = value\n }\n return $O(id).innerHTML\n}",
"function changeType(sel_obj, ind, htmlId) {\r\n\r\n if (!htmlId) { // while configuring a new grid\r\n\r\n NewGridObj.dataTypes[ind] = parseInt(sel_obj.value);\r\n\r\n } else {\r\n\r\n\tvar gridId = getGridIdOfHtmlId(htmlId); // find grid id from step\r\n\tvar gO = CurFuncObj.allGrids[gridId]; // get grid obj from func\r\n\tgO.dataTypes[ind] = parseInt(sel_obj.value);\r\n }\r\n}",
"renderSetterButton() {\n const button = this._buttonRenderer(true);\n button.classList.add('set-reminder', 'pulse');\n return button;\n }",
"function infoWrap( html ) {\n\treturn T( 'infoWrap', { html:html } );\n}",
"function elfinderMarkitupSettings(settings, type) {\n settings = $.extend({}, settings);\n type = type || 'html';\n var folders = ['Images', 'Files'];\n\n function editorCallback(folder, type) {\n return function (url) {\n var filename = url.split('/').pop().replace(/\\.\\w+$/, '');\n var options\n switch (type) {\n case 'html':\n if (folder == 'Images')\n options = { replaceWith: '<img src=\"'+url+'\" alt=\"'+filename+'\" />' };\n else if (folder == 'Files')\n options = {\n openWith: '<a href=\"'+url+'\" title=\"'+filename+'\">',\n closeWith: '</a>',\n placeHolder: filename\n };\n break;\n case 'textile':\n if (folder == 'Images')\n options = { replaceWith: '!'+url+'('+filename+')!' };\n else if (folder == 'Files')\n options = {\n openWith: '\"',\n closeWith: '('+filename+')\":'+url,\n placeHolder: filename\n };\n break;\n };\n\n $.markItUp(options);\n };\n };\n\n function beforeInsert(folder, type) {\n return function(h) {\n // Initialize elfinder\n $('<div id=\"elfinder\" />').elfinder({\n url: '/admin/elfinder?folder=' + folder,\n lang: 'ru',\n dialog: { width: 700, modal: true, title: folder }, // open in dialog window\n closeOnEditorCallback: true, // close after file select\n editorCallback: editorCallback(folder, type)\n });\n }\n };\n\n for (var i = 0; i < settings.markupSet.length; i++)\n if ($.inArray(settings.markupSet[i]['name'], folders) != -1)\n settings.markupSet[i]['beforeInsert'] = beforeInsert(settings.markupSet[i]['name'], type);\n\n return settings;\n }",
"toString() {\n let normalisedContent = pureAssign(get(this, CONTENT), {});\n return `changeset:${normalisedContent.toString()}`;\n }",
"function processComplexTypeAsMarkdown(diff,showMarkdownDiffCode){\n diff.forEach(function(part){\n // Render as markdown result\n var modifier = part.added ? \"+ \" : part.removed ? \"- \" : \" \";\n part.value.split(\"\\n\").forEach(function(item,index){\n if(item){\n showMarkdownDiffCode += modifier + item + \"\\n\";\n }\n });\n });\n return showMarkdownDiffCode;\n}",
"get html() {\n return this.element.innerHTML;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert size from percent to pixels, using max as reference for 100% | function percentToPixel(size, max)
{
let percentRegexp = /^[0-9]{1,3}%$/;
let pixelRegexp = /^[0-9]*px$/;
if (pixelRegexp.exec(size))
{
return parseInt(size);
}
else if (percentRegexp.exec(size))
{
return (parseInt(size) / 100.0) * max;
}
else
return parseInt(size);
} | [
"function scalePercent(percent, min, max) {\n const scale = max - min;\n return clamp((percent - min) / scale, 0, 1);\n }",
"pixelToPercent(x)\n {\n if (!this.field || !this.field.offsetWidth)\n {\n return 0;\n }\n\n const percent = x / this.field.offsetWidth;\n\n if (this.props.steps)\n {\n const oneStep = 1 / this.props.steps;\n return Math.round(percent / oneStep) * oneStep;\n }\n\n return percent;\n }",
"function scale(value) {\r\n return Math.floor(screenHeight / baselineHeight * value);\r\n}",
"static RangeToPercent(num, min, max) {\n return (num - min) / (max - min);\n }",
"function getPercentage(str) {\n return parseFloat((str / max_cgMLST_count) * 100).toFixed(2);\n }",
"function find_dimensions()\n{\n numColsToCut= parseInt(NumberofColumns);\n numRowsToCut= parseInt(NumberofRows);\n \n widthOfOnePiece=Target_width/numColsToCut;\n heightOfOnePiece=Target_height/numRowsToCut; \n}",
"gridCellSize() {\n return (gridCellSizePercent * canvasWidth) / 100;\n }",
"function scaleToFit(x, scaleW, scaleH, type) {\n\tif (type == \"h\") {\n\t\t// x : res = scaleW : scaleH\n\t\treturn Math.round((x * scaleH) / scaleW)\n\t} else {\n\t\t// res : x = scaleW : scaleH\n\t\treturn Math.round((x * scaleW) / scaleH)\n\t}\n}",
"function _updateProjectSizeIndicator(currentSize, maxSize, percent) {\n $projectSizeIndicator.removeClass(\"project-size-warning project-size-exceeded\");\n\n percent = parseInt(percent);\n if(percent < 10) {\n $projectSizeIndicator.addClass(\"hidden\");\n return;\n }\n\n $projectSizeIndicator.removeClass(\"hidden\");\n\n if(percent > 80 && percent < 100) {\n $projectSizeIndicator.addClass(\"project-size-warning\");\n } else if(percent === 100) {\n $projectSizeIndicator.addClass(\"project-size-exceeded\");\n }\n\n $projectSizeIndicator.find(\".space-used-bar\").css(\"width\", percent + \"%\");\n $projectSizeIndicator.find(\".space-used\").text(currentSize);\n $projectSizeIndicator.find(\".max-project-size\").text(maxSize);\n }",
"percOfMaxHP(perc){\n\t inRange(0, perc, 1.0);\n\t\treturn this.getStatValue(Stat.HP) * perc;\n }",
"function calculatePercentage(percentage) {\n return (5000 / 100) * percentage;\n}",
"function scaleImage(scalePercentage){\n\n imgInContainer.style.width=scalePercentage+\"%\";\n imgInContainer.style.height= \"auto\";\n\n}",
"function toCSSPixels(number) {\r\n if (Object.isString(number) && number.endsWith('px'))\r\n return number;\r\n return number + 'px'; \r\n }",
"function calculateImageSize(value) {\r\n\r\n}",
"scaleToRange(x) {\r\n var t;\r\n t = this.minHeight + ((x - this.minTemp) * (this.maxHeight - this.minHeight)) / (this.maxTemp - this.minTemp); // Based on a formula googled from various sources.\r\n return t;\r\n }",
"function getResolution($item) {\n return Number($item.attr('width') || 0) * Number($item.attr('height') || 0);\n}",
"function f_getQuality() {\n var el = document.getElementById(\"id_resolution\");\n var wh = (el.options[el.selectedIndex].value).split(\"x\");\n l_maxWidth = wh[0];\n l_maxHeight = wh[1];\n}",
"function mm2pt(value) {\n return value * 72 / 25.4;\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces the contents of devices collection with the new device list minimizing the number of collection events fired during the update. This is achieved by adding new devices and deleting removed devices (vs. emptying the collection and filling it up from scratch). | function updateDeviceCollection(collDevices, devices) {
var keysToDelete = [];
// compare current device collection with the newly built set;
// after this array devices should contain only new devices to be
// added to the devices collection and keysToDelete
// should contain keys of the devices to be deleted from the
// device collection
collDevices.each(function (device, key) {
var isPresent = false, i;
for (i = 0; i < devices.length; i++) {
if (device.id() == devices[i].id()) {
isPresent = true;
devices.splice(i, 1);
break;
}
}
if (!isPresent)
keysToDelete.push(key);
});
// remove deleted devices
foreach(keysToDelete, function (key) {
collDevices.remove(key);
});
// add new devices
foreach(devices, function (device) {
collDevices.add(device);
});
} | [
"update() {\n for (let device of this.devices) {\n device.update();\n }\n }",
"loadDevices() {\n\t\t\t$.get('/devices', devices => {\n\n\t\t\t\tdevices.forEach(device => {\n\t\t\t\t\tif (device.id in this.entities)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Update existing\n\t\t\t\t\t\tthis.entities[device.id].device = device;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Create new object\n\t\t\t\t\t\tthis.addDevice(device);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}",
"updateResources() {\n let energyCollection = new ResourceCollection();\n this._compartments.forEach(compartment => {\n energyCollection.addFromCollection(compartment.collectResources());\n });\n this._compartments.forEach(compartment => {\n compartment.providePower(energyCollection);\n });\n let resources = new ResourceCollection();\n this._compartments.forEach(compartment => {\n resources.addFromCollection(compartment.collectResources());\n });\n resources.set(new Energy(energyCollection.energy));\n this._resources = resources;\n }",
"updateList() {\n console.log(\"$$$$$$$$ updateList\");\n this.forceUpdate();\n }",
"async modifyOtherDevices(client, data, trx) {\n await client.otherDevices().delete(trx);\n if (data && data.length) {\n await client.otherDevices().createMany(data, trx);\n }\n }",
"addProducts() {\n document.querySelector('#product-list').innerHTML = '';\n document.querySelector('#update').innerHTML = '';\n Product.all.forEach(\n product => (document.querySelector('#product-list').innerHTML += product.renderProduct())\n );\n }",
"function refreshSelect()\n{\n var select = $(\"#deviceList\");\n var old_value = select.val();\n $(\"#deviceList option\").remove();\n select.prop(\"disabled\", false);\n\n $.each( _device_list, function( key, value ) {\n if ($(\"#deviceList option[value='\" + value + \"']\").length == 0) {\n select.append($(\"<option></option>\")\n .attr(\"value\", value)\n .text(key));\n } else {\n console.log(\"Found duplicate IP addresses for devices!\");\n }\n });\n\n /* Set currently selected device to previously selected one */\n if (_current_device != undefined) {\n $(\"#deviceList\").val(_current_device.getIp());\n }\n\n /* Trigger onChange event */\n if (select.val() != old_value) {\n select.change();\n }\n}",
"_updateItems(newItems = []) {\n const oldItems = this._cuttingItems.filter((i) => !newItems.includes(i))\n this._items = newItems\n\n this._eventEmitter.emit(\n 'textae-event.clip-board.change',\n this._cuttingItems,\n oldItems\n )\n }",
"replaceContextFileList() {\n if (this.context_.fileList !== this.fileList_) {\n // TODO(yawano): While we should update the list with adding or deleting\n // what actually added and deleted instead of deleting and adding all\n // items, splice of array data model is expensive since it always runs\n // sort and we replace the list in this way to reduce the number of splice\n // calls.\n const spliceArgs = this.fileList_.slice();\n const fileList = this.context_.fileList;\n spliceArgs.unshift(0, fileList.length);\n fileList.splice.apply(fileList, spliceArgs);\n this.fileList_ = fileList;\n\n // Check updated files and dispatch change events.\n if (this.metadataSnapshot_) {\n const updatedIndexes = [];\n const entries = /** @type {!Array<!Entry>} */ (this.fileList_.slice());\n const newMetadatas =\n this.context_.metadataModel.getCache(entries, ['modificationTime']);\n\n for (let i = 0; i < entries.length; i++) {\n const url = entries[i].toURL();\n const newMetadata = newMetadatas[i];\n // If the Files app fails to obtain both old and new modificationTime,\n // regard the entry as not updated.\n if ((this.metadataSnapshot_[url] &&\n this.metadataSnapshot_[url].modificationTime &&\n this.metadataSnapshot_[url].modificationTime.getTime()) !==\n (newMetadata.modificationTime &&\n newMetadata.modificationTime.getTime())) {\n updatedIndexes.push(i);\n }\n }\n\n if (updatedIndexes.length > 0) {\n this.fileList_.updateIndexes(updatedIndexes);\n }\n }\n }\n }",
"function addDevice(data) {\n try {\n if (data.id === \"SenseMonitor\" || data.id === 'solar') { //The monitor device itself is treated differently\n deviceList[data.id] = data;\n } else {\n\n //Ignore devices that are hidden on the Sense app (usually merged devices)\n if (data.tags.DeviceListAllowed == \"false\"){\n return 0\n }\n\n tsLogger(\"Adding New Device: (\" + data.name + \") to DevicesList...\");\n let isGuess = (data.tags && data.tags.NameUserGuess && data.tags.NameUserGuess === 'true');\n let devData = {\n id: data.id,\n name: (isGuess ? data.name.trim() + ' (?)' : data.name.trim()),\n state: \"unknown\",\n usage: -1,\n currentlyOn: false,\n recentlyChanged: true,\n lastOn: new Date().getTime()\n };\n\n if (data.id !== \"SenseMonitor\") {\n devData.location = data.location || \"\";\n devData.make = data.make || \"\";\n devData.model = data.model || \"\";\n devData.icon = data.icon || \"\";\n if (data.tags) {\n devData.mature = (data.tags.Mature === \"true\") || false;\n devData.revoked = (data.tags.Revoked === \"true\") || false;\n devData.dateCreated = data.tags.DateCreated || \"\";\n }\n }\n deviceList[data.id] = devData;\n deviceIdList.push(data.id);\n }\n } catch (error) {\n tsLogger(error.stack);\n }\n\n}",
"function resetLists(){\n\t\tlog(\"resetLists()\",\"info\");\n\t\timages_listForInsert \t= Array();\n\t\tcompass_listForInsert\t= Array();\n\t}",
"beginUpdate(batchSize, reset) {\n // pause observers so users don't see flicker when updating several\n // objects at once (including the post-reconnect reset-and-reapply\n // stage), and so that a re-sorting of a query can take advantage of the\n // full _diffQuery moved calculation instead of applying change one at a\n // time.\n if (batchSize > 1 || reset) self._collection.pauseObservers();\n if (reset) self._collection.remove({});\n }",
"function refreshProductList() {\n loadProducts()\n .then(function (results) {\n vm.products = results;\n });\n }",
"_updatePeers() {\n var peers = this.peers;\n peers.clear();\n mergeMaps(peers, this.ocluster, this.ncluster);\n this.configAry = Array.from(peers);\n peers.delete(this.peerId);\n }",
"function updateDailyUsage(){\n if (dailyUsageData.consumption.devices){\n for (let usageDevice of dailyUsageData.consumption.devices){\n updateDeviceDailyUsage({id: usageDevice.id, dailyUsage: (usageDevice.pct/100) * dailyUsageData.consumption.total});\n }\n }\n if (dailyUsageData.production.devices){\n for (let usageDevice of dailyUsageData.production.devices){\n updateDeviceDailyUsage({id: usageDevice.id, dailyUsage: (usageDevice.pct/100) * dailyUsageData.production.total});\n }\n }\n}",
"stopTrackingAllDeviceLists() {\n for (const userId of Object.keys(this._deviceTrackingStatus)) {\n this._deviceTrackingStatus[userId] = TRACKING_STATUS_NOT_TRACKED;\n }\n this._dirty = true;\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 }",
"updateCustomerList() {\r\n this.customers = this.calculateCustomerInfo(this.orders);\r\n }",
"function updateListSensors() {\n\n // clean DOM\n var $mylistSensors = $(\"#list-captors\").empty();\n\n // if no filters are checked\n if( filters.length == 0 ){\n $.each( listSensors ,function(i) {\n\n // add sensor to DOM\n $mylistSensors.append(\n '<div class=\"draggableSensor\" id=\"' + listSensors[i].name + '\" style=\"cursor: -webkit-grab; cursor:-moz-grab;\">'\n + '<img class=\"sensorIcon\" src=\"/assets/images/sensorIcons/' + listSensors[i].kind + '.png\">'\n + listSensors[i].displayName\n + '</img> </div>'\n );\n\n });\n\n // if filters are checked\n }else{\n $.each( listSensors , function(i) {\n\n // if sensor category is in filters array\n if ( $.inArray(listSensors[i].category,filters) !== -1 ) {\n\n // add sensor to DOM\n $mylistSensors.append(\n '<div class=\"draggableSensor\" id=\"' + listSensors[i].name + '\" style=\"cursor: -webkit-grab; cursor:-moz-grab;\">'\n + '<img class=\"sensorIcon\" src=\"/assets/images/sensorIcons/' + listSensors[i].kind + '.png\">'\n + listSensors[i].displayName\n + '</img> </div>'\n );\n\n }\n });\n }\n\n // add sensors draggable\n $(\".draggableSensor\").draggable({\n helper: function (event) {\n return $(\"<div style='cursor:-webkit-grabbing; cursor:-moz-grabbing;' id='\" + event.currentTarget.id + \"'>\" + event.currentTarget.innerHTML + \"</div>\");\n },\n revert: \"invalid\",\n cursorAt: { bottom: 10, left: 60 }\n });\n\n // filter by value in the search input\n $( '#search' ).keyup();\n}",
"function update(routers, metrics) {\n // first, check for new clients and add them\n var addedClients = [];\n\n _.each(metrics, function(metric, key) {\n var match = key.match(clientRE);\n if (match) {\n var name = match[1], id = match[2],\n router = routers[name];\n if (router && !router.dstIds[id]) {\n var addedClient = mkDst(name, id);\n addedClients.push(addedClient)\n router.dstIds[id] = addedClient;\n }\n }\n });\n\n if (addedClients.length)\n $(\"body\").trigger(\"addedClients\", [addedClients]);\n\n\n // TODO: Remove any unused clients. This will require more intelligent\n // color assignment to ensure client => color mapping is deterministic.\n\n // then, attach metrics to each appropriate scope\n\n _.each(metrics, function(metric, key){\n var scope = findByMetricKey(routers, key);\n if (scope) {\n var descoped = key.slice(scope.prefix.length);\n scope.metrics[descoped] = metric;\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes an HTML string, converts to HTML using a DOM parser and recursivly parses the content into pdfmake compatible doc definition | convertHtml(htmlText, lnMode) {
const docDef = [];
this.lineNumberingMode = lnMode || LineNumberingMode.None;
// Cleanup of dirty html would happen here
// Create a HTML DOM tree out of html string
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(htmlText, 'text/html');
// Since the spread operator did not work for HTMLCollection, use Array.from
const htmlArray = Array.from(parsedHtml.body.childNodes);
// Parse the children of the current HTML element
for (const child of htmlArray) {
const parsedElement = this.parseElement(child);
docDef.push(parsedElement);
}
return docDef;
} | [
"function buildDom(htmlString) {\r\n const div = document.createElement(\"div\");\r\n div.innerHTML = htmlString;\r\n return div.children[0];\r\n}",
"function Markdown(text){var parser;return\"undefined\"==typeof arguments.callee.parser?(parser=eval(\"new \"+MARKDOWN_PARSER_CLASS+\"()\"),parser.init(),arguments.callee.parser=parser):parser=arguments.callee.parser,parser.transform(text)}",
"function parse(html, shouldSort) {\n var $ = cheerio.load(html);\n\n return $('page').map((idx, pageElem) => {\n var $page = $(pageElem);\n\n return new Page(\n $page.attr('width'), $page.attr('height'),\n $page.children('word').map((idx, wordElem) => {\n var $word = $(wordElem);\n\n return new Text(\n $word.attr('xmin'), $word.attr('xmax'),\n $word.attr('ymin'), $word.attr('ymax'), $word.text().trim()\n );\n }).get()\n );\n }).get();\n}",
"async cleanUpDocString() {\n const removeStreams = /stream(.*?)endstream/gs\n const removeComments = /%(.[^(PDF)][^%EOF]*?)\\n/g\n const removeMultiSpace = /[^\\S\\n\\r]{2,}/g\n const addNewLine = /(%%EOF)/gms\n\n return this.docString = this.docString\n .replace(addNewLine, '%%EOF\\n')\n .replace(removeStreams, '\\nstream\\nendstream\\n')\n .replace(removeMultiSpace, ' ')\n .replace(removeComments, '\\n')\n }",
"function htmlToPDF(args, cb) {\n\tvar pdfFilePath = args.pdfFilePath;\n\tvar rawHTML = args.rawHTML;\n\tvar timeout = _.isNumber(args.timeout) ? args.timeout : DEFAULT_TIMEOUT;\n\tcb = _.once(cb); // ensure the callback is only called once\n\n\tjsreport.render({\n\t\ttemplate: {\n\t\t\tcontent: rawHTML,\n\t\t\tengine: 'handlebars',\n\t\t\trecipe: 'phantom-pdf',\n\t\t\t'phantom': {\n\t\t\t\tformat: 'A4',\n\t\t\t\tmargin: '0px',\n\t\t\t\tprintDelay: timeout\n\t\t\t}\n\t\t}\n\t})\n\t.then(out => {\n\t\tif (!pdfFilePath) {\n\t\t\t// if no file path to save the pdf was given, return the raw stream for the pdf\n\t\t\treturn cb(null, out.result);\n\t\t}\n\n\t\tvar stream = out.result.pipe(fs.createWriteStream(pdfFilePath));\n\n\t\tstream.on('finish', () => cb(null, pdfFilePath));\n\t\tstream.on('error', err => cb(err));\n\t})\n\t.catch(err => {\n\t\tcb(err);\n\t});\n}",
"function wikiparse( contents )\n{\n //global config;\n //patterns = [];\n //replacements = [];\n patterns = [];\n replacements = [];\n //contents = htmlspecialchars(contents, ENT_COMPAT, \"UTF-8\");\n contents = htmlspecialchars(contents.addSlashes());\n // webpage links\n patterns[0] = \"/\\\\[\\\\[([^\\\\[]*)\\\\]\\\\]/\";\n replacements[0] = \"\\\"+webpagelink( \\\"$1\\\" )+\\\"\"; \n\n // images\n patterns[1] = \"/{{([^{]*)}}/\";\n replacements[1] = \"\\\"+image( \\\"$1\\\" )+\\\"\"; \n\n // coloured text\n patterns[2] = \"/~~#([^~]*)~~/\";\n replacements[2] = \"\\\"+colouredtext( \\\"$1\\\" )+\\\"\"; \n \n patterns[3] = '/\\\\$/';\n replacements[3] = \"&DOLLAR;\";\n \n // verbatim text\n patterns[4] = \"/~~~(.*)~~~/\";\n replacements[4] = \"\\\"+verbatim( \\\"$1\\\" )+\\\"\";\n\n if ( config.SYNTAX.HTMLCODE )\n {\n patterns[5] = \"/%%(.*)%%/\";\n replacements[5] = \"\\\"+htmltag( \\\"$1\\\" )+\\\"\"; \n }\n\n // substitute complex expressions\n contents = wikiEval( contents.preg_replace( patterns, replacements ) );\n //contents = contents.preg_replace( patterns, replacements );\n //contents = wikiEval( contents );\n patterns = [];//[];\n replacements = [];//array();\n\n // h1\n patterns[0] = \"/==([^=]*[^=]*)==/\";\n replacements[0] = \"<h1>$1</h1>\";\n\n // italic\n patterns[1] = \"/''([^']*[^']*)''/\";\n replacements[1] = \"<i>$1</i>\";\n\n // bold\n patterns[2] = \"/\\\\*\\\\*([^\\\\*]*[^\\\\*]*)\\\\*\\\\*/\";\n replacements[2] = \"<b>$1</b>\";\n\n // underline\n patterns[3] = \"/__([^_]*[^_]*)__/\";\n replacements[3] = \"<span style=\\\\\\\"text-decoration: underline;\\\\\\\">$1</span>\"; \n\n // html shortcuts\n patterns[4] = \"/@@([^@]*)@@/\";\n replacements[4] = \"<a name=\\\\\\\"$1\\\\\\\"></a>\";\n \n // wiki words \n if ( config.SYNTAX.WIKIWORDS )\n {\n patterns[5] = \"/([A-Z][a-z0-9]+[A-Z][A-Za-z0-9]+)/\";\n replacements[5] = \"\\\"+wikilink( \\\"$1\\\" )+\\\"\"; \n }\n\n // substitute simple expressions & final expansion\n contents = wikiEval( contents.preg_replace( patterns, replacements ) );\n //contents = contents.preg_replace( patterns, replacements );\n patterns = [];//array();\n replacements = [];//array();\n\n // replace some whitespace bits & bobs \n patterns[0] = \"/\\t/\";\n replacements[0] = \" \";\n patterns[1] = \"/ /\";\n replacements[1] = \" \";\n patterns[2] = \"/&DOLLAR;/\";\n replacements[2] = \"$\";\n patterns[3] = \"/\\n/\";\n replacements[3] = \"<br>\\n\";\n contents = contents.preg_replace( patterns, replacements );\n return contents;\n}",
"function transform (input, output) {\n\n switch (input.nodeType) {\n case 3: // Text\n var text = input.wholeText.trim();\n if(text) {\n // Split text elements, making it possible to calculate\n // line numbers and page breaks with more precision.\n text.split(' ').forEach(function (txt, i) {\n if (i) txt = ' ' + txt;\n var el = document.createElement('span');\n el.className = 'fragment';\n el.appendChild(document.createTextNode(txt));\n output.appendChild(el);\n });\n }\n break;\n\n case 9: // Document\n case 1: // Element\n var el = document.createElement('div');\n output.appendChild(el);\n el.className = input.nodeName;\n if (input.hasAttributes && input.hasAttributes())\n for (var i = 0; i < input.attributes.length; i++) {\n var name = input.attributes[i].name.replace('ndiff:', '');\n el.dataset[name] = input.attributes[i].value;\n }\n\n var children = input.childNodes;\n for (var i = 0; i < children.length; i++)\n transform(children[i], el);\n break;\n\n default:\n console.log('Unknown node type:', input.nodeType);\n }\n}",
"cleanupHTML(html) {\n const parser = new DOMParser();\n const document = parser.parseFromString(html, \"text/html\");\n const rootNode = document.body;\n const preprocessedNode = this.preprocessNodes(rootNode);\n const cleanedHtml = DomPurify.sanitize(preprocessedNode.innerHTML, {ALLOWED_TAGS: this.safeTags, ALLOWED_ATTR: this.safeAttributes, ADD_URI_SAFE_ATTR: this.uriSafeAttr});\n return cleanedHtml;\n }",
"createDocument(html, documentId) {\n documentId = documentId || uuid()\n let documentPath = path.join(this.userLibraryDir, documentId)\n let storageArchivePath = path.join(documentPath, 'storage')\n let buffer = new FileSystemBuffer(documentPath)\n let mainFileName = 'index.html'\n let storer = new FileSystemStorer(storageArchivePath, mainFileName)\n let converter = this._getConverter(mainFileName)\n\n return storer.writeFile('index.html', 'text/html', html).then(() => {\n return converter.importDocument(\n storer,\n buffer\n ).then((manifest) => {\n return this._setLibraryRecord(documentId, manifest)\n }).then(() => {\n return documentId\n })\n })\n }",
"parse(text,context){\n\t\tconst title=context.title||\"\",s1=new Section(1,[new Text(title)]),\n\t\t\tarticle=new Article(title,[s1]),tl=text.length;\n\t\t\n\t\tcontext=context||{};\n\t\tcontext.self_close=context.self_close||(()=>false);\n\t\t\n\t\tthis.pos=0;\n\t\tthis.cur=article.subsections[0];\n\t\tthis.path=[];\n\t\t\n\t\twhile(this.pos<tl){\n\t\t\tlet x;\n\t\t\twhile(\n\t\t\t\t!(x=this.parse_start(text,context)) ||\n\t\t\t\tthis.parse_header(text)\n\t\t\t){\n\t\t\t\tthis.cur.paragraphs.push(x);\n\t\t\t}\n\t\t\t\n\t\t\tx=this.parse_rest(text,context);\n\t\t\tif(x){\n\t\t\t\tthis.cur.paragraphs.push(new Paragraph(x));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn article;\n\t}",
"_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }",
"convertDocCommentToParagraph() {\n let result = this.props.text;\n // Strip \"<summary>\", \"</summary>\"\n result = result.replace(/<summary>/g, '');\n result = result.replace(/<\\/summary>/g, '');\n // Strip \"<para>\", \"</para>\"\n result = result.replace(/<para>/g, '');\n result = result.replace(/<\\/para>/g, '');\n // Strip \"///\"\n result = result.replace(/\\/\\/\\//g, '');\n // Strip extra consecutive spaces\n result = result.replace(/[ \\t]+/g, ' ');\n // Delete whitespace from blank lines\n result = result.replace(/\\n\\s+\\n/g, '\\n\\n');\n // Delete single newlines (leaving multi-newline paragraph breaks).\n // (Credit: Tim Pietzcker - http://stackoverflow.com/a/18012521/12484 )\n result = result.replace(/(^|[^\\n])\\n(?!\\n)/g, \"$1\");\n // Clean up remaining leading whitespace on each line\n result = result.replace(/\\n[ \\t]+/g, '\\n');\n result = result.trim();\n this.props.setText(result);\n }",
"function emphasizeRegExpInDOM(re,elt,lvl){\nlvl=lvl?lvl+1:1;\nvar S=null;\ntry{\n if(!elt)return;\n var i;\n try{\n if(elt.nodeType==1)\n for(i=0; i< elt.childNodes.length;i++){emphasizeRegExpInDOM(re,elt.childNodes[i],lvl);};\n }catch(ex1){alert(\"ex1:\"+ex1+\"; i=\"+i+\": ecN[i]=\"+elt.childNodes[i]);}\n if(!elt.nodeValue)return;\n if(!re.test(elt.nodeValue))return;\n var container=wrapNode(elt,\"span\",\"emph\",null,document,true);\n S=elt.nodeValue.replace(re,\"<em><b>$1</b></em>\");\n container.innerHTML=S;\n}catch(x){alert(\"G:\"+lvl+\": x=\"+x+\"; S=\"+S+\"; elt=\"+doc2String(elt));}\n}",
"async function createPdf(htmlContent, options = { path: 'Output.pdf', format: 'A4' }) {\n\t// launchs a puppeteer browser instance and opens a new page\n\tconst browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], headless: true });\n\tconst context = await browser.createIncognitoBrowserContext();\n\tconst page = await context.newPage();\n\n\t// wait until everything is loaded before rendering the PDF\n\tawait page.goto(`data: text/html, ${htmlContent}`, { waitUntil: 'networkidle0' });\n\n\t// sets the html of the page to htmlContent argument\n\tawait page.setContent(htmlContent);\n\n\t// Prints the html page to pdf document and saves it to given outputPath\n\tawait page.emulateMediaType('screen');\n\tconst file = await page.pdf({ ...options, printBackground: true });\n\n\t// Closing the puppeteer browser instance\n\tawait browser.close();\n\n\treturn file;\n}",
"function extractIssues(html, repoName, topicName) {\n let selTool = cheerio.load(html);\n let IssuesAnchAr = \n selTool(\"a.Link--primary.v-align-middle.no-underline.h4.js-navigation-open.markdown-title\");\n let arr = [];\n for (let i = 0; i < IssuesAnchAr.length; i++) {\n let name = selTool(IssuesAnchAr[i]).text();\n let link = selTool(IssuesAnchAr[i]).attr(\"href\");\n arr.push({\n \"Name\": name,\n \"Link\": \"https://github.com\" + link\n })\n }\n //console.log(arr);\n //path of pdf file\n let filePath = path.join(__dirname, topicName, repoName + \".pdf\");\n\n //instance for pdf file functions\n let pdfDoc = new PDFDocument;\n\n //save the file\n pdfDoc.pipe(fs.createWriteStream(filePath));\n\n //add contents to the file\n pdfDoc.text(JSON.stringify(arr));\n\n //end the stream\n pdfDoc.end();\n // fs.writeFileSync(filePath, JSON.stringify(arr));\n // file write \n console.table(arr);\n}",
"getPandocAst() {\n return tokens && markdownItPandocRenderer(tokens, this.converter.options);\n }",
"function fixXML( text, parsetext ) {\n\tvar bug1a = text.indexOf( '<head>' );\n\tvar bug1b = text.indexOf( '<!-- start content -->' );\n\tif( bug1a != -1 || bug1b != -1 ) {\n\t\tvar text = text.substring( 0, bug1a ) + '<body><div id=\"bodyContent\">' + text.substring( bug1b );\n\t}\n\n\tvar bug2 = text.indexOf( '<!-- end content -->' );\n\tif( bug2 != -1 ) {\n\t\tvar text = text.substring( 0, bug2 ) + '</div></body></html>';\n\t} else {\n\t\treturn null;\n\t}\n\n\tif( parsetext == false ) {\n\t\treturn text;\n\t}\n\n\ttry {\n\t\tvar fixedXML = new ActiveXObject(\"Microsoft.XMLDOM\");\n\t\tfixedXML.async = 'false';\n\t\tfixedXML.loadXML( text );\n\t\treturn fixedXML;\n\t} catch( e ) {\n\t\ttry {\n\t\t\tvar parser = new DOMParser();\n\t\t\tvar fixedXML = parser.parseFromString( text, \"text/xml\" );\n\t\t\treturn fixedXML;\n\t\t} catch( e ) {\n\t\t\treturn false;\n\t\t}\n\t}\n}",
"function exportHTML(html){\r\n var header = \"<html xmlns:o='urn:schemas-microsoft-com:office:office' \"+\r\n \"xmlns:w='urn:schemas-microsoft-com:office:word' \"+\r\n \"xmlns='http://www.w3.org/TR/REC-html40'>\"+\r\n \"<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>\";\r\n var footer = \"</body></html>\";\r\n var sourceHTML = header+html+footer;\r\n \r\n var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);\r\n var fileDownload = document.createElement(\"a\");\r\n document.body.appendChild(fileDownload);\r\n fileDownload.href = source;\r\n fileDownload.download = 'myResume.doc';\r\n fileDownload.click();\r\n document.body.removeChild(fileDownload);\r\n}",
"function parseText( string, parsedText ) {\n var matches;\n parsedText = parsedText || [];\n\n if ( !string ) {\n return parsedText;\n }\n\n matches = descriptionRegex.exec( string );\n if ( matches ) {\n // Check if the first grouping needs more processing,\n // and if so, only keep the second (markup) and third (plaintext) groupings\n if ( matches[ 1 ].match( descriptionRegex ) ) {\n parsedText.unshift( matches[ 2 ], matches[ 3 ] );\n } else {\n parsedText.unshift( matches[ 1 ], matches[ 2 ], matches[ 3 ] );\n }\n\n return parseText( matches[ 1 ], parsedText );\n } else if ( !parsedText.length ) {\n // No links found\n parsedText.push( string );\n }\n\n return parsedText;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes word from display | function removeWord () {
firstWord.remove();
} | [
"function hideLetters() {\n\t\t\thide = '';\n\t\t\tfor(i = 0; i < word.length; i++) {\n\t\t\t\thide += \"-\";\n\t\t\t}\n\t\t\tconsole.log(hide);\n\t\t\tvar targetA = document.getElementById(\"word\");\n\t\t\ttargetA.innerHTML = hide;\n\t\t}",
"function unfocusWord() {\n $('.word').removeClass('word-active');\n\n if (typeof currentPopper.destroy === 'function') {\n currentPopper.destroy();\n }\n\n $('.tools').hide();\n }",
"function wordGuessClear() {\n targetWordGuessArea.textContent = \"\";\n censoredWord = [];\n}",
"function HideWord(orig) {\n hidden = \"\";\n for (let i = 0; i < orig.length; i++)\n {\n hidden += \"*\";\n }\n\n return [orig, hidden];\n}",
"function _hideHello() {\n Main.uiGroup.remove_actor(text);\n text = null;\n}",
"function removeCurrMoves(word) {\n var state = new GameState(myTurn, board, []);\n for (var i = 0; i < currMovesList.length; i++) {\n if (word.indexOf(state.convertToWord(currMovesList[i])) != -1) {\n currMovesList.splice(i, 1); // remove this word\n }\n }\n }",
"function del(e) {\n current = display.innerHTML;\n if (calcReset) {\n current = '';\n calcReset = false;\n } else {\n current = current.slice(0, -1);\n }\n display.textContent = current;\n }",
"function invalidWord() {\n // *** crosses off word \n GameDatabase.players[GameDatabase.currentPlayer].removeScore(); // *** update changes score \n}",
"function removeWord(data) {\n\tif (player != \"\" && room != -1) {\n\t\tvar geturl = \"/sanaruudukko/rest/sr/process?func=removeword&player=\" + player + \"&passcode=\" + passcode + \"&word=\" + data;\n\t\t$.ajax({\n\t\t\tcache: false,\n\t\t\tdataType : 'xml',\n\t\t\ttype : 'GET',\n\t\t\turl : geturl,\n\t\t\tsuccess : function(data) {\n\t\t\t\tupdatewords(data);\n\t\t\t}\n\t\t});\n\t}\n}",
"function removeNbsp () {\n\t\tif (screenDown.innerHTML == \" \") screenDown.innerHTML = \"\";\n\t}",
"function playAgain(){\n\n console.log(currentWord.split(\"\").join(\" \")); // Displays the solved word\n\n wordBank.splice(wordBank.indexOf(currentWord),1); // Removes the current word from the wordBank array\n\n if(wordBank.length > 0) // If there are still words left...\n letsPlay();\n else\n console.log(\"That's all the words! You won!!\");\n\n}",
"function removewords(text, words){\n if(isUndefined(words)){words = wordstoignore;}\n text = text.toLowerCase().split(\" \");\n for(var i=text.length-1; i>-1; i--){\n if(words.indexOf(text[i]) > -1){\n removeindex(text, i);\n }\n }\n text = removemultiples(text.join(\" \"), \" \", \" \");\n return text;\n}",
"function replaceWord(id, newWord)\r\n{\r\n\tdocument.getElementById(id).innerHTML = trim(newWord);\r\n\tif(spellingSuggestionsDiv)\r\n\t{\r\n\t\tspellingSuggestionsDiv.parentNode.removeChild(spellingSuggestionsDiv);\r\n\t\tspellingSuggestionsDiv = null;\r\n\t}\r\n\tdocument.getElementById(id).className = \"corrected_word\";\r\n}",
"function removeServiceProviderFromLabel(label) {\n\tvar position = label.lastIndexOf(\" \");\n\tvar text = label.substring(position);\n\treturn text;\n}",
"function updateUsedWords(){\n \t$('.js-used-words').html(\"\");\n\n $.each(usedLetters, function(i, val){\n\t\t\t$('.js-used-words').append(val + \" \");\n \t});\n }",
"function removeThis() {\n var spaced = addSpace(document.getElementById(\"removeMe\").value);\n var Sanitize2 = spaced;\n var upperCase = Sanitize2.toUpperCase();\n var re = /^[A-Z]{4}\\s{1}[A-Z0-9]+/;\n if (re.test(upperCase) == 0) {\n alert(\"Not a Valid Input. Please follow this format: COEN 10\");\n document.getElementById(\"removeMe\").innerHTML = \"\";\n return;\n }\n\n var y = upperCase;\n var d = courses.indexOf(y);\n if (courses.indexOf(y) >= 0) {\n courses.splice(d, 1);\n populate();\n reset();\n populate();\n } else {\n alert(\"Cannot Remove\");\n }\n}",
"function revealLetter() {\n\t\t\tuserGuessIndex = word.indexOf(userGuess);\n\t\t\tfor (i=0; i < word.length; i++) {\n\t\t\t\tif (word[i] === userGuess) {\n\t\t\t\t\thide = hide.split(\"\");\n\t\t\t\t\thide[i] = userGuess;\n\t\t\t\t\thide = hide.join(\"\");\n\t\t\t\t\ttargetA.innerHTML = hide;\n\n\t\t\t\t}\n\t\t\t}\t\n\t\t}",
"function cleanText(screenplay) {\n // First cycle to remove all blanks\n let _s;\n screenplay.forEach((s, index, array) => {\n _s = s.replace(/\\s\\s+|\\r\\n/g, \"\");\n array[index] = trim(_s);\n array.splice(index, s);\n });\n\n // Second cycle to remove all the empty elements from the array\n // It can be optimized but I couldn't quite manage how to do that\n // (Two forEach are a bit overkill)\n screenplay.forEach((s, index, array) => {\n if (s === \"\") {\n console.log(\"Linea Vuota\");\n array.splice(index, 1);\n }\n });\n}",
"function erase() {\n\tif (eachLetter >= 0) {\n var str=openTo[adding].toString().substring(0, eachLetter);\n document.getElementById(\"demo\").innerHTML = str;\n eachLetter--;\n setTimeout(erase, speed-25);\n } else {\n adding++;\n if(adding>=openTo.length) \n adding=0;\n setTimeout(typingTexts, speed);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that applies styling to the uv index to call attention to the different levels | function uvStyles(uvIndex){
if(uvIndex > 0 && (uvIndex < 3)) {
cityUv.className = "low";
}
if(uvIndex > 3 && (uvIndex < 6)){
cityUv.className = "medium";
}
if(uvIndex > 6 && (uvIndex < 8)){
cityUv.className = "high";
}
if(uvIndex > 8 && (uvIndex < 11)){
cityUv.className = "very-high";
}
if(uvIndex > 11 && (uvIndex < 3)){
cityUv.className = "extreme";
}
} | [
"function uvIndexBackground(uviNum) {\n let uvi = $(\"#uvi\");\n console.log(\"uvi\", uviNum);\n // let uvIndP = $(\"#uvIndexPara\");\n if (uviNum >= 0 && uviNum < 3) {\n uvi.css(\"background\", \"greenyellow\");\n } else if (uviNum >= 3 && uviNum <= 5) {\n uvi.css(\"background\", \"yellow\");\n } else if (uviNum > 5 && uviNum <= 7) {\n uvi.css(\"background\", \"darkorange\");\n } else if (uviNum > 7 && uviNum <= 10) {\n uvi.css(\"background\", \"orangered\");\n } else if (uviNum > 10) {\n uvi.css(\"background\", \"darkorchid\");\n }\n }",
"function showLevels() {\n nodes.forEach(node => {\n node.color = Colorlvl[node.lvl - 1];\n });\n recharge();\n}",
"function updateRenderingOrdinals(controlArray) {\n if (!controlArray) {\n return;\n }\n\n for (var i = 0; i < controlArray.length; i++) {\n setRenderingOrdinal(controlArray[i], i);\n }\n }",
"function setIndex(val) {\n index = val;\n for (let i = 0; i < num_bars; i++) {\n byId('myProgress_' + i).classList.remove(\"mystyle\");\n }\n byId('myProgress_' + index).classList.add(\"mystyle\");\n}",
"setTextureVScale(v) {\n //TODO\n }",
"visitIndex_attributes(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function createLevelbugCSS() {\n var levelStyle = document.createElement('style');\n\n for (var i = UserStorage.REAL_MAX_LVL; i <= UserStorage.FAKE_MAX_LVL; i++)\n levelStyle.innerHTML += '.level_' + i + '{background-position: 100% ' + ( - 1555 - 20 * (i - UserStorage.REAL_MAX_LVL)) + 'px;}';\n\n document.head.appendChild(levelStyle);\n}",
"function calculateNumColors(level) {\n return level * 3;\n}",
"function UVindexing(event){\n if (event < 3){\n $(\".cityUV\").addClass(\"btn btn-success cityUVstyle\");\n } else if (event < 6){\n $(\".cityUV\").addClass(\"btn btn-warning cityUVstyle\");\n } else if (event < 8){\n $(\".cityUV\").addClass(\"btn btn-warning orange cityUVstyle\");\n } else if (event < 11){\n $(\".cityUV\").addClass(\"btn btn-danger cityUVstyle\");\n } else if (event > 11){\n $(\".cityUV\").addClass(\"btn btn-danger purple cityUVstyle\");\n }}",
"function setLevelAttributes(level){\n\tif(level >= 8){\n\t\twaitTime = 500;\n\t\tfallingTime = 95;\n\t}\n\telse{\n\t\twaitTime = 1000 - ((level - 1) * 70);\n\t\tfallingTime = 200 - ((level - 1) * 15);\n\t}\n\tif(level >= 9){\n\t\tgetNewWords(10);\n\t}\n\telse{\n\t\tgetNewWords(level + 1);\n\t}\n\tfor(var x = 0; x < wordsArray.length; x++){\n\t\twordsArray[x] = wordsArray[x].toUpperCase();\n\t}\n\tfor(var i = 0; i < wordsArray.length; i++){\n\t\twordExistsInArray[i] = true;\n\t\tlistCountersArray[i] = 1;\n\t}\n\tsetLetterPicker();\n\tinitializeGame();\n\tinitializeList();\n\tcalculatePossible();\n\tdropAblock();\n}",
"function renderStats() {\n let stimulant = 0;\n let sedative = 0;\n let hallucinogic = 0;\n let delirant = 0;\n let dissociative = 0;\n let depressant = 0;\n for(substance in selectedSubstances) {\n let substanceAmount = selectedSubstances[substance];\n let substanceConfig = SUBSTANCES[substance];\n power = limitRange(Math.floor(substanceAmount / 2), 1, 5);\n if(substanceConfig.stats.stimulant) {\n stimulant += power;\n }\n if(substanceConfig.stats.sedative) {\n sedative += power;\n }\n if(substanceConfig.stats.hallucinogic) {\n hallucinogic += power;\n }\n if(substanceConfig.stats.delirant) {\n delirant += power;\n }\n if(substanceConfig.stats.dissociative) {\n dissociative += power;\n }\n if(substanceConfig.stats.depressant) {\n depressant += power;\n }\n }\n if(stimulant > 5) stimulant = 5;\n if(sedative > 5) sedative = 5;\n if(hallucinogic > 5) hallucinogic = 5;\n if(delirant > 5) delirant = 5;\n if(dissociative > 5) dissociative = 5;\n if(depressant > 5) depressant = 5;\n\n stimulantData = STATS_LEVELS[stimulant];\n sedativeData = STATS_LEVELS[sedative];\n hallucinogicData = STATS_LEVELS[hallucinogic];\n delirantData = STATS_LEVELS[delirant];\n dissociativeData = STATS_LEVELS[dissociative];\n depressantData = STATS_LEVELS[depressant];\n renderStat('stimulant', stimulantData.value, stimulantData.name, stimulantData.class);\n renderStat('sedative', sedativeData.value, sedativeData.name, sedativeData.class);\n renderStat('hallucinogic', hallucinogicData.value, hallucinogicData.name, hallucinogicData.class);\n renderStat('delirant', delirantData.value, delirantData.name, delirantData.class);\n renderStat('dissociative', dissociativeData.value, dissociativeData.name, dissociativeData.class);\n renderStat('depressant', depressantData.value, depressantData.name, depressantData.class);\n}",
"handleColorScaleMemberChange(memberIndex, value) {\n const state = this.state;\n state.configuration.charts[0].colorScale[memberIndex] = value;\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }",
"function restyleGaugeChart(subjindex) {\n\n value = justmetadata[subjindex].wfreq;\n Plotly.restyle('gauge', \"value\", [value]);\n\n }",
"_updateItemIndexContext() {\r\n const viewContainer = this._nodeOutlet.viewContainer;\r\n for (let renderIndex = 0, count = viewContainer.length; renderIndex < count; renderIndex++) {\r\n const viewRef = viewContainer.get(renderIndex);\r\n const context = viewRef.context;\r\n context.count = count;\r\n context.first = renderIndex === 0;\r\n context.last = renderIndex === count - 1;\r\n context.even = renderIndex % 2 === 0;\r\n context.odd = !context.even;\r\n context.index = renderIndex;\r\n }\r\n }",
"rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }",
"function setColors(n, c) {\n if (n.strokeWidth == '1') {\n if (c == gr1Color){\n var tempindex = zparams.zgroup1.indexOf(n.name);\n if (tempindex > -1){\n n.group1 = false;\n del(zparams.zgroup1, tempindex);\n } else {\n n.group1 = true;\n zparams.zgroup1.push(n.name);\n };\n } else if (c == gr2Color){\n var tempindex = zparams.zgroup2.indexOf(n.name);\n if (tempindex > -1){\n n.group2 = false;\n del(zparams.zgroup2, tempindex);\n } else {\n n.group2 = true;\n zparams.zgroup2.push(n.name);\n };\n } else {\n // adding time, cs, dv, nom to node with no stroke\n n.strokeWidth = '4';\n n.strokeColor = c;\n n.nodeCol = taggedColor;\n let push = ([color, key]) => {\n if (color != c)\n return;\n zparams[key] = Array.isArray(zparams[key]) ? zparams[key] : [];\n zparams[key].push(n.name);\n if (key == 'znom') {\n findNodeIndex(n.name, true).nature = \"nominal\";\n transform(n.name, t = null, typeTransform = true);\n }\n if (key == 'zdv'){ // remove group memberships from dv's\n if(n.group1){\n n.group1 = false;\n del(zparams.zgroup1, -1, n.name);\n };\n if(n.group2){\n n.group2 = false;\n del(zparams.zgroup2, -1, n.name);\n };\n }\n };\n [[dvColor, 'zdv'], [csColor, 'zcross'], [timeColor, 'ztime'], [nomColor, 'znom']].forEach(push);\n }\n } else if (n.strokeWidth == '4') {\n if (c == n.strokeColor) { // deselecting time, cs, dv, nom\n n.strokeWidth = '1';\n n.strokeColor = selVarColor;\n n.nodeCol = colors(n.id);\n zparamsReset(n.name);\n if (nomColor == c && zparams.znom.includes(n.name)) {\n findNodeIndex(n.name, true).nature = findNodeIndex(n.name, true).defaultNature;\n transform(n.name, t = null, typeTransform = true);\n }\n } else { // deselecting time, cs, dv, nom AND changing it to time, cs, dv, nom\n zparamsReset(n.name);\n if (nomColor == n.strokeColor && zparams.znom.includes(n.name)) {\n findNodeIndex(n.name, true).nature = findNodeIndex(n.name, true).defaultNature;\n transform(n.name, t = null, typeTransform = true);\n }\n n.strokeColor = c;\n if (dvColor == c){\n var dvname = n.name;\n zparams.zdv.push(dvname);\n if(n.group1){ // remove group memberships from dv's\n ngroup1 = false;\n del(zparams.zgroup1, -1, dvname);\n };\n if(n.group2){\n ngroup2 = false;\n del(zparams.zgroup2, -1, dvname);\n };\n }\n else if (csColor == c) zparams.zcross.push(n.name);\n else if (timeColor == c) zparams.ztime.push(n.name);\n else if (nomColor == c) {\n zparams.znom.push(n.name);\n findNodeIndex(n.name, true).nature = \"nominal\";\n transform(n.name, t = null, typeTransform = true);\n }\n }\n }\n}",
"visitAlter_index(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function makeAllNodesFullOpacity(){\n model.nodeDataArray.forEach(node => {\n setOpacity(node, 1);\n })\n}",
"function drawTerrainEdges()\n{\n gl.polygonOffset(1,1);\n gl.bindBuffer(gl.ARRAY_BUFFER, tVertexPositionBuffer);\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, tVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);\n\n // Bind normal buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, tVertexNormalBuffer);\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, tVertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0); \n \n //Draw \n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, tIndexEdgeBuffer);\n gl.drawElements(gl.LINES, tIndexEdgeBuffer.numItems, gl.UNSIGNED_SHORT,0); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
optimisticGet transforms a get promise and sets response data into object | function optimisticGet(get, injectInto, withPropertyName) {
get.then(function (response) {
injectInto[withPropertyName] = response.data;
return response;
});
} | [
"function get_load(id, req){\r\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\r\n const key = datastore.key([LOAD, parseInt(id, 10)]);\r\n var format = []; \r\n return new Promise( function(resolve, reject){\r\n datastore.get(key, (err, entity)=>{\r\n if(err || entity === undefined){\r\n reject(new Error());\r\n }\r\n else{\r\n if(entity.carrier.length > 0)\r\n {\r\n // Format boat display to include self url\r\n format.push({\"boat_id\": entity.carrier[0], \"self\": req.protocol + '://' + req.get('host') + '/boats/' + entity.carrier[0]}); \r\n }\r\n else\r\n {\r\n format = entity.carrier; \r\n }\r\n var result = {\"id\": key.id, \"weight\": entity.weight, \"content\": entity.content, \"delivery_date\": entity.delivery_date, \"carrier\": format, \"self\": fullUrl};\r\n resolve(result)};\r\n });\r\n });\r\n\r\n}",
"getMarketCapSymbols() {\n // check cache\n let data = this._getMarketCapCachedData('symbols');\n if (undefined !== data) {\n return new Promise((resolve, reject) => {\n resolve(data);\n });\n }\n let path = '/marketCap/symbols';\n let url = this._getUrl(path);\n const params = {includeAliases:true};\n return this._sendRequest('get', url, {params:params}, (data) => {\n this._cacheMarketCapData('symbols', data)\n });\n\n}",
"singleFetch(predicates, options){\n return new Promise((resolve) => {\n this.prismic.getResults(predicates, options)\n .then((content) => resolve(content))\n .catch((error) => console.error(error));\n });\n }",
"load(personId) {\n return this.getJson(this.targetUrl + personId)\n .then(this._first.bind(this));\n }",
"_get_data(callback, force) {\n if (this._query.params) {\n this.loading(true);\n\n if (this._current_request) {\n this._current_request.cancel();\n }\n\n if (this._query_is_valid()) {\n this._current_request = DataThing.get(\n this._query,\n (data, query_key) => {\n this._register_query_key(query_key);\n\n if (this._mapping) {\n data = this._mapping(data);\n }\n this.data(data);\n this.error(undefined);\n\n this.loading(false);\n\n if (typeof callback === 'function') {\n callback(data, undefined);\n }\n },\n (error, query_key) => {\n this._register_query_key(query_key);\n this.error(error);\n this.data(undefined);\n\n this.loading(false);\n\n if (typeof callback === 'function') {\n callback(undefined, error);\n }\n },\n force,\n );\n } else {\n this.data(undefined);\n this.error(undefined);\n\n for (let callback of this._invalid_query_callbacks) {\n callback();\n }\n\n this.loading(false);\n }\n }\n }",
"load(endpoint, method, data, jsonify, raw) {\n let _self = this;\n // Default method argument to \"GET\"\n if (typeof(method) === \"undefined\") {\n method = \"GET\";\n }\n // JSONify data if supplied and jsonified data needed\n if (typeof(data) !== \"undefined\" && (typeof(jsonify) === \"undefined\" || jsonify)) {\n data = JSON.stringify(data);\n }\n // Kick-back a promise for this load\n return new Promise(function (resolve, reject) {\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n // Parse as JSON or send back raw error\n\t\tif (this.readyState == 4 && this.status == 200 && raw) {\n resolve(this.responseText);\n\t\t} else if (this.readyState == 4 && this.status == 200) {\n let dataObj = JSON.parse(this.responseText);\n resolve(dataObj);\n } else if(this.readyState == 4) {\n reject(this.responseText);\n }\n };\n let random = new Date().getTime().toString();\n xhttp.open(method, endpoint + \"?_no_cache=\" + random + \"&session=\" + _self.session, method != \"DELETE\");\n if (typeof(data) === \"undefined\") {\n xhttp.send();\n } else if (typeof(jsonify) === \"undefined\" || jsonify) {\n xhttp.setRequestHeader(\"Content-Type\", \"application/json\")\n xhttp.send(data);\n } else {\n xhttp.send(data);\n }\n });\n }",
"async getPartage(id){\n try{\n const partage = Object.assign(new Partage(), await this.partageApi.get(id));\n return partage;\n }\n catch (e) {\n if (e === 404) return null;\n if (e === 403) return 403;\n return undefined;\n }\n }",
"function quickFetch(url, func, param){\n fetch(url)\n .then(function(response){\n if (response.status !== 200){\n console.log('There was an error with your fetch. Response was not 200.')\n }\n return response.json()\n })\n .then(function(data){\n param = data;\n func(param)\n })\n}",
"function getElencoEsamiUltimoAnno(matId,anno){ \n return new Promise(function(resolve, reject) {\n var options = { \n method: 'GET',\n url: strUrlGetSingoloEsame + matId +'/righe/' + '?filter=esito.aaSupId%3D%3D' + anno,\n headers: \n { \n 'cache-control': 'no-cache',\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic czI2OTA3MjpDR1ZZUDNURQ=='\n },\n json: true \n }\n request(options, function (error, response, body) {\n console.log('url di getElencoEsamiUltimoAnno '+ options.url);\n if (error) {\n reject(error);\n console.log('errore in getElencoEsamiUltimoAnno '+ error);\n } else {\n if (response.statusCode==200){\n \n resolve(body); \n } else {\n\n console.log('status code getElencoEsamiUltimoAnno = '+response.statusCode);\n resolve(response.statusCode);\n }\n }\n \n });\n \n }); \n}",
"async function fetchTasksFromSource(objTaskSource) {\n\n var objReturn = new Object();\n objReturn.retStatus = 0;\n objReturn.retMessage = null;\n objReturn.retObject = undefined;\n\n self.endpointAddress = objTaskSource.epTaskListApi;\n var ep = RestHelper.get(self.endpointAddress);\n\n var objTasks;\n try {\n\n ep.responseBodyFormat('json');\n await ep.fetch()\n .then(result => {\n objTasks = result.body;\n })\n .catch(error => {\n objReturn.retStatus = -1;\n objReturn.retMessage = error;\n return objReturn;\n });\n\n //Format objects to a format acceptable to Array data provider. \n //Use the attribute mapping in the task source.\n objReturn.retObject = [];\n\n\n\n if (objTasks != null) {\n //loop through tasks and exatrct attributes\n var countTasks = objTasks.items.length;\n for (var currTask = 0; currTask < countTasks; currTask++) {\n objReturn.retObject[currTask] = new Object;\n objReturn.retObject[currTask].Status = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .Status);\n objReturn.retObject[currTask].TaskID = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .TaskID);\n objReturn.retObject[currTask].Subject = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .Subject);\n objReturn.retObject[currTask].DateAssigned = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .DateAssigned);\n objReturn.retObject[currTask].AssignedBy = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .AssignedBy);\n objReturn.retObject[currTask].Source = objTaskSource.name;\n }\n }\n\n } catch (error) {\n objReturn.retStatus = -1;\n objReturn.retMessage = error;\n objReturn.undefined;\n return objReturn;\n }\n\n return objReturn;\n }",
"function get(url) {\n return fetch('https://my-little-cors-proxy.herokuapp.com/' + url)\n .then(function(response) {\n return response.json();\n })\n .then(function(data){\n return data;\n });\n}",
"function getRoutine(id) {\n return fetch(`${url}/${id}`)\n .then(response => {\n return response.json();\n })\n .then(json => {\n return json.data;\n })\n .catch(err => {\n console.log(err);\n });\n}",
"async getQuoteAffiliationPendingList() {\n \n let url = API_URL + \"/affilliatepending/affiliatependinglistquotes\";\n return await fetch(url)\n .then(res => res.json())\n .then(response => {\n return response;\n })\n .catch(error => {\n console.log(error);\n return undefined;\n });\n }",
"async request(keypath) {\n \n if (this.isCachedInMemory(keypath)) {\n // We have it in memory so skip the stack and publish the value\n let value = this.getFromMemory(keypath)\n // Publish for anyone waiting on it\n this.publishKeypath(keypath, value)\n // Return it (we are async so this wraps as a promise)\n return value\n }\n \n // Otherwise we need to wait at least for disk\n let promise = this.waitFor(keypath)\n\n // Just dump it into the stack.\n // TODO: It would be more debuggable to vet it here\n this.stack.push(keypath)\n\n if (!this.running) {\n // We just disturbed a sleeping Datasource, so start processing stuff\n \n this.running = true\n\n // Schedule the waiting tasks to be handled\n timers.setImmediate(() => {\n this.processStack()\n })\n }\n\n return promise\n }",
"static getAllCachedRestaurants(id) {\r\n //console.log('getAllCachedRestaurants');\r\n let dbPromise = DBHelper.getRestaurantDB();\r\n //Obtaining Result\r\n let res = dbPromise.then(function(db) {\r\n if(!db) return;\r\n let transaction = db.transaction('restaurants_mst');\r\n let allRestaurents = transaction.objectStore('restaurants_mst');\r\n return id!==null ? allRestaurents.get(Number(id)) : allRestaurents.getAll();\r\n }).catch((err) => {\r\n console.log('Problem in Getting All Restaurents '+err);\r\n });\r\n //Returning All Records\r\n //console.log('getAllCachedRestaurants'+res);\r\n return res;\r\n }",
"async fetchArticleData(props, wiki) {\n if (!props) return;\n\n const promiseObject = {};\n\n promiseObject.details = this.fetchArticleDetails(props, wiki);\n promiseObject.json = this.fetchArticleJson(props, wiki);\n promiseObject.og = this.fetchArticleOpenGraph(props, wiki);\n promiseObject.thread = this.fetchThreadData(props, wiki);\n\n await this.awaitPromiseObject(promiseObject);\n\n return promiseObject;\n }",
"getOrderbook(id, type) {\n return new Promise((resolve, reject) => {\n\n return new Request({\n path: '/_mobile/order/' + type.toLowerCase() + '?' + querystring.stringify({\n orderbookId: id\n }),\n headers: {\n 'X-AuthenticationSession': this.authenticationSession,\n 'X-SecurityToken': this.securityToken\n }\n }).then(orderbook => {\n\n let object = {}\n\n object.instrumentId = orderbook.id\n object.orders = []\n object.trades = []\n\n for(let i = 0; i < orderbook.latestTrades.length; i++) {\n const trade = orderbook.latestTrades[i]\n object.trades.push({\n price: trade.price,\n volume: trade.volume,\n time: new Date(trade.dealTime).getTime(),\n seller: trade.seller || '-',\n buyer: trade.buyer || '-'\n })\n }\n\n resolve(object)\n\n }).catch(error => reject(error));\n\n })\n }",
"getHeroes() {\n return this.http.get(this.heroesUrl)\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"tap\"])(_ => this.log('fetched heroes')), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"catchError\"])(this.handleError('getHeroes', [])));\n }",
"getAccountImportances() {\n return rxjs_1.of(\"importances\")\n .pipe(operators_1.flatMap((url) => requestPromise.get(this.nextNode() + url, { json: true })), operators_1.retryWhen(this.replyWhenRequestError), operators_1.map((importanceData) => {\n return importanceData.data.map((accountImportanceViewModel) => {\n return AccountImportanceInfo_1.AccountImportanceInfo.createFromAccountImportanceViewModelDTO(accountImportanceViewModel);\n });\n }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets the default interpolation time in millis. | setDefaultInterpolationTime(duration) {
this.timedRot .default_duration = duration;
this.timedPan .default_duration = duration;
this.timedzoom.default_duration = duration;
} | [
"function changeDefaultTimeOut() {\n let user = db.ref('users/' + userId);\n\n const newDefaultTime = app.getArgument('newDefaultTime');\n\n if (newDefaultTime && (newDefaultTime * 60) > 0) {\n let minutes = parseInt(newDefaultTime) * 60;\n let promise = user.set({userId: userId, defaultCheckOutTime: minutes});\n\n app.tell(`Done. The new default session time out is now set to ${newDefaultTime} hours.`);\n } else {\n app.ask(`Sorry! can you please repeat that.`);\n }\n }",
"setBakingTime() {}",
"function calculateDatafeedFrequencyDefaultSeconds() {\n const bucketSpan = parseInterval($scope.job.analysis_config.bucket_span);\n if (bucketSpan !== null) {\n $scope.ui.datafeed.frequencyDefault = juCalculateDatafeedFrequencyDefaultSeconds(bucketSpan.asSeconds()) + 's';\n }\n }",
"setDefaultSpeed_() {\r\n const {gameSpeed} = this.gameConfig_;\r\n\r\n this.gameSpeed_ = gameSpeed;\r\n this.board_.setBoardSpeed(this.gameSpeed_);\r\n }",
"resetToMax() {\n this._currentBaseMs = this._maxDelayMs;\n }",
"function updateMillisecondsPerDay() {\n var inputValue = document.getElementById('millisecondsPerDay').value,\n info = document.getElementById('millisecondsPerDayInfo'),\n millisecondsPerDay = parseInt(inputValue, 10),\n secondsPerDay = millisecondsPerDay / 1000,\n html = '1 Earth day = ';\n\n if (secondsPerDay < 1) {\n html += millisecondsPerDay + ' milliseconds';\n }\n else {\n html += (secondsPerDay + ' ') + (secondsPerDay > 1 ? 'seconds' : 'second');\n }\n\n info.innerHTML = html;\n }",
"updateTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n\r\n // divide by 1000 to get it into seconds\r\n this.time = (this.timeAtThisFrame - this.timeAtFirstFrame) / 1000.0;\r\n\r\n this.deltaTime = (this.timeAtThisFrame - this.timeAtLastFrame) / 1000.0;\r\n this.timeAtLastFrame = this.timeAtThisFrame;\r\n\r\n // update and set our scene time uniforms\r\n this.t = this.time / 10;\r\n this.dt = this.deltaTime;\r\n }",
"function setTempo(newTempo) {\n tempo = newTempo;\n tic = (60 / tempo) / 4; // 16th\n}",
"initializeTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n this.timeAtFirstFrame = new Date().getTime();\r\n this.timeAtLastFrame = this.timeAtFirstFrame;\r\n\r\n // time and deltaTime are local scene properties\r\n // we set the dynamically created t and dt in the update frame\r\n this.time = 0;\r\n this.deltatime = 0;\r\n }",
"function refreshMainTimeView() {\n setText(document.querySelector(\"#text-main-hour\"),\n addLeadingZero(Math.floor(setting.timeSet / 3600), 2));\n setText(document.querySelector(\"#text-main-minute\"),\n addLeadingZero(Math.floor(setting.timeSet / 60) % 60, 2));\n setText(document.querySelector(\"#text-main-second\"),\n addLeadingZero(setting.timeSet % 60, 2));\n applyStyleTransition(document.querySelector(\"#box-hand-hour\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 43200) / 43200);\n applyStyleTransition(document.querySelector(\"#box-hand-minute\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 3600) / 3600);\n applyStyleTransition(document.querySelector(\"#box-hand-second\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 60) / 60);\n }",
"function setTimestamp_() {\n const currentTime = formatTime_(sketchPlayer.sketch.getCurrentTime());\n const duration = formatTime_(sketchPlayer.sketch.videoDuration());\n $timestamp.text(currentTime + '/' + duration);\n\n // Clear any pending timer, since this function could either be called as the\n // result of an onSeekUpdate update event, or from a previous timer firing.\n clearTimeout(timestampUpdateTimer);\n timestampUpdateTimer = setTimeout(setTimestamp_, 500);\n}",
"function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}",
"function changeDelayBetweenSteps() {\n drawing.delay = stepDelaySlider.value;\n updateStepDelaySliderText(drawing.delay);\n}",
"printTime(){\n let min = Math.floor(this.project._pot/60);\n let sec = Math.floor(this.project._pot)-min*60;\n let msec = Math.floor((this.project._pot-Math.floor(this.project._pot))*1000);\n if(sec<10) sec = \"0\"+sec;\n if(min<10) min = \"0\"+min;\n return min+\":\"+sec+\":\"+msec;\n }",
"calculate() {\n this.times.miliseconds += 1;\n if (this.times.miliseconds >= 100) {\n this.times.seconds += 1;\n this.times.miliseconds = 0;\n }\n if (this.times.seconds >= 60) {\n this.times.minutes += 1;\n this.times.seconds = 0;\n }\n }",
"itsTime() {\r\n\r\n // Get the current time\r\n let t = this.setCurrentTime();\r\n\r\n // Change hue based on minutes passed\r\n let totalMinutes = (parseInt(t.hour) * 60) + parseInt(t.minute) ;\r\n let hue = totalMinutes * 0.25;\r\n\r\n // Keep saturation in the mid ranges\r\n let sat = parseInt(t.minute) + 10;\r\n\r\n // Keep lightness in the mid ranges\r\n let light = parseInt(t.second) + 15;\r\n\r\n // Set the data for the view\r\n this.currentTime = `${t.hour}:${t.minute}:${t.second}`;\r\n this.hsl = `${hue}, ${sat}%, ${light}%`;\r\n\r\n // Notify the observer\r\n super.notify();\r\n }",
"function setDefault() {\n if (ctrl.rrule.bymonthday || ctrl.rrule.byweekday) return\n ctrl.rrule.bymonthday = ctrl.startTime.getDate()\n }",
"set OverrideSampleRate(value) {}",
"function updateTime() {\n const datetime = tizen.time.getCurrentDateTime();\n const hour = datetime.getHours();\n const minute = datetime.getMinutes();\n const second = datetime.getSeconds();\n\n const separator = second % 2 === 0 ? \":\" : \" \";\n\n $(\"#time-text\").html(padStart(hour.toString()) + separator + padStart(minute.toString()));\n\n // Update the hour/minute/second hands\n rotateElements((hour + (minute / 60) + (second / 3600)) * 30, \"#hands-hr-needle\");\n rotateElements((minute + second / 60) * 6, \"#hands-min-needle\");\n clearInterval(interval);\n if (!isAmbientMode) {\n let anim = 0.1;\n rotateElements(second * 6, \"#hands-sec-needle\");\n interval = setInterval(() => {\n rotateElements((second + anim) * 6, \"#hands-sec-needle\");\n anim += 0.1;\n }, 100);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resolution du maze automatiquement | function resolveMaze(){
tryMaze(positionFixe);
traceRoad(chemin_parcouru,"color2");
traceRoad(tabVisite);
} | [
"get gridResolutionZ() {}",
"set gridResolutionZ(value) {}",
"get gridResolutionY() {}",
"function Maze($where, size) {\n\t\n\tvar $canvas = $where.find('canvas')\n\t$canvas.attr({width:size, height:size})\n\tthis.$log = $where.find('#moves').eq(0)\n\tthis.$description = $where.find('#description').eq(0)\n\tthis.canvas = $canvas[0]\n\tvar ctx = this.ctx = this.canvas.getContext('2d')\n\tthis.definePaths()\n\tthis.reset()\n\n\tthis.drawThread = setInterval(new function(maze) { return function() {\n\t\tif(undefined == maze.lockdraw)\n\t\tif(maze.drawaction) {\n\t\t\tmaze.drawaction()\n\t\t\tmaze.drawaction = null\n\t\t}\n\t}}(this), $.browser.msie ? 1000/2 : 1000/60)\n\tthis.drawUpdateThread = setInterval(new function(maze) { \n\t\tfunction zoom(maze, level, t) {\n\t\t\tvar target = maze.offset(level.box)\n\t\t\tvar old_scale = maze.scale\n\n\t\t\tctx.save()\n\t\t\t\tmaze.scale = old_scale * (t*t*4+1)\n\t\t\t\tctx.scale(t*t*4+1,t*t*4+1)\n\t\t\t\tctx.translate(-t*(target[0]),-t*(target[1]))\n\t\t\t\tmaze.draw(level.up)\n\t\t\t\tctx.translate(target[0],target[1])\n\t\t\t\tctx.scale(1/5,1/5)\n\t\t\t\tmaze.scale *= 1/5\n\t\t\t\tctx.globalAlpha = 1*t + 0.25*(1-t)\n\t\t\t\tmaze.drawMaze(maze.ctx, level)\n\t\t\tctx.restore()\n\t\t\tmaze.scale = old_scale\n\t\t}\n\t\treturn function() {\n\t\t\tvar camera = maze.camera\n\t\t\twhile(camera.target[1] == camera.target[0]) {\n\t\t\t\tcamera.target.shift()\n\t\t\t}\n\t\t\tif(camera.target.length > 1 && camera.interp >= 1) {\n\t\t\t\tif(!(maze.replay && camera.target.length == 2 && camera.target[1].up == camera.target[0])) {\n\t\t\t\t\tcamera.interp = 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(camera.interp < 1) {\n\t\t\t\tif(camera.interp < 0) camera.interp = 0\n\t\t\t\tif(camera.target[2] == camera.target[0] \n\t\t\t\t\t&& camera.target[2].depth < camera.target[1].depth) {\n\t\t\t\t\tcamera.target.shift()\n\t\t\t\t\tcamera.interp = 1-camera.interp\n\t\t\t\t}\n\t\t\t\tvar level = camera.target[1]\n\t\t\t\tvar t = camera.interp\n\t\t\t\tvar speed = 0.03\n\t\t\t\tif(camera.target[1] == camera.target[0].up) {\n\t\t\t\t\tt = 1-t\n\t\t\t\t\tlevel = camera.target[0]\n\t\t\t\t}\n\t\t\t\tif(camera.target[1].depth <= camera.target[0].depth)\n\t\t\t\t\tspeed = 0.08\n\t\t\t\tmaze.drawaction = new function(level,t) { return function() { \n\t\t\t\t\tzoom(maze, level, t) } } (level,t)\n\t\t\t\tcamera.interp += speed*(camera.target.length-1)\n\t\t\t\tif(camera.interp >= 1) {\n\t\t\t\t\tcamera.interp = 1\n\t\t\t\t\tcamera.target.shift()\n\t\t\t\t}\n\t\t\t\tmaze.redraw = true\n\t\t\t} else if(maze.redraw) {\n\t\t\t\tmaze.drawaction = function() { maze.draw(camera.target[0]) }\n\t\t\t\tmaze.redraw = 0\n\t\t\t}\n\t\t}\n\t}(this), 1000/30)\n}",
"function drawMaze(){\n\t//xy offsets so that the map is centered in the canvas\n\toffsetx = (canvas.width/2)-(width*imgSize)/2;\n\toffsety = (canvas.height/2)-(height*imgSize)/2;\n\t\n\t//Drawing coloured background, and then setting draw colour back to black.\n\tcontext.fillStyle=\"#D1FFF0\";\n\tcontext.fillRect( 0 , 0 , canvas.width, canvas.height );/*Clearing canvas*/\t\n\tcontext.fillStyle=\"#000000\";\n\t\n\t\n\tfor(var i=0; i<height; i++){\n\t\tfor(var j=0; j<width; j++){\n\t\t\t\n\t\t\t//If they can see the whole map, or the position is located directly next to the player.\n\t\t\tif(!limitedSight||\n\t\t\t((j>=playerPositionx-1&&j<=playerPositionx+1\n\t\t\t&&i>=playerPositiony-1&&i<=playerPositiony+1)&&!isPaused)){\n\t\t\t\t\n\t\t\t\tif(map[j][i]=='.'){/*Wall*/\n\t\t\t\t\tcontext.drawImage(wall, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t} else if(map[j][i]=='P'&&solutionVisible){/*Path*/\n\t\t\t\t\tcontext.drawImage(path, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t}else {/*Ground*/\n\t\t\t\t\tcontext.drawImage(floor, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(j==playerPositionx&&i==playerPositiony)/*player*/\n\t\t\t\t\tcontext.drawImage(character, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t\t\n\t\t\t\tif(j==targetx&&i==targety)/*toilet (maze end)*/\n\t\t\t\t\tcontext.drawImage(toiletGraphic, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t\n\t\t\t\tif(showDistances)/*showing movement distance from the player to this tile*/\n\t\t\t\t\tcontext.fillText(distanceMap[j][i], offsetx+j*imgSize, offsety+(i+1)*imgSize);\n\t\t\t\t\t\n\t\t\t}else{\n\t\t\t\t//if it isnt a tile the player can see, draw a black square.\n\t\t\t\tcontext.drawImage(darkSquareGraphic, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t}\n\t\t\t\n\t\t\tif(isPaused)context.drawImage(pausedTextGraphic, canvas.width/2-pausedTextGraphic.width/2, canvas.height/2-pausedTextGraphic.height/2);\n\t\t\t\n\t\t\t//Drawing lower background panel\n\t\t\tcontext.drawImage(lowerBackgroundGraphic, 0, canvas.height-40, canvas.width, 40);\n\t\t\t//Drawing hint button\n\t\t\tcontext.drawImage(hintButtonGraphic, hintButtonX, hintButtonY, 50, 20);\n\t\t\t//Drawing mute button\n\t\t\tif(isMuted){\n\t\t\t\tcontext.drawImage(mutedGraphic, muteButtonX, muteButtonY);\n\t\t\t}else{\n\t\t\t\tcontext.drawImage(speakerGraphic, muteButtonX, muteButtonY);\n\t\t\t}\n\t\t\t\n\t\t\t//Drawing upper buttons\n\t\t\tcontext.drawImage(trophyGraphic, muteButtonX-20, muteButtonY);\n\t\t\tcontext.drawImage(pauseGraphic, muteButtonX-40, muteButtonY);\n\t\t\t\n\t\t\t//Drawing guide graphics for first level\n\t\t\tif(gameLevel==1){\n\t\t\t\tcontext.drawImage(leftArrowGraphic, 10, (canvas.height/2)-(leftArrowGraphic.height/2));\n\t\t\t\tcontext.drawImage(rightArrowGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2));\t\t\t\n\t\t\t\tcontext.drawImage(upArrowGraphic, (canvas.width/2)-(upArrowGraphic.width/2), 10);\n\t\t\t\tcontext.drawImage(downArrowGraphic, (canvas.width/2)-(downArrowGraphic.width/2), canvas.height-40-downArrowGraphic.height);\n\t\t\t}\t\t\n\t\t\t//Text portion of guide graphics\n\t\t\tif(controlVisualVisible){\n\t\t\t\tcontext.font = \"17px Arial\";\n\t\t\t\tcontext.fillText(\"Memorize this path to the toilet\", offsetx-32, offsety-12);\n\t\t\t\tcontext.fillText(\"Then retrace it as fast as you can!\", offsetx-50, offsety+width*imgSize+16);\n\t\t\t\t\n\t\t\t\tif(fingerGraphicDown){/*Checking if the finger graphic is up or down*/\n\t\t\t\t\tcontext.drawImage(fingerGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2));\n\t\t\t\t}else{\n\t\t\t\t\tcontext.drawImage(fingerGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2)-20);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//Drawing graphic for achievement menu window\n\t\t\tif(isAchievementMenu){\n\t\t\t\tcontext.drawImage(achievementsWindowGraphic, canvas.width/2-achievementsWindowGraphic.width/2, canvas.height/2-achievementsWindowGraphic.height/2);\t\t\t\t\n\t\t\t\tif(firstPlayAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+44);\n\t\t\t\tif(firstLevelAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+74);\n\t\t\t\tif(firstHintAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+104);\n\t\t\t\tif(fifthLevelAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+136);\n\t\t\t}\n\t\t\t\n\t\t\t//draw achievement window if its currently being displayed\n\t\t\tif(isShowingMessage)displayAchievement();\n\t\t}\n\t}\n\t//prints score and time at the bottom of the screen\n\ttestingOutput();\n}",
"function getVirtualCoord(event, $objet) { \r\n// console.log(\"entree getvirtual\");\r\n// var heightSlide = 700; //pour le moment la hauteur de la slide conditionne la hauteur \"vue\" à l'écran, lorsque zoomable fonctionnera il faudra un autre repere\r\n var MRH = window.innerHeight; //MaxRealHeight\r\n\r\n\r\n //var MVH = heightSlide * parseInt(parseFloat($slideArea.css(\"perspective\")) / 1000); //MaxVirtualHeight //prise en compte deu zoom\r\n // var scale = ($slideArea.hasClass(\"step\"))? parseInt(parseFloat($slideArea.css(\"perspective\")) / 1000) : 1;\r\n //scale = $objet.attr(\"data-scale\");\r\n //console.log($qui);\r\n var dico = getTrans3D();\r\n\r\n\r\n var scale = Math.abs(dico.translate3d[2] / $objet.attr('data-z')) * 1/1.18;\r\n //console.log(\"scale \"+scale);\r\n\r\n\r\n// console.log(\"scale \" + scale + \" \" + parseFloat($slideArea.css(\"perspective\")) + \" \" + $objet.attr(\"data-scale\"));\r\n var MVH = scale * 700;//$objet.height();//parseFloat($slideArea.css(\"perspective\"));//heightSlide * scale; //MaxVirtualHeight //prise en compte deu zoom\r\n //console.log( MVH + \" \"+ scale + \" \" + $objet.attr('data-z') + \" \" + $objet.height() );\r\n var RTop = event.pageY; //RealTop (de la souris)\r\n\r\n //VirtualTop (position dans le monde des slides)\r\n var VTop = MVH * RTop / MRH; //prise en compte de la proportion\r\n VTop = Math.round(VTop);\r\n\r\n var MRL = window.innerWidth; //MaxRealWidth\r\n var ratio = MRL / MRH; //rapport de zone d'écran du navigateur\r\n var MVL = ratio * MVH; //MaxVirtualWidth\r\n var RLeft = event.pageX; //RealTop (de la souris)\r\n\r\n //VirtualTop (position dans le monde des slides)\r\n var VLeft = MVL * RLeft / MRL; //prise en compte de la proportion\r\n VLeft = Math.round(VLeft);\r\n\r\n //console.log(\"MRH \" + MRH + \" MVH \" + MVH + \" VTop \" + VTop + \" Rtop \" + RTop);\r\n //console.log(\"MRL \" + MRL + \" MVL \" + MVL + \" VLeft \" + VLeft + \" RLeft \" + RLeft);\r\n\r\n var tab = new Array(VTop, VLeft);\r\n// console.log(\"sortie getvirtual\");\r\n return tab;\r\n\r\n}",
"find_initial_direction() {\n this.direction = maze.start_dir;\n }",
"function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}",
"_mapMaze () {\n return this.maze.map((row, rowIndex) => {\n const mappedRow = row.map((column, columnIndex) => ({\n row: rowIndex,\n column: columnIndex,\n parent: null,\n value: column,\n f: 0,\n g: 0,\n h: 0\n }))\n\n return mappedRow\n })\n }",
"function mazeRunner(maze, directions) {\n let startLocation;\n let currentLocation;\n \n maze.forEach((arr, i) => {\n if(arr.indexOf(2) !== -1) {\n startLocation = [i, arr.indexOf(2)];\n }\n })\n \n currentLocation = startLocation.slice();\n \n for(let i = 0; i < directions.length; i++) {\n let lastMovement = false;\n \n decideMovement(directions[i]);\n \n if(i === directions.length - 1) {\n lastMovement = true;\n }\n \n if(currentLocation[0] < 0 || currentLocation[0] > maze[0].length -1 ||\n currentLocation[1] < 0 || currentLocation > maze.length -1) {\n return 'Dead'\n }\n \n if(decideFate(maze[currentLocation[0]][currentLocation[1]]) === 'Dead') {\n return 'Dead';\n } else if (decideFate(maze[currentLocation[0]][currentLocation[1]]) === 'Finish') {\n return 'Finish';\n } else if (decideFate(maze[currentLocation[0]][currentLocation[1]], lastMovement) === 'Lost') {\n return 'Lost';\n }\n }\n \n function decideMovement(direction) {\n switch(direction) {\n case 'N':\n return currentLocation[0] = currentLocation[0] - 1;\n case 'S':\n return currentLocation[0] = currentLocation[0] + 1;\n case 'E':\n return currentLocation[1] = currentLocation[1] + 1;\n case 'W':\n return currentLocation[1] = currentLocation[1] - 1;\n }\n }\n \n function decideFate(newBlock, lastMovement) {\n switch(newBlock) {\n case 0:\n if(lastMovement === true) {\n return 'Lost'\n }\n break;\n case 1:\n return 'Dead';\n case 2: \n if(lastMovement === true) {\n return 'Lost'\n }\n break;\n case 3:\n return 'Finish';\n case undefined:\n return 'Dead';\n }\n }\n \n }",
"function findPath(world, pathStart, pathEnd) {\n // shortcuts for speed\n var abs = Math.abs;\n var max = Math.max;\n var pow = Math.pow;\n var sqrt = Math.sqrt;\n\n // keep track of the world dimensions\n // Note that this A-star implementation expects the world array to be square:\n // it must have equal height and width. If your game world is rectangular,\n // just fill the array with dummy values to pad the empty space.\n var worldWidth = world[0].length;\n var worldHeight = world.length;\n var worldSize = worldWidth * worldHeight;\n\n // which heuristic should we use?\n // default: no diagonals (Manhattan)\n var distanceFunction = ManhattanDistance;\n var findNeighbours = function () {\n }; // empty\n\n // distanceFunction functions\n // these return how far away a point is to another\n\n function ManhattanDistance(Point, Goal) {\t// linear movement - no diagonals - just cardinal directions (NSEW)\n return abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n }\n\n // Neighbours functions, used by findNeighbours function\n // to locate adjacent available cells that aren't blocked\n\n // Returns every available North, South, East or West\n // cell that is empty. No diagonals,\n // unless distanceFunction function is not Manhattan\n function Neighbours(x, y) {\n var N = y - 1,\n S = y + 1,\n E = x + 1,\n W = x - 1,\n myN = N > -1 && canWalkHere(x, N),\n myS = S < worldHeight && canWalkHere(x, S),\n myE = E < worldWidth && canWalkHere(E, y),\n myW = W > -1 && canWalkHere(W, y),\n result = [];\n if (myN)\n result.push({x: x, y: N});\n if (myE)\n result.push({x: E, y: y});\n if (myS)\n result.push({x: x, y: S});\n if (myW)\n result.push({x: W, y: y});\n findNeighbours(myN, myS, myE, myW, N, S, E, W, result);\n return result;\n }\n\n // returns boolean value (world cell is available and open)\n function canWalkHere(x, y) {\n return ((world[y] != null) &&\n (world[y][x] != null) &&\n (world[y][x] !== '#'));\n }\n\n // Node function, returns a new object with Node properties\n // Used in the calculatePath function to store route costs, etc.\n function Node(Parent, Point) {\n var newNode = {\n // pointer to another Node object\n Parent: Parent,\n // array index of this Node in the world linear array\n value: Point.x + (Point.y * worldWidth),\n // the location coordinates of this Node\n x: Point.x,\n y: Point.y,\n // the distanceFunction cost to get\n // TO this Node from the START\n f: 0,\n // the distanceFunction cost to get\n // from this Node to the GOAL\n g: 0\n };\n\n return newNode;\n }\n\n // Path function, executes AStar algorithm operations\n function calculatePath() {\n // create Nodes from the Start and End x,y coordinates\n var mypathStart = Node(null, {x: pathStart[0], y: pathStart[1]});\n var mypathEnd = Node(null, {x: pathEnd[0], y: pathEnd[1]});\n // create an array that will contain all world cells\n var AStar = new Array(worldSize);\n // list of currently open Nodes\n var Open = [mypathStart];\n // list of closed Nodes\n var Closed = [];\n // list of the final output array\n var result = [];\n // reference to a Node (that is nearby)\n var myNeighbours;\n // reference to a Node (that we are considering now)\n var myNode;\n // reference to a Node (that starts a path in question)\n var myPath;\n // temp integer variables used in the calculations\n var length, max, min, i, j;\n // iterate through the open list until none are left\n while (length = Open.length) {\n max = worldSize;\n min = -1;\n for (i = 0; i < length; i++) {\n if (Open[i].f < max) {\n max = Open[i].f;\n min = i;\n }\n }\n // grab the next node and remove it from Open array\n myNode = Open.splice(min, 1)[0];\n // is it the destination node?\n if (myNode.value === mypathEnd.value) {\n myPath = Closed[Closed.push(myNode) - 1];\n do\n {\n result.push([myPath.x, myPath.y]);\n }\n while (myPath = myPath.Parent);\n // clear the working arrays\n AStar = Closed = Open = [];\n // we want to return start to finish\n result.reverse();\n }\n else // not the destination\n {\n // find which nearby nodes are walkable\n myNeighbours = Neighbours(myNode.x, myNode.y);\n\n // test each one that hasn't been tried already\n for (i = 0, j = myNeighbours.length; i < j; i++) {\n myPath = Node(myNode, myNeighbours[i]);\n if (!AStar[myPath.value]) {\n // estimated cost of this particular route so far\n myPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n // estimated cost of entire guessed route to the destination\n myPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n // remember this new path for testing above\n Open.push(myPath);\n // mark this node in the world graph as visited\n AStar[myPath.value] = true;\n }\n }\n // remember this route as having no more untested options\n Closed.push(myNode);\n }\n } // keep iterating until until the Open list is empty\n return result;\n }\n // actually calculate the a-star path!\n // this returns an array of coordinates\n // that is empty if no path is possible\n return calculatePath();\n\n} // end of findPath() function",
"displacementFor(i, j, time){\n return this.map.heightForPosition(i,j);\n }",
"function carvePath(cell1, cell2){\n\t//cell1 = random frontier, cell2 = adjacent in maze\n\tif(cell1.location.row === cell2.location.row+1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.N = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.S = {row: cell1.location.row, col: cell1.location.col}\n\t}\n\tif(cell1.location.row === cell2.location.row-1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.S = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.N = {row: cell1.location.row, col: cell1.location.col}\n\t}\n\tif(cell1.location.col === cell2.location.col+1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.W = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.E = {row: cell1.location.row, col: cell1.location.col}\n\t}\n\tif(cell1.location.col === cell2.location.col-1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.E = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.W = {row: cell1.location.row, col: cell1.location.col}\n\t}\n}",
"function clearMazes(){\r\n for(var i=0;i<width;i++){\r\n for(var ii=0;ii<height;ii++){\r\n //recursive backtrack\r\n RBMaze[i][ii] = new Object();\r\n RBMaze[i][ii].north = 1;\r\n RBMaze[i][ii].south = 1;\r\n RBMaze[i][ii].east = 1;\r\n RBMaze[i][ii].west = 1;\r\n RBMaze[i][ii].visited = 0;\r\n\r\n //prims\r\n primsMaze[i][ii] = new Object();\r\n primsMaze[i][ii].north = 1;\r\n primsMaze[i][ii].south = 1;\r\n primsMaze[i][ii].east = 1;\r\n primsMaze[i][ii].west = 1;\r\n primsMaze[i][ii].visited = 0;\r\n primsMaze[i][ii].mark = 0;\r\n }\r\n }\r\n}",
"getDimensions() {\n return {\n length: this.topLeft.lat - this.bottomLeft.lat,\n width: Math.abs(this.topLeft.long) - Math.abs(this.topRight.long)\n }\n }",
"function setup(){\n\n c = createCanvas(windowWidth, height1);\n\n var res = 20;\n var countX = ceil(width/res) + 1;\n var countY = ceil(height1/res) + 1;\n\n for (var j = 0; j < countY; j++) {\n for (var i = 0; i < countX; i++) {\n locs.push( new p5.Vector(res*i, res*j) );\n }\n };\n\n noFill();\n stroke(249,78,128); // add the pink color effect\n\n}",
"function bajarPlanta() {\n if (pisoActual > pisoMin) {\n removeFloors(pisoActual);\n removeMeasuresLayer();\n pisoActual--;\n addMeasuresLayer(pisoActual);\n addFloors(pisoActual);\n floors.addTo(map);\n }\n}",
"function calcTileExtents() {\n\n\tvar section = map.getView().calculateExtent(map.getSize())\n\tvar s1 = proj4('EPSG:21781', 'EPSG:4326', [section[0], section[1]])\n\tvar s2 = proj4('EPSG:21781', 'EPSG:4326', [section[2], section[3]])\n\tsection = [s1[0],s1[1],s2[0],s2[1]]\n\tconsole.log(section)\n\n\t\n\n\tsection.forEach(function(point, i) {\n\t\tsection[i] = point - point % state.tileSize\n\t})\n\n\tvar lons = [section[0], section[2]]\n\n\tif (!(lons[1] - lons[0]) / state.tileSize) {\n\t\tlons = [lons[0]]\n\t} else {\n\t\tfor (var i = 1; i < (lons[1] - lons[0]) / state.tileSize; i++) {\n\t\t\tlons.push(lons[0] + state.tileSize * i)\n\t\t}\n\t}\n\n\tvar lats = [section[1], section[3]]\n\tif (!(lats[1] - lats[0]) / state.tileSize) {\n\t\tlats = [lats[0]]\n\t} else {\n\t\tfor (var i = 1; i < (lats[1] - lats[0]) / state.tileSize; i++) {\n\t\t\tlats.push(lats[0] + state.tileSize * i)\n\t\t}\n\t}\n\n\tvar tiles = []\n\tvar tiles2 = []\n\n\tconsole.log(lons)\n\tconsole.log(lats)\n\tlons.forEach(function(lon) {\n\t\tlats.forEach(function(lat) {\n\t\t\tvar coord1 = [lon, lat]\n\t\t\tvar coord2 = [lon + state.tileSize, lat + state.tileSize]\n\t\t\ttiles.push([coord1[0], coord1[1], coord2[0], coord2[1]])\n\t\t\ttiles2.push([lon, lat, lon + state.tileSize, lat + state.tileSize])\n\t\t})\n\t})\n\tconsole.log(JSON.stringify(tiles))\n\tconsole.log(JSON.stringify(tiles2))\n\n\treturn tiles\n}",
"calculateDimensions() {\r\n let leftMostCoordinate = this.transformedPolygon[0][0],\r\n rightMostCoordinate = this.transformedPolygon[0][0],\r\n topMostCoordinate = this.transformedPolygon[0][1],\r\n bottomMostCoordinate = this.transformedPolygon[0][1];\r\n\r\n for(let i=0; i<this.transformedPolygon.length; i++) {\r\n if(this.transformedPolygon[i][0] < leftMostCoordinate) {\r\n leftMostCoordinate = this.transformedPolygon[i][0];\r\n } else if(this.transformedPolygon[i][0] > rightMostCoordinate) {\r\n rightMostCoordinate = this.transformedPolygon[i][0];\r\n }\r\n\r\n if(this.transformedPolygon[i][1] < topMostCoordinate) {\r\n topMostCoordinate = this.transformedPolygon[i][1];\r\n } else if(this.transformedPolygon[i][1] > bottomMostCoordinate) {\r\n bottomMostCoordinate = this.transformedPolygon[i][1];\r\n }\r\n }\r\n\r\n this.width = Math.abs(rightMostCoordinate - leftMostCoordinate);\r\n this.height = Math.abs(bottomMostCoordinate - topMostCoordinate);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1s after load, Mole appears in random hole | function assignMole() {
var circle = circles[Math.floor(Math.random() * circles.length)];
circle.style.backgroundImage = "url(mole.png)";
circle.hasMole = true;
} | [
"function repeatMoles () {\r\n randHoleIdx = Math.floor(Math.random()*(holes.length)+1);\r\n holes[randHoleIdx].classList.toggle(\"mole\");\r\n}",
"function moveMole() {\n let timerId = null;\n //performs randomSquare function every 1000ms or 1s\n timerId = setInterval(randomSquare, 1000);\n}",
"relocateMole() {\n\t\tgameState.mole.anims.play('disappear');\n\t}",
"function randomLocatePacman(){\n\tif (shape.i != undefined && shape.j != undefined){\n\t\tboard[shape.i][shape.j] = 0;\n\t}\n\n\tlet pacmanCell = findRandomEmptyCell(board);\n\tboard[pacmanCell[0]][pacmanCell[1]] = 2;\n\tshape.i = pacmanCell[0];\n\tshape.j = pacmanCell[1];\n}",
"randomInitTile() {\n let randX = this.getRandomInt()\n let randY = this.getRandomInt()\n while (this.isOccupied(randX, randY)) {\n randX = this.getRandomInt();\n randY = this.getRandomInt();\n }\n this.board[randY][randX] = 2;\n this.append(randX, randY);\n }",
"start(){\n this.picture = DRAWINGS[Math.floor(Math.random()*DRAWINGS.length)];\n this.setRoundTime(ROUND_TIME_VAR)\n }",
"function randomMonter() {\n \tvar number = Math.floor((Math.random()*6)+1);\n \tmonters[number].isShow = true;\n }",
"randomize () {\n\t\tfor (var column = 0; column < this.numberOfColumns; column ++) {\n for (var row = 0; row < this.numberOfRows; row++) {\n this.cells[column][row].setIsAlive(floor(random(2)));\n\t\t\t\tthis.cells[column][row].draw();\n }\n }\n\t}",
"function random_start()\n {\n var random = Math.floor(Math.random()*(height*width));\n var two_four = random_two_four();\n $(\".empty:eq(\"+random+\")\").removeClass('empty').addClass(two_four);\n }",
"function load_next_planet() {\n gamer.planet.type = gamer.next.type;\n gamer.planet.assigned = false;\n gamer.planet.removed = false;\n gamer.planet.checked = false;\n gamer.planet.x = gamer.x;\n gamer.planet.y = gamer.y;\n\n var sun = random(1,100);\n if(sun <= 3) {\n gamer.next.type = planet_types.sun;\n } else if(gamer.available_planets <= 5) {\n var types = [];\n for(var j = 0; j < map.rows; j++) {\n for(var i = 0; i < map.columns; i++) {\n var planet = map.planets[i][j];\n if(planet.type >= planet_types.mercury\n && planet.type <= planet_types.saturn\n && !planet.removed\n && !planet.assigned) {\n types.push(planet.type);\n }\n }\n }\n gamer.next.type = types[Math.floor(Math.random() * types.length)];\n } else {\n gamer.next.type = random(1,6);\n }\n }",
"function createMob() {\n var rand = Math.random();\n var tear = 1;\n if (rand < 0.5) {\n tear = 1;\n } else if (rand < 0.8) {\n tear = 2;\n } else if (rand < 0.95) {\n tear = 3;\n } else {\n tear = 4;\n }\n enemy = new Monster(LEVEL, tear);\n updateMob();\n}",
"function randomThunder() {\r\n console.log('rayo');\r\n var rand = Math.floor(Math.random() * 120000) + 20000;\r\n thunder();\r\n setTimeout(function () {\r\n randomThunder();\r\n }, rand);\r\n }",
"function delay(){\n\tsetTimeout(makeShapeAppear, Math.random() * 2000);\n}",
"plantSeed() {\n\t\tthis.stop();\n\t\tthis.loops = 0;\n\t\tthis.myTree = new FractalTree({x: ground.width/2-100, y: ground.height-20}, this.myDNA);\n\t\tthis.settingsClose();\n\t\tthis.play();\n\t}",
"function createMazes(){\r\n //set the seed and let the user know what the seed is\r\n seed = Math.floor(Math.random() * (89898989898989898989 - 29898989898989898989 + 1)) + 29898989898989898989;\r\n document.getElementById(\"mazeSeed\").innerHTML = \"Seed used for mazes generated: \" + seed;\r\n\r\n //clear all the mazes\r\n clearMazes();\r\n\r\n //create and draw the recusive backtrack maze\r\n RBGenerate(0,0);\r\n RBDraw();\r\n primsGenerate(0,0);\r\n primsDraw();\r\n}",
"function randomColour() {\r\n pattern.push(colours[Math.floor(Math.random() * 4)]);\r\n animations(pattern);\r\n levelAndScoreCount();\r\n\r\n}",
"function diamond3() {\n return Math.floor(Math.random() * 11 + 1);\n }",
"function createMonsters(number) {\n for (let i = 0; i < number; i++) {\n monsterArray.push(new Obstacles(Math.random()*3 + 1))\n }\n //player must die\n setTimeout(() => {\n monsterArray.push(new Obstacles(Math.random()*3 + 1))\n }, 50000);\n}",
"function rotateTiles() {\n\t\tfor(var i = 0; i < tiles.length; i++){\n\t\t\tvar rotation = Math.random() * 360;\n\t\t\ttiles[i].setRotation(rotation);\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unregisters the listener for detecting an NFC peertopeer target. | function unsetPeerListener() {
if (!_security.unsetPeerListener) {
throw new WebAPIException(errorcode.SECURITY_ERR);
}
if (!powered || !_data.listener.onPeerDetected) {
return;
}
_data.listener.onPeerDetected = null;
} | [
"static detachListener(cb) {\n firebase.database().ref(BASE).off(\"value\", cb);\n }",
"disconnectedCallback() {\n super.disconnectedCallback();\n document.removeEventListener('incoming-custom-event', this.handleIncoming)\n }",
"undelegate(eventName, selector, listener, uid) {\n\n\t\tif (this.el){\n\t\t\tif (selector){\n\t\t\t\tconst items = [...this.el.querySelectorAll(selector)];\n\t\t\t\tif (items.length > 0 ) items.forEach((item) => item.removeEventListener(eventName, listener) );\n\t\t\t} else {\n\t\t\t\tthis.el.removeEventListener(eventName, listener);\n\t\t\t}\n\t\t}\n\t\t// remove event from array based on uid\n\t\t_.remove(this.delegatedEvents, (event) => {\n\t\t\treturn event.uid === uid;\n\t\t});\n\n\t\treturn this;\n\t}",
"removeConnectivityStateListener(listener) {\n this.stateListeners.delete(listener);\n }",
"function doHumanDetectFaceUnregister(serviceId, sessionKey) {\r\n\r\n dConnect.removeEventListener({\r\n profile: 'humandetection',\r\n attribute: 'onfacedetection',\r\n params: {\r\n serviceId: serviceId\r\n }\r\n }).catch(e => {\r\n alert(e.errorMessage);\r\n });\r\n}",
"function tiproxy_remove_fire_listener(e) {\r\n throw new Error(\"should not be called\");\r\n }",
"function nfcListen(enabled) {\n\t\tif (enabled) {\n\t\t\tnfc.ontagfound = function(event) {\n\t\t\t\treadOnAttach(event.tag);\n\t\t\t};\n\t\t\tnfc.ontaglost = function(event) {\n\t\t\t\toutLog.innerHTML += \"<br><b>Tag detached</b><hr>\";\n\t\t\t};\n\t\t\tnfc.onpeerfound = function(event) {\n\t\t\t\tpeerOnAttach(event.peer);\n\t\t\t};\n\t\t\tnfc.onpeerlost = function(event) {\n\t\t\t\toutLog.innerHTML += \"<br><b>Peer detached</b><hr>\";\n\t\t\t};\n\t\t\tnfc.startPoll().then(function() {\n\t\t\t\toutLog.innerHTML += \"<hr><b>Tag / Peer read listeners registered</b><hr>\";\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tnfc.ontagfound = null;\n\t\t\tnfc.ontaglost = null;\n\t\t\tnfc.onpeerfound = null;\n\t\t\tnfc.onpeerlost = null;\n\t\t\tnfc.stopPoll().then(function() {\n\t\t\t\toutLog.innerHTML += \"<hr><b>Tag / Peer read listeners removed</b><hr>\";\n\t\t\t});\n\t\t}\n\t}",
"unregisterListener(aListener) {\n let idx = this._listeners.indexOf(aListener);\n if (idx >= 0) {\n this._listeners.splice(idx, 1);\n }\n }",
"function removeListeners() {\n removeEventListener('pointerup', onPointerUp, listenerOpts);\n removeEventListener('pointercancel', onPointerCancel, listenerOpts);\n }",
"function offOnLostFocusListener(selector){\n\tselector.off(\"focusout\");\n}",
"static unbind(keys, classRef) {\n for (const key of keys) {\n for (const i in listeners[key]) {\n if (listeners[key][i] === classRef) {\n delete listeners[key][i]\n }\n }\n }\n }",
"function unbindFollowUnfollowButton(){\n var unfollowButtons = document.getElementsByClassName(\"unfollow\");\n var followButtons = document.getElementsByClassName(\"follow\");\n for(var x = 0; x < unfollowButtons.length; x++){\n unfollowButtons[x].removeEventListener(\"click\", unfollow);\n }\n for(var x = 0; x < followButtons.length; x++){\n followButtons[x].removeEventListener(\"click\", follow);\n\n }\n}",
"unregisterForecastUpdates (probe) {\n const refreshCallbackName = this.getRefreshCallbackName(probe)\n // Retrieve target elements\n const services = this.getElementServicesForProbe(probe)\n services.forEach(service => {\n // Unregister for forecast data update\n debug('Removing existing refresh callback for probe ' + probe._id.toString() + ' on element ' + service.forecast.name + '/' + service.element.name + ', registering')\n service.removeListener('created', service[refreshCallbackName])\n })\n }",
"_removeUserInputListeners() {\n if (!this._resumeContextCallback) {\n return;\n }\n\n USER_INPUT_EVENTS.forEach((eventName) => {\n window.removeEventListener(eventName, this._resumeContextCallback, false);\n });\n this._resumeContextCallback = null;\n }",
"removeEventListener(listener) {\n const index = this.listeners.indexOf(listener);\n\n if (index === -1) {\n throw new Error(\n \"Cannot remove an unknown listener. This listener has never been registered\"\n );\n }\n\n this.listeners.splice(index, 1);\n }",
"function detachHistoryListener() {\n window.removeEventListener('hashchange', onHashChange);\n}",
"function BACleanUpEventListeners() {\n\tif (BA_EVENTLISTENER_STORED_NODES) {\n\t\tBA_EVENTLISTENER_STORED_NODES.forEach(function(node) {\n\t\t\tfor (var type in node.__addEventListenerBA_stored__) {\n\t\t\t\tif (type != 'unload') {\n\t\t\t\t\tnode['on' + type] = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnode.__addEventListenerBA_stored__ = null;\n\t\t});\n\t}\n}",
"stopListening() {\n this._eventsNames.forEach((eventName) => {\n process.removeListener(eventName, this.handler);\n });\n }",
"onDeviceDiscovered(listener) {\n return this.createBluetoothEventSubscription(BluetoothEventType.DEVICE_DISCOVERED, listener);\n }",
"unregisterLoadCallback () {\n this.loadCallback = null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the given function throws the given value when invoked. The value may be: undefined, to merely assert there was a throw a constructor function, for comparing using instanceof a regular expression, to compare with the error message a string, to find in the error message | function functionThrows(fn, context, args, value) {
try {
fn.apply(context, args);
} catch (error) {
if (value == null) return true;
if (isFunction(value) && error instanceof value) return true;
var message = error.message || error;
if (typeof message === 'string') {
if (_isRegex2['default'](value) && value.test(error.message)) return true;
if (typeof value === 'string' && message.indexOf(value) !== -1) return true;
}
}
return false;
} | [
"function raises (fn, errorValidator) {\n\t verify(low.fn(fn), 'expected function that raises')\n\t try {\n\t fn()\n\t } catch (err) {\n\t if (typeof errorValidator === 'undefined') {\n\t return true\n\t }\n\t if (typeof errorValidator === 'function') {\n\t return errorValidator(err)\n\t }\n\t return false\n\t }\n\t // error has not been raised\n\t return false\n\t}",
"function ISFUNCTION(value) {\n return value && Object.prototype.toString.call(value) == '[object Function]';\n}",
"isFunctionOrBreed(value) {\n doCheck(\n value.constructor.name === \"Function\" || value.constructor === BreedType,\n \"Attempt to call a non-function\"\n );\n }",
"function ISERR(value) {\n return value !== error$2.na && value.constructor.name === 'Error' || typeof value === 'number' && (Number.isNaN(value) || !Number.isFinite(value));\n}",
"function assertion(value) {\n return expression.test(value)\n }",
"function notExistsOrErro(value, msg) {\n try {\n existsOrErro(value, msg)\n } catch (msg) {\n return\n }\n throw msg\n}",
"function ISERROR(value) {\n return ISERR(value) || value === error$2.na;\n}",
"function testTrace(name, fun, expected, unexpected) {\n var threw = false;\n try {\n fun();\n } catch (e) {\n for (var i = 0; i < expected.length; i++) {\n assertTrue(e.stack.indexOf(expected[i]) != -1,\n name + \" doesn't contain expected[\" + i + \"] stack = \" + e.stack);\n }\n if (unexpected) {\n for (var i = 0; i < unexpected.length; i++) {\n assertEquals(e.stack.indexOf(unexpected[i]), -1,\n name + \" contains unexpected[\" + i + \"]\");\n }\n }\n threw = true;\n }\n assertTrue(threw, name + \" didn't throw\");\n}",
"static isFailedFuncTrigger(result) {\n if (CommonUtil.isDict(result)) {\n for (const fid in result) {\n const funcResult = result[fid];\n if (CommonUtil.isFailedFuncResultCode(funcResult.code)) {\n return true;\n }\n if (!CommonUtil.isEmpty(funcResult.op_results)) {\n for (const opResult of Object.values(funcResult.op_results)) {\n if (CommonUtil.isFailedTx(opResult.result)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }",
"validate(value) {\n if (value < 0) throw new Error('Valor negativo para preço');\n }",
"function assert$c(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}",
"function assertNever(theValue) {\n throw new Error(\"Unhandled case for value: '\".concat(theValue, \"'\"));\n }",
"function isError(str){\n if(str.startsWith(\"Error: \")){\n return true;\n }\n return false;\n}",
"static checkCallbackFnOrThrow(callbackFn){if(!callbackFn){throw new ArgumentException('`callbackFn` is a required parameter, you cannot capture results without it.');}}",
"function TestCallThrow(callTrap) {\n var f = new Proxy(() => {\n ;\n }, {\n apply: callTrap\n });\n\n (() => f(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n }).x(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n })[\"x\"](11))();\n\n \"myexn\";\n\n (() => Function.prototype.call.call(f, {}, 2))();\n\n \"myexn\";\n\n (() => Function.prototype.apply.call(f, {}, [1]))();\n\n \"myexn\";\n var f = Object.freeze(new Proxy(() => {\n ;\n }, {\n apply: callTrap\n }));\n\n (() => f(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n }).x(11))();\n\n \"myexn\";\n\n (() => ({\n x: f\n })[\"x\"](11))();\n\n \"myexn\";\n\n (() => Function.prototype.call.call(f, {}, 2))();\n\n \"myexn\";\n\n (() => Function.prototype.apply.call(f, {}, [1]))();\n\n \"myexn\";\n}",
"function checkHandler(handler, functionName) {\n if (typeof handler !== 'function') throw new TypeError(functionName, 'requires a handler that is a function!');\n}",
"function isValidFunctionExpression(node) {\n if (node && node.type === 'FunctionExpression' && node.body) {\n return true;\n }\n return false;\n}",
"static isFioPublicKeyValid(fioPublicKey) {\n const validation = (0, validation_1.validate)({ fioPublicKey }, { fioPublicKey: validation_1.allRules.fioPublicKey });\n if (!validation.isValid) {\n throw new ValidationError_1.ValidationError(validation.errors);\n }\n return true;\n }",
"validate(value){\n if(validator.isEmpty(value)){\n throw new Error('Password cannot be empty buddy!')\n }\n if(value.toLowerCase().includes('password')){\n throw new Error('Password contains \"password\" buddy! Try something by your own!') \n }\n if(!validator.isByteLength(value,{min:7})){\n throw new Error('Password cannt have length less than 7,buddy!')\n }\n }",
"function callValidator(v, value) {\n if (is.Function(v)) {\n v(value)\n }\n else if (is.Function(v.__call__)) {\n v.__call__(value)\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether the button is checked. | get checked() {
return this.buttonToggleGroup ? this.buttonToggleGroup._isSelected(this) : this._checked;
} | [
"isItemChecked(item) {\n return this.composer.getItemPropertyValue(item, 'selected') === true;\n }",
"get defaultChecked() {\n return this.hasAttribute('checked');\n }",
"function checkCheckBox(cb){\r\n\treturn cb.checked;\r\n}",
"isTriggered() {\n return this.buttonClicked;\n }",
"hasButtonStateChanged( vButton ){\n if( VIRTUAL_BUTTONS_STATE[ vButton ] === VIRTUAL_BUTTONS_OLD_STATE[ vButton ] ) return false;\n else return true;\n }",
"async hasToggleIndicator() {\n return (await this._expansionIndicator()) !== null;\n }",
"function alert_state() {\n var cb = document.getElementById('add_marker_CBX');\n \n console.log(cb.checked);\n}",
"function agree_check()\n{\n var acceptButton = findObject(\"buttonAccept\");\n SetEnabled(acceptButton, document.cbAgree.checked);\n}",
"toggle() {\n if (this.isChecked()) {\n this.unCheck();\n\n } else {\n this.check()\n }\n }",
"function anyRadioButtonsUnchecked()\n{\n\tvar traceChecked = radChecked(\"#traceYes\") || radChecked(\"#traceNo\");\n\tvar handChecked = radChecked(\"#chooseLeft\") || radChecked(\"#chooseRight\");\n\t\n\treturn traceChecked == false || handChecked == false;\n}",
"isSet() {\n return this._isSet === true;\n }",
"function CheckSubscriptionOptions() {\r\n if (!document.getElementById(\"subscribeNewsletter\").checked && !document.getElementById(\"subscribeBreakingNews\").checked) {\r\n return false;\r\n } else {\r\n return true;\r\n }\r\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 }",
"async getCheckedStatus() {\r\n let dxpRadioGroups = this.element.querySelector(RADIO_BTN) ? this.element.querySelectorAll(RADIO_BTN) : this.element.querySelectorAll(RADIO_BTN);\r\n this.showError = this.radioSelect ? (this.required ? !this.radioSelect.isChecked : false) : this.required;\r\n dxpRadioGroups = Array.from(dxpRadioGroups);\r\n if (dxpRadioGroups.length > 0) {\r\n if (this.showError) {\r\n for (const dxpRadioButton of dxpRadioGroups) {\r\n dxpRadioButton.setAttribute('show-error', this.showError);\r\n dxpRadioButton.querySelector('label').setAttribute('class', 'dxp-error');\r\n }\r\n }\r\n else {\r\n for (const dxpRadioButton of dxpRadioGroups) {\r\n dxpRadioButton.setAttribute('show-error', this.showError);\r\n dxpRadioButton.querySelector('label').removeAttribute('class');\r\n }\r\n }\r\n }\r\n }",
"function handleCheck(e) {\n\t\tsetIsComplete(e.target.checked)\n\t}",
"'click .toggle-checked'() {\n\t\tlet checked = {\n\t\t\ttaskId: \tthis._id,\n\t\t\tsetChecked: !this.checked,\n\t\t};\n\t\tMeteor.call('tasks.setChecked', checked, (error, result) => {\n\t\t\tif (result === false)\n\t\t\t\tBert.alert( 'Good job, task done!', 'default', 'growl-top-right' );\n\t\t});\n\t}",
"function isOneBoxChecked(list) {\n for (let i = 0; i < list.length; i++) {\n if (list[i].firstElementChild.checked) {\n return true;\n }\n }\n return false;\n}",
"isSelected() {\n return this.selected;\n }",
"getClearButtonStatus() {\n let buttonEnabled = false;\n\n for (var i = 0; i < this._clearEls.length; i++) {\n if (hasClass(this._clearEls[i], 'spark-filter-module__clear--hidden') || hasClass(this._clearEls[i], 'spark-filter-module__clear--disabled')) {\n buttonEnabled = false;\n }\n else {\n buttonEnabled = true;\n }\n }\n\n return buttonEnabled;\n }",
"function isChecked(elementValue) {\n return $(\"[value='\" + elementValue + \"']\").prop(\"checked\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A searchable list of journal entries | function JournalEntryList(elementId, entries, filterCallback = () => {
}) {
// The element Id containing the list
this.elementId = elementId;
// The list of journal entries
this.entries = entries.slice();
this.entries.sort();
this.entries.reverse();
// The list entries currently displayed
this.resultSet = this.entries.slice();
// The containing element for this searchable list
const elem = document.getElementById(elementId);
// The earliest timestamp in the list
const minTimestamp = Math.min(...entries.map((entry) => {
return entry.properties.timestamp;
}));
// The most recent timestamp in the list
const maxTimestamp = Math.max(...entries.map((entry) => {
return entry.properties.timestamp;
}));
// The search bar
elem.innerHTML = `<div id="journal-search-bar">
<form id="journal-search-form" class="inline-searchbar">
<div style="width: 50%; display: inline-flex;">
<label for="journal-search-text" class="sr-only">Search</label>
<input type="text" name="search-text" id="journal-search-text" class="form-control inline-searchbar-item journal-form-input" autocomplete="off">
</div>
<div style="width: 50%; display: inline-flex;">
<label for="journal-search-after" class="sr-only">After</label>
<input type="date" name="after" id="journal-search-after" class="form-control inline-searchbar-item journal-form-input">
<label for="journal-search-before" class="sr-only">Before</label>
<input type="date" name="before" id="journal-search-before" class="form-control inline-searchbar-item journal-form-input">
</div>
<div style="width: 100%; display: inline-flex;">
<label for="sentiment-slider" class="sr-only">Sentiment Slider</label>
<input type="range" name="sentiment-slider" id="sentiment-slider" class="form-control inline-searchbar-item journal-form-input transparentButton" min="0.0" max="1.0" step="0.01">
<div class="form-group">
<div class="checkbox">
<label for="sentiment-toggle" class="">
<input type="checkbox" name="sentiment-toggle" id="sentiment-toggle" class="inline-searchbar-item journal-form-toggle transparentButton">
</label>
</div>
</div>
<label for="timeline-slider" class="sr-only">Sentiment Slider</label>
<input type="range" name="timeline-slider" id="timeline-slider" class="form-control inline-searchbar-item journal-form-input transparentButton" min="0.0" max="1.0" step="0.01">
<div class="checkbox form-group">
<label for="timeline-toggle" class="">
<input type="checkbox" name="timeline-toggle" id="timeline-toggle" class="form-check-input inline-searchbar-item journal-form-toggle transparentButton">
</label>
</div>
</div>
</form>
</div>`;
/**
* Add a new entry to the list
*
* @param entry
*/
this.add = (entry) => {
// TODO: There is the issue of whether the new entry satisfies the current filter
const dc = JSON.parse(JSON.stringify(entry));
this.entries.unshift(dc);
this.resultSet.unshift(dc);
};
/**
* Display the entry list in its current state
*/
this.display = () => {
// Clear the container before displaying
entryContainer.innerHTML = "";
let entryHtml = this.resultSet.map((entry) => {
return `<div class='journal-entry-text partialBorder centerTextContent' id="${entry.properties.id}">
<p class="inferredSubjectList">${entry.properties.inferredSubjects.join(", ").replace(new RegExp("_", "g"), " ")}</p>
<p>${entry.properties.text}</p>
<div class="journal-entry-control-bar">
<form class="journal-publicity-form control-bar-item">
<input type="text" name="id" value="${entry.properties.id}" hidden>
<input type="text" name="public" value="${!entry.properties.public}" hidden>
<button type="submit" class="transparentButton" style="color: ${entry.properties.public ? "#78A4FF" : "#707073"};"><i class="fa fa-users"></i></button>
</form>
<form class="journal-delete-form control-bar-item">
<input type="text" name="id" value="${entry.properties.id}" hidden>
<button type="submit" class="transparentButton journal-delete-button"><i class="fa fa-trash"></i></button>
</form>
<div class="journalEntryTimestamp control-bar-item">${moment(entry.properties.timestamp).format('YYYY-MM-DD HH:mm')}</div>
</div>
</div>`;
});
entryContainer.innerHTML = entryHtml.join("");
// Get a reference to the current JournalEntryList object
let self = this;
// Handler for deletion
$('.journal-delete-form').submit(function (e) {
// Prevent the form from clearing
e.preventDefault();
if (confirm("Delete this entry forever?")) {
// Submit the form asynchronously
$.ajax({
method: "post",
url: "/journal/delete",
data: $(this).serialize(),
dataType: "json",
success: (responseData, textStatus, jqXHR) => {
if (responseData.payload) {
self.remove(responseData.payload);
}
}
});
}
});
// Handler for publicity setting
$('.journal-publicity-form').submit(function (e) {
// Prevent the form from clearing
e.preventDefault();
if (confirm("Change the publicity of this entry?")) {
// Submit the form asynchronously
$.ajax({
method: "post",
url: "/journal/publicity",
data: $(this).serialize(),
dataType: "json",
success: (responseData, textStatus, jqXHR) => {
if (responseData['success'] === true) {
console.log(responseData);
// TODO: change publicity on front-end
}
}
});
}
});
};
/**
* Remove an entry from the list
*
* @param entry_id
*/
this.remove = function (entry_id) {
// Remove element from page
document.getElementById(entry_id).remove();
// Remove element from entry list
this.entries = this.entries.filter((entry) => {
return entry.properties.id !== entry_id;
});
// Remove element from result set
this.resultSet = this.resultSet.filter((entry) => {
return entry.properties.id !== entry_id;
});
};
/**
* Sort the entries by timestamp
*
* @param oldestFirst
*/
this.sort = function (oldestFirst = false) {
const factor = (oldestFirst === true) ? -1 : 1;
this.resultSet.sort((a, b) => {
return factor * Math.sign(b.properties.timestamp - a.properties.timestamp);
});
};
/**
* Find all entries containing a search term
*
* @param rawSearchTerm
*/
const _filterText = (rawSearchTerm) => {
// Ignore case when searching
const searchTerm = rawSearchTerm.toLowerCase();
this.resultSet = this.resultSet.filter(function (elem) {
return elem.properties.text.toLowerCase().includes(searchTerm);
});
// Highlight the search term wherever it is found
this.resultSet.forEach((elem) => {
elem.properties.text = elem.properties.text.replace(new RegExp(searchTerm, 'i'), "<span class='search-highlight'>$&</span>")
})
};
/**
* Filter journal entries by date
*
* @param from
* @param to
* @private
*/
const _filterDates = (from, to) => {
this.resultSet = this.resultSet.filter((elem) => {
return from <= elem.properties.timestamp && elem.properties.timestamp <= to;
});
};
/**
* Find all entries near the given coordinates
*
* @param coords The position to compare against
* @param radius The radius of inclusion
*/
const _filterNear = (coords, radius) => {
this.resultSet = this.resultSet.filter(function (elem) {
return distance(coords[0], coords[1], elem.geometry.coordinates[0], elem.geometry.coordinates[1]) < radius;
});
};
const passesFilter = (entry, formData) => {
let passes = true;
formData.forEach((field) => {
if (field.name === 'search-text') {
}
});
return passes;
};
/**
* Filter the journal entries according to the filter form
*
* TODO: There is a visual bug caused by map circles being redrawn after they are sorted.
*
* TODO: Refactor so that the entry list is only iterated over once
*
* @param formData
*/
this.filter = (formData) => {
// Start with a clean result set - deep copy
this.resultSet = this.entries.map((entry) => {
return JSON.parse(JSON.stringify(entry));
});
let sentimentToggle = false;
let sentimentSlider = 0.5;
const sentimentRadius = 0.2;
let timelineToggle = false;
let timelineSlider = 0.5;
const timelineRadius = 0.2;
let afterToggle = false;
let afterDate = 0;
let beforeToggle = false;
let beforeDate = (new Date()).getTime();
// Apply each of the filters specified in the form
formData.forEach((field) => {
// Substring search of entry text
if (field['name'] === 'search-text') {
_filterText(field['value']);
}
// Proximity search
else if (field['name'] === 'near-me') {
_filterNear([0, 0], 100)
}
// Find entries older than
else if (field['name'] === 'after') {
if (field['value'] !== "") {
afterToggle = true;
afterDate = (new Date(field['value'])).getTime();
}
}
// Find entries younger than
else if (field['name'] === 'before') {
if (field['value'] !== "") {
beforeToggle = true;
beforeDate = (new Date(field['value'])).getTime();
}
}
// Record that the sentiment slider should be used
else if (field['name'] === 'sentiment-toggle' && field['value'] === 'on') {
sentimentToggle = true;
}
// Get the value of the sentiment slider
else if (field['name'] === 'sentiment-slider') {
sentimentSlider = field['value'];
}
// Record that the timeline slider should be used
else if (field['name'] === 'timeline-toggle' && field['value'] === 'on') {
timelineToggle = true;
}
// Get the value of the timeline slider
else if (field['name'] === 'timeline-slider') {
timelineSlider = field['value'];
}
});
// Filter the entries by the search criteria
this.resultSet = this.resultSet.filter((entry) => {
// Filter by sentiment value
if (sentimentToggle === true) {
if (Math.abs(sentimentSlider - entry.properties.sentiment) > sentimentRadius) {
return false;
}
}
// Filter by timeline value
if (timelineToggle === true) {
if (Math.abs(timelineSlider - ((entry.properties.timestamp - minTimestamp) / (maxTimestamp - minTimestamp))) > timelineRadius) {
return false;
}
}
if (afterToggle === true) {
if (entry.properties.timestamp < afterDate) {
return false;
}
}
if (beforeToggle === true) {
if (entry.properties.timestamp > beforeDate) {
return false;
}
}
// The entry didn't fail any filter test. Include it in the result set
return true;
});
// Pass the updated result set to the callback
filterCallback(this.resultSet);
};
// The containing element for the list
const entryContainer = document.createElement('div');
elem.append(entryContainer);
// Handlers for checkboxes
$('.journal-form-toggle').on('change', () => {
const formData = $('#journal-search-form').serializeArray();
this.filter(formData);
this.sort();
this.display();
});
// Handlers for other inputs
$('.journal-form-input').on('input', () => {
const formData = $('#journal-search-form').serializeArray();
this.filter(formData);
this.sort();
this.display();
});
$('#journal-search-form').submit((event) => {
event.preventDefault();
});
// The initial display
this.sort();
this.display();
} | [
"function EntryList() { }",
"getJournals() {\n console.log(\"fetching journals\")\n API.getJournalEntries().then(parsedJournals => {\n displayJournals(parsedJournals);\n })\n }",
"function entries() {\n var each = function each(callback) {\n for (var i = 0; i < this.length; i++) {\n callback(this[i]);\n }\n };\n\n var els = this.elsByTag('entry');\n els.each = each;\n return els;\n}",
"function makeDiaryItemList(journalEntries, newEntry, entryDate, subject) {\n \n var d = new Date(); //current time\n var entryId = d.getTime(); // current time in milliseconds\n console.log(entryId);\n var entryTexts = journalEntries;\n var subject = subject;\n\n var newEntryText = { \"date\": entryDate, \"subject\": subject, \"diaryText\": newEntry, \"textID\": entryId };\n entryTexts.push(newEntryText); //new entry is pushed to an array of old entries\n\n return entryTexts;\n}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'list', kparams);\n\t}",
"'entries.get' (entryId) {\n console.log('get text for entry');\n\n // If no user is logged in, throw an error\n if (!Meteor.user()) {\n console.log(\"No user is logged in!\");\n throw Error(\"User is not logged in\");\n }\n \n // Locate the entry\n let entry = JournalEntryCollection.findOne({_id: entryId});\n\n // If no entry exists, the logged in user can't access it\n if (!entry) {\n console.log(`entry with ID ${entryId} wasn't found`);\n throw Error(\"Unable to find entry with given ID\");\n }\n\n console.log(`Entry found: ${entry._id}, ${entry.text}`);\n\n // If the entry's owner is not the logged in user, they\n // can't access it\n if (entry.ownerId != Meteor.userId()) {\n console.log(`This entry belongs to ${entry.ownerId} but the logged in user is ${Meteor.userId()}`);\n throw Error(\"Logged in user does not have permission to view this entry\");\n }\n\n // The entry exists and the logged in user is the owner,\n // so they can access it\n return entry;\n }",
"getAllEntries() {\n //return a Promise object, which can be resolved or rejected\n return new Promise((resolve, reject) => {\n //use the find() function of the database to get the data, \n //with error first callback function, err for error, entries for data\n this.db.find({}, function(err, entries) {\n //if error occurs reject Promise\n if (err) {\n reject(err);\n //if no error resolve the promise and return the data\n } else {\n resolve(entries);\n //to see what the returned data looks like\n console.log('function all() returns: ', entries);\n }\n })\n })\n }",
"function BlogObj(SEARCH_PATH) {\n var articles = []\n , ARTICLES_PATH = SEARCH_PATH;\n \n /**\n * Clear the list of articles\n * @method clearArticles\n */\n this.clearArticles = function () {\n articles = [];\n \n return this;\n }\n /**\n * Returns the number of articles currenty cached\n * @method count\n */\n this.count = function() {\n return articles.length;\n }\n /**\n * Checks whether an article with the specified slug exists\n * @method hasArticle\n */\n this.hasArticle = function(slug) {\n for (var i=0; i < articles.length; i++) {\n if (articles[i].slug === slug) {\n return true;\n }\n }\n return false;\n }\n /**\n * Returns an article with the specified slug if it exists\n * @method getArticle\n */\n this.getArticle = function(slug) {\n for (var i=0; i < articles.length; i++) {\n if (articles[i].slug === slug) {\n return articles[i];\n }\n }\n }\n /**\n * Returns an array of all articles\n * @method getArticles\n */\n this.getArticles = function() {\n return articles;\n }\n /**\n * Returns the latest article added to the list\n * if the list contains at least one article\n * @method getLatest\n */\n this.getLatest = function() {\n if (articles.length > 0) {\n return articles[0];\n }\n return [];\n }\n /**\n * Adds an article to the article list\n * @method addArticle\n */\n this.addArticle = function(article) {\n articles.push(article);\n \n articles.sort(dSort);\n \n return this;\n }\n /**\n * Used internally to sort the article array\n * based on the date of an article (newest first)\n */\n var dSort = function(a,b) {\n if (a.date > b.date) return -1;\n if (a.date < b.date) return 1;\n }\n \n /**\n * Used internally to walk through the specified filesystem directory\n * where the .md-articles are located. Parses each article to HTML and\n * extracts title, slug, author, date.\n * Only adds articles that has the published flag set to true\n */\n var parseArticles = function() {\n console.log(\"*** Parsing Articles ***\");\n \n // matches files w/ file extension .md\n var is_md = /.(\\.md)$/\n , that = this; \n \n fs.readdir(ARTICLES_PATH, function(err, files) {\n if (err) { throw err; };\n\n that.clearArticles();\n\n files.forEach(function(file) {\n if (is_md.test(file)) {\n fs.readFile(ARTICLES_PATH+file, 'utf8', function (err, data) {\n if (err) { throw err; }\n \n // Lets read the data and parse the first line\n var first_line = /^(?:(.+)(?:\\n|\\r|\\r\\n)+)/ ;\n var match = first_line.exec(data); \n var head = match[1].split('||');\n\n (function(head, match) {\n var publish = UTILS.parseBool(head[3]);\n \n // Only collect articles that are published\n if (publish) {\n that.addArticle({\n slug: UTILS.slugify(head[0])\n , title: head[0]\n , author: head[1]\n , date: new Date(Date.parse(head[2]))\n , body: UTILS.getHTML(data.replace(match[0], ''))\n });\n } \n }(head, match));\n });\n }\n });\n });\n }\n \n /**\n * Updates the list of articles by calling parseArticles\n * @method update\n */\n this.update = function() {\n parseArticles.call(this);\n \n return this;\n }\n}",
"function findUsersEntries(jsonContents, user) {\n var writerFound = false;\n var emptyArray = [];\n\n for (var indeksi in jsonContents) {\n\n if (jsonContents[indeksi].name == user) { //if writer was found from data.json\n writerFound = true;\n var oldJournalEntries = jsonContents[indeksi].diaryItemList;\n return oldJournalEntries; //returns writers old diary entries as an array\n }\n }\n\n if (!writerFound) {\n return emptyArray;\n }\n}",
"function search(length, a, noteList, input) {\n times++;\n if (length === 0) {\n a.push(noteList);\n return;\n } else {\n for (var i = 0; i < allNextNotes(input, noteList).length; i++) {\n \n var note = allNextNotes(input, noteList)[i];\n \n if (isGood(input, noteList, allNextNotes(input, noteList)[i])) {\n var copy = [];\n for (var j = 0; j < noteList.length; j++) {\n var data = noteList[j];\n copy.push(data);\n }\n copy.push(note);\n search(length - 1, a, copy, input);\n }\n }\n }\n}",
"function searchJobs(searchQuery, jobList){\n//used to assist GET /jobs/search/:search\n return jobList.filter( x => x.title.includes(searchJobs) || x.company_id.includes(searchQuery) || x.skills.includes(searchQuery) )\n}",
"static list(collection, filter={}) {\n return db.db.allDocs({include_docs: true});\n }",
"function list(root, predicate = TRUE_PREDICATE) {\n debugging.assert(typeof predicate === 'function',\n 'Predicate must be a function');\n\n return new Promise((resolve, reject) => {\n var entities = [];\n var walker = walk.walk(root, { followLinks: false });\n\n walker.on('directory', function (root, stat, next) {\n // Add this directory to the list of entities\n var dirname = path.join(root, stat.name);\n if (predicate(dirname, 'directory')) {\n entities.push(dirname);\n }\n next();\n });\n\n walker.on('file', function (root, stat, next) {\n // Add this file to the list of entities\n var filename = path.join(root, stat.name);\n if (predicate(filename, 'file')) {\n entities.push(filename);\n }\n next();\n });\n\n walker.on('end', () => resolve(entities));\n });\n}",
"function findAllBy(filter) {\n return db('marks')\n .where(filter)\n .select();\n}",
"function processEntries(response) {\n\t\tfor (i=0; i<response[1].length; i++) {\n\t\t\tvar title = response[1][i];\n\t\t\tvar description = response[2][i];\n\t\t\tvar link = response[3][i];\n\t\t\t//creates new object with current article title, desc and link\n\t\t\tvar thisArticle = new createEntry(title, description, link);\n\t\t\t//passes current article object to be added to DIV\n\t\t\tappendEntry(thisArticle, link);\n\t\t}\n\n\t\tif (response[1].length >= 1) {\n\t\t\tendSearch();\n\t\t}\n\t}",
"function showEntry(list, type, title, amount, id){\n const entry = `<li id = \"${id}\" class = \"${type}\">\n <div class = \"entry\">${title}: $${amount} </div>\n <div id = \"edit\"></div>\n <div id = \"delete\"></div>\n </li>`;\n // make the newest entries appear at the top of list\n const position = \"afterbegin\";\n list.insertAdjacentHTML(position,entry);\n }",
"function insertJournalEntry(doc) {\n var html = '';\n html += '<tr name=\"journal_entry_metadata\" class=\"row-vm journal_view_header\" data-id=\"' + doc._id + '\">';\n html += '<td>' + ++glob_journal_counter + '</td>';\n html += '<td>' + escapeHtml(doc.author) + '</td>';\n html += '<td>' + wordwrap(escapeHtml(doc.subject), 60, '<br />', 1) + '</td>';\n html += '<td>' + moment(doc.event_time).format('YYYY/MM/DD HH:mm:ss ZZ') + '</td>';\n html += '<td title=\"' + doc.classification + '\">' + classReplacement(doc.classification) + '</td>';\n html += '<td> </td>'; // Here comes the number of comments\n html += '<td> </td>'; // Here comes the number of actions\n html += '<td title=\"YYYY-MM-DD HH:MM:SS TZ (Difference from external and local time)\" nowrap>' + moment(doc.added_timestamp_local).format('YYYY/MM/DD HH:mm:ss ZZ');\n \n // If the doc doesn't have Internet time, then we display \"N/A\" in the offset\n if (doc.added_timestamp_external) {\n offset = getTimeOffset(doc.added_timestamp_external, doc.added_timestamp_local);\n html += ' (' + (offset >= 0? '+' :'') + Math.round(offset / 1000) + ')';\n } else {\n html += ' (N/A)';\n }\n \n html += '</td>';\n html += '</tr>';\n html += '<tr name=\"journal_entry_content\" class=\"row-details expand-child\" data-id=\"' + doc._id + '\">';\n html += '<td class=\"journal_view_content\" colspan=\"8\">' + wordwrap(doc.content, 120, '<br />', 1);\n \n if (doc.keywords) {\n html += ' <span class=\"keywords\">(' + escapeHtml(doc.keywords) + ')</span>';\n }\n \n html += '</td>';\n html += '</tr>';\n html += '<tr name=\"journal_entry_appendices\" class=\"expand-child\" data-id=\"' + doc._id + '\">';\n html += '<td data-id=\"' + doc._id + '\" colspan=\"8\" style=\"border: 0px;\">';\n \n // Appendix table\n html += '<table name=\"table_appendix\" data-id=\"' + doc._id + '\" style=\"display:none;\" class=\"tablesorter-child\">';\n html += '<thead>';\n html += '<tr>';\n html += '<th><span>Author</span></th>';\n html += '<th><span>Comment</span></th>';\n html += '<th><span>Marked solved by</span></td>';\n html += '<th><span>Attachment / Deadline</span></th>';\n html += '<th><span>Added Time (Offset)</span></th>';\n html += '<th>Goto</th>';\n html += '</tr>';\n html += '</thead>';\n html += '<tbody>';\n html += '</tbody>';\n html += '</table>';\n\n html += '</td>';\n html += '</tr>';\n html += '<tr name=\"journal_entry_appendix_form\" class=\"row-details expand-child\" data-id=\"' + doc._id + '\">';\n html += '<td name=\"appendix_form\" data-id=\"' + doc._id + '\" colspan=\"8\">';\n \n // Appendix submission form\n html += '<table name=\"table_appendix_form\" data-id=\"' + doc._id + '\" style=\"margin-top:20px; display:none;\">';\n html += '<tr>';\n html += '<td>';\n html += '<form class=\"add_appendix\" id=\"' + doc._id + '\" method=\"post\" action=\"\" enctype=\"multipart/form-data\">';\n html += '<input id=\"add_appendix_refers_to\" type=\"hidden\" value=\"' + doc._id + '\" />';\n html += '<select id=\"add_appendix_type\" data-id=\"' + doc._id + '\">';\n html += '<option value=\"comment\" default>Comment</option>';\n html += '<option value=\"action\">Action</option>';\n html += '</select><br />';\n html += '<div class=\"row\">';\n html += '<div style=\"float:left;\" class=\"col-md-4\">';\n html += '<textarea id=\"add_appendix_cont\" style=\"resize: vertical;\" cols=\"80\" rows=\"4\" class=\"form-control\" placeholder=\"Content\"></textarea>';\n html += '</div>';\n html += '<input id=\"_id\" name=\"_id\" type=\"hidden\" />';\n html += '<input id=\"_rev\" name=\"_rev\" type=\"hidden\" />';\n html += '<input id=\"_db\" name=\"_db\" type=\"hidden\" value=\"journal\" />';\n \n html += '<div name=\"add_appendix_type_action\" style=\"display:none;\" class=\"col-md-4\" data-id=\"' + doc._id + '\">';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-addon\">Add a deadline</span>';\n html += '<input id=\"add_appendix_deadline\" placeholder=\"yyyy/mm/dd hh:mm:ss\" type=\"text\" class=\"form-control\" size=\"33\" />';\n html += '</div>';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-addon\">Who is responsible</span>';\n html += '<input id=\"add_appendix_responsible\" placeholder=\"Username, real name, role etc\" size=\"33\" type=\"text\" class=\"form-control\" />';\n html += '</div>';\n html += '</div>';\n \n html += '<div name=\"add_appendix_type_comment\" class=\"col-md-4\" data-id=\"' + doc._id + '\">';\n html += '<span class=\"label label-secondary\">Upload file or use filed copy</span>';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-btn\">';\n html += '<span class=\"btn btn-secondary btn-file\">';\n html += 'Browse… <input id=\"_attachments\" name=\"_attachments\" type=\"file\" class=\"form-control\" style=\"width:100%;\" />';\n html += '</span>';\n html += '</span>';\n html += '<input id=\"add_attachment_filename_label\" type=\"text\" class=\"form-control\" readonly>';\n html += '</div>';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-addon\">Filed copy</span>';\n html += '<span class=\"input-group-addon\"><input id=\"add_appendix_use_filed_copy\" type=\"checkbox\"/></span>';\n html += '<input id=\"add_appendix_filed_copy\" type=\"text\" value=\"' + randStr(5) + '\" size=\"28\" readonly class=\"text-center form-control\"/>';\n html += '</div>';\n html += '</div>';\n \n html += '<div style=\"float:left; padding-left:3%;\">';\n html += '<input name=\"appendix_submit_button\" type=\"submit\" class=\"btn btn-secondary\" class=\"Submit\" value=\"Add comment\" data-id=\"' + doc._id + '\"/>';\n html += '</div>';\n\n html += '</div>';\n html += '</form>';\n html += '</td>';\n html += '</tr>';\n html += '</table>';\n \n html += '</td>';\n html += '</tr>';\n $('#table_journal > tbody').append(html);\n}",
"searchDocuments() {\n\n let searchObj = {}\n if (this.searchType === 'query') {\n searchObj.query = this.query;\n } else if (this.searchType === 'field') {\n searchObj.fieldCode = this.queryField;\n searchObj.fieldValue = this.queryFieldValue;\n }\n this.etrieveViewer.Etrieve.searchDocuments(searchObj)\n .catch(err => {\n console.error(err);\n });\n }",
"function GetTitleArchive(search_params) {\n return $http.get('/api/public/articles/titles/archive?'+search_params.textsearch+'&'+search_params.username).then(handleSuccess, handleError('Error getting titles'));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
class ChatWindow encapsulates the data and methods required to display chat messages and notifications, and to process the user events generated for a specific chat channel | function ChatWindow(channelName,chatClient) {
var self= this;
self._channel = channelName;
self._client = chatClient;
self._players = {};
//set up the main chat area
self._chatWindow = $('<div class="ChatWindow"></div>');
//setup the chat log area
self._chatLogContainer = $('<div class="Log">Chat Channel:' + self._channel + '<br /></div>');
self._chatLogContainer.append('<div class="LogMessages"></div>');
self._chatLogWindow = $('<div></div>');
self._chatLogContainer.find('.LogMessages').append(self._chatLogWindow);
self._chatWindow.append(self._chatLogContainer);
//setup the player list
self._chatPlayerListWindow = $('<div class="Players">Current players:</div>');
self._chatPlayerList = $('<ul></ul>');
self._chatPlayerListWindow.append(self._chatPlayerList);
self._chatWindow.append(self._chatPlayerListWindow);
//setup the chat input line
self._chatInputArea = $('<div class="chatInput"></div>');
self._chatInput = $('<input name="messageText"></input>');
self._chatInput.keyup(function (e) {
if(e.which == 13)
{
self.sendMessage();
}
});
self._chatSaySomethingButton = $('<input type="button" value="Say Something" class="ChatButton"></input>');
self._chatSaySomethingButton.click(function(){self.sendMessage();});
self._chatInputArea.append(self._chatInput);
self._chatInputArea.append(self._chatSaySomethingButton);
self._chatLogContainer.append(self._chatInputArea);
//process the new player event
self.NewPlayer = function (player) {
self._players[player] = player;
self._chatLogWindow.append( player + " has joined the fun<br />");
self._chatPlayerList.append('<li name=' + player + '>' + player + '</li>');
};
//process the remove player event
self.RemovePlayer = function (player) {
self._players[player] = null;
self._chatPlayerList.find('[name="' + player +'"]').remove();
};
//process the new chat message event
self.NewMessage = function (message) {
self._chatLogWindow.append(message.player + ": " + message.message + "<br/>");
self._chatLogWindow.prop({ scrollTop: self._chatLogWindow.prop("scrollHeight") });
};
//send a new chat message
self.sendMessage = function (messageText) {
if (messageText === undefined){
messageText = self._chatInput.val();
}
var message = new chatMessage(self._channel,messageText);
self._client.SendMessage(message);
self._chatInput.val("");
};
//process the welcome event when joining a channel
self.Welcome = function (playerlist) {
for (var i=0;i< playerlist.length;i++) {
self._chatPlayerList.append('<li name=' + playerlist[i] + '>' + playerlist[i] + '</li>');
}
};
//add the chat window to the DOM, and make sure the current player is in the player list
self.NewPlayer(self._client._me.name());
$('#chat').append(self._chatWindow);
return true;
} | [
"function ChatBoxWindow( userObject, parentElement )\n{\n\t/** private variables **/\n\t\n\tvar myUser = userObject;\n\tvar windowElement = null;\n\tvar chatBoxContentElement = null;\n\tvar chatBoxBufferTextInputElement = null;\n\tvar listenerList = new Array( );\n\tvar selfReference = this;\n\t\n\t/** methods **/\n\t\n\t/**\n\t * This function registers the specified listener with this chat box window.\n\t * @param listener The listener to register.\n\t * @return void \n\t */\n\tChatBoxWindow.prototype.registerListener = this.registerListener = function( listener )\n\t{\n\t\tlistenerList.push( listener );\n\t};\n\t\n\t/**\n\t * This function unregisters the specified listener from this chat box window.\n\t * @param listener The listener to be unregistered.\n\t * @return void\n\t */\n\tChatBoxWindow.prototype.unregisterListener = this.unregisterListener = function( listener )\n\t{\n\t\tvar index = listenerList.indexOf( listener );\n\t\tif ( index >= 0 )\n\t\t{\n\t\t\tlistenerList.splice( index, 1 );\n\t\t}\n\t};\n\t\n\t/**\n\t * This function returns the user object associated with this window.\n\t * @return The user object associated with this window.\n\t */\n\tChatBoxWindow.prototype.getUserObject = this.getUserObject = function( )\n\t{\n\t\treturn myUser;\n\t};\n\t\n\t/**\n\t * This private function notifies all registered listeners that a message is being sent from this chat box window.\n\t * @param message The message to be sent.\n\t * @return void\n\t */\n\tfunction notifyListenersMessageSend( message )\n\t{\n\t\tvar listenerListIterator = new ArrayIterator( listenerList );\n\t\twhile( listenerListIterator.hasNext( ) )\n\t\t{\n\t\t\tvar listener = listenerListIterator.next( );\n\t\t\tlistener.notifyChatBoxMessageSend( selfReference, message );\n\t\t}\n\t}\n\t\n\t/**\n\t * This private function notifies all registered listeners that this chat box window has closed.\n\t * @return void\n\t */\n\tfunction notifyListenersClose( )\n\t{\n\t\tvar listenerListIterator = new ArrayIterator( listenerList );\n\t\twhile( listenerListIterator.hasNext( ) )\n\t\t{\n\t\t\tvar listener = listenerListIterator.next( );\n\t\t\tlistener.notifyChatBoxWindowClosed( selfReference );\n\t\t}\n\t}\n\t\n\t/**\n\t * This private function closes this chat box window causing it to be removed from it's parent element.\n\t * @return void\n\t */\n\tfunction close( )\n\t{\n\t\t// remove the window element from it's parent\n\t\twindowElement.remove( );\n\t\t// notify listeners of this window closing\n\t\tnotifyListenersClose( );\n\t\t\n\t\tmyUser.unregisterListener( selfReference );\n\t}\n\t\n\t/**\n\t * This function process's the specified message. It will update the chat box content div.\n\t * @param sender If the specified message is a user sent message, this is the user object whom the message originated from.\n\t * Otherwise, specify a value of null.\n\t * @param string message The message to process.\n\t * @param messageType The type of message being processed.\n\t * @return void\n\t */\n\tfunction processMessage( sender, message, messageType )\n\t{\t\n\t\t// prepare the new p element container for the message\n\t\tvar newMessageContainer = $( \"<p></p>\" );\n\t\t\n\t\t// if the message is a system message\n\t\tif ( messageType == ChatBoxWindow.MESSAGE_TYPE_SYSTEM )\n\t\t{\n\t\t\t// prepare the message span, and apply the .chatBoxContentSystemMessageText style to it\n\t\t\tvar messageSpan = $( \"<span></span>\", { class: \"chatBoxContentSystemMessageText\" } );\n\t\t\t// append the message to the message span\n\t\t\t$( messageSpan ).append( message );\n\t\t\t// append it to the new message container\n\t\t\t$( newMessageContainer ).append( messageSpan );\n\t\t}\n\t\t// otherwise format as a user message\n\t\telse\n\t\t{\n\t\t\tvar senderNameSpan = $(\"<span></span>\" );\n\t\t\t// if the sender name is the same as this window's id, then the message is from the other user\n\t\t\tif ( messageType == ChatBoxWindow.MESSAGE_TYPE_OTHER_USER )\n\t\t\t{\n\t\t\t\t$( senderNameSpan ).addClass(\"chatBoxContentMessageSenderOther\" );\n\t\t\t\t// set the sender name in the span\n\t\t\t\t$( senderNameSpan ).html( \"[\" + sender.getUsername( ) +\"]: \" );\n\t\t\t}\n\t\t\t// otherwise assume the message was from this client's user.\n\t\t\telse\n\t\t\t{\n\t\t\t\t$( senderNameSpan ).addClass( \"chatBoxContentMessageSenderSelf\" );\n\t\t\t\t$( senderNameSpan ).html( \"[You]: \" );\n\t\t\t}\n\t\t\t\n\t\t\t// append the sender name span to the new message container\n\t\t\t$( newMessageContainer ).append( senderNameSpan );\n\t\t\t\n\t\t\t// create and append the message span to the new message container\n\t\t\tvar messageSpan = $( \"<span></span>\", { class: \"chatBoxContentUserMessageText\" } );\n\t\t\t$( messageSpan ).append( message );\n\t\t\t$( newMessageContainer ).append( messageSpan );\n\t\t}\n\t\t\n\t\t// append the new message container to the chat content box\n\t\t$( chatBoxContentElement ).append( newMessageContainer );\n\t\t\n\t\t// automatically scroll the div\n\t\t$( chatBoxContentElement ).prop( { scrollTop: $( chatBoxContentElement ).prop( \"scrollHeight\" ) } );\n\t};\n\t\n\t/**\n\t * This function facilitates the sending of a message from this chat box window.\n\t * @return void\n\t */\n\tfunction processSendMessage( )\n\t{\n\t\t// retrieve the value from the input buffer\n\t\tvar message = $(chatBoxBufferTextInputElement).val( );\n\t\t\n\t\t// if there is a message to send\n\t\tif ( message )\n\t\t{\t\n\t\t\t// clear the input buffer\n\t\t\t$(chatBoxBufferTextInputElement).val( \"\" );\n\t\t\t\n\t\t\t// append the send message to the chat content element\n\t\t\tprocessMessage( null, message, ChatBoxWindow.MESSAGE_TYPE_SELF );\n\t\t\t\n\t\t\t// notify listeners of the sent message\n\t\t\tnotifyListenersMessageSend( message );\n\t\t}\n\t}\n\t\n\t/**\n\t * This function handles a notification of a change in status from the specified user object.\n\t * @param user The notifying user object.\n\t * @param newStatus The new status being notified of.\n\t * @return void\n\t */\n\tChatBoxWindow.prototype.notifyUserStatusChange = this.notifyUserStatusChange = function( user, newStatus )\n\t{\n\t\t// notify the client' user of this user's new status\n\t\tvar notificationMessage = \"Changed status to: \" + newStatus.statusStringValue; \n\t\tprocessMessage( null, notificationMessage, ChatBoxWindow.MESSAGE_TYPE_SYSTEM ); \n\t};\n\t\n\t/**\n\t * This function handles a notification of a message being sent from the specified user object.\n\t * @param user The user sending the message.\n\t * @param message The message being sent.\n\t * @return void\n\t */\n\tChatBoxWindow.prototype.notifyUserSentMessage = this.notifyUserSentMessage = function( user, message )\n\t{\n\t\tprocessMessage( user, message, ChatBoxWindow.MESSAGE_TYPE_OTHER_USER );\n\t};\n\t\n\t/** initialization **/\n\t\n\t// register this window as a listener for it's user object.\n\tmyUser.registerListener( this );\n\t\n\t/* initialize the HTML element's structure for the ChatBoxWindow */\n\t\n\t// create the out window div\n\twindowElement = $( \"<div/>\", { class: \"chitChatWindow\", width: \"300px\" } );\n\t\n\t\n\t// create the chat box title div\n\tvar chatBoxTitleDiv = $( \"<div/>\", { class: \"chitChatWindowTitle\" } );\n\t// create the chat box title text span\n\tvar chatBoxTitleTextSpan = $( \"<span></span>\" );\n\t$( chatBoxTitleTextSpan ).html( myUser.getUsername( ) );\n\t// append the title span to the box title div\n\t$( chatBoxTitleDiv ).append( chatBoxTitleTextSpan );\n\t// create the title close button\n\tvar chatBoxTitleCloseButton = $( \"<input></input>\", { type: \"button\", class: \"chitChatWindowTitleButton\", value: \"X\" } );\n\t// register the event handler for the close button\n\t$( chatBoxTitleCloseButton ).click( function( )\n\t{\n\t\t$( windowElement ).fadeOut( \"slow\", function( ) { close( ); } );\n\t} );\n\t// append the close button to the title div\n\t$( chatBoxTitleDiv ).append( chatBoxTitleCloseButton );\n\t\n\t// append the chat box title div to the chat box window\n\t$( windowElement ).append( chatBoxTitleDiv );\n\t\n\t// create the chat box content div\n\tchatBoxContentElement = $( \"<div/>\", { class: \"chitChatWindowContent\", height: \"150px\" } );\n\t// append the chat box content div to the chat box window\n\t$( windowElement ).append( chatBoxContentElement );\n\t\n\t// create the chat box buffer div\n\tvar chatBoxBufferDiv = $( \"<div/>\", { class: \"chatBoxBuffer\" } );\n\t// create the buffer text input and append it to the chat box buffer\n\tchatBoxBufferTextInputElement = $( \"<input></input>\", { type: \"text\" } );\n\t// ensure that when the text field receives focus to select all text inside of it\n\t$( chatBoxBufferTextInputElement ).focus( function ( ) { $( chatBoxBufferTextInputElement ).select( ); } );\n\t// assign the event for handling sending a message\n\t$( chatBoxBufferTextInputElement ).keyup( function( event )\n\t\t{\n\t\t\tif ( event.keyCode == 13 )\n\t\t\t{\n\t\t\t\tprocessSendMessage( );\n \t\t\t}\n\t\t} );\n\t\n\t\n\t$( chatBoxBufferDiv ).append( chatBoxBufferTextInputElement );\n\t// create the buffer text send button and append it to the chat box buffer\n\tvar sendButton = $( \"<input></input>\", { type: \"button\", value: \"Send\" } );\n\t$( sendButton ).click( function( event ) { processSendMessage( ); } );\n\t$( chatBoxBufferDiv ).append( sendButton );\n\t\n\t// append the chat box buffer div to the chat box window div\n\t$( windowElement ).append( chatBoxBufferDiv );\n\t\n\t// append the element to the content pane\n\t$( parentElement ).append( windowElement );\n\t// slowly fade in to look slick ;)\n\t$( windowElement ).css( { display: \"none\" } );\n\t$( windowElement ).fadeIn( \"slow\" );\n}",
"renderChatPage () {\n this.clearShadowRoot()\n this.shadowRoot.appendChild(chatLayoutTemp.content.cloneNode(true))\n this.getElement('#chatUsernameP').textContent = this.username\n\n this.socket.addEventListener('message', this.boundGetMsgFromServer)\n this.getElement('form').addEventListener('submit', this.boundHandleUserMsg)\n this.getElement('form').addEventListener('keypress', this.boundFindKeyPress)\n this.handleDropdown()\n }",
"function chatEventHandler(event) {\n\tlet responseObj = JSON.parse(event.data);\n\tconst dateStr = getDateNow();\n\tif (String(responseObj.group_id) == groupID) { //Allow type conversion\n\t\tlet allChats = document.getElementById(\"allChat\");\n\t\tif (String(responseObj.user_id) != userID) { //Allow type conversion\n\t\t\tlet nodeStr = addChatSender(responseObj.msg_content, responseObj.fname + \" \" + responseObj.lname, dateStr);\n\t\t\tallChats.insertAdjacentHTML('beforeend', nodeStr);\n\t\t}\n\t\telse {\n\t\t\tlet nodeStr = addChatReciever(responseObj.msg_content, dateStr);\n\t\t\tallChats.insertAdjacentHTML('beforeend', nodeStr);\n\t\t}\n\t}\n}",
"function receiveWindowMessage(evt) {\n if (evt) {\n // For now we handle messages that contain strings (for opening a report or a\n // screen in a new task window) or objects (for other purposes such as showing\n // Notes for a given entity such as an AR Customer).\n // NOTE: To test that we have a string, we use typeof (in case the string happens\n // to be ''), but to test for an object we need to use instanceof since it\n // returns false for null and true for an object whereas typeof returns\n // \"object\" for null as well as for objects.\n if (typeof evt.data === \"string\") {\n // We are being asked to open a report or screen as a new task window.\n openNewTask(evt.data);\n }\n else if (evt.data instanceof Object) {\n // Handle different types of messages that contain objects. For now, the\n // only type we handle is for showing Notes, but in future we might handle\n // other types of messages too.\n if (evt.data.notesOptions) {\n // We are being asked to show Notes for a given entity (e.g. an AR Customer).\n openNotesCenter(evt.data.notesOptions);\n }\n }\n }\n }",
"function showChats(channel, listOFMessages){\n\n\t// format the iso time coming from the server into something readable\n\tlistOFMessages.map(x => x.date = luxon.DateTime.fromISO(x.date).toLocaleString(luxon.DateTime.DATETIME_MED))\n\t// if the messages is not empty\n\tif (listOFMessages.length > 0){\n\n\t\tconsole.log(listOFMessages[0].date)\n\t\t// compile handle bar template that takes in a list of message dictionaries as input and renders it\n\t\tconst template = Handlebars.compile(document.querySelector(\"#chatstemplate\").innerHTML);\n\t\tconst messages = template({\"messages\": listOFMessages});\n\n\t\t// add the message to the dom\n\t\tdocument.querySelector(\".chat-box\").innerHTML = messages;\n\t}\n\telse\n\t{ \n\t \t// if a channel has no messages display nothing\n\t\tdocument.querySelector(\".chat-box\").innerHTML = \"\";\n\t}\n\n\t// if it contains a hyphen then its a user pair and we want the banner to be just the other guys name\n\tlet header = channel\n\tif (channel.includes('-')){\n\t\tpair = channel.split('-')\n\t\tif (pair.includes(username)){\n\t\t\tothername = (username === pair[0]) ? pair[1] : pair[0]\n\t\t\theader = othername\n\t\t}\n\t}\n\t// change name to reflect current channel\n\tdocument.querySelector(\"#channelname-header\").innerText = header;\n}",
"function chat_stream() {\n if (\"WebSocket\" in window) {\n var id = $('.message').attr('id');\n var last_update = $('.message #created_at:last-child').html();\n var ws = new WebSocket(\"ws://127.0.0.1:3045/chatrooms/\"+id);\n ws.onopen = function() {\n // Web Socket is connected. You can send data by send() method.\n ws.send({id:id, last_update:last_update});\n };\n ws.onmessage = function (evt) { \n var received_msg = evt.data;\n received_msg = \"hi\";\n };\n ws.onclose = function() { };// websocket is closed.\n } else {\n // the browser doesn't support WebSocket.\n //var holdTheInterval = setInterval(poll_server_for_new_messages, 5000);\n }\n}",
"function Chat(support_email) {\n var self = {\n available: false,\n expanded: false,\n shown: false,\n support_email: support_email,\n };\n\n self.init = function() {\n olark('api.chat.onOperatorsAvailable', function() { self.available = true; });\n olark('api.chat.onOperatorsAway', function() { self.available = false; });\n olark('api.box.onExpand', function() { self.expanded = true; });\n olark('api.box.onShrink', function() { self.expanded = false; });\n olark('api.box.onShow', function() { self.shown = true; });\n olark('api.box.onHide', function() { self.shown = false; });\n\n olark('api.visitor.updateCustomFields', {\n report_url: window.location.host + '/tickets/' + ui.options.ticket_id\n });\n };\n\n // Wait until the chat window is loaded and expanded, then execute onReady.\n self.waitUntilReady = function(onReady, onFailure) {\n var n_tries = 15, interval = 300;\n function poll() {\n if (self.shown && self.expanded)\n onReady();\n else if (n_tries-- > 0)\n setTimeout(poll, interval);\n else\n onFailure();\n }\n\n poll();\n };\n\n self.pulse = function() {\n $('#habla_window_div').animate({\n 'transform': 'scale(1.2)'\n }, 200).animate({\n 'transform': 'scale(1)'\n }, 200);\n };\n\n self.fail = function(err) {\n Console.msg_error(\"Sorry, loading the chat failed.<br>\" +\n \"If you require assistance, please contact \" +\n \"<a href='mailto:\" + self.support_email +\n \"' target=_blank>\" + self.support_email + \"</a>.\");\n Log.error(\"couldn't load candidate chat\", err);\n };\n\n // DWIM: show Olark chat and attract user's attention.\n self.activate = function() {\n if (!self.shown)\n olark('api.box.show');\n if (!self.expanded)\n olark('api.box.expand');\n\n self.waitUntilReady(self.pulse, self.fail);\n };\n\n self.init();\n\n return self;\n}",
"function redrawWindowList() {\n\t\tutilsModule.clearChildren(windowListElem);\n\t\tself.windowNames.forEach(function(windowName) {\n\t\t\t// windowName has type str, and is of the form (profile+\"\\n\"+party)\n\t\t\tvar parts = windowName.split(\"\\n\");\n\t\t\tvar profile = parts[0];\n\t\t\tvar party = parts[1];\n\t\t\tvar window = windowData[windowName];\n\t\t\t\n\t\t\t// Create the anchor element\n\t\t\tvar a = utilsModule.createElementWithText(\"a\", party != \"\" ? party : profile);\n\t\t\tvar n = window.numNewMessages;\n\t\t\tif (n > 0) {\n\t\t\t\t[\" (\", n.toString(), \")\"].forEach(function(s) {\n\t\t\t\t\ta.appendChild(utilsModule.createElementWithText(\"span\", s));\n\t\t\t\t});\n\t\t\t}\n\t\t\tutilsModule.setClasslistItem(a, \"nickflag\", window.isNickflagged);\n\t\t\ta.onclick = function() {\n\t\t\t\tself.setActiveWindow(windowName);\n\t\t\t\treturn false;\n\t\t\t};\n\t\t\ta.oncontextmenu = function(ev) {\n\t\t\t\tvar menuItems = [];\n\t\t\t\tif (window.isMuted)\n\t\t\t\t\tmenuItems.push([\"Unmute window\", function() { window.isMuted = false; }]);\n\t\t\t\telse {\n\t\t\t\t\tmenuItems.push([\"Mute window\", function() {\n\t\t\t\t\t\tvar win = window;\n\t\t\t\t\t\twin.isMuted = true;\n\t\t\t\t\t\twin.numNewMessages = 0;\n\t\t\t\t\t\twin.isNickflagged = false;\n\t\t\t\t\t\tredrawWindowList();\n\t\t\t\t\t}]);\n\t\t\t\t}\n\t\t\t\tvar closable = !(profile in connectionData) || (party != \"\" && !(party in connectionData[profile].channels));\n\t\t\t\tvar func = function() { networkModule.sendAction([[\"close-window\", profile, party]], null); };\n\t\t\t\tmenuItems.push([\"Close window\", closable ? func : null]);\n\t\t\t\tif (utilsModule.isChannelName(party) && profile in connectionData) {\n\t\t\t\t\tvar mode = party in connectionData[profile].channels;\n\t\t\t\t\tvar func = function() {\n\t\t\t\t\t\tnetworkModule.sendAction([[\"send-line\", profile, (mode ? \"PART \" : \"JOIN \") + party]], null);\n\t\t\t\t\t};\n\t\t\t\t\tmenuItems.push([(mode ? \"Part\" : \"Join\") + \" channel\", func]);\n\t\t\t\t}\n\t\t\t\tmenuModule.openMenu(ev, menuItems);\n\t\t\t};\n\t\t\t\n\t\t\tvar li = document.createElement(\"li\");\n\t\t\tli.appendChild(a);\n\t\t\tif (party == \"\")\n\t\t\t\tutilsModule.setClasslistItem(li, \"profile\", true);\n\t\t\twindowListElem.appendChild(li);\n\t\t});\n\t\trefreshWindowSelection();\n\t\t\n\t\tvar totalNewMsg = 0;\n\t\tfor (var key in windowData)\n\t\t\ttotalNewMsg += windowData[key].numNewMessages;\n\t\tvar activeWin = self.activeWindow\n\t\tif (activeWin != null) {\n\t\t\tvar s = (activeWin[1] != \"\" ? activeWin[1] + \" - \" : \"\") + activeWin[0] + \" - MamIRC\";\n\t\t\tdocument.title = (totalNewMsg > 0 ? \"(\" + totalNewMsg + \") \" : \"\") + s;\n\t\t\tif (optimizeMobile)\n\t\t\t\tdocument.querySelector(\"#main-screen header h1\").firstChild.data = s;\n\t\t}\n\t}",
"function onMessage(evt) {\n let obj = JSON.parse(evt.data);\n if(obj.isMsg == true) {\n chatMsg(obj);\n } else {\n updateUsersList(obj);\n }\n}",
"function scroll_chat_window() {\n $(\"div.chat div.conversation\").scrollTop($(\"div.chat div.conversation\")[0].scrollHeight);\n }",
"function ChatBox(options){\n\n \n\n this.opt = jQuery.extend({\n\n chatBoxId: null,\n\n chatUserList: null,\n\n open: true,\n\n dispayTitle: null,\n\n messages: new Array()\n\n }, options);\n\n this.chatBoxId = this.opt.chatBoxId;\n\n this.chatUserList = this.opt.chatUserList;\n\n this.box = null;\n\n this.textarea = null;\n\n this.initialized = false;\n\n this.init();\n\n this.blinkInterval = null;\n\n var len=this.opt.messages.length;\n\n for ( var i=0; i<len; i++ ){\n\n this.retrieveMessage(this.opt.messages[i]);\n\n }\n\n this.initialized = true;\n\n\n\n if(this.opt.open){\n\n this.show(); \n\n }else {\n\n this.hide();\n\n }\n\n }",
"onUpdatedChannels () {\n //OnX modules\n this._privMsg = new PrivMsg(this.bot)\n this._userNotice = new UserNotice(this.bot)\n this._clearChat = new ClearChat(this.bot)\n this._clearMsg = new ClearMsg(this.bot)\n this._userState = new UserState(this.bot)\n\n setInterval(this.updateBotChannels.bind(this), UPDATE_ALL_CHANNELS_INTERVAL)\n\n Logger.info(\"### Fully setup: \" + this.bot.userId + \" (\" + this.bot.userName + \")\")\n }",
"function open_chat_box() {\n\n if(window.key_follow==false){\n var camera_chat = '<a href=\"camera\" class=\"com com_camera\" reason=\"camera\"><i class=\"mdi-notification-voice-chat\"></i></a>';\n var attach_file = '<a href=\"file\" class=\"com com_file\" reason=\"file\"> <i class=\"mdi-editor-attach-file\"></i></a>';\n }else{\n var camera_chat = '';\n var attach_file = '';\n }\n\n \n // var follow = '<a href=\"follow\" class=\"com\" reason=\"follow\"> <i class=\"following mdi-social-share\"></i></a>';\n var minimize = '<a class=\"\" style=\"color:#FFF;cursor:pointer;\" > <i class=\"mdi-content-remove\"></i></a>';\n var close = '<a href=\"close\" class=\"com\" reason=\"close_box\"> <i class=\"mdi-navigation-close\"></i></a>';\n\n \n $(\"#chat_div\").chatbox({id : \"chat_div\",\n title : '<span class=\"name_box truncate\"></span><span class=\"title_box_style\"><span class=\"ui-chatbox-icon\">'+camera_chat+attach_file+minimize+close+'</span></span>',\n user : \"can be anything\",\n hidden: false, // show or hide the chatbox\n offset:0,\n width: 230, // width of the chatbox\n messageSent: function(id,user,msg){ \n \n $(\"#chat_div\").chatbox(\"option\", \"boxManager\").addMsg(window.username, msg);//on écrit son message en local\n\n socket.emit('send_message',{'sender_name':window.username,'sender_num':window.user_number,'sender_msg':msg,'interloc_num':window.interloc_num});\n\n }\n });\n \n window.open_chat = true;\n }",
"function addMessage(msg, roomName, username, other) {\n var roomNameClass = toClassString(roomName);\n\n //check if user is in the room. If not, add 1 new unread message.\n if (currentRoom != roomName) {\n var index = userRoomsList.map(function(e) { return e.roomName; }).indexOf(roomName);\n userRoomsList[index].numNewMsgs++;\n //show badge if it is hidden\n if($('#' + roomNameClass + '-badge').is(\":hidden\")){\n $('#' + roomNameClass + '-badge').parent().addClass(\"tab-badge-notification-bg\");\n $('#' + roomNameClass + '-badge').show();\n }\n $('#' + roomNameClass + '-badge').text(userRoomsList[index].numNewMsgs);\n }\n \n //create message timestamp\n var time = new Date();\n var hour = time.getHours();\n var minute = time.getMinutes();\n var second = time.getSeconds();\n var sign = \"am\";\n if (hour > 11) {\n sign = \"pm\";\n if (hour > 12) {\n hour = hour % 12;\n }\n } else if (hour == 0) {\n hour = 12;\n }\n if (minute < 10) {\n minute = \"0\" + minute;\n }\n if (second < 10) {\n second = \"0\" + second;\n }\n time = hour + \":\" + minute + \":\" + second + \" \" + sign;\n\n //append to the right div/ie to the right room\n var bgCSSClass = other ? \"bg-info\" : \"bg-primary\";\n bgCSSClass = username == \"@UWBot\" ? \"bg-success\" : bgCSSClass;\n var message = username == \"@UWBot\" ? msg : escapeHtml(msg);\n $('div#chat-panel div#room-' + roomNameClass + ' div.chat-entries').append('<div class=\"message ' + bgCSSClass + '\"><span class=\"msg-user\">'\n + username + '</span> : <span class=\"msg-content\">' + message + '</span>' + '<span class=\"message-timestamp\">'\n + time + '</span>' + '</div>');\n\n var roomChatEntries = $('div#chat-panel div#room-' + roomNameClass + ' div.chat-entries');\n if (Math.abs((roomChatEntries[0].scrollHeight - roomChatEntries.scrollTop() - roomChatEntries.outerHeight())) < $(\"#chat-panel\").height() + 200) {\n roomChatEntries.animate({\n scrollTop: roomChatEntries[0].scrollHeight\n }, 200);\n }\n else {\n $('#more-msgs').filter(':hidden').fadeIn(500).delay(1500).fadeOut(500);\n }\n\n emojify.run(); //enable emojis\n}",
"function showChat() {\n\tdocument.getElementById(\"app\").innerHTML = chatHTML;\n\n\t// Find the latest 10 messages. They will come with the newest first\n\t// which is why we have to reverse before adding them\n\tclient\n\t\t.service(\"messages\")\n\t\t.find({\n\t\t\tquery: {\n\t\t\t\t$params: {\n\t\t\t\t\t$sort: { createdAt: -1 },\n\t\t\t\t\t$limit: 25\n\t\t\t\t},\n\t\t\t\ttotal: 1,\n\t\t\t\tlimit: 1,\n\t\t\t\tskip: 1,\n\t\t\t\tdata: {\n\t\t\t\t\ttext: 1,\n\t\t\t\t\towner: {\n\t\t\t\t\t\tname: 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.then(page => {\n\t\t\tpage.data.reverse().forEach(addMessage);\n\t\t});\n}",
"function startChatDialog(to_user_id, to_user_name) {\n if (!document.getElementById(\"chat_\" + to_user_id)) {\n var chat = document.createElement(\"div\");\n chat.title = \"Chat met \" + to_user_name;\n chat.id = \"chat_\" + to_user_id;\n var messages = document.createElement(\"div\");\n messages.style = \"height:400px; border: 1px solid #ccc overflow\";\n messages.id = \"messages_\" + to_user_id;\n var input = document.createElement(\"input\");\n input.id = \"msg_\" + to_user_id;\n var button = document.createElement(\"button\");\n button.id = \"send_\" + to_user_id;\n button.innerHTML = \"SEND\";\n\n var status = document.createElement('p');\n status.id = \"status_\" + to_user_id;\n status.innerHTML = \"Unknown\";\n chat.appendChild(status);\n\n chat.appendChild(messages);\n chat.appendChild(input);\n chat.appendChild(button);\n document.getElementById(\"chatbox\").appendChild(chat);\n console.log('created');\n } else {\n console.log('already exists');\n }\n\n}",
"_renderChatMessage(message, html, _data) {\r\n\t\tif (html.find('.narrator-span').length) {\r\n\t\t\thtml.find('.message-sender').text('');\r\n\t\t\thtml.find('.message-metadata')[0].style.display = 'none';\r\n\t\t\thtml[0].classList.add('narrator-chat');\r\n\t\t\tif (html.find('.narration').length) {\r\n\t\t\t\thtml[0].classList.add('narrator-narrative');\r\n\t\t\t\tconst timestamp = new Date().getTime();\r\n\t\t\t\tif (message.data.timestamp + 2000 > timestamp) {\r\n\t\t\t\t\tconst content = $(message.data.content)[0].textContent;\r\n\t\t\t\t\tlet duration = this.messageDuration(content.length);\r\n\t\t\t\t\tclearTimeout(this._timeouts.narrationCloses);\r\n\t\t\t\t\tthis.elements.content[0].style.opacity = '0';\r\n\t\t\t\t\tthis._timeouts.narrationOpens = setTimeout(this._narrationOpen.bind(this, content, duration), 500);\r\n\t\t\t\t\tthis._timeouts.narrationCloses = setTimeout(this._narrationClose.bind(this), duration);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\thtml[0].classList.add('narrator-description');\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function ChatEvents() {\n\n events.EventEmitter.call(this);\n\n}",
"function showchatUserSelect(){\n if(userChat==null)\n {return;}\n /*eventAddChat(message);*/\n $(\".inyect-commit\").html(\"\");\n $(\"#bienvenida\").hide();\n listOfChat.forEach(function(message){\n if((message.name.id==userChat.id && message.userSend.id==JSON.parse($.session.get(\"ObjectUser\")).id) || (message.name.id==JSON.parse($.session.get(\"ObjectUser\")).id && message.userSend.id==userChat.id)){\n\n eventAddChat(message);\n }\n });\n $(\".inyect-commit\").scrollTo(10000,0)/*mejorar la parte del scroll*/\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the last node entry in a root node from a path. | last(root, path) {
var p = path.slice();
var n = Node$1.get(root, p);
while (n) {
if (Text.isText(n) || n.children.length === 0) {
break;
} else {
var i = n.children.length - 1;
n = n.children[i];
p.push(i);
}
}
return [n, p];
} | [
"function getLastPath() {\n if (url.path.components.length > 0) {\n return url.path.components[url.path.components.length - 1];\n }\n }",
"function lastRealPoint(path) {\n if (path.isEmpty()) {\n console.warn(\"Attemtped to obtain the last segment of an empty path\");\n return undefined;\n }\n\n // Technically, such a point could intentionally be added to a path, but\n // this seems to be a cap that is added by Paper.JS. I thought it was on\n // all paths, but it is less consistent than expected.\n let lastPoint = path.lastSegment.point;\n if (isNaN(lastPoint.x) && isNaN(lastPoint.y)) {\n lastPoint = path.firstSegment.point;\n }\n return lastPoint;\n }",
"leaf(root, path) {\n var node = Node$1.get(root, path);\n\n if (!Text.isText(node)) {\n throw new Error(\"Cannot get the leaf node at path [\".concat(path, \"] because it refers to a non-leaf node: \").concat(node));\n }\n\n return node;\n }",
"next(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the next path of a root path [\".concat(path, \"], because it has no next index.\"));\n }\n\n var last = path[path.length - 1];\n return path.slice(0, -1).concat(last + 1);\n }",
"function lastAncestor(node,pred){var ancestors=listAncestor(node);return lists.last(ancestors.filter(pred));}",
"get(root, path) {\n var node = root;\n\n for (var i = 0; i < path.length; i++) {\n var p = path[i];\n\n if (Text.isText(node) || !node.children[p]) {\n throw new Error(\"Cannot find a descendant at path [\".concat(path, \"] in node: \").concat(JSON.stringify(root)));\n }\n\n node = node.children[p];\n }\n\n return node;\n }",
"function last() {\n return _navigationStack[_navigationStack.length - 1];\n }",
"getLast() {\n if (!this.head) {\n return null;\n }\n let node = this.head;\n while (node) {\n // If next is null, then we are at the last node\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }",
"function backtrackPath(last_node){\n var path = [];\n var temp = last_node;\n path.push(temp);\n\n while(temp.previous){\n path.push(temp.previous);\n temp = temp.previous;\n }\n\n return path;\n}",
"function compareLastValue(path, value) {\n\t\t\t\treturn lastValue(path, value, true)\n\t\t\t}",
"previous(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the previous path of a root path [\".concat(path, \"], because it has no previous index.\"));\n }\n\n var last = path[path.length - 1];\n\n if (last <= 0) {\n throw new Error(\"Cannot get the previous path of a first child path [\".concat(path, \"] because it would result in a negative index.\"));\n }\n\n return path.slice(0, -1).concat(last - 1);\n }",
"function get_last_word_in_path(req) {\n\t\tconst parts = req.path ? req.path.split('/') : [];\t\t\t\t\t// grab the last word in the request's path\n\t\treturn parts[parts.length - 1] || '-';\t\t\t\t\t\t\t\t// return '-' when we can't find it\n\t}",
"async function getLeftMostLeaf(leafCheckArray) { //LeafCheckArray must be a since array - in this case it is\n\n let mostRecentLeaf = {}\n let leafURL = '';\n\n //First time you come upon an empty next is your leftmost leaf\n for (annot in leafCheckArray) {\n \tif (leafCheckArray[annot].__rerum.history.next.length == 0) {\n \t\tmostRecentLeaf = leafCheckArray[annot];\n \t\tbreak;\n \t}\n\n }\n\n return mostRecentLeaf;\n}",
"first(root, path) {\n var p = path.slice();\n var n = Node$1.get(root, p);\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break;\n } else {\n n = n.children[0];\n p.push(0);\n }\n }\n\n return [n, p];\n }",
"function getLastKey(data) {\r\n let keys = Object.keys(data[0]);\r\n let lastKey = keys[keys.length -1];\r\n return lastKey;\r\n}",
"function getRootPathname() {\n let pathname,\n pathRoot,\n indEnd\n\n pathname = window.location.pathname;\n\n if (pathname === '/') {\n pathRoot = pathname;\n } else {\n indEnd = pathname.indexOf('/', 1);\n pathRoot = pathname.slice(0, indEnd);\n }\n return pathRoot;\n }",
"function lastElementChild(element) {\n var child = element.lastChild;\n while (child !== null && child.nodeType !== 1) {\n child = child.previousSibling;\n }\n return child;\n}",
"function getLastSibling(node) {\n let sibling = node;\n\n while (sibling && sibling.next) {\n sibling = sibling.next;\n }\n\n return sibling;\n}",
"function getFirstPathPiece (ramlsRoot, ramlPath) {\n const relPath = path.relative(ramlsRoot, ramlPath)\n return relPath.split(path.sep)[0].toLowerCase()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Match mother of the person | mother(person) {
return person.mother;
} | [
"function calcMotherAge(p) {\n console.log(\"person: \" + JSON.stringify(p));\n var mother = byName[p.mother]\n var mother_age = p.born - mother.born;\n console.log(\"mother: \" + p.mother + \", age: \" + mother_age);\n return mother_age;\n}",
"function extractMother(paragraph) {\n var start = paragraph.indexOf(\"(mother \") + \"(mother \".length;\n var end = paragraph.indexOf(\")\");\n return paragraph.slice(start, end);\n}",
"equalTo(other) {\n other = new Complex(other);\n return this.re == other.re && this.im == other.im;\n }",
"function matchProfile(target, candidates) {\n\tvar candidateDifference = [];\n\n\n\t//repeat for each candidate\n\tfor(var i = 0;i<candidates.length;i++) {\n\t\t//take candidate\n\t\tvar candidate = candidates[i];\n\t\n\t\t//do not compare the same profile, assuming name is unique\n\t\tif(candidate.name == target.name) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvar profileDifference = 0;\n\t\t//sum difference for each score between target profile and candidate score\n\t\tfor(var j = 0;j<target['scores[]'].length;j++) {\n\t\t\tprofileDifference += Math.abs((target['scores[]'][j] - candidate.scores[j]))\n\t\t}\n\t\t//add candidate with score difference\n\t\tcandidateDifference.push({\n\t\t\tdifference:profileDifference, \n\t\t\tcandidate:candidate\n\t\t})\n\t}\n\t//order candidate by lowesr difference to highest\n\tsortByDifference(candidateDifference);\n\t//take the lowest difference candidate as the matcg\n\treturn candidateDifference[0].candidate;\n}",
"brothers(person) {\n if(person !== undefined){\n var father = person.father;\n if (father === undefined) {\n return [];\n }\n var sons = father.sons;\n const brother = [];\n sons.forEach(function (son) {\n if (son.name != person.name && son.gender === 'male') {\n brother.push(son);\n }\n }, this);\n return brother;\n }\n else{\n return [];\n }\n \n }",
"function isMessageFromOpponent(data)\n{\n // Is it from our opponent and is it intended for us?\n return (data.payload.sender == g_remote_uuid && data.payload.target == g_local_uuid);\n}",
"function matchFriends(friends, newFriend) {\n var closestDifference;\n var matchedFriend;\n\n //loop through the old friends array\n for (var i = 0; i < friends.length; i++) {\n\n //define a new varible equal to one friend at any index\n var friend = friends[i];\n\n //set the difference equal to 0 to start\n var difference = 0;\n\n\n\n //loop through the length of the scores in the new friend array\n for (var j = 0; j < newFriend.scores.length; j++) {\n\n //set the index of each score for the newFriend equal to a new variable\n var answerA = newFriend.scores[j];\n\n //call that same variable since the indexes will be the same for the friend variable\n var answerB = friend.scores[j];\n\n //redefine the difference variable equal to the total sum of each absolute value difference between each difference\n difference = difference + (Math.abs(answerA - answerB));\n\n }\n if (difference < closestDifference || closestDifference === undefined) {\n closestDifference = difference;\n matchedFriend = friend;\n }\n }\n return {\n name: matchedFriend.name,\n photo: matchedFriend.photo\n };\n}",
"function findParty(party) {\n return party.partyID === this.partyID;\n}",
"function mappingRefersToMember(mappingEntity, memberInfo) {\n if (!mappingEntity) return false; // assert false\n if (!memberInfo) return false; // assert false\n var memberId = memberInfo.getEntity().idP;\n var isMatch = sp.result(mappingEntity, 'mappedField.idP') === memberId;\n if (!isMatch) {\n var isRelMatch = sp.result(mappingEntity, 'mappedRelationship.idP') === memberId;\n var isDirMatch = memberInfo.isReverse && mappingEntity.mapRelationshipInReverse === memberInfo.isReverse();\n isMatch = isRelMatch && isDirMatch;\n }\n return isMatch;\n }",
"brotherinlaw(person) {\n if (person.gender === 'male') {\n var spouse = person.ismanof;\n var brother = this.brothers(spouse);\n var sisters = this.sisters(person);\n if (sisters.length > 0) {\n sisters.forEach(function (sis) {\n if (sis.iswomanof !== undefined) {\n brother.push(sis.iswomanof);\n }\n }, this);\n }\n return brother;\n } else {\n var spouse = person.iswomanof;\n var brother = this.brothers(spouse);\n var sisters = this.sisters(person);\n if(sisters.length > 0){\n sisters.forEach(function (sis) {\n if (sis.iswomanof !== undefined) {\n brother.push(sis.iswomanof);\n }\n }, this);\n }\n return brother;\n }\n\n }",
"visitIdentified_other_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getMentorByName(mentorName) {\n const allMentors = this.getMentorList();\n return allMentors.find(mentor => mentor.name.toLowerCase() === mentorName.toLowerCase());\n }",
"function findMatch(newFriend){\n\n\tvar bestMatchIndex = null;\n\tvar bestMatchScore = null;\n\n\t//iterates over the array of friends \n\tfor( var i = 0; i < friends.length; i++ ){\n\n\t\tvar currentMatchScore = 0;\n\n\t\t//comparing each of their survey answers\n\t\tfor( var j = 1; j < 11; j++ ){\n\n\t\t\tvar currentQuestion = 'question' + j;\n\t\t\tcurrentMatchScore = currentMatchScore + Math.abs( friends[i][currentQuestion] - newFriend[currentQuestion] );\n\n\t\t}\n\n\t\t//if this score is better than all priors, set this friend as the best match\n\t\tif( currentMatchScore < bestMatchScore || bestMatchScore === null ){\n\t\t\tbestMatchScore = currentMatchScore;\n\t\t\tbestMatchIndex = i;\n\t\t}\n\n\t}\n\n\t// console.log('Best Match is:');\n\t// console.log(friends[bestMatchIndex].name);\n\n\treturn(bestMatchIndex);\n\n}",
"maternaluncle(person) {\n var mother = person.mother;\n if(mother === undefined){\n return []; \n }\n var uncles = this.brothers(mother);\n var brotherlaw = this.brotherinlaw(mother);\n if (brotherlaw.length > 0) {\n brotherlaw.forEach(function (brother) {\n uncles.push(brother);\n }, this);\n }\n return uncles;\n }",
"function isFriend(name, object) {\n if (object.friends !== undefined) {\n for (var i = 0; i < object.friends.length; i++) {\n if (name === object.friends[i]) {\n return true;\n }\n } \n return false;\n } return false;\n}",
"function sendWinner(connection, res, name1, name2, stat) {\n connection.query(\"SELECT name FROM team_stats \"+\n \"JOIN teams ON teams.id = team_stats.team_id \"+\n \"WHERE name='\"+name1+\"' OR name='\"+name2+\n \"' ORDER BY team_stats.\"+stat+\" DESC LIMIT 1\",\n function(err, result, fields) {\n if(err) {\n throw err;\n //Tell client that query ran into error\n res.sendStatus(500);\n } else {\n //Otherwise, send winning team's name to client\n res.send(JSON.stringify(result));\n }\n });\n }",
"async function findRelationBetween(personOne, personTwo) {\n qres = await _modifiedBfs(personOne, personTwo);\n ans = [];\n if (!qres || qres.dist == -1) return returnFailure();\n else {\n /* Getting data about the people */\n peopleFromPath = await _getDataHandler(qres.path.reverse());\n reltypes = await _getRelationMany(qres.path, qres.dist + 1);\n /* Re arrange into actual path */\n relPath = '';\n\n for (let i = 0; i < qres.path.length; i++) {\n pers = peopleFromPath.find((b) => b.id == qres.path[i]);\n if (i == 0) {\n pers.relPath = 'Self';\n }\n if (i > 0) {\n t1 = Object.values(reltypes.rows).find((key) => key.id == qres.path[i]);\n\n t2 = Object.keys(t1).find((key) => qres.path[i - 1] == t1[key]);\n if (t2 == 'father_id' || t2 == 'mother_id') {\n pers.prev = 0;\n } else if (t2 == 'spouse_id') {\n pers.prev = 3;\n } else if (t2 == undefined || t2 == 'children_id') {\n if (pers.gender == 'Male') pers.prev = 1;\n else pers.prev = 2;\n }\n relPath += pers.prev;\n pers.relPath = familyMap.get(relPath);\n }\n ans.push(_unflatten(pers));\n }\n }\n return returnSuccess(ans);\n}",
"function isFriend(candidate) {\r\n\t//todo search as json instead?\r\n\treturn (friends.indexOf(candidate)!=-1);\r\n}",
"function matchCandidate(state, queryAtom, queriedAtom, queryNbr, queriedNbr, maps) {\n // make sure the neighbor atom isn't in the paths already\n if (goog.array.indexOf(state.queryPath, queryNbr) !== -1) {\n return false;\n }\n if (goog.array.indexOf(state.queriedPath, queriedNbr) !== -1) {\n return false;\n }\n\n // check if the atoms match\n if (!queryNbr.matches(queriedNbr, state.queried, state.sssr)) {\n return false;\n }\n\n var queryBond = state.query.findBond(queryAtom, queryNbr);\n var queriedBond = state.queried.findBond(queriedAtom, queriedNbr);\n\n // check if the bonds match\n if (!queryBond.matches(queriedBond, state.queried, state.sssr)) {\n return false;\n }\n\n // add the neighbors to the paths\n state.queryPath.push(queryNbr);\n state.queriedPath.push(queriedNbr);\n\n // check if this is a full match\n checkForMap(state, maps);\n\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
targetSlide display slide containing ID=target, or the target'th slide | function targetSlide(target)
{
var h, n;
if ((h = document.getElementById(target)))
/* Find enclosing .slide or preceding H1 */
while (h && !isStartOfSlide(h)) h = h.previousSibling || h.parentNode;
else if ((n = parseInt(target)) > 0)
/* Find the start of the n'th slide. */
for (h = document.body.firstChild; h; h = h.nextSibling)
if (h.b6slidenum && h.b6slidenum == n) break;
/* If found, and it is not already displayed, display it */
if (h != null && h != curslide) makeCurrent(h);
} | [
"function MM_effectSlide(targetElement, duration, from, to, toggle)\n{\n\tSpry.Effect.DoSlide(targetElement, {duration: duration, from: from, to: to, toggle: toggle});\n}",
"moveToSlide( slide) {\n console.debug( \"dia-show › moveToSlide()\", slide);\n this.slide = slide != undefined ? slide : null;\n }",
"function displaySlide()\n{\n var h;\n\n /* curslide has class=slide, page-break-before=always or is an H1 */\n curslide.style.cssText = curslide.b6savedstyle;\n curslide.classList.add(\"active\");\t\t// Compatibility with Shower\n liveregion.innerHTML = \"\";\t\t\t// Make it empty\n\n if (!curslide.classList.contains('slide')) {\n liveregion.appendChild(cloneNodeWithoutID(curslide));\n /* Unhide all elements until the next slide. And copy the slide to\n the live region so that it is spoken */\n for (h = curslide.nextSibling; h && !isStartOfSlide(h); h = h.nextSibling)\n if (h !== liveregion) {\n\tif (h.nodeType === 1) h.style.cssText = h.b6savedstyle;\n\tliveregion.appendChild(cloneNodeWithoutID(h));\n }\n\n } else {\t\t\t\t\t// class=slide\n /* Copy the contents of the slide to the live region so that it is spoken */\n for (h = curslide.firstChild; h; h = h.nextSibling)\n liveregion.appendChild(cloneNodeWithoutID(h));\n }\n\n updateProgress();\n initIncrementals();\n}",
"function slideHandler (e) {\r\n var target = $(e.target);\r\n if (target.hasClass('gallery__preview-item')) {\r\n var img = target.closest('.gallery__preview-show').find('.gallery__preview-pic');\r\n var src = target.data('src');\r\n img.attr('src', src).hide().fadeIn(200);\r\n }\r\n }",
"function show_curr_slide(){\n slides.eq(curr).show();\n adjust_nav();\n }",
"function displaySlide(n) {\r\n slideIndex = n;\r\n showSlides();\r\n}",
"function hashchange(e)\n{\n if (slidemode) targetSlide(location.hash.substring(1));\n}",
"function clickSlide(e){\n let my_id = e.currentTarget.id;\n let id = my_id.split('_');\n let i = parseInt(id[1]);\n let j = parseInt(id[2]);\n \n fif.slide(i,j);\n \n divs.forEach((row,i) => row.forEach((s,j) => s.textContent = (fif.board[i][j])));\n \n if(fif.solved()){\n //setTimeout(() = > alert(\"You Solved The Puzzle!\"),1); \n alert(\"You solved the puzzle\");\n }\n}",
"function goToSlide(slideIn)\n{\n\tbuttonPressed = true;\n\tplaceInfront = false;\n\tif(!(currentItem == maxSlides && slideIn == 0)) //current item is changed as long as user hasn't called first slide on the last, identical one that seals the loop\n\t\tcurrentItem = slideIn;\n\t//resets the timer so the timer doesn't go off half-way/too early\n\tclearInterval(timer);\n\ttimer = setInterval(nextSlide, 5000);\n\tnextSlide();\n}",
"urlAlias(record) {\n return {\n alias: '/slide/' + record.id,\n target: '/slide/' + record.id,\n };\n }",
"moveTo( slide, display) {\n console.debug( \"dia-show › moveTo()\", slide, display);\n this.moveToSlide( slide);\n this.moveToDisplay( display);\n }",
"_onSlideSelected( event) {\n const selectedSlide = event.detail.slide;\n console.debug( `dia-show › on-slide-selected: ${selectedSlide}`);\n this.moveToSlide( selectedSlide);\n if( event.cancellable) { event.stopPropagation(); }\n }",
"get target() {\n\t\treturn this.#target;\n\t}",
"function firstSlide()\n{\n var h;\n\n h = document.body.firstChild;\n while (h && !isStartOfSlide(h)) h = h.nextSibling;\n\n if (h != null) makeCurrent(h);\n}",
"function makeCurrent(elt)\n{\n /* assert(elt) */\n if (curslide != elt) {\n hideSlide();\n curslide = elt;\n displaySlide();\n }\n}",
"function changeSlide(slideId) {\n clearInterval(slideShow);\n\n setSlide(slideId);\n\n updateSlideVars(slideId);\n\n if (autoPlay) {\n play()\n }\n}",
"function selectSlide(time) {\n nearest = -1;\n for (i in slideIndices) {\n var numi = parseInt(i);\n $(slideIndices[i].displayDiv).addClass('unselected');\n $(slideIndices[i].displayDiv).removeClass('selected');\n if (numi<=time && numi>nearest) {\n nearest=numi;\n }\n }\n if (nearest >-1){\n var selected = slideIndices[''+nearest].displayDiv;\n $(selected).addClass('selected');\n $(selected).removeClass('unselected');\n $('#slideIndex').scrollLeft(selected.offsetLeft-($('#slideIndex').width()-$(selected).width())/2);\n }\n}",
"function goToByScroll(dataslide, mstime) {\n $('html,body').animate({\n scrollTop: $('.slide[data-slide=\"' + dataslide + '\"]').offset().top\n }, mstime);\n setActivePage(dataslide);\n}",
"function get_elem(target) {\n return document.querySelector(target);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! longDate(date) ! Returns a long Date ! ! QML: MoviePage.qml and MovieDetails.qml | function longDate(date)
{
var myDate=date;
myDate=myDate.split("-");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
var d = new Date(newDate).getDay();
var m = new Date(newDate).getMonth();
var month_names_short = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var month = month_names_short[m];
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var day = weekday[d];
return day + ", " + month + ". " + myDate[0] + ", " + myDate[2];
} | [
"function movieDateDetail(date)\n{\n\n var myDate=date;\n myDate=myDate.split(\"-\");\n var newDate=myDate[1]+\"/\"+myDate[0]+\"/\"+myDate[2];\n var m = new Date(newDate).getMonth();\n\n var month_names_short = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n var month = month_names_short[m];\n\n return month + \". \" + myDate[0];\n}",
"function getUnixDate(date) {\n return unixConverter.naturalToUnix(date);\n}",
"get raceMeetingNewsVideo_ContentDate() {return browser.element(\"//android.view.ViewGroup[3]/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.widget.TextView[2]\");}",
"function dateConvert(unixDate){\r\n var dateStr = new Date(unixDate * 1000)\r\n var n = dateStr.toDateString()\r\n var displayStr = n.substring(4, n.length)\r\n return \"(\" + displayStr + \")\"\r\n }",
"function extractStamp(date) {\r\n\treturn Math.round(date.getTime() / 1000);\r\n}",
"cutDate(num) {\n return num.substr(1,1);\n }",
"function fromUnixToNatural(timestamp){\n var naturalDate = new Date(timestamp*1000).toString();\n naturalDate = naturalDate.split(\" \");\n naturalDate = months[naturalDate[1]] +\" \"+naturalDate[2]+ \", \"+ naturalDate[3];\n return naturalDate;\n}",
"toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }",
"function toTimeStamp(date) {\n\t\t\ttry {\n\t\t\t\tvar x=\"\";\n\t\t\t\tif(date!=\"\"){\n\t\t\t\t\tx= new Date(date).getTime()/1000;\n\t\t\t\t}\n\n\t\t\t\t// console.log('try'+x +' '+date);\n\t\t\t\treturn x;\n\t\t\t} catch (e) {\n\t\t\t\t// console.log(e);\n\t\t\t\tvar x= new Date().getTime()/1000;\n\t\t\t\t// console.log('catch '+x);\n\t\t\t\treturn x;\n\t\t\t}\n\t\t}",
"shortYear() {\n return this.date.getYear();\n }",
"function dateToUnix(inputDate){\r\n\tvar unixDate = new Date(inputDate);\r\n\tconsole.log('date is '+unixDate);\r\n\t// console.log('unix time is '+(unixDate.getTime()/1000));\r\n\treturn (unixDate.getTime()/1000);\r\n}",
"function esFechaMenorActual(date) {\n\tvar x = new Date();\n\tvar fecha = date.split(\"-\");\n\tif (fecha[0]>1000) {\n\t\tx.setFullYear(fecha[0], fecha[1]-1, fecha[2]);\n\t} else {\n\t\tx.setFullYear(fecha[2], fecha[1]-1, fecha[0]);\t\n\t}\n\tvar today = new Date();\n\tif (x >= today) {\n\t\tvar error = \"La fecha de desaparición es posterior al día de hoy\";\n\t\tmostrarModal(\"rojo\", error);\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}",
"monthViewTitle({ date, locale }) {\n return new Intl.DateTimeFormat(locale, {\n year: 'numeric',\n month: 'long'\n }).format(date);\n }",
"function isAfter(date, ref_date){\n\tvar date_year = parseInt(date.substring(0, 4));\n\tvar date_month = parseInt(date.substring(5, 7));\n\tvar ref_date_year = parseInt(ref_date.substring(0, 4));\n\tvar ref_date_month = parseInt(ref_date.substring(5, 7));\n\t\n\tif(date_year > ref_date_year){\n\t\treturn true;\n\t}\n\tif(date_year == ref_date_year){\n\t\treturn date_month > ref_date_month;\n\t}\n\treturn false;\n}",
"date(time){\n return moment(time);\n }",
"function dateToEpoch(date) {\n return date.getTime() / 1000\n}",
"function GetMonthFromRawDateFunc(date) {\n var date = new Date(date);\n return date.getMonth() + 1;\n }",
"function returnDateStr (date) {\n let year = date.getFullYear();\n let month = date.getMonth() + 1;\n let day = date.getDate();\n if (month < 10) {\n month = `0${month}`;\n }\n if (day < 10) {\n day = `0${day}`;\n }\n return `${year}-${month}-${day}`;\n}",
"function makeDateFromXML(xmlDate) {\n var dd, mm, yyyy;\n dd = $(xmlDate).find(\"day\").text();\n if (dd < 10) {\n dd = '0' + dd;\n }\n mm = $(xmlDate).find(\"month\").text();\n if (mm < 10) {\n mm = '0' + mm;\n }\n yyyy = $(xmlDate).find(\"year\").text();\n return yyyy + '-' + mm + '-' + dd;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set Const.prototype.__proto__ to Super.prototype | function inherit (Const, Super) {
function F () {}
F.prototype = Super.prototype;
Const.prototype = new F();
Const.prototype.constructor = Const;
} | [
"function extend(__proto__) {\n for (var key in __proto__) {\n if (hasOwnProperty.call(__proto__, key)) {\n this[key] = __proto__[key];\n }\n }\n return this;\n }",
"function inheritPrototype(subType, superType) {\n var prototype = object(superType.prototype); //this is a function defined eariler in this document\n //or use the following:\n //var prototype = Object.create(superType.prototype); //ECMAScript 5\n \n prototype.constructor = subType;\n subType.prototype = prototype;\n}",
"function protoIsConst2() {\n return {b: 3, __proto__: 10};\n}",
"function overridePrototype(prototype, methodName, func) {\n prototype['_' + methodName] = prototype[methodName];\n prototype[methodName] = func;\n }",
"function protoShorthandMix1(func) {\n var __proto__ = 42;\n return {__proto__, __proto__: {}};\n}",
"function inheritFrom(parentConstructor, prototypeProps, constructorProps) {\n // Get or create a child constructor\n var childConstructor\n if (prototypeProps && object.hasOwn(prototypeProps, 'constructor')) {\n childConstructor = prototypeProps.constructor\n }\n else {\n childConstructor = function() {\n parentConstructor.apply(this, arguments)\n }\n }\n\n // Base constructors should only have the properties they're defined with\n if (parentConstructor !== Concur) {\n // Inherit the parent's prototype\n object.inherits(childConstructor, parentConstructor)\n childConstructor.__super__ = parentConstructor.prototype\n }\n\n // Add prototype properties, if given\n if (prototypeProps) {\n object.extend(childConstructor.prototype, prototypeProps)\n }\n\n // Add constructor properties, if given\n if (constructorProps) {\n object.extend(childConstructor, constructorProps)\n }\n\n return childConstructor\n}",
"static cleanNamespace(namespace) {\n this.getNamespace(namespace).__proto__ = null\n }",
"function superExpr (sup) {\n var parent = sup.parent;\n var grandparent = parent.parent;\n\n if (grandparent.type == 'CallExpression' &&\n grandparent.callee === parent) {\n superCall(sup);\n } else if (parent.type == 'ExpressionStatement' ||\n parent.type == 'AssignmentExpression' ||\n parent.type == 'UpdateExpression' ||\n grandparent.operator == 'delete') {\n sup.parent.replace(sup, b.thisExpression());\n } else if (grandparent.type == 'AssignmentExpression') {\n //superSet(sup);\n if (grandparent.operator == '=') {\n sup.parent.parent.parent.replace(sup.parent.parent, getSetCall(\"set\", sup, sup.parent.parent.right));\n dependencies[\"set\"] = true;\n } else {\n sup.parent.replace(sup, b.thisExpression());\n }\n } else {\n //superGet(sup);\n sup.parent.parent.replace(sup.parent, getSetCall(\"get\", sup));\n dependencies[\"get\"] = true;\n }\n }",
"function getFakeProtoOf(func) {\n if (typeof func === 'function') {\n var shadow = getShadow(func);\n return shadow.prototype;\n } else if (typeof func === 'object' && func !== null) {\n return func.prototype;\n } else {\n return void 0;\n }\n }",
"function inherit(base, derived)\n{\n\tderived.constructor.prototype = Object.create(base.prototype);\n\tderived.constructor.prototype.constructor = derived.constructor;\n\tfor (var k in derived) {\n\t\tif (derived.hasOwnProperty(k))\n\t\t\tderived.constructor.prototype[k] = derived[k];\n\t}\n\treturn derived.constructor;\n}",
"function ParentThirdPartyClass() {}",
"inherit(property) {\n }",
"function SuperType(name) {\n this.colors = ['red', 'green'];\n this.name = name;\n}",
"setModelSuperClassOfs() {\n for (const [modelType, subModelType] of Generator.getModelSuperClasses(this.models)) {\n if (!(modelType in this.models)) {\n // Many schema and cores skos models are missing. This is fine. If you want to see which ones, uncomment below.\n // console.warn(`setModelSuperClassOfs() - cannot find parent model \"${modelType}\"`);\n continue;\n }\n const model = this.models[modelType];\n const superClassOf = Generator.getOrSetDefaultValue(model, 'superClassOf', () => []);\n superClassOf.push(subModelType);\n }\n }",
"function ProxyBase(receiver) {\n this[kProxyProperties] = new ProxyProperties(receiver);\n\n // TODO(hansmuller): Temporary, for Chrome backwards compatibility.\n if (receiver instanceof Router)\n this.receiver_ = receiver;\n }",
"function inherit(p) {\n if (p == null) throw TypeError(); // p must be a non-null object\n if (Object.create) // If Object.create() is defined...\n return Object.create(p); // then just use it.\n \n var t = typeof p; // Otherwise do some more type checking\n if (t !== \"object\" && t !== \"function\") throw TypeError();\n function f() {}; // Define a dummy constructor function.\n f.prototype = p; // Set its prototype property to p.\n return new f(); // Use f() to create an \"heir\" of p.\n}",
"function applyInheritance() {\n // Validate arguments\n if (arguments.length < 2) {\n throw new Error(\"No inheritance classes given\");\n }\n \n var toClass = arguments[0];\n var fromClasses = Array.prototype.slice.call(arguments, 1, arguments.length);\n \n // Check if class referencer has been created\n if (applyInheritance.allClasses === undefined) {\n applyInheritance.allClasses = [];\n }\n \n // Check for inheritance metadata in toClass\n if (toClass.meta === undefined) {\n toClass.meta = {\n index: applyInheritance.allClasses.length,\n fromClasses : [],\n toClasses: []\n };\n toClass.meta.fromClasses[toClass.meta.index] = true; // class links to itself\n applyInheritance.allClasses.push(toClass);\n }\n \n // Apply inheritance fromClasses\n var fromClass = null;\n for (var i = 0; i < fromClasses.length; i++) {\n fromClass = fromClasses[i];\n \n // Check for inheritance metadata in fromClass\n if (fromClass.meta === undefined) {\n fromClass.meta = {\n index: applyInheritance.allClasses.length,\n fromClasses: [],\n toClasses: []\n };\n fromClasses[i].meta.fromClasses[fromClass.meta.index] = true; // class links to itself\n applyInheritance.allClasses.push(fromClass);\n }\n \n // Link toClass and fromClass\n toClass.meta.fromClasses[fromClass.meta.index] = true;\n fromClass.meta.toClasses[toClass.meta.index] = true;\n \n // Copy prototype fromClass toClass\n for (var property in fromClass.prototype) {\n if (toClass.prototype.hasOwnProperty(property) === false) {\n // Copy missing property from the parent class to the inheritance class\n toClass.prototype[property] = fromClass.prototype[property];\n }\n }\n }\n}",
"Super() {\n this._eat(\"super\");\n return {\n type: \"Super\",\n };\n }",
"static lokify() {\n var args = Array.prototype.slice.call(arguments)\n if (args && args.length > 0) {\n args.forEach((klass) => {\n klass.prototype.transform = Loki.prototype.transform\n })\n }\n }",
"enterInheritanceModifier(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Universal Coordinated Time (UTC) of solar noon for the given day at the given location on earth in degrees in minutes from zero Z | function calcSolNoonUTC(t, longitude) {
// First pass uses approximate solar noon to calculate eqtime
var tnoon = calcTimeJulianCent(calcJDFromJulianCent(t) + longitude/360.0);
var eqTime = calcEquationOfTime(tnoon);
var solNoonUTC = 720 + (longitude * 4) - eqTime; // min
var newt = calcTimeJulianCent(calcJDFromJulianCent(t) -0.5 + solNoonUTC/1440.0);
eqTime = calcEquationOfTime(newt);
// var solarNoonDec = calcSunDeclination(newt);
solNoonUTC = 720 + (longitude * 4) - eqTime; // min
return solNoonUTC;
} | [
"function calcSunriseUTC(JD, latitude, longitude) {\n var t = calcTimeJulianCent(JD);\n // Find the time of solar noon at the location, and use that declination.\n // This is better than start of the Julian Day\n var noonmin = calcSolNoonUTC(t, longitude);\n var tnoon = calcTimeJulianCent (JD+noonmin/1440.0);\n // First pass to approximate sunrise (using solar noon)\n var eqTime = calcEquationOfTime(tnoon);\n var solarDec = calcSunDeclination(tnoon);\n var hourAngle = calcHourAngleSunrise(latitude, solarDec);\n var delta = longitude - radToDeg(hourAngle);\n var timeDiff = 4 * delta; // in minutes of time\n var timeUTC = 720 + timeDiff - eqTime; // in minutes\n // alert(\"eqTime = \" + eqTime + \"\\nsolarDec = \" + solarDec + \"\\ntimeUTC = \" + timeUTC);\n // Second pass includes fractional jday in gamma calc\n var newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); \n eqTime = calcEquationOfTime(newt);\n solarDec = calcSunDeclination(newt);\n hourAngle = calcHourAngleSunrise(latitude, solarDec);\n delta = longitude - radToDeg(hourAngle);\n timeDiff = 4 * delta;\n timeUTC = 720 + timeDiff - eqTime; // in minutes\n // alert(\"eqTime = \" + eqTime + \"\\nsolarDec = \" + solarDec + \"\\ntimeUTC = \" + timeUTC);\n return timeUTC;\n}",
"function calculate_time_zone() {\n\tvar rightNow = new Date();\n\tvar jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); // jan 1st\n\tvar june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st\n\tvar temp = jan1.toGMTString();\n\tvar jan2 = new Date(temp.substring(0, temp.lastIndexOf(\" \")-1));\n\ttemp = june1.toGMTString();\n\tvar june2 = new Date(temp.substring(0, temp.lastIndexOf(\" \")-1));\n\tvar std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);\n\tvar daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);\n\tvar dst;\n\tif (std_time_offset == daylight_time_offset) {\n\t\tdst = \"0\"; // daylight savings time is NOT observed\n\t} else {\n\t\t// positive is southern, negative is northern hemisphere\n\t\tvar hemisphere = std_time_offset - daylight_time_offset;\n\t\tif (hemisphere >= 0)\n\t\t\tstd_time_offset = daylight_time_offset;\n\t\tdst = \"1\"; // daylight savings time is observed\n\t}\n\tvar i;\n\t// check just to avoid error messages\n\tif (document.getElementById('timezone')) {\n\t\tfor (i = 0; i < document.getElementById('timezone').options.length; i++) {\n\t\t\tif (document.getElementById('timezone').options[i].value == convert(std_time_offset)+\",\"+dst) {\n\t\t\t\tdocument.getElementById('timezone').selectedIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}",
"function calcSun() {\n\tvar latitude = getLatitude();\n\tvar longitude = getLongitude();\n\tvar indexRS = solarDateTimeLatLong.mos;\n if (isValidInput(indexRS)) {\n if((latitude >= -90) && (latitude < -89)) {\n alert(\"All latitudes between 89 and 90 S\\n will be set to -89\");\n solarDateTimeLatLong.latDeg = -89;\n latitude = -89;\n }\n if ((latitude <= 90) && (latitude > 89)) {\n alert(\"All latitudes between 89 and 90 N\\n will be set to 89\");\n solarDateTimeLatLong.latDeg = 89;\n latitude = 89;\n }\n // Calculate the time of sunrise\n var JD = calcJD(parseFloat(solarDateTimeLatLong.year), indexRS + 1, parseFloat(solarDateTimeLatLong.day));\n var dow = calcDayOfWeek(JD);\n var doy = calcDayOfYear(indexRS + 1, parseFloat(solarDateTimeLatLong.day), isLeapYear(solarDateTimeLatLong.year));\n var T = calcTimeJulianCent(JD);\n var alpha = calcSunRtAscension(T);\n var theta = calcSunDeclination(T);\n var Etime = calcEquationOfTime(T);\n // solarRiseSet.dbug = doy;\n var eqTime = Etime;\n var solarDec = theta;\n // Calculate sunrise for this date if no sunrise is found, set flag nosunrise\n var nosunrise = false;\n var riseTimeGMT = calcSunriseUTC(JD, latitude, longitude);\n if (!isNumber(riseTimeGMT)) {\n nosunrise = true;\n }\n // Calculate sunset for this date if no sunset is found, set flag nosunset\n var nosunset = false;\n var setTimeGMT = calcSunsetUTC(JD, latitude, longitude);\n if (!isNumber(setTimeGMT)) {\n nosunset = true;\n }\n var daySavings = solarDateTimeLatLong.daySavings; // = 0 (no) or 60 (yes)\n var zone = solarDateTimeLatLong.hrsToGMT;\n if(zone > 12 || zone < -12.5) {\n alert(\"The offset must be between -12.5 and 12. \\n Setting \\\"Off-Set\\\"=0\");\n zone = \"0\";\n solarDateTimeLatLong.hrsToGMT = zone;\n }\n if (!nosunrise) { // Sunrise was found\n var riseTimeLST = riseTimeGMT - (60 * zone) + daySavings; // in minutes\n var riseStr = timeStringShortAMPM(riseTimeLST, JD);\n var utcRiseStr = timeStringDate(riseTimeGMT, JD);\n solarRiseSet.sunrise = riseStr;\n solarRiseSet.utcSunrise = utcRiseStr;\n }\n if (!nosunset) { // Sunset was found\n var setTimeLST = setTimeGMT - (60 * zone) + daySavings;\n var setStr = timeStringShortAMPM(setTimeLST, JD);\n var utcSetStr = timeStringDate(setTimeGMT, JD);\n solarRiseSet.sunset = setStr;\n solarRiseSet.utcSunset = utcSetStr;\n }\n // Calculate solar noon for this date\n var solNoonGMT = calcSolNoonUTC(T, longitude);\n var solNoonLST = solNoonGMT - (60 * zone) + daySavings;\n var solnStr = timeString(solNoonLST);\n var utcSolnStr = timeString(solNoonGMT);\n solarRiseSet.solnoon = solnStr;\n solarRiseSet.utcSolnoon = utcSolnStr;\n var tsnoon = calcTimeJulianCent(calcJDFromJulianCent(T) -0.5 + solNoonGMT/1440.0);\n eqTime = calcEquationOfTime(tsnoon);\n solarDec = calcSunDeclination(tsnoon);\n solarRiseSet.eqTime = (Math.floor(100*eqTime))/100;\n solarRiseSet.solarDec = (Math.floor(100*(solarDec)))/100;\n // Convert lat and long to standard format\n convLatLong();\n // report special cases of no sunrise\n if(nosunrise) {\n solarRiseSet.utcSunrise = \"\";\n // if Northern hemisphere and spring or summer, OR\n // if Southern hemisphere and fall or winter, use\n // previous sunrise and next sunset\n if (((latitude > 66.4) && (doy > 79) && (doy < 267)) || ((latitude < -66.4) && ((doy < 83) || (doy > 263)))) {\n newjd = findRecentSunrise(JD, latitude, longitude);\n newtime = calcSunriseUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n if (newtime > 1440) {\n newtime -= 1440;\n newjd += 1.0;\n }\n if (newtime < 0) {\n newtime += 1440;\n newjd -= 1.0;\n }\n solarRiseSet.sunrise = timeStringAMPMDate(newtime, newjd);\n solarRiseSet.utcSunrise = \"prior sunrise\";\n }\n // if Northern hemisphere and fall or winter, OR\n // if Southern hemisphere and spring or summer, use\n // next sunrise and previous sunset\n else if (((latitude > 66.4) && ((doy < 83) || (doy > 263))) || ((latitude < -66.4) && (doy > 79) && (doy < 267))) {\n newjd = findNextSunrise(JD, latitude, longitude);\n newtime = calcSunriseUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n if (newtime > 1440) {\n newtime -= 1440;\n newjd += 1.0;\n }\n if (newtime < 0) {\n newtime += 1440;\n newjd -= 1.0;\n }\n solarRiseSet.sunrise = timeStringAMPMDate(newtime, newjd);\n // solarRiseSet.sunrise = calcDayFromJD(newjd) + \" \" + timeStringDate(newtime, newjd);\n solarRiseSet.utcSunrise = \"next sunrise\";\n }\n else {\n alert(\"Cannot Find Sunrise!\");\n }\n // alert(\"Last Sunrise was on day \" + findRecentSunrise(JD, latitude, longitude));\n // alert(\"Next Sunrise will be on day \" + findNextSunrise(JD, latitude, longitude));\n }\n if(nosunset) {\n solarRiseSet.utcSunset = \"\";\n // if Northern hemisphere and spring or summer, OR\n // if Southern hemisphere and fall or winter, use\n // previous sunrise and next sunset\n if (((latitude > 66.4) && (doy > 79) && (doy < 267)) || ((latitude < -66.4) && ((doy < 83) || (doy > 263)))) {\n newjd = findNextSunset(JD, latitude, longitude);\n newtime = calcSunsetUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n if (newtime > 1440) {\n newtime -= 1440;\n newjd += 1.0;\n }\n if (newtime < 0) {\n newtime += 1440;\n newjd -= 1.0;\n }\n solarRiseSet.sunset = timeStringAMPMDate(newtime, newjd);\n solarRiseSet.utcSunset = \"next sunset\";\n solarRiseSet.utcSolnoon = \"\";\n }\n // if Northern hemisphere and fall or winter, OR\n // if Southern hemisphere and spring or summer, use\n // next sunrise and last sunset\n else if (((latitude > 66.4) && ((doy < 83) || (doy > 263))) || ((latitude < -66.4) && (doy > 79) && (doy < 267))) {\n \tnewjd = findRecentSunset(JD, latitude, longitude);\n \tnewtime = calcSunsetUTC(newjd, latitude, longitude) - (60 * zone) + daySavings;\n \tif (newtime > 1440) {\n \t\tnewtime -= 1440;\n \t\tnewjd += 1.0;\n \t}\n \tif (newtime < 0) {\n \t\tnewtime += 1440;\n \t\tnewjd -= 1.0;\n \t}\n \tsolarRiseSet.sunset = timeStringAMPMDate(newtime, newjd);\n \tsolarRiseSet.utcSunset = \"prior sunset\";\n \tsolarRiseSet.solnoon = \"N/A\";\n \tsolarRiseSet.utcSolnoon = \"\";\n }\n else {\n alert (\"Cannot Find Sunset!\");\n }\n }\n }\n}",
"function fake_sun_position(now, dawn, dusk) {\n const n = new Date(now);\n const hour = n.getHours() + n.getMinutes() / 60 + n.getSeconds() / 3600;\n winston.debug(\"calculating fake sun position\", hour, dawn, dusk);\n const x = (hour + 24 - dawn) % 24; // hours since dawn\n const y = (dusk + 24 - dawn) % 24; // hours in day\n return Math.min(2, x / y) * Math.PI;\n}",
"function pacificTimeOffset(date) {\n return isDaylightTime(date) ? PDT : PST;\n}",
"function utcTime() {\n var today = new Date();\n var hh = today.getHours();\n var mm = today.getMinutes();\n var ss = today.getSeconds();\n hh = checkTime(hh);\n mm = checkTime(mm);\n ss = checkTime(ss);\n\n updateElement('span.utcdigit.hours',hh);\n updateElement('span.utcdigit.minutes',mm);\n updateElement('span.utcdigit.seconds',ss);\n updateElement('span.value_gmttimestring',hh+ ' '+ mm + \"o clock\");\n }",
"function getTime(city) {\n let time = new Date();\n time.setHours(time.getUTCHours() + city.gmtOffset);\n return time;\n}",
"async localTimeToUTC(localTime) {\n let dateIsoString;\n if (typeof localTime === \"string\") {\n dateIsoString = localTime;\n }\n else {\n dateIsoString = dateAdd(localTime, \"minute\", localTime.getTimezoneOffset() * -1).toISOString();\n }\n const res = await spPost(TimeZone(this, `localtimetoutc('${dateIsoString}')`));\n return hOP(res, \"LocalTimeToUTC\") ? res.LocalTimeToUTC : res;\n }",
"function convertToUtc(dateInLocal, timeInLocal, timezone) {\n // Construct a new time \n var workTime = new Date(dateInLocal.getFullYear(), dateInLocal.getMonth(), dateInLocal.getDate(), timeInLocal.getHours(), timeInLocal.getMinutes());\n var timeWrapper = moment(workTime);\n // The above time should be interpreted in the given timezone\n if (timezone) {\n // Utc time\n timeWrapper.subtract(timezone, 'hours');\n }\n // Convert to UTC time\n var timeInUtc = new Date(Date.UTC(timeWrapper.year(), timeWrapper.month(), timeWrapper.date(), timeWrapper.hour(), timeWrapper.minute(), timeWrapper.second()));\n return timeInUtc;\n }",
"function findAndSetSuntimeOnDate(whatDay, bSunRise, d) {\n var thatDaysSunInfo = new SunriseSunset( whatDay.getFullYear(), whatDay.getMonth()+1, whatDay.getDate(), my.data.latitude, my.data.longitude );\n\n var rawTime;\n\n if ( bSunRise ) {\n rawTime = thatDaysSunInfo.sunriseLocalHours( -( whatDay.getTimezoneOffset() ) / 60 );\n } else {\n rawTime = thatDaysSunInfo.sunsetLocalHours( -( whatDay.getTimezoneOffset() ) / 60 );\n }\n\n d.setHours(Math.abs(rawTime));\n d.setMinutes(Math.abs((rawTime % 1)* 60)); // mod 1 gives just decimal part of number\n }",
"function getUtcNow() {\n var now = new Date();\n var offset = getTimezoneOffset();\n return convertToUtc(now, now, offset);\n }",
"function getEasternOffset() {\r\n return 300;\r\n }",
"function getOnsetAsUTC(obs, localdate) {\n //return new Date(localdate.getTime() - obs.offsetFrom);\n return localdate - obs.offsetFrom;\n }",
"browser_timezone_offset(minute_offset) {\n const offset_string = (minute_offset / -60).toString()\n\n var sign;\n var hours;\n\n if (offset_string.includes(\".\")) {\n throw \"Critter4Us doesn't work in timezones a fractional hour away from UTC\";\n }\n\n if (offset_string.slice(0, 1) == \"-\") {\n sign = \"-\";\n hours = offset_string.slice(1);\n } else {\n sign = \"+\";\n hours = offset_string;\n }\n\n if (hours.length == 1) {\n hours = \"0\" + hours;\n }\n\n return sign + hours + \":00\";\n }",
"function findRecentSunset(jd, latitude, longitude) {\n var julianday = jd;\n var time = calcSunsetUTC(julianday, latitude, longitude);\n while(!isNumber(time)) {\n julianday -= 1.0;\n time = calcSunsetUTC(julianday, latitude, longitude);\n }\n return julianday;\n}",
"function calcSunEqOfCenter(t) {\n var m = calcGeomMeanAnomalySun(t);\n var mrad = degToRad(m);\n var sinm = Math.sin(mrad);\n var sin2m = Math.sin(mrad+mrad);\n var sin3m = Math.sin(mrad+mrad+mrad);\n var C = sinm * (1.914602 - t * (0.004817 + 0.000014 * t)) + sin2m * (0.019993 - 0.000101 * t) + sin3m * 0.000289;\n return C; // in degrees\n}",
"function findRecentSunrise(jd, latitude, longitude) {\n var julianday = jd;\n var time = calcSunriseUTC(julianday, latitude, longitude);\n while(!isNumber(time)) {\n julianday -= 1.0;\n time = calcSunriseUTC(julianday, latitude, longitude);\n }\n return julianday;\n}",
"function calcSunApparentLong(t) {\n var o = calcSunTrueLong(t);\n var omega = 125.04 - 1934.136 * t;\n var lambda = o - 0.00569 - 0.00478 * Math.sin(degToRad(omega));\n return lambda; // in degrees\n}",
"function SunLongitude(jdn) {\r\n var T, T2, dr, M, L0, DL, lambda, theta, omega;\r\n T = (jdn - 2451545.0) / 36525; // Time in Julian centuries from 2000-01-01 12:00:00 GMT\r\n T2 = T * T;\r\n dr = PI / 180; // degree to radian\r\n M = 357.5291 + 35999.0503 * T - 0.0001559 * T2 - 0.00000048 * T * T2; // mean anomaly, degree\r\n L0 = 280.46645 + 36000.76983 * T + 0.0003032 * T2; // mean longitude, degree\r\n DL = (1.9146 - 0.004817 * T - 0.000014 * T2) * Math.sin(dr * M);\r\n DL =\r\n DL +\r\n (0.019993 - 0.000101 * T) * Math.sin(dr * 2 * M) +\r\n 0.00029 * Math.sin(dr * 3 * M);\r\n theta = L0 + DL; // true longitude, degree\r\n // obtain apparent longitude by correcting for nutation and aberration\r\n omega = 125.04 - 1934.136 * T;\r\n lambda = theta - 0.00569 - 0.00478 * Math.sin(omega * dr);\r\n // Convert to radians\r\n lambda = lambda * dr;\r\n lambda = lambda - PI * 2 * INT(lambda / (PI * 2)); // Normalize to (0, 2*PI)\r\n return lambda;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an anum type. Examples ```ts db.schema.createType('species').asEnum(['cat', 'dog', 'frog']) ``` | asEnum(values) {
return new CreateTypeBuilder({
...this.#props,
node: create_type_node_js_1.CreateTypeNode.cloneWithEnum(this.#props.node, values),
});
} | [
"function addType() {\n\t\tvar args = extract(\n\t\t\t{ name: 'name', test: function(o) { return typeof o === 'string'; } },\n\t\t\t{ name: 'type', parse: function(o) {\n\t\t\t\treturn (o instanceof Type) ? o : new Type(this.name || o.name, o);\n\t\t\t} }\n\t\t).from(arguments);\n\n\t\ttypeList.push(args.type);\n\t}",
"_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}",
"function AddEnumItem() {\n let e = d.Config.enums\n let enumName = u.ID(\"selectAdminEnum\").value;\n e[enumName].push(\"\");\n u.WriteConfig();\n}",
"function makeEnum(strArr) {\n\tvar ret = {};\n\tfor (var i=0;i<strArr.length;++i) {\n\t\tvar str = strArr[i];\n\t\tif (typeof str == 'string') {\n\t\t\tret[str] = i;\n\t\t} else { // assume an object with a 'name' member\n\t\t\tret[str.name] = i;\n\t\t}\n\t}\n\treturn ret;\n}",
"static from(type, value) {\n return new Typed(_gaurd, type, value);\n }",
"typeSpec() {\n const token = this.currentToken;\n if (this.currentToken.type === tokens.INTEGER) {\n this.eat(tokens.INTEGER);\n } else if (this.currentToken.type === tokens.REAL) {\n this.eat(tokens.REAL);\n }\n return new Type(token);\n }",
"function createTypeOpAttr(attrName, dtype) {\n return {\n name: attrName,\n type: nodeBackend().binding.TF_ATTR_TYPE,\n value: getTFDType(dtype)\n };\n}",
"static registerType(type) { ShareDB.types.register(type); }",
"static of(type) {\n return new ResponseType(type.toUpperCase());\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 }",
"createOrReplaceType(name) {\n\t\treturn this.declareType(name);\n\t}",
"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 }",
"addTypes(types) {\n for (const [key, value] of Object.entries(types)) {\n this.addType(key, value);\n }\n return this;\n }",
"function AddElementType (type)\n{\n\treturn (doActionEx('MPEA_ADD_ELEMENT', 'ElementID', 'ElementType', type));\n}",
"function factory (type, config, load, typed) {\n // create a new data type\n function MyType (value) {\n this.value = value\n }\n MyType.prototype.isMyType = true\n MyType.prototype.toString = function () {\n return 'MyType:' + this.value\n }\n\n // define a new data type\n typed.addType({\n name: 'MyType',\n test: function (x) {\n // test whether x is of type MyType\n return x && x.isMyType\n }\n })\n\n // return the construction function, this will\n // be added to math.type.MyType when imported\n return MyType\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 }",
"consoleParseTypes(input) { return Parser.parse(input, { startRule: 'TYPES' }); }",
"function createAssetType(axios$$1, assetType) {\n return restAuthPost(axios$$1, 'assettypes/', assetType);\n }",
"function caricaSelectEnum(list, select, /* Optional */ emptyValue) {\n var i;\n var el;\n var len = list.length;\n var str = \"<option value='\" + (emptyValue || \"\") + \"'></option>\";\n for (i = 0; i < len; i++) {\n el = list[i];\n str += \"<option value='\" + el._name + \"'>\" + el.codice + \" - \" + el.descrizione + \"</option>\";\n }\n return select.append(str);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the keys of current user's favorites. | getFavoriteKeys() {
return apiFetch(
{
path: '/vtblocks/v1/layouts/favorites',
method: 'GET',
}
).then(
favorite_keys => {
return favorite_keys;
}
).catch(
error => console.error( error )
);
} | [
"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}",
"function checkFavorites() {\n if (localStorage.getItem(\"favorites\") == null) {\n favoritesArray = [];\n localStorage.setItem(\"favorites\", JSON.stringify(favoritesArray));\n } else {\n favoritesArray = JSON.parse(localStorage.getItem(\"favorites\"));\n }\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 }",
"getFavorite(cardId) {\n if(this.user==false)return false;\n for(const card of this.user.savedCards){\n //console.log(card.cardID+\" vs \"+cardId);\n if(card.cardID == cardId)return card.favorited;\n\n }\n return false;\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 checkForFavs() {\n for(let favStory of $(user.favorites)){\n let favStoryID = favStory.storyId;\n\n $(`#${favStoryID}`).find(\".fa-heart\").toggleClass(\"far fas\");\n }\n }",
"function getFavorites(success, error){\n let baseUrl = \"/favorites\";\n baseXHRGet(baseUrl, success, error);\n }",
"function checkOwnFavs(){\n if( ! conf.ownFavs || ! tweet.favorited ){\n return checkFinal();\n }\n checkOwnFavourite( tweet.id_str, function( favourited ){\n if( favourited ){\n console.log('Keeping tweet favourited by self');\n return nextTweet();\n }\n checkFinal();\n } );\n }",
"function listKeys() {\n let keyString = \"\";\n for (let key in flower) {\n keyString += key + \", \";\n }\n return keyString;\n}",
"static async getAllKeys() {\n try {\n const allKeys = await StorageSystem.getAllKeys();\n return allKeys\n } catch (err) {\n return []\n }\n }",
"function printFavorites() {\n\t// DONE: clear out favorites section each time\n\t// before displaying new list of favorites\n\tlist.innerHTML = '';\n\n\n\t// TODO: concatenate all the favorites into one string\n\t// - hint: loop through all the favorites\n\t// - this should be stored in a variable named favoritesText\n\t// - each favorite should have an html br element between it (EG: \"<br>\")\n\tvar favoritesText='';\n\t\n\tfavorites.forEach(print);\n\tfunction print(favorite) {\n\t\tfavoritesText += favorite + '<br />';\n\t};\n\n\n\t// DONE: update the list element with the\n\t// new list of favorites\n\tlist.innerHTML = favoritesText;\n}",
"getDatasetsKeys(){\n let keys=this.localStorageService.keys();\n\n return keys;\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 addToFavorites(event) {\n event.preventDefault()\n let favorites = JSON.parse(localStorage.getItem(\"favorites\"))\n let id = getId(this)\n if (favorites.indexOf(id) < 0) {\n favorites.push(id)\n }\n localStorage.setItem(\"favorites\", JSON.stringify(favorites))\n changeTextIfFavorite(this)\n animateHeart(event.x, event.y)\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 }",
"selectInputSourceFavorites() {\n this._selectInputSource(\"i_favorites\");\n }",
"InitialState () {\n const state = localStorage.getItem(this.key)\n if (state) {\n try {\n const parsedState = JSON.parse(state)\n return {\n Favorites: parsedState\n }\n } catch (e) {\n return { Favorites: { favorites: {} } }\n }\n } else return { Favorites: { favorites: {} } }\n }",
"async retrieveUserTopTracks() {\n let topTracks = await this.spotify.getMyTopTracks();\n const features = await this.getAudioFeatures(topTracks.body.items);\n return features;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
import BeerFavourites from './components/BeerFavourites'; | function App() {
return (
<div className="App">
<img src="brewdoglogo.png" width="175" height="200"/>
<BeerContainer />
{/* <BeerFavourites /> */}
</div>
);
} | [
"function bouUp () {\r\n return(\r\n \r\n <AppComponent/>\r\n\r\n //<displayWeather/>\r\n\r\n \r\n );\r\n}",
"function App() {\n return (\n <div>\n {/* <BaiTapBurger /> */}\n <BaiTapBauCua />\n </div>\n );\n}",
"function App() {\n return (\n <div className=\"App\">\n <h1>PokeList</h1>\n <VisibilityButton/>\n <PokeList />\n </div>\n );\n}",
"componentDidMount() {\n this.props.listRestaurants();\n }",
"function index() {\n return (\n <div>\n <ShowHome />\n </div>\n )\n}",
"function App() {\n return (\n <div className=\"App\">\n <Navbar/>\n <ListCards/>\n </div>\n );\n}",
"ImportComponent(string, string) {\n\n }",
"function ListOfAnimals() {\n const [animals, setAnimals] = useState([]);\n\n useEffect(() => {\n import(\n /* webpackChunkName: \"animal-picker\" */\n /* webpackPrefetch: true */\n \"./utils/animal-picker\"\n ).then(({ default: animalPicker }) => {\n setAnimals(animalPicker('turtle'));\n });\n }, []);\n\n return (\n <div>\n <h2>Here are some animals</h2>\n {animals.map((animal) => (\n <div key={animal}>{animal}</div>\n ))}\n </div>\n );\n}",
"function App() {\n return (\n <div className=\"App\">\n <Provider store={store}>\n <BoardContainer></BoardContainer>\n </Provider>\n </div>\n );\n}",
"function JokeApp() {\n var jokeComponents\n\n //this de hua more longer\n //jokeComponents = jokesData.map(joke => <Meme id={joke.id} question={joke.question} punchLine={joke.punchLine} />)\n\n //this de hua shorter, but need add something in the Meme.js --> add 'jd'\n jokeComponents = jokesData.map(joke => <Meme id={joke.id} jd={joke}/>)\n\n return (\n <div>\n {jokeComponents} \n </div>\n )\n}",
"render(){\n return (\n <div>\n <h1>This is the Read component!</h1>\n <Movies movies={this.state.movies}></Movies>\n </div>\n );\n }",
"function App() {\n return (\n <div className=\"App\">\n <TopBar/>\n\n <RecentDonations/>\n\n {/* <ProgressDonations/> */}\n </div>\n\n );\n}",
"buildFavoriteBadge(){\n const displayFavBadge = <BuildFavBadge />;\n this.setState({displayFavBadge: displayFavBadge});\n }",
"function fetchBurgers(){\n fetch(\"http://localhost:3000/burgers\")\n .then(r=>r.json())\n .then(burgers => renderAllBurgers(burgers))\n}",
"componentDidMount(){\n const detailId = this.props.match.params.id\n\n axios.get(`${BASE_API_URL}/guest/favorites/${detailId}`).then((response) => {\n this.setState({\n details:response.data.data\n })\n })\n }",
"render () {\n let contents = this.state.loading\n ? <p><em>Loading...</em></p>\n : FetchData.renderForecastsTable(this.state.forecasts);\n\n return (\n <div>\n <h1>Weather forecast</h1>\n <p>This component demonstrates fetching data from the server.</p>\n {contents}\n </div>\n );\n }",
"function App() {\n return (\n <GlobalProvider>\n <header className=\"text-center\">\n <h2>Crocodic Test</h2>\n </header>\n <Switch>\n <Route path=\"/\" component={ListUser} exact />\n <Route path=\"/create\" component={CreateUser} exact />\n <Route path=\"/edit/:id\" component={EditUser} exact />\n <Route path=\"/detail/:id\" component={DetailUser} exact />\n </Switch>\n\n {/* <div className=\"container\">\n <h2>Backend DataTest</h2>\n\n <TestUser />\n </div> */}\n </GlobalProvider>\n );\n}",
"function BioBricksItem(props) {\n return (\n <div className=\"team-item\">\n <h2 className=\"team-item-header\">\n {props.item.title}</h2>\n <p className=\"team-item-descr\">{props.item.description}</p>\n <p className=\"team-item-wiki\">{\"url: \"}\n <a className=\"wiki-link\"\n href={props.item.wiki}\n target=\"_blank\"\n rel=\"noopener noreferrer\">\n {props.item.wiki}\n </a>\n </p>\n <hr/>\n </div>\n )\n}",
"importFromBookmarksFile() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the wip segment only exists if there is a wipshape in progress with a point. | get wipSegment() {
if (this.wip == null) return null;
if (this.wip.points.length === 0) return null;
return [ last(this.wip.points), this.mouse ];
} | [
"function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}",
"function check_point(p) {\n if (p.x < 0 || p.x > 9) {\n return false;\n } else if (p.y < 0 || p.y > 9) {\n return false;\n } else if (spielfeld[p.y][p.x]) {\n //console.log(\"point already in use:\", p);\n return false;\n } else {\n //console.log(\"point ok:\", p);\n return true;\n }\n}",
"localClipped (x, y) {\n if (x !== null && (x < 0 || x >= this.Config.size.width)) return true;\n if (y !== null && (y < 0 || y >= this.Config.size.height)) return true;\n return false;\n }",
"function isPointOnBezierExtension(ps, p) {\n if (ps.length === 4) {\n return isPointOnBezierExtension3(ps, p);\n }\n if (ps.length === 3) {\n return isPointOnBezierExtension2(ps, p);\n }\n return isPointOnBezierExtension1(ps, p);\n}",
"isInside(modelSpacePoint) {\n\t\t// jshint unused:vars\n\t\treturn false;\n\t}",
"function pointIsInCanvas(x, y, w, h) {\n return x >= 0 && x <= w && y >= 0 && y <= h;\n}",
"point(param) {\n return this._edgeSegment.point(param);\n }",
"function projectPointOntoSegment(px, py, vx, vy, wx, wy) {\n var l2 = dist2(vx, vy, wx, wy);\n if (l2 === 0) return new Point(vx, vy);\n \n var t = ((px - vx) * (wx - vx) + (py - vy) * (wy - vy)) / l2;\n if (t < 0) return new Point(vx, vy);\n if (t > 1) return new Point(wx, wy);\n return new Point( vx + t * (wx - vx),\n vy + t * (wy - vy));\n}",
"allow_point(idea_id, user_socket_id, positive_point){\n let add_socket_id = true;\n let existing = false\n let index = -1\n // Finds if the user already gave some sort of point and gets the index of it\n for(let i = 0; i < this.parent.room.ideas[idea_id].socket_ids_who_gave_point.length && !existing; i++){\n existing = (String(this.parent.room.ideas[idea_id].socket_ids_who_gave_point[i].socket_id) == String(user_socket_id))\n if(existing){\n index = i\n }\n }\n \n // If the user gave any points\n if(index >= 0){\n // if the user wants to give positive point, but already gave negative, or\n // if the user wants to give negative point, but already gave positive,\n // delete the existing one, and allow the user to make change\n if(positive_point != this.parent.room.ideas[idea_id].socket_ids_who_gave_point[index].positive_point){\n add_socket_id = false;\n this.parent.room.ideas[idea_id].socket_ids_who_gave_point.splice(index, 1);\n return true;\n }\n }\n\n if(add_socket_id && index < 0){\n this.parent.room.ideas[idea_id].socket_ids_who_gave_point.push({\n socket_id: user_socket_id,\n positive_point: positive_point\n });\n }\n\n return index < 0;\n }",
"contains(x, y) {\r\n if (!this.isEnabled()) return false;\r\n if (x < this.at().x || x > (this.at().x + this.width())) return false;\r\n if (y < this.at().y || y > (this.at().y + this.height())) return false;\r\n return true;\r\n }",
"function includes(b, p) {\n return p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height;\n}",
"snappingVertexData(point) {\n // build a list of vertices (in RWU) available for snapping\n // deep copy all vertices on the current story\n let snappableVertices = [...this.currentStoryGeometry.vertices];\n\n // TODO: conditionally combine this list with vertices from the next story down if it is visible\n if (this.previousStoryGeometry) {\n snappableVertices = snappableVertices.concat(JSON.parse(JSON.stringify(this.previousStoryGeometry.vertices)));\n }\n\n // if the polygon tool is active and the polygon being drawn has at least 3 existing points allow snapping to the origin of the polygon\n if (this.points.length >= 3 && this.currentTool === 'Polygon') {\n // convert the polygon origin from grid units to real world units before adding it as a snappable vertex\n snappableVertices.push({\n ...this.points[0],\n origin: true, // set a flag to mark the origin\n });\n }\n\n if (this.points.length === 1 && this.currentTool === 'Rectangle') {\n snappableVertices = snappableVertices.concat(\n geometryHelpers.syntheticRectangleSnaps(\n snappableVertices,\n this.points[0],\n point),\n );\n }\n\n if (!snappableVertices.length) { return null; }\n\n // find the vertex closest to the point being tested\n const nearestVertex = snappableVertices.reduce((a, b) => {\n const aDist = this.distanceBetweenPoints(a, point);\n const bDist = this.distanceBetweenPoints(b, point);\n return aDist < bDist ? a : b;\n });\n\n // return the nearest vertex if it is within the snap tolerance of the point\n if (this.distanceBetweenPoints(nearestVertex, point) < this.$store.getters['project/snapTolerance']) {\n return {\n ...nearestVertex,\n type: 'vertex',\n };\n }\n }",
"remove(point) {\n if (this.divided) {\n // If there are children then perform the removal on them\n this.children.forEach(child => {\n child.remove(point);\n });\n // Check if quads can be merged, being placed here is performed recursively from inner to outer quads\n this.merge();\n }\n\n // There are no children so check the current quad\n if (this.boundary.contains(point)) {\n // Filter the points that coincide with the target to remove\n this.points = this.points.filter(p => p.x !== point.x || p.y !== point.y);\n }\n }",
"function insideAnyPolygon(point, vs) { \r\n if(typeof vs == 'string'){\r\n\t vs = JSON.parse(vs);\t \r\n }\r\n if(typeof point == 'string'){\r\n\t point = JSON.parse(point);\t \r\n }\r\n var isInside = false; \r\n var isArray = Array.isArray(vs);\r\n var lengthArray = 0;\r\n if(isArray){\r\n \tlengthArray = vs.length;\r\n } \r\n for (var dim = 0; dim < lengthArray; dim++) {\r\n\t \tconsole.log(\"polygon dimension: \"+dim)\r\n\t \t//console.log(vs[dim])\r\n\t \tisInside = isInside || inside(point, vs[dim]);\r\n\t \tconsole.log(\"Point is inside polygon: \"+isInside) \r\n\t \tif(isInside) return isInside;\r\n } \r\n return isInside;\r\n}",
"function CheckArrayContainsW(w) {\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 return arrWidth[i];\r\n }\r\n}",
"addDot(x,y){\n\n if (x >= this.lines || y >= this.lines){\n // out of range!!\n //console.log(\"(addDot): index out of range\");\n return;\n }\n\n let empty_pos = this.free_pos.findIndex((element) => (element.x == x && element.y == y));\n if (empty_pos != -1)\n {\n this.free_pos.splice(empty_pos,1);\n }\n else\n {\n //console.log(\"(addDot): spot already taken.\");\n return;\n }\n\n let shift = this.size/4;\n let line_distance = (this.size/this.lines) /2;\n\n let x_pos = x*line_distance+(line_distance/2)-shift;\n\n let y_pos = y*line_distance+(line_distance/2)-shift;\n\n this.dots.push(new Polygon({\n win: this.win,\n name: 'circle',\n size: this.dot_size,\n lineColor: new Color('black'),\n fillColor: new Color('white'),\n edges: 32,\n pos: [x_pos,y_pos]\n }));\n }",
"function is_pivot(piece, x, y)\n{\n\treturn piece.pivot_x == x && piece.pivot_y == y;\n}",
"hasWallInDirection (x, y, direction) {\n return !(this.getBlockValue(x, y) & direction);\n }",
"contains(x, y) {\r\n return inside([x, y], this.polygon);\r\n }",
"isOverflight() {\n return this.origin === '' && this.destination === '';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Date picker manager. Use the singleton instance of this class, $.datepick, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. | function Datepick() {
this._uuid = new Date().getTime(); // Unique identifier seed
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
clearText: 'Clear', // Display text for clear link
clearStatus: 'Erase the current date', // Status text for clear link
closeText: 'Close', // Display text for close link
closeStatus: 'Close without change', // Status text for close link
prevText: '<Prev', // Display text for previous month link
prevStatus: 'Show the previous month', // Status text for previous month link
prevBigText: '<<', // Display text for previous year link
prevBigStatus: 'Show the previous year', // Status text for previous year link
nextText: 'Next>', // Display text for next month link
nextStatus: 'Show the next month', // Status text for next month link
nextBigText: '>>', // Display text for next year link
nextBigStatus: 'Show the next year', // Status text for next year link
currentText: 'Today', // Display text for current month link
currentStatus: 'Show the current month', // Status text for current month link
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months for drop-down and formatting
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
monthStatus: 'Show a different month', // Status text for selecting a month
yearStatus: 'Show a different year', // Status text for selecting a year
weekHeader: 'Wk', // Header for the week of the year column
weekStatus: 'Week of the year', // Status text for the week of the year column
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
dayStatus: 'Set DD as first week day', // Status text for the day of the week selection
dateStatus: 'Select DD, M d', // Status text for the date selection
dateFormat: 'mm/dd/yy', // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
initStatus: 'Select a date', // Initial Status text on opening
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: '' // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
useThemeRoller: false, // True to apply ThemeRoller styling, false for default styling
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
showAnim: 'show', // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
duration: 'normal', // Duration of display/closure
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
alignment: 'bottom', // Alignment of popup - with nominated corner of input:
// 'top' or 'bottom' aligns depending on language direction,
// 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'
autoSize: false, // True to size the input for the date format, false to leave as is
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
showDefault: false, // True to populate field with the default date
appendText: '', // Display text following the input box, e.g. showing the format
closeAtTop: true, // True to have the clear/close at the top,
// false to have them at the bottom
mandatory: false, // True to hide the Clear link, false to include it
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
showBigPrevNext: false, // True to show big prev/next links
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: true, // True if month can be selected directly, false if only prev/next
changeYear: true, // True if year can be selected directly, false if only prev/next
yearRange: 'c-10:c+10', // Range of years to display in drop-down,
// either relative to currently displayed year (c-nn:c+nn), relative to
// today's year (-nn:+nn), absolute (nnnn:nnnn), or a combination (nnnn:-nn)
changeFirstDay: false, // True to click on day name to change, false to remain as set
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
highlightWeek: false, // True to highlight the selected week
showWeeks: false, // True to show week of the year, false to omit
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: '+10', // Short year values < this are in the current century,
// > this are in the previous century, string value starting with '+'
// for current year + value, -1 for no change
showStatus: false, // True to show status bar at bottom, false to not show it
statusForDate: this.dateStatus, // Function to provide status text for a date -
// takes date and instance as parameters, returns display text
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multiple months at which to show the current month (starting at 0)
rangeSelect: false, // Allows for selecting a date range on one date picker
rangeSeparator: ' - ', // Text between two dates in a range
multiSelect: 0, // Maximum number of selectable dates
multiSeparator: ',', // Text between multiple dates
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
// [2] = cell title (optional), e.g. $.datepick.noWeekends
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onHover: null, // Define a callback function when hovering over a day
onSelect: null, // Define a callback function when a date is selected
onClose: null, // Define a callback function when the datepicker is closed
altField: '', // Selector for an alternate field to store selected dates into
altFormat: '', // The date format to use for the alternate field
constrainInput: true // The input is constrained by the current date format
};
$.extend(this._defaults, this.regional['']);
this.dpDiv = $('<div style="display: none;"></div>');
} | [
"function createDatePicker(controlId, options) {\n var fieldId = jQuery(\"#\" + controlId).closest(\"div[data-role='InputField']\").attr(\"id\");\n jQuery(function () {\n var datePickerControl = jQuery(\"#\" + controlId);\n datePickerControl.datepicker(options);\n datePickerControl.datepicker('option', 'onClose',\n function () {\n getValidationData(jQuery(\"#\" + fieldId)).messagingEnabled = true;\n jQuery(this).trigger(\"focusout\");\n jQuery(this).trigger(\"focus\");\n });\n datePickerControl.datepicker('option', 'beforeShow',\n function () {\n getValidationData(jQuery(\"#\" + fieldId)).messagingEnabled = false;\n });\n\n //KULRICE-7310 can't change only month or year with picker (jquery limitation)\n datePickerControl.datepicker('option', 'onChangeMonthYear',\n function (y, m, i) {\n var d = i.selectedDay;\n jQuery(this).datepicker('setDate', new Date(y, m - 1, d));\n });\n\n //KULRICE-7261 fix date format passed back. jquery expecting mm-dd-yy\n if (options.dateFormat == \"mm-dd-yy\" && datePickerControl[0].getAttribute(\"value\").indexOf(\"/\") != -1) {\n datePickerControl.datepicker('setDate', new Date(datePickerControl[0].getAttribute(\"value\")));\n }\n });\n\n // in order to compensate for jQuery's \"Today\" functionality (which does not actually return the date to the input box), alter the functionality\n jQuery.datepicker._gotoToday = function (id) {\n var target = jQuery(id);\n var inst = this._getInst(target[0]);\n if (this._get(inst, 'gotoCurrent') && inst.currentDay) {\n inst.selectedDay = inst.currentDay;\n inst.drawMonth = inst.selectedMonth = inst.currentMonth;\n inst.drawYear = inst.selectedYear = inst.currentYear;\n }\n else {\n var date = new Date();\n inst.selectedDay = date.getDate();\n inst.drawMonth = inst.selectedMonth = date.getMonth();\n inst.drawYear = inst.selectedYear = date.getFullYear();\n }\n this._notifyChange(inst);\n this._adjustDate(target);\n\n // The following two lines are additions to the original jQuery code\n this._setDateDatepicker(target, new Date());\n this._selectDate(id, this._getDateDatepicker(target));\n }\n}",
"function M_datepicker(dp_date_picker) {\n var dp_origen = document.getElementById(dp_date_picker); //Obtener datepicker.//\n //Obtiene un datepicker y lo inicializa.//\n M.Datepicker.init(dp_origen, opciones_fecha);\n}",
"function _init_datedropdown() {\n var monthtext = ['January,'February','March','April','May','June','July','August','September','October','November','December'];\n var today = new Date();\n var todayDate = today.getDate();\n var todayMonth = today.getMonth();\n var todayYear = today.getFullYear();\n var $day = $('.dd-dayfield');\n var $month = $('.dd-monthfield');\n var $year = $('.dd-yearfield');\n \n $day.each(function() {\n for (var i=0; i<31; i++) {\n if (i+1 == todayDate) {\n this.options[i] = new Option(i+1, i+1, true, true);\n } else {\n this.options[i] = new Option(i+1, i+1);\n }\n }\n });\n\n $month.each(function() {\n for (var m=0; m<12; m++) {\n if (m+1 == todayMonth) {\n this.options[m] = new Option(monthtext[m], m+1, true, true);\n } else {\n this.options[m] = new Option(monthtext[m], m+1);\n }\n }\n });\n\n $year.each(function() {\n var startYear = todayYear-10;\n for (var y=0; y<20; y++) {\n if (startYear == todayYear) {\n this.options[y] = new Option(startYear, startYear, true, true);\n } else {\n this.options[y] = new Option(startYear, startYear);\n };\n startYear+=1;\n } \n });\n}",
"function getDateControl()\n{\n // CSS classes specific to this component\n const CLASS_DATE_INPUT_WRAPPER = \"date-input-wrapper\";\n const CLASS_DATE_INPUT = \"date-input\";\n const CLASS_HIDDEN_DATE_INPUT = \"hidden-date-input\";\n const CLASS_DATE_LAUNCHER = \"date-launcher\";\n const DATE_LAUNCHER_TEXT = \"📅\"; // Unicode calendar character\n\n function DateControl()\n {\n this.init();\n }\n\n //\n // Sets up the control's HTML markup and associated logic.\n // The size of the date launcher is restricted so that it never uses more\n // space than is necessary to display the calendar character.\n // The markup looks something like this:\n // <div class=\"date-input-wrapper\">\n // <div class=\"grid-container\" style=\"grid-template-columns: minmax(90%, 100%) 0% minmax(min-content, max-content)\">\n // <input type=\"text\" class=\"date-input\">\n // <input type=\"text\" class=\"hidden-date-input\">\n // <div class=\"date-launcher\"></div>\n // </div>\n // </div>\n //\n DateControl.prototype.init = function()\n {\n // Root element: as a member variable and a local reference\n let controlGrid = this.root = document.createElement(\"div\");\n controlGrid.classList.add(CLASS_DATE_INPUT_WRAPPER);\n\n // Set up the manual date input, hidden date input & launcher button\n let dateInput = this.dateInput = document.createElement(\"input\");\n dateInput.classList.add(CLASS_DATE_INPUT);\n\n let hiddenDateInput = document.createElement(\"input\");\n hiddenDateInput.classList.add(CLASS_HIDDEN_DATE_INPUT);\n\n let dateLauncher = document.createElement(\"div\");\n dateLauncher.classList.add(CLASS_DATE_LAUNCHER);\n dateLauncher.innerHTML = DATE_LAUNCHER_TEXT;\n\n controlGrid.appendChild(dateInput);\n controlGrid.appendChild(hiddenDateInput);\n controlGrid.appendChild(dateLauncher);\n\n // Attach the event handlers, etc.\n this.setupGuiHooks();\n }\n\n DateControl.prototype.setupGuiHooks = function()\n {\n let dateControl = this;\n\n // Get access to the miscellaneous elements of the control\n let hiddenDateInput = this.root.querySelector(CLASS_SELECTOR(CLASS_HIDDEN_DATE_INPUT));\n let dateLauncher = this.root.querySelector(CLASS_SELECTOR(CLASS_DATE_LAUNCHER));\n\n // Set up a change event handler on the visible date input\n this.dateInput.addEventListener(DATE_CHANGE_EVENT_TYPE, this.onDateInputChanged.bind(this));\n\n // Set up the date picker, attaching it to the hidden input.\n // When a date is picked, notify the visible date input, but ensure the\n // change event handler won't update the date picker\n // (i.e. avoid a recursive loop of events).\n let datePicker = flatpickr(hiddenDateInput,\n {\n dateFormat: \"Y-m-d\",\n onChange: this.onDatePicked.bind(this)\n });\n\n // ag-grid specific: ensure that clicking within the date picking\n // widget is interpreted as a selection within the control\n datePicker.calendarContainer.classList.add(\"ag-custom-component-popup\");\n\n // Set up the launcher button to launch the date picker\n dateLauncher.addEventListener(\"click\", function() { datePicker.open(); });\n }\n\n DateControl.prototype.getGui = function()\n {\n return this.root;\n };\n\n //\n // Synchs the manual date input and date picker\n //\n DateControl.prototype.onDateInputChanged = function(event)\n {\n let target = event.target;\n let dateStr = target.value;\n let dateComponents = parseDate(dateStr);\n\n // Temporary validation code\n if (dateStr && !dateComponents)\n {\n target.classList.add(\"cat-invalid-data\");\n }\n else\n {\n target.classList.remove(\"cat-invalid-data\");\n }\n\n //\n // Update the date picker, suppressing raising of further change events.\n // Use setDate() for a fully specified date (including null/empty date),\n // jumpDate() otherwise.\n //\n let fullySpecifiedDate = (!dateStr) ||\n (dateComponents\n &&\n (\n dateComponents[DATE_COMP_YEAR] &&\n dateComponents[DATE_COMP_MONTH] &&\n dateComponents[DATE_COMP_DAY]\n )\n );\n let datePicker = target.nextSibling._flatpickr;\n\n if (fullySpecifiedDate)\n {\n datePicker.setDate(dateStr, false);\n }\n else\n {\n datePicker.jumpToDate(dateStr, false);\n }\n }\n\n //\n // Processes a date update by:\n // 1. Setting the manual date input (if a date string is provided)\n // 2. [OPTIONAL] Raising a change event on the manual date input\n // The final parameter controls bubbling (propagation) of this event\n //\n DateControl.prototype.processDateUpdate = function(dateStr, raiseEvent, bubbleEvent = true)\n {\n if (dateStr != null)\n {\n this.dateInput.value = dateStr;\n }\n\n if (raiseEvent)\n {\n let changeEventDetails = {};\n changeEventDetails[EVENT_BUBBLE_OPTION] = bubbleEvent;\n let changeEvent = new Event(DATE_CHANGE_EVENT_TYPE, changeEventDetails);\n\n this.dateInput.dispatchEvent(changeEvent);\n }\n }\n\n //\n // Handles selection of a date in the picker selection by\n // updating the manual date input, without forcing raising of another event\n //\n DateControl.prototype.onDatePicked = function(selectedDates, dateStr, instance)\n {\n this.processDateUpdate(dateStr, false);\n }\n\n //\n // Ensures the manual date input and date picker are synched\n //\n DateControl.prototype.synchGUI = function()\n {\n this.processDateUpdate(null, true);\n }\n\n //\n // Retrieves the date of the control\n //\n DateControl.prototype.getDate = function()\n {\n return this.dateInput.value;\n }\n\n //\n // Sets the date of the control, optionally propagating any change events\n //\n DateControl.prototype.setDate = function(dateStr, bubble = true)\n {\n this.processDateUpdate(dateStr, true, bubble);\n }\n\n return new DateControl();\n}",
"function pgvar_dtpdfecha_inicial__init(){\n $('#pgvar_dtpdfecha_inicial').datepicker({\n language: \"es\",\n todayBtn: \"linked\",\n format: \"dd/mm/yyyy\",\n multidate: false,\n todayHighlight: true,\n autoclose: true,\n\n }).datepicker(\"setDate\", new Date());\n}",
"function enableDatePicker () {\n $('input[data-field-type=date]').datepicker({\n autoclose: true, // close on loast focus\n orientation: 'top auto', // show above the fiels\n todayBtn: 'linked', // show button to return to 'today'\n todayHighlight: true, // highlight current day\n endDate: '+1y', // set max date to +1 year\n startDate: '0d', // set the minimum date to today\n maxViewMode: 'decade' // set maximum zoom out to decades view\n })\n}",
"function updateDatePickers(fromdate, todate) {\n threemonthdateObject = new Date(todate.getFullYear(), todate.getMonth(), todate.getDate()),\n threemonthdateObject.setMonth(threemonthdateObject.getMonth() - 3);\n\n $(\"#startdate\").datepicker({\n dateFormat: 'mm/dd/yy',\n maxDate: new Date(todate.getFullYear(), todate.getMonth(), todate.getDate()),\n minDate: new Date(fromdate.getFullYear(), fromdate.getMonth(), fromdate.getDate()),\n onSelect: function () {\n fromDate = $(this).datepicker('getDate');\n visionZero.toDate = $(\"#enddate\").datepicker('getDate');\n\n if (visionZero.toDate != \"\") {\n var fDate = new Date(fromDate);\n var tDate = new Date(visionZero.toDate);\n var fMnth = Number(fDate.getMonth()) + 1;\n var tMnth = Number(tDate.getMonth()) + 1;\n visionZero.sqlDate = \"CRASH_DATE BETWEEN '\" + fMnth + \"/\" + fDate.getDate() + \"/\" + fDate.getFullYear() + \"' AND '\" + tMnth + \"/\" + tDate.getDate() + \"/\" + tDate.getFullYear() + \"'\";\n $(\"#daterange\").html(fMnth + \"/\" + fDate.getDate() + \"/\" + fDate.getFullYear() + \" to \" + tMnth + \"/\" + tDate.getDate() + \"/\" + tDate.getFullYear());\n $(\"#daterangeMobile\").html(fMnth + \"/\" + fDate.getDate() + \"/\" + fDate.getFullYear() + \" to \" + tMnth + \"/\" + tDate.getDate() + \"/\" + tDate.getFullYear());\n if (crashLayer.visible) {\n\n constructSQL();\n }\n }\n else {\n visionZero.sqlDate = \"\";\n }\n },\n onClose: function () {\n this.fixFocusIE = true;\n $(\"#topContainer\").change().focus(); //If this is the JQuery datepicker, apparently there is a newer version that might fix this, but this seems to be cleaner. for the short term\n }\n }).keyup(function (e) {\n if (e.keyCode == 8 || e.keyCode == 46) {\n $.datepicker._clearDate(this);\n }\n });\n $(\"#startdate\").datepicker('setDate', threemonthdateObject);\n $(\"#enddate\").datepicker({\n dateFormat: 'mm/dd/yy',\n maxDate: new Date(todate.getFullYear(), todate.getMonth(), todate.getDate()),\n minDate: new Date(fromdate.getFullYear(), fromdate.getMonth(), fromdate.getDate()),\n onSelect: function () {\n fromDate = $(\"#startdate\").datepicker('getDate');\n visionZero.toDate = $(this).datepicker('getDate');\n if (fromDate != \"\") {\n var fDate = new Date(fromDate);\n var tDate = new Date(visionZero.toDate);\n var fMnth = Number(fDate.getMonth()) + 1;\n var tMnth = Number(tDate.getMonth()) + 1;\n visionZero.sqlDate = \"CRASH_DATE BETWEEN '\" + fMnth + \"/\" + fDate.getDate() + \"/\" + fDate.getFullYear() + \"' AND '\" + tMnth + \"/\" + tDate.getDate() + \"/\" + tDate.getFullYear() + \"'\";\n $(\"#daterange\").html(fMnth + \"/\" + fDate.getDate() + \"/\" + fDate.getFullYear() + \" to \" + tMnth + \"/\" + tDate.getDate() + \"/\" + tDate.getFullYear());\n $(\"#daterangeMobile\").html(fMnth + \"/\" + fDate.getDate() + \"/\" + fDate.getFullYear() + \" to \" + tMnth + \"/\" + tDate.getDate() + \"/\" + tDate.getFullYear());\n if (crashLayer.visible) {\n constructSQL();\n }\n }\n else {\n visionZero.sqlDate = \"\";\n }\n\n },\n onClose: function () {\n this.fixFocusIE = true;\n $(\"#topContainer\").change().focus(); //If this is the JQuery datepicker, apparently there is a newer version that might fix this, but this seems to be cleaner. for the short term\n }\n }).keyup(function (e) {\n if (e.keyCode == 8 || e.keyCode == 46) {\n $.datepicker._clearDate(this);\n }\n });\n $(\"#enddate\").datepicker('setDate', todate);\n $(\"#startdate\").datepicker(\"refresh\");\n $(\"#enddate\").datepicker(\"refresh\");\n enddateObject = new Date(todate.getFullYear(), todate.getMonth() + 1, todate.getDate());\n\n var fromMnth = Number(threemonthdateObject.getMonth()) + 1;\n var toMnth = Number(todate.getMonth()) + 1;\n\n visionZero.sqlDate = \"CRASH_DATE BETWEEN '\" + fromMnth + \"/\" + threemonthdateObject.getDate() + \"/\" + threemonthdateObject.getFullYear() + \"' AND '\" + toMnth + \"/\" + todate.getDate() + \"/\" + todate.getFullYear() + \"'\";\n $(\"#daterange\").html(fromMnth + \"/\" + threemonthdateObject.getDate() + \"/\" + threemonthdateObject.getFullYear() + \" to \" + toMnth + \"/\" + todate.getDate() + \"/\" + todate.getFullYear());\n $(\"#daterangeMobile\").html(fromMnth + \"/\" + threemonthdateObject.getDate() + \"/\" + threemonthdateObject.getFullYear() + \" to \" + toMnth + \"/\" + todate.getDate() + \"/\" + todate.getFullYear());\n constructSQL();\n $(\"#LastAvailableData\").html(\"Date of Last Available Data: \" + enddateObject.getMonth() + \"-\" + enddateObject.getDate() + \"-\" + enddateObject.getFullYear());\n\n\n\n}",
"function runDatePickerWidget() {\n var date_input=$('input[name=\"date\"]'); //our date input has the name \"date\"\n var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : \"body\";\n var options={\n format: 'dd/mm/yyyy',\n container: container,\n todayHighlight: true,\n autoclose: true,\n clearBtn: true\n };\n date_input.datepicker(options);\n}",
"function setDateHandlers(field){\n \n $(field).on({\n \n // On focus...\n \n 'focus': function(event){\n \n // Remove validation\n \n $(this).removeClass('invalid');\n \n // Show date picker if not shown already\n \n if(!$(this).siblings('.date-picker').is(':visible')){\n \n showDatePicker(this);\n \n }\n \n },\n \n // On defocus, validate\n \n 'blur': function(event){\n \n // If valid date, format\n \n if(isValidDate($(this).val())){\n \n let date = new Date($(this).val());\n $(this).val(zeroPad(date.getMonth() + 1, 2) + '/' + zeroPad(date.getDate(), 2) + '/' + date.getFullYear());\n \n }\n \n // Otherwise, make invalid\n \n else if($(this).val().length > 0){\n \n $(this).addClass('invalid');\n \n }\n \n },\n \n // On tab, hide date picker\n \n 'keydown': function(event){\n \n if(event.which == 9){\n \n $(this).siblings('.date-picker').hide();\n \n }\n \n },\n \n // On typing...\n \n 'keyup': function(event){\n \n // Get current cursor position\n \n let cursorPosition = this.selectionStart;\n \n // Remove non-date characters\n \n let value = $(this).val();\n $(this).val(value.replace(/[^0-9\\/]/g, ''));\n \n // If if typed character was removed, adjust cursor position\n \n let startLength = value.length;\n let endLength = $(this).val().length;\n \n if(startLength > endLength){\n \n setCursorPosition(this, cursorPosition - 1);\n \n }\n \n // If valid date, adjust date picker\n \n if(isValidDate($(this).val())){\n \n showDatePicker(this);\n \n }\n \n }\n \n });\n \n}",
"function showDatePicker(field){\n \n // Get date picker\n \n let datePicker = $(field).siblings('.date-picker');\n \n // If date picker doesn't exist, create it\n \n if(datePicker.length == 0){\n \n // Create date picker\n \n datePicker = $('<table></table>');\n $(datePicker).addClass('date-picker');\n \n // HTML for date picker\n \n let html = '';\n \n // Add header\n \n html += '<tr class=\"date-picker-header\">';\n html += '<td colspan=\"7\">';\n html += '<span>';\n html += '<select class=\"month-width\"></select><select class=\"year-width\"></select>';\n html += '<select class=\"month\">';\n \n // Add months to picklist\n \n for(let i = 1; i <=12; i++){\n \n html += '<option>' + getMonthName(i) + '</option>';\n \n }\n \n html += '</select><select class=\"year\">';\n \n // Add years to picklist\n \n for(let i = 1900; i <= new Date().getFullYear() + 5; i++){\n \n html += '<option>' + i + '</option>';\n \n }\n \n html += '</select></span>';\n \n // Add previous/next buttons\n \n html += '<button type=\"button\" class=\"prev-year\"></button>';\n html += '<button type=\"button\" class=\"prev-month\"></button>';\n html += '<button type=\"button\" class=\"today\"></button>';\n html += '<button type=\"button\" class=\"next-month\"></button>';\n html += '<button type=\"button\" class=\"next-year\"></button>';\n html += '</td></tr>'\n \n // Add days of week\n \n html += '<tr class=\"days-of-week\"><td>S</td><td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td></tr>';\n \n // Add HTML for date picker\n \n datePicker.html(html);\n \n // Add date picker after field\n \n $(field).after(datePicker);\n \n // Set event handlers for header\n \n setDatePickerHeaderHandlers(datePicker);\n \n }\n \n // Show date picker\n \n $(datePicker).show();\n \n // If valid date, set date picker to month/year of date\n \n if(isValidDate($(field).val())){\n \n let selectedDate = new Date($(field).val());\n setDatePicker(datePicker, selectedDate.getMonth() + 1, selectedDate.getFullYear(), selectedDate);\n \n }\n \n // Otherwise, set date picker to month/year of today\n \n else{\n \n let today = new Date();\n setDatePicker(datePicker, today.getMonth() + 1, today.getFullYear(), new Date($(field).val()));\n \n }\n \n}",
"function mdl_dtpdguia_fecha_recepcion_editar__init(){\n $(\"#dtpdguia_fecha_recepcion_editar\").datepicker({\n language: \"es\",\n todayBtn: \"linked\",\n format: \"dd/mm/yyyy\",\n multidate: false,\n todayHighlight: true,\n autoclose: true,\n\n }).datepicker(\"setDate\", new Date());\n\n}",
"function dtpdmanifiesto_fecha_salida__init(){\n $('#pgmanifiesto_dtpdmanifiesto_fecha_salida2').datepicker({\n language: \"es\",\n todayBtn: \"linked\",\n format: \"dd/mm/yyyy\",\n multidate: false,\n todayHighlight: true,\n autoclose: true\n\n }).datepicker(\"setDate\", new Date());\n}",
"function mdl_dtpdguia_fecha_vencimiento_editar__init(){\n $(\"#dtpdguia_fecha_vencimiento_editar\").datepicker({\n language: \"es\",\n todayBtn: \"linked\",\n format: \"dd/mm/yyyy\",\n multidate: false,\n todayHighlight: true,\n autoclose: true,\n\n }).datepicker(\"setDate\", new Date());\n}",
"_updateDatePane() {\n var DateChooser = qx.ui.control.DateChooser;\n\n var today = new Date();\n var todayYear = today.getFullYear();\n var todayMonth = today.getMonth();\n var todayDayOfMonth = today.getDate();\n\n var selDate = this.getValue();\n var selYear = selDate == null ? -1 : selDate.getFullYear();\n var selMonth = selDate == null ? -1 : selDate.getMonth();\n var selDayOfMonth = selDate == null ? -1 : selDate.getDate();\n\n var shownMonth = this.getShownMonth();\n var shownYear = this.getShownYear();\n\n var startOfWeek = qx.locale.Date.getWeekStart();\n\n // Create a help date that points to the first of the current month\n var helpDate = new Date(this.getShownYear(), this.getShownMonth(), 1);\n\n var monthYearFormat = new qx.util.format.DateFormat(\n DateChooser.MONTH_YEAR_FORMAT\n );\n\n this.getChildControl(\"month-year-label\").setValue(\n monthYearFormat.format(helpDate)\n );\n\n // Show the day names\n var firstDayOfWeek = helpDate.getDay();\n var firstSundayInMonth = 1 + ((7 - firstDayOfWeek) % 7);\n var weekDayFormat = new qx.util.format.DateFormat(\n DateChooser.WEEKDAY_FORMAT\n );\n\n for (var i = 0; i < 7; i++) {\n var day = (i + startOfWeek) % 7;\n\n var dayLabel = this.__weekdayLabelArr[i];\n\n helpDate.setDate(firstSundayInMonth + day);\n dayLabel.setValue(weekDayFormat.format(helpDate));\n\n if (qx.locale.Date.isWeekend(day)) {\n dayLabel.addState(\"weekend\");\n } else {\n dayLabel.removeState(\"weekend\");\n }\n }\n\n // Show the days\n helpDate = new Date(shownYear, shownMonth, 1, 12, 0, 0);\n var nrDaysOfLastMonth = (7 + firstDayOfWeek - startOfWeek) % 7;\n helpDate.setDate(helpDate.getDate() - nrDaysOfLastMonth);\n\n var weekFormat = new qx.util.format.DateFormat(DateChooser.WEEK_FORMAT);\n\n for (var week = 0; week < 6; week++) {\n this.__weekLabelArr[week].setValue(weekFormat.format(helpDate));\n\n for (var i = 0; i < 7; i++) {\n var dayLabel = this.__dayLabelArr[week * 7 + i];\n\n var year = helpDate.getFullYear();\n var month = helpDate.getMonth();\n var dayOfMonth = helpDate.getDate();\n\n var isSelectedDate =\n selYear == year && selMonth == month && selDayOfMonth == dayOfMonth;\n\n if (isSelectedDate) {\n dayLabel.addState(\"selected\");\n } else {\n dayLabel.removeState(\"selected\");\n }\n\n if (month != shownMonth) {\n dayLabel.addState(\"otherMonth\");\n } else {\n dayLabel.removeState(\"otherMonth\");\n }\n\n var isToday =\n year == todayYear &&\n month == todayMonth &&\n dayOfMonth == todayDayOfMonth;\n\n if (isToday) {\n dayLabel.addState(\"today\");\n } else {\n dayLabel.removeState(\"today\");\n }\n\n dayLabel.setValue(\"\" + dayOfMonth);\n dayLabel.dateTime = helpDate.getTime();\n dayLabel.setEnabled(!this.__exceedsLimits(helpDate));\n\n // Go to the next day\n helpDate.setDate(helpDate.getDate() + 1);\n }\n }\n\n monthYearFormat.dispose();\n weekDayFormat.dispose();\n weekFormat.dispose();\n }",
"function datePickerHook() {\n $('.select-options li').each(function () {\n $(this).on('click', function () {\n let startMonth = document.getElementById('date-range--start-month')\n .value\n let startYear = document.getElementById('date-range--start-year').value\n let endMonth = document.getElementById('date-range--end-month').value\n let endYear = document.getElementById('date-range--end-year').value\n const facetDate = document.getElementsByClassName(\n 'facetwp-facet-publish_date'\n )[0]\n\n facetDate.querySelectorAll('.fs-option').forEach(function (el) {\n const startDate = new Date(startYear, startMonth, 1)\n const endDate = new Date(endYear, endMonth, 1)\n const elDate = new Date(\n el.getAttribute('data-value').slice(0, 4),\n el.getAttribute('data-value').slice(4, 6) - 1,\n 1\n )\n if (elDate >= startDate && elDate <= endDate) {\n el.click()\n }\n })\n })\n })\n }",
"function initCal() {\n const cal = document.querySelector('#calendar');\n const datepicker = new Datepicker(cal, {\n autohide: true\n });\n \n cal.addEventListener('changeDate', updatePlaykit);\n}",
"function changeDay(){\n $(date_picker).val($(this).data('day'));\n}",
"function hideAllOpen() {\r\n $(\".datePickerTab\").each(function (i, el) {\r\n hideDatepicker(el.id);\r\n });\r\n}",
"setConfig() {\n if (this._datepicker) {\n this._datepicker.hide();\n }\n this._config = Object.assign({}, this._config, this.bsConfig, {\n value: this._bsValue,\n isDisabled: this.isDisabled,\n minDate: this.minDate || this.bsConfig && this.bsConfig.minDate,\n maxDate: this.maxDate || this.bsConfig && this.bsConfig.maxDate,\n dateCustomClasses: this.dateCustomClasses || this.bsConfig && this.bsConfig.dateCustomClasses,\n dateTooltipTexts: this.dateTooltipTexts || this.bsConfig && this.bsConfig.dateTooltipTexts,\n datesDisabled: this.datesDisabled || this.bsConfig && this.bsConfig.datesDisabled,\n datesEnabled: this.datesEnabled || this.bsConfig && this.bsConfig.datesEnabled\n });\n this._datepickerRef = this._datepicker\n .provide({ provide: BsDatepickerConfig, useValue: this._config })\n .attach(BsDatepickerInlineContainerComponent)\n .to(this._elementRef)\n .show();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs every monitor frame. Each repeater will then be ran the number of times required to appear to be running at the required frames per second | function runRepeaters () {
var i = 0,
j,
dte = +new Date(),
repeater;
for (; i<repeaters.length; i+=1 ) {
repeater = repeaters[i];
if ( repeater.isrunning ) {
j = repeater.mspt === -1 ? 1 :
Math.floor( (dte - repeater.tick) / repeater.mspt );
for (; j>0; j-=1 ) {
repeater.tick += repeater.mspt;
repeater.func();
}
}
}
// Need to add a shiv for this at some point...
repeatAtAnimationFrame = requestAnimationFrame( runRepeaters );
} | [
"function start_loop(fps) {\n fps_interval = 1000 / fps;\n then = Date.now();\n loop();\n }",
"function loop() {\n\tcount = new Date().getHours();\n\tdocument.body.style.backgroundImage = ((count > 3 && count < 21) ? url_day : url_night);\n\tdocument.body.style.backgroundPosition = \"top, bottom\";\n\tdocument.body.style.backgroundRepeat = \"no-repeat, no-repeat\";\n\tdocument.body.style.backgroundSize = \"contain, contain\";\n\tdocument.body.style.backgroundColor = hourCodes[count];\n\tsetInterval(update, 1.5 * 1000);\n\tcount++;\n}",
"run() {\n function main(tFrame) {\n game = window.game;\n game.stopMain = window.requestAnimationFrame(main);\n var nextTick = game.lastTick + game.tickLength;\n var numTicks = 0;\n\n //If tFrame < nextTick then 0 ticks need to be updated (0 is default for numTicks).\n //If tFrame = nextTick then 1 tick needs to be updated (and so forth).\n //Note: As we mention in summary, you should keep track of how large numTicks is.\n //If it is large, then either your game was asleep, or the machine cannot keep up.\n if (tFrame > nextTick) {\n var timeSinceTick = tFrame - game.lastTick;\n numTicks = Math.floor(timeSinceTick / game.tickLength);\n }\n\n queueUpdates(game, numTicks);\n game.render(tFrame);\n game.lastRender = tFrame;\n }\n\n function queueUpdates(game, numTicks) {\n for (var i = 0; i < numTicks; i++) {\n game.lastTick = game.lastTick + game.tickLength; //Now lastTick is this tick.\n game.update(game.lastTick);\n }\n }\n\n this.lastTick = performance.now();\n this.lastRender = this.lastTick; //Pretend the first draw was on first update.\n this.tickLength = 20; //This sets your simulation to run at 20Hz (50ms)\n\n this.setInitialState();\n\n this.time_start = performance.now();\n main(performance.now()); // Start the cycle\n }",
"function run() {\n if (running) {\n // all times in msec\n // minimum time per frame for not exceeding the given fps speed\n // fps=60 means maximum speed\n const minimumFrameTime = 1000 / animation.fps - 1000 / 60;\n // do the current frame\n const startOfFrame = Date.now();\n advance();\n if (recorder.recording) {\n const filename = makeFilename();\n guiUtils.saveCanvasAsFile(output.canvas, filename, recorder.movieType,\n function() {\n const timeUsed = Date.now() - startOfFrame;\n // prepare next frame\n timeoutID = setTimeout(function() {\n requestAnimationFrame(run);\n }, minimumFrameTime - timeUsed);\n });\n } else {\n const timeUsed = Date.now() - startOfFrame;\n // prepare next frame\n timeoutID = setTimeout(function() {\n requestAnimationFrame(run);\n }, minimumFrameTime - timeUsed);\n }\n }\n}",
"function runClock() {\n\t\tcurrenttime = setInterval(updateRegularClock, 1000);\n\t}",
"function startTimer() {\n setInterval(displayNextImage, 3000);\n}",
"function repeatAnims() {\n missileInterval = setInterval(beginDroppingMissiles, 500)\n}",
"function Timing() {\n\tvar timer = setInterval(Draw, 2);\n}",
"function gamePatterReplay() {\n for (var i = 0; i < gamePattern.length; i++) {\n (function(i) {\n setTimeout(function() {\n $('#' + gamePattern[i]).fadeOut(100).fadeIn(100);\n console.log(gamePattern[i]);\n }, 500 * i);\n })(i);\n }\n setTimeout(nextSequence, 500 * i);\n}",
"function loopAnim() {\n // flake.animate({\n // top: 0,\n // left: thisLeft + Math.floor(Math.random() * (max - min + 1)) + min\n // }, 0)\n // .animate({\n // top: '100%',\n // left: thisLeft + Math.floor(Math.random() * (max - min + 1)) + min\n // }, thisSpeed, 'linear', function() {\n // loopAnim();\n // });\n // console.log(1111);\n flake.css({ \"transform\": \"translate(\" + (thisLeft + Math.floor(Math.random() * (max - min + 1)) + min) + \"px,\" + 0 + \"px)\", \"transition-duration\": \"0ms\", \"transition-timing-function\": \"linear\" });\n flake.timer = setTimeout(function() {\n loopAnim2();\n }, 16)\n }",
"function playPattern() {\n var i = 0;\n\n function playEach() {\n setTimeout(function() {\n play(pattern[i]);\n i++;\n if (i < pattern.length) {\n playEach();\n }\n }, 750);\n }\n playEach();\n // allow user action after full playback\n setTimeout(function() {\n userTurn = true;\n }, 400);\n}",
"function runGame(){\n var i = 0;\n var interval = $interval(\n function(){ // make the buttons blink with 500 milliseconds between every blink.\n if(i >= gameList.length){\n activateButtons();\n $interval.cancel(interval);\n }\n else{\n blinkCorrectButton(i);\n i+=1;\n }\n }, 1000);\n\n }",
"function runAllInstructions(){\n\t// Sets a timer to run a instruction every 'runInterval' seconds;\n\tinstructionInterval = setInterval(runInstruction, runIntervalTime);\n\t// Sets a timer to clear the interval after the last instruction is ran.\n\tsetTimeout(()=>{clearInterval(instructionInterval)}, runIntervalTime*instructionList.length);\n}",
"timeProcess(itself=(cov_50nz68pmo.b[1][0]++,this)){cov_50nz68pmo.f[3]++;cov_50nz68pmo.s[7]++;// define begin cooldown\ninitTime=new Date().getTime();// function to send clockBar instant to setInterval\nfunction sendTosetInterval(){cov_50nz68pmo.f[4]++;cov_50nz68pmo.s[8]++;return itself;}// define time cooldown\nvar process=(cov_50nz68pmo.s[9]++,setInterval(function(){cov_50nz68pmo.f[5]++;// get clockBar instant\nlet itself=(cov_50nz68pmo.s[10]++,sendTosetInterval());// get current time\nvar now=(cov_50nz68pmo.s[11]++,new Date().getTime());// find the distance between now and the init time\nvar distance=(cov_50nz68pmo.s[12]++,now-initTime);cov_50nz68pmo.s[13]++;if(distance>limited){cov_50nz68pmo.b[2][0]++;cov_50nz68pmo.s[14]++;drawFluid('0%');cov_50nz68pmo.s[15]++;clearInterval(process);cov_50nz68pmo.s[16]++;itself.setTimeout('true');}else{cov_50nz68pmo.b[2][1]++;}// set percentage of time cooldown\ncov_50nz68pmo.s[17]++;fracTime=Math.round(100-distance/limited*100);// draw percentage to page\ncov_50nz68pmo.s[18]++;drawFluid(fracTime+'%');},timeUpdate));}",
"loop() {\n clearTimeout(this.persistentLoop);\n // emit loop event to any active persistent tool\n EventBus.$emit(\"loop\", this.loopCount);\n\n // redraw canvas\n if (this.file && this.file.selectionCanvas) this.onRedrawCanvas();\n\n // increase loop iteration\n ++this.loopCount;\n\n // re-run persistence loop\n this.persistentLoop = setTimeout(() => this.loop(), 25);\n }",
"loopLights() {\n console.log('[johnny-five] Lights Looping.');\n this.buildLoop();\n\n this.loop = setTimeout(() => {\n this.buildLoop();\n }, 8000);\n }",
"function gameLoop() {\n requestAnimationFrame(gameLoop, ga.canvas);\n if (ga._fps === undefined) {\n\n //Run the code for each frame.\n update();\n }\n\n //If `fps` has been set, clamp the frame rate to that upper limit.\n else {\n\n //Calculate the time that has elapsed since the last frame\n var current = Date.now(),\n elapsed = current - ga._startTime;\n\n if (elapsed > 1000) elapsed = ga._frameDuration;\n\n //For interpolation:\n ga._startTime = current;\n\n //Add the elapsed time to the lag counter\n ga._lag += elapsed;\n\n //Update the frame if the lag counter is greater than or\n //equal to the frame duration\n while (ga._lag >= ga._frameDuration) {\n\n //Capture the sprites' previous positions for rendering\n //interpolation\n capturePreviousSpritePositions();\n\n //Update the logic\n update();\n\n //Reduce the lag counter by the frame duration\n ga._lag -= ga._frameDuration;\n }\n\n //Calculate the lag offset and use it to render the sprites\n var lagOffset = ga._lag / ga._frameDuration;\n ga.render(ga.canvas, lagOffset);\n }\n }",
"function render() {\n\t\tvar timer;\n\t\t\n\t\tfor (timer = 0; timer < renderThese.length; timer++) {\n\t\t\treportTimer(renderThese[timer]);\n\t\t}\n\t\t\n\t\trenderThese.length = 0;\n\t}",
"function fps()\n{\n $(\"#fps\").html(frameCount + \" fps\");\n frameCount=0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns the header height for a table to be a given value of the height of another table's header. tableid the table id headerheight desired height of last header row in pixels releatedid the id of a related table (typcially a master in a sync case) return none Compatibility: IE restrictions : single row headers only | function i2uiAssignHeaderHeight(tableid, headerheight, relatedid)
{
var headeritem = document.getElementById(tableid+"_header");
if (relatedid != null)
{
var relatedheaderitem = document.getElementById(relatedid+"_header");
headerheight = relatedheaderitem.rows[0].style.height;
}
headeritem.rows[0].style.height = headerheight;
} | [
"function i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight, slave)\r\n{\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n\r\n if (headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeColumnsWithFixedHeaderHeight id=\"+tableid);\r\n\r\n if (headeritem.style.tableLayout != \"fixed\")\r\n {\r\n var newrow = headeritem.insertRow();\r\n if (newrow != null)\r\n {\r\n newrow.className = \"tableColumnHeadings\";\r\n\r\n var i;\r\n var lastheaderrow = headeritem.rows.length - 2;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var newcell;\r\n var attempts;\r\n var newcellwidth;\r\n var widths = new Array();\r\n\r\n // initial width is for cell dividers\r\n var overallwidth = len - 1;\r\n\r\n //i2uitrace(1,\"pre header width=\"+headeritem.clientWidth);\r\n\r\n // shrink cells if slave table present\r\n if (slave != null || slave == 1)\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * dataitem.rows[0].cells.length;\r\n }\r\n\r\n // don't shrink last cell for performance reasons\r\n for (i=0; i<len-1; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n\r\n // insert 1 new cell\r\n newcell = newrow.insertCell();\r\n if (newcell != null)\r\n {\r\n // make some room in the header for the cells to grow\r\n var growthfactor;\r\n if (scrolleritem.offsetWidth > headeritem.clientWidth)\r\n growthfactor = Math.max(100,scrolleritem.offsetWidth-headeritem.clientWidth);\r\n else\r\n growthfactor = 100;\r\n \r\n //i2uitrace(1,\"scroller=\"+scrolleritem.offsetWidth+\" client=\"+headeritem.clientWidth+\" growthfactor=\"+growthfactor);\r\n\r\n headeritem.style.width = headeritem.clientWidth + growthfactor;\r\n\r\n for (i=0; i<len; i++)\r\n {\r\n //i2uitrace(1,\"cell #\"+i+\" headerwidth=\"+headeritem.clientWidth+\" newrow width=\"+newrow.clientWidth);\r\n newcell.style.width = 15;\r\n newcell.innerHTML = headeritem.rows[lastheaderrow].cells[i].innerHTML;\r\n newcellwidth = newcell.clientWidth;\r\n //i2uitrace(1,\"prelimit i=\"+i+\" cell width=\"+newcellwidth);\r\n\r\n attempts = 0;\r\n while (attempts < 8 &&\r\n newrow.clientHeight > headerheight)\r\n {\r\n attempts++;\r\n newcellwidth = parseInt(newcellwidth * 1.25);\r\n //i2uitrace(1,\" attempt=\"+attempts+\" width=\"+newcellwidth);\r\n newcell.style.width = newcellwidth;\r\n }\r\n //i2uitrace(1,\"postlimit i=\"+i+\" cell width=\"+newcell.clientWidth+\" attempts=\"+attempts+\" lastcellwidth=\"+newcellwidth+\" rowheight=\"+newrow.clientHeight);\r\n widths[i] = Math.max(newcell.clientWidth,\r\n dataitem.rows[0].cells[i].clientWidth);\r\n overallwidth += widths[i];\r\n }\r\n\r\n //i2uitrace(1,\"post header width=\"+headeritem.clientWidth+\" overall=\"+overallwidth);\r\n\r\n var spread = parseInt((scrolleritem.clientWidth - overallwidth) / len);\r\n //i2uitrace(1,\"header row height=\"+headerheight+\" header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth+\" spread=\"+spread);\r\n //i2uitrace(1,\"pre spread overallwidth=\"+overallwidth);\r\n if (spread > 0)\r\n {\r\n overallwidth += spread * len;\r\n for (i=0; i<len; i++)\r\n widths[i] += spread;\r\n }\r\n\r\n //i2uitrace(1,\"post spread overallwidth=\"+overallwidth);\r\n\r\n // this solution leverages fixed table layout. IE uses\r\n // the width information from the COL tags to determine how\r\n // wide each column of every row should be. table rendering is\r\n // much faster. more importantly, more deterministic.\r\n var newitem;\r\n for (i=0; i<len; i++)\r\n {\r\n // create new tag and insert into table\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n headeritem.appendChild(newitem);\r\n }\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n dataitem.appendChild(newitem);\r\n }\r\n }\r\n\r\n // now that the table has the necessary data, make it fixed layout\r\n headeritem.style.tableLayout = \"fixed\";\r\n dataitem.style.tableLayout = \"fixed\";\r\n\r\n //apparently not needed\r\n //headeritem.style.width = overallwidth;\r\n //dataitem.style.width = overallwidth;\r\n\r\n // make last header row desired height\r\n headeritem.rows[lastheaderrow].style.height = headerheight;\r\n\r\n // set cell width\r\n for (i=0; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].style.width = widths[i];\r\n dataitem.rows[0].cells[i].style.width = widths[i];\r\n }\r\n }\r\n // delete sizer row\r\n headeritem.deleteRow(headeritem.rows.length - 1);\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"returned width=\"+headeritem.clientWidth);\r\n return headeritem.clientWidth;\r\n}",
"function i2uiResizeColumnsWithFixedHeaderHeight_new(tableid, headerheight, slave, fixedWidths )\r\n{\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n\r\n if (headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeColumnsWithFixedHeaderHeight id=\"+tableid);\r\n if (headeritem.style.tableLayout != \"fixed\")\r\n {\r\n var newrow = headeritem.insertRow();\r\n if (newrow != null)\r\n {\r\n newrow.className = \"tableColumnHeadings\";\r\n\r\n var i;\r\n var lastheaderrow = headeritem.rows.length - 2;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var newcell;\r\n var attempts;\r\n var newcellwidth;\r\n var widths = new Array();\r\n\r\n // initial width is for cell dividers\r\n var overallwidth = len - 1;\r\n widths = fixedWidths;\r\n \r\n for (i=0; i<len; i++)\r\n {\r\n if(!widths[i] || widths[i] < 1 )\r\n {\r\n widths[i] = dataitem.rows[0].cells[i].clientWidth;\r\n }\r\n }\r\n\r\n for (i=0; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n\r\n // insert 1 new cell\r\n newcell = newrow.insertCell();\r\n if (newcell != null)\r\n {\r\n for (i=0; i<len; i++)\r\n {\r\n //i2uitrace(1,\"cell #\"+i+\" headerwidth=\"+headeritem.clientWidth+\" newrow width=\"+newrow.clientWidth);\r\n newcellwidth = widths[i];\r\n newcell.style.width = newcellwidth;\r\n }\r\n\r\n var spread = parseInt((scrolleritem.clientWidth - overallwidth) / len);\r\n //i2uitrace(1,\"header row height=\"+headerheight+\" header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth+\" spread=\"+spread);\r\n\r\n // this solution leverages fixed table layout. IE uses\r\n // the width information from the COL tags to determine how\r\n // wide each column of every row should be. table rendering is\r\n // much faster. more importantly, more deterministic.\r\n var newitem;\r\n for (i=0; i<len; i++)\r\n {\r\n // create new tag and insert into table\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n headeritem.appendChild(newitem);\r\n }\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n dataitem.appendChild(newitem);\r\n }\r\n }\r\n\r\n // make last header row desired height\r\n headeritem.rows[lastheaderrow].style.height = headerheight;\r\n\r\n // set cell width\r\n for (i=0; i<len; i++)\r\n {\r\n headeritem.rows[0].cells[i].style.width = widths[i];\r\n headeritem.rows[lastheaderrow].cells[i].style.width = widths[i];\r\n dataitem.rows[0].cells[i].style.width = widths[i];\r\n }\r\n headeritem.style.tableLayout = \"fixed\";\r\n dataitem.style.tableLayout = \"fixed\";\r\n }\r\n // delete sizer row\r\n headeritem.deleteRow(headeritem.rows.length - 1);\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"returned width=\"+headeritem.clientWidth);\r\n return headeritem.clientWidth;\r\n}",
"function i2uiSetTabFillerHeight(id)\r\n{\r\n var filler_obj = document.getElementById(id+\"_filler\");\r\n var tab_table_obj = document.getElementById(id);\r\n if (filler_obj != null && tab_table_obj != null)\r\n {\r\n var container_table_obj = tab_table_obj.parentNode;\r\n while (container_table_obj != null)\r\n {\r\n if (container_table_obj.tagName == 'TABLE')\r\n {\r\n break;\r\n }\r\n container_table_obj = container_table_obj.parentNode;\r\n }\r\n if (container_table_obj != null &&\r\n tab_table_obj != null)\r\n {\r\n //i2uitrace(1,\"container height=\"+container_table_obj.offsetHeight);\r\n //i2uitrace(1,\"tab height=\"+tab_table_obj.offsetHeight);\r\n filler_obj.style.height = container_table_obj.offsetHeight -\r\n tab_table_obj.offsetHeight;\r\n }\r\n }\r\n}",
"function fixHeightTable(){\r\n\t// Set height table body\r\n\tif ($(\"#resultTable\").height() > calcDataTableHeight(6)){\r\n\t\t// $(\"div.dataTables_scrollBody\").css(\"height\",calcDataTableHeight(6));\r\n\t}\r\n\t// Set height table forzen (3 column first table body)\r\n\t// $(\"div.DTFC_LeftBodyWrapper\").css(\"height\",calcDataTableHeight(6));\r\n\t// $(\"div.DTFC_LeftBodyLiner\").css(\"height\",calcDataTableHeight(6));\r\n\t// $(\"div.DTFC_LeftBodyLiner\").css(\"max-height\",calcDataTableHeight(6));\r\n\t// Get height DTFC_LeftBody\r\n\t// var heightDTFC = $(\"div.DTFC_LeftBodyWrapper\").height();\r\n\t$(\"div.DTFC_LeftBodyWrapper\").addClass(\"heightTable\");\r\n\t$(\"div.DTFC_LeftBodyLiner\").addClass(\"heightTable\");\r\n\t$(\"div.DTFC_LeftBodyLiner\").addClass(\"maxHeightTable\")\r\n}",
"setDatatableFixedHeight() {\n var holder = this.shadowRoot.querySelector('#datatable-holder');\n if (this.headerFixed && this.height && this._datatable) {\n if (!this._datatable.headerFixed) {\n var header = this.shadowRoot.querySelector('#topBlock');\n holder.style.height = this.height;\n holder.onscroll = () => {\n var stop = holder.scrollTop - (holder.clientTop || 0);\n if (stop == 0) header.style.borderBottom = \"none\";\n if (stop > 0) header.style.borderBottom = \"1px solid #ddd\";\n };\n }\n if (this._datatable.headerFixed && !this._datatable.height) {\n this._datatable.height = this.height;\n }\n } else {\n if (holder.getAttribute(\"style\")) holder.removeAttribute(\"style\");\n }\n }",
"function constructHeaderTbl1() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:580px;max-height:580px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"function i2uiResizeColumns(tableid, shrink, copyheader, slave, headerheight)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var len2 = len;\r\n\r\n //i2uitrace(1,\"ResizeColumns entry scroller width=\"+scrolleritem.offsetWidth);\r\n\r\n if (headerheight != null && len > 1)\r\n return i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight, slave);\r\n\r\n // check first if resize needed\r\n //i2uitrace(1,\"check alignment in ResizeColumns\");\r\n if (i2uiCheckAlignment(tableid))\r\n {\r\n //i2uitrace(1,\"skip alignment in ResizeColumns\");\r\n return headeritem.clientWidth;\r\n }\r\n\r\n // insert a new row which is the same as the header row\r\n // forces very nice alignment whenever scrolling rows alone\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check for bypass\");\r\n for (var i=0; i<len; i++)\r\n {\r\n if (headeritem.rows[lastheaderrow].cells[i].innerHTML !=\r\n dataitem.rows[dataitem.rows.length-1].cells[i].innerHTML)\r\n break;\r\n }\r\n if (i != len)\r\n {\r\n //i2uitrace(1,\"insert fake row table=[\"+tableid+\"]\");\r\n\t // this is the DOM api approach\r\n\t var newrow = document.createElement('tr');\r\n\t if (newrow != null)\r\n\t {\r\n\t\t dataitem.appendChild(newrow);\r\n\t\t var newcell;\r\n\t\t for (var i=0; i<len; i++)\r\n\t \t {\r\n\t\t newcell = document.createElement('td');\r\n\t\t newrow.appendChild(newcell);\r\n\t\t if (newcell != null)\r\n\t\t {\r\n\t\t\t newcell.innerHTML = headeritem.rows[lastheaderrow].cells[i].innerHTML;\r\n\t\t }\r\n\t\t }\r\n\t }\r\n }\r\n\r\n //i2uitrace(1,\"ResizeColumns post copy scroller width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"post copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n var newwidth;\r\n newwidth = dataitem.scrollWidth;\r\n\r\n //i2uitrace(1,\"assigned width=\"+newwidth);\r\n dataitem.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n headeritem.width = newwidth;\r\n headeritem.style.width = newwidth;\r\n\r\n //i2uitrace(1,\"post static width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n // if processing master table, delete newly insert row and return\r\n if (scrolleritem2 != null && (slave == null || slave == 0))\r\n {\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check5 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check5 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"delete/hide fake row table=\"+tableid);\r\n var lastrow = dataitem.rows[dataitem.rows.length - 1];\r\n dataitem.deleteRow(dataitem.rows.length - 1);\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check6 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check6 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // size header columns to match data columns\r\n for (i=0; i<len; i++)\r\n {\r\n newColWidth=(i==0?dataitem.rows[0].cells[i].clientWidth:dataitem.rows[0].cells[i].clientWidth-12);\r\n headeritem.rows[lastheaderrow].cells[i].style.width = newColWidth;\r\n headeritem.rows[lastheaderrow].cells[i].width = newColWidth;\r\n if(i==0)\r\n {\r\n for(j=0; j<dataitem.rows.length; j++)\r\n {\r\n dataitem.rows[j].cells[0].style.width = newColWidth;\r\n dataitem.rows[j].cells[0].width = newColWidth;\r\n }\r\n }\r\n }\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check7 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check7 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"post hide width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns short version=\"+i2uiCheckAlignment(tableid));\r\n return newwidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$2 scroller: width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentNode.tagName+\" owner height=\"+tableitem.parentNode.offsetHeight);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n // may need to adjust width of header to accomodate scroller\r\n //i2uitrace(1,\"data height=\"+dataitem.clientHeight+\" scroller height=\"+scrolleritem.clientHeight+\" header height=\"+headeritem.clientHeight);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // if horizontal scrolling and scroller needed\r\n var adjust;\r\n if ((scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth) ||\r\n headeritem.rows[lastheaderrow].cells.length < 3)\r\n {\r\n adjust = 0;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"header cellpadding=\"+headeritem.cellPadding);\r\n adjust = headeritem.cellPadding * 2;\r\n\r\n // do not alter last column unless it contains a treecell\r\n if(dataitem.rows[0].cells[len-1].id.indexOf(\"TREECELL_\") == -1)\r\n len--;\r\n }\r\n //i2uitrace(1,\"adjust=\"+adjust+\" len=\"+len+\" headeritem #cols=\"+headeritem.rows[0].cells.length);\r\n\r\n // if window has scroller, must fix header\r\n // but not if scrolling in both directions\r\n //i2uitrace(1,\"resizecolumns scrolleritem.style.overflowY=\"+scrolleritem.style.overflowY);\r\n //i2uitrace(1,\"resizecolumns scrolleritem2=\"+scrolleritem2);\r\n if(scrolleritem.style.overflowY == 'scroll' ||\r\n scrolleritem.style.overflowY == 'hidden')\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n dataitem.width = dataitem.clientWidth;\r\n dataitem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header and data widths\");\r\n }\r\n else\r\n {\r\n if(scrolleritem2 != null)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header2 shrink=\"+shrink+\" copyheader=\"+copyheader);\r\n shrink = 0;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$3 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n if (document.body.clientWidth < headeritem.clientWidth)\r\n {\r\n len++;\r\n adjust = 0;\r\n //i2uitrace(1,\"new adjust=\"+adjust+\" new len=\"+len);\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$4 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n if (shrink != null && shrink == 1)\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * dataitem.rows[0].cells.length;\r\n\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<headeritem.rows[lastheaderrow].cells.length-1; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink\");\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$5 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n len = Math.min(len, headeritem.rows[0].cells.length);\r\n\r\n //i2uitrace(1,\"start data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n var w1, w2, w3;\r\n for (var i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n\r\n //i2uitrace(1,\"pre i=\"+i+\" w1=\"+w1+\" w2=\"+w2+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" w1=\"+headeritem.rows[0].cells[i].clientWidth+\" w2=\"+dataitem.rows[0].cells[i].clientWidth+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // try to handle tables that need window scrollers\r\n if (headeritem.clientWidth != dataitem.clientWidth)\r\n {\r\n //i2uitrace(1,\"whoa things moved. table=\"+tableid+\" i=\"+i+\" len=\"+len);\r\n\r\n // if window has scroller, resize to window unless slave table\r\n if (document.body.scrollWidth != document.body.offsetWidth)\r\n {\r\n //i2uitrace(1,\"window has scroller! slave=\"+slave);\r\n if (slave == null || slave == 0)\r\n {\r\n dataitem.width = document.body.scrollWidth;\r\n dataitem.style.width = document.body.scrollWidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n if (headeritem.clientWidth < dataitem.clientWidth)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n }\r\n else\r\n {\r\n dataitem.width = headeritem.clientWidth;\r\n dataitem.style.width = headeritem.clientWidth;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"$$$$$$6 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // now delete the fake row\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n if (scrolleritem2 == null && (slave == null || slave == 0))\r\n {\r\n if (document.all)\r\n {\r\n dataitem.deleteRow(dataitem.rows.length-1);\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"post delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n }\r\n\r\n width = headeritem.clientWidth;\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns long version\");\r\n //i2uiCheckAlignment(tableid);\r\n }\r\n //i2uitrace(1,\"WIDTH=\"+width);\r\n return width;\r\n}",
"function BindTableHeader(jsondata, tableid) {\n var columnSet = [];\n var headerTr$ = $('<tr/>');\n for (var i = 0; i < jsondata.length; i++) {\n var rowHash = jsondata[i];\n for (var key in rowHash) {\n if (rowHash.hasOwnProperty(key)) {\n // Add each unique column names to a variable array*/\n if ($.inArray(key, columnSet) === -1) {\n columnSet.push(key);\n headerTr$.append($('<th/>').html(key));\n }\n }\n }\n }\n $('#table-1 tr, #table-2 tr').remove();\n $(tableid).append(headerTr$);\n return columnSet;\n}",
"function constructHeaderTbl() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:700px;max-height:780px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"function i2uiManageTableScroller(id,maxheight,newheight)\r\n{\r\n if (document.layers || document.all)\r\n return;\r\n var table_obj = document.getElementById(id);\r\n var scroller_obj = document.getElementById(id+\"_data\");\r\n if (table_obj != null && scroller_obj != null)\r\n {\r\n var len = table_obj.rows[0].cells.length;\r\n if (len > 1)\r\n {\r\n var scrollercell = table_obj.rows[0].cells[len-1];\r\n if (scrollercell != null && scrollercell.id==\"scrollerspacer\")\r\n {\r\n if (newheight < maxheight)\r\n {\r\n if (scroller_obj.style.overflow==\"hidden\")\r\n {\r\n var cmd = \"document.getElementById('\"+id+\"_data').style.overflow='auto'\";\r\n setTimeout(cmd, 50);\r\n }\r\n scrollercell.style.display = \"\";\r\n scrollercell.style.visibility = \"visible\";\r\n }\r\n else\r\n {\r\n scroller_obj.style.overflow=\"hidden\";\r\n scrollercell.style.display = \"none\";\r\n }\r\n }\r\n }\r\n }\r\n}",
"function i2uiResizeTable(mastertableid, minheight, minwidth, slavetableid, flag)\r\n{\r\n //i2uitrace(0,\"ResizeTable = \"+mastertableid);\r\n var tableitem = document.getElementById(mastertableid);\r\n var headeritem = document.getElementById(mastertableid+\"_header\");\r\n var dataitem = document.getElementById(mastertableid+\"_data\");\r\n var scrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(mastertableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n scrolleritem2 != null)\r\n {\r\n //i2uitrace(0,\"resizetable pre - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(0,\"resizetable pre - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(0,\"resizetable pre - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n scrolleritem2.width = \"100px\";\r\n scrolleritem2.style.width = \"100px\";\r\n scrolleritem.style.height = \"100px\";\r\n scrolleritem.width = \"100px\";\r\n scrolleritem.style.width = \"100px\";\r\n\r\n tableitem.style.width = \"100px\";\r\n dataitem.width = \"100px\";\r\n dataitem.style.width = \"100px\";\r\n headeritem.width = \"100px\";\r\n headeritem.style.width = \"100px\";\r\n\r\n //i2uitrace(0,\"resizetable post - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(0,\"resizetable post - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(0,\"resizetable post - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n var cmd = \"i2uiResizeScrollableArea('\"+mastertableid+\"', '\"+minheight+\"', '\"+minwidth+\"', '\"+slavetableid+\"', '\"+flag+\"')\";\r\n //setTimeout(cmd, 250);\r\n for (var i=0; i<4; i++)\r\n {\r\n eval(cmd);\r\n if (i2uiCheckAlignment(mastertableid))\r\n {\r\n break;\r\n }\r\n //i2uitrace(0,\"realigned after \"+i+\" attempts\");\r\n }\r\n }\r\n}",
"function i2uiResizeMasterColumns(tableid, column1width, headerheight, fixedColumnWidths)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeMasterColumns id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n\r\n var len, i, w1, w2, w3, adjust, len2;\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n len2 = len;\r\n\r\n // if horizontal scrolling and scroller needed\r\n if (scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth)\r\n {\r\n adjust = 0;\r\n len--;\r\n }\r\n else\r\n {\r\n adjust = headeritem.cellPadding * 2;\r\n // do not alter last column\r\n len--;\r\n }\r\n\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n if( fixedColumnWidths )\r\n {\r\n i2uiResizeColumnsWithFixedHeaderHeight_new(tableid, headerheight, null, fixedColumnWidths );\r\n }\r\n else if (headerheight != null)\r\n {\r\n\t i2uiResizeColumns(tableid);\r\n i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight);\r\n }\r\n else\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<len; i++)\r\n {\r\n //headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n //dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink. adjust=\"+adjust);\r\n\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n //i2uitrace(1,\"pre i=\"+i+\" header=\"+w1+\" data=\"+w2+\" max=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n }\r\n //i2uitrace(1,\"end data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check1 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check1 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n }\r\n\r\n if (dataitem.clientWidth > headeritem.clientWidth)\r\n {\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"header width set to data width\");\r\n }\r\n else\r\n if (dataitem.clientWidth < headeritem.clientWidth)\r\n {\r\n dataitem.style.width = headeritem.clientWidth;\r\n //i2uitrace(1,\"data width set to header width\");\r\n }\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check2 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check2 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n\r\n if (scrolleritem.clientWidth > dataitem.clientWidth)\r\n {\r\n dataitem.style.width = scrolleritem.clientWidth;\r\n headeritem.style.width = scrolleritem.clientWidth;\r\n //i2uitrace(1,\"both widths set to scroller width\");\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check3 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check3 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // one last alignment\r\n if (!i2uiCheckAlignment(tableid))\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n if (w1 != w3)\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n if (w2 != w3)\r\n dataitem.rows[0].cells[i].width = w3;\r\n //LPMremoved\r\n //if (i2uitracelevel == -1)\r\n // dataitem.rows[0].cells[i].width = w1;\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check4 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check4 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"FINAL data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n // if column 1 has a fixed width\r\n if (column1width != null && column1width > 0 && len > 1)\r\n {\r\n // assign both first columns to desired width\r\n headeritem.rows[lastheaderrow].cells[0].width = column1width;\r\n dataitem.rows[0].cells[0].width = column1width;\r\n\r\n // assign both first columns to narrowest\r\n var narrowest = Math.min(dataitem.rows[0].cells[0].clientWidth,\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n headeritem.rows[lastheaderrow].cells[0].width = narrowest;\r\n dataitem.rows[0].cells[0].width = narrowest;\r\n\r\n // determine the width difference between the first columns\r\n var spread = Math.abs(dataitem.rows[0].cells[0].clientWidth -\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n // determine how much each non-first column should gain\r\n spread = Math.ceil(spread/(len-1));\r\n\r\n // spread this difference across all non-first columns\r\n if (spread > 0)\r\n {\r\n for (i=1; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = headeritem.rows[lastheaderrow].cells[i].clientWidth + spread;\r\n dataitem.rows[0].cells[i].width = dataitem.rows[0].cells[i].clientWidth + spread;\r\n }\r\n }\r\n\r\n // if desiring abolsute narrowest possible\r\n if (column1width == 1)\r\n {\r\n // if not aligned, take difference and put in last column of data table\r\n var diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n var loop = 0;\r\n // well, one call may not be enough\r\n while (diff > 0)\r\n {\r\n dataitem.rows[0].cells[len-1].width = dataitem.rows[0].cells[len-1].clientWidth + diff;\r\n loop++;\r\n\r\n // only try 4 times then stop\r\n if (loop > 4)\r\n break;\r\n diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n }\r\n }\r\n }\r\n\r\n width = dataitem.clientWidth;\r\n }\r\n //i2uitrace(1,\"i2uiResizeMasterColumns exit. return width=\"+width);\r\n return width;\r\n}",
"function updateHeaderHeight() {\n\n // Set the current header height (window height sans menu).\n _.headerHeight = _.header.height() - headerMenuHeight;\n }",
"setupBodyHeights () {\n const headerMiddleSelector = this.get('_headerMiddleSelector')\n const headerHeight = this.$(headerMiddleSelector).outerHeight()\n const tableHeight = this.$().outerHeight()\n const bodyHeight = tableHeight - headerHeight\n\n const bodyLeftSelector = this.get('_bodyLeftSelector')\n const bodyMiddleSelector = this.get('_bodyMiddleSelector')\n const bodyRightSelector = this.get('_bodyRightSelector')\n\n ;[bodyLeftSelector, bodyMiddleSelector, bodyRightSelector].forEach((selector) => {\n this.$(selector).css({height: `${bodyHeight}px`})\n })\n\n // Empty rows still need height set so border shows when row is selected\n const rowHeight = this.$('.frost-table-row:not(:empty) .frost-table-row-cell').outerHeight()\n this.$('.frost-table-row:empty').css({height: `${rowHeight}px`})\n }",
"function GetHeaderHeight() {\n var styleSheetName = SiebelApp.S_App.GetStyleSheetName();\n var headerheight = utils.GetstyleSheetPropVal(styleSheetName, \".siebui .ListAppletHeader\", \"height\");\n\n return headerheight || siebConsts.get(\"DFLT_HEADHGT\");\n }",
"function settaAltezzaRow(total_h) {\n var h = total_h / 2;\n $('.myf-row').height(h);\n}",
"function selectHeader(headerid) {\n var cellDomLocations = new Array();\n var headerIndex = headerid;\n\n if (headerid.indexOf(\"column\") > -1) {\n //mark selected header and update header relationships\n markSelectedLevelHeader(headerid);\n\n headerIndex = parseInt(headerid.split(\"column\")[1].split(\"_\")[0]);\n\n if (cellHeaders[headerIndex + \"\"] != null) {\n cellDomLocations = cellHeaders[headerIndex].replace(\"undefined\", \"\").split(\",\");\n for (var l = 0; l < cellDomLocations.length - 1; l++) {\n levelHeaders[headerIndex].push(document.getElementById(cellDomLocations[l]));\n }\n cellHeaders[headerIndex + \"\"] = null;\n }\n if (levelHeaders[headerIndex] != undefined) {\n for (var k = 0; k < levelHeaders[headerIndex].length; k++) {\n cell = levelHeaders[headerIndex][k];\n cellid = cell.id;\n cellIdParts = cellid.split(\"column\");\n columnNum = cellIdParts[1].split(\"_\")[0];\n selectCellNum = cellid.split(\"_cellID_\")[1];\n selectedSampleID = cellIdParts[0];\n levelHeaders[columnNum].length > 0 ? totalSelectableCol = levelHeaders[columnNum].length : totalSelectableCol = cellHeaders[columnNum].split(\",\").length - 1;\n if (selectedCells[selectCellNum] == null) {\n selectCell(cell, \"headerCol\", selectCellNum, selectedSampleID, columnNum, totalSelectableCol, cellHeaders[selectedSampleID].split(\",\").length);\n }\n }\n }\n\n } else if (cellHeaders[headerIndex] != undefined) {\n //the string is likely to lead with undefined if first batch had no 'availables'\n var idString = cellHeaders[headerIndex].replace(\"undefined,\", \"\");\n\n if (idString.length > 0) {\n var idArray = idString.split(\",\");\n\n if (headerIndex.indexOf(\"_sample\") == -1 && headerIndex.indexOf(\"column\") == -1) {\n //if its batch header clicked, recursively apply to each sample id\n for (var j = 0; j < idArray.length; j++) {\n selectHeader(idArray[j]);\n }\n\n } else {\n for (var i = 0; i < idArray.length; i++) {\n cellid = idArray[i];\n cell = document.getElementById(cellid);\n cellIdParts = cellid.split(\"column\");\n columnNum = cellIdParts[1].split(\"_\")[0];\n selectCellNum = cellid.split(\"_cellID_\")[1];\n selectedSampleID = cellIdParts[0];\n levelHeaders[columnNum].length > 0 ? totalSelectableCol = levelHeaders[columnNum].length : totalSelectableCol = cellHeaders[columnNum].split(\",\").length - 1;\n\n if (selectedCells[selectCellNum] == null) {\n selectCell(cell, \"header\", selectCellNum, selectedSampleID, columnNum, totalSelectableCol, cellHeaders[selectedSampleID].split(\",\").length);\n }\n }\n }\n } else if (!tcga.util.hasClass(document.getElementById(headerIndex), \"selected\")) {\n markSelectedSampleHeader(headerIndex);\n }\n }\n}",
"function i2uiShrinkScrollableTable(tableid)\r\n{\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null)\r\n {\r\n var newwidth = 100;\r\n //i2uitrace(1,\"==========\");\r\n //i2uitrace(1,\"tableitem clientwidth=\"+tableitem.clientWidth);\r\n //i2uitrace(1,\"tableitem offsetwidth=\"+tableitem.offsetWidth);\r\n //i2uitrace(1,\"tableitem scrollwidth=\"+tableitem.scrollWidth);\r\n //i2uitrace(1,\"headeritem clientwidth=\"+headeritem.clientWidth);\r\n //i2uitrace(1,\"headeritem offsetwidth=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"headeritem scrollwidth=\"+headeritem.scrollWidth);\r\n //i2uitrace(1,\"dataitem clientwidth=\"+dataitem.clientWidth);\r\n //i2uitrace(1,\"dataitem offsetwidth=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"dataitem scrollwidth=\"+dataitem.scrollWidth);\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n if (scrolleritem2 != null)\r\n {\r\n scrolleritem2.style.width = newwidth;\r\n scrolleritem2.width = newwidth;\r\n }\r\n scrolleritem.style.width = newwidth;\r\n scrolleritem.width = newwidth;\r\n tableitem.style.width = newwidth;\r\n tableitem.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n dataitem.width = newwidth;\r\n }\r\n}",
"function SetRowHeight() {\n var grid = this.GetGrid();\n var rowHeight = GetRowHeight.call(this);\n var ids = grid.getDataIDs();\n\n for (var i = 0, len = ids.length; i < len; i++) {\n grid.setRowData(ids[i], false, { height: rowHeight });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Filter Group Key Name | async function getFilterGroupKeyName(internalName, key){
let data = await FiltersService.getFilter(key, internalName);
let filterName = key;
if(internalName == 'peopleId'){
let peopleData = await PeopleService.getPeople(key);
filterName = peopleData[0].firstName + " " + peopleData[0].lastName;
}
if(data !== null){
return data[0];
}
else{
return { filterName: filterName,
filterValue: key
};
}
} | [
"function _getGroupKeySelector(item) {\n return item.group.key;\n }",
"function FILTER_KEY(key) {\n var string = %ToString(key);\n if (%HasProperty(this, string)) return string;\n return 0;\n}",
"function extGroup_getDataSourceFileName(groupName)\n{\n return dw.getExtDataValue(groupName, \"dataSource\");\n}",
"static keyField() {\n return new lt([\"__name__\"]);\n }",
"async function getGroupName(group) {\n const result = await db.collection(\"Groups\")\n .findOne({ _id: ObjectId(group) }, { projection: { _id: 0, name: 1 } });\n\n if (result === null) {\n throw new RequestError('group does not exist');\n }\n\n return result.name;\n}",
"function getGroupNames(){\n var ret = [];\n for (var i = 0; i < this.groups.length; i++) {\n ret.push(this.groups[i].name);\n }\n return ret;\n}",
"function outputFldName(fld) {\n const prefixLen = currentSettingGroup.length,\n shortFldName = prefixLen && fld.startsWith(`${currentSettingGroup}_`)\n ? ` ${fld.substring(prefixLen + 1)}`\n : fld;\n return shortFldName.replaceAll('_', ' ');\n }",
"function _getGroupDataSelector(item) {\n return item.group;\n }",
"function GetGroupID() {\n //return parent.ORYX.I18N.PropertyWindow.ProcGroupID;\n return \"\";\n }",
"groupSpecifier() {\n this._lastStrValue = \"\";\n if (this.eat(unicode_1.QuestionMark)) {\n if (this.eatGroupName()) {\n if (!this._groupNames.has(this._lastStrValue)) {\n this._groupNames.add(this._lastStrValue);\n return;\n }\n this.raise(\"Duplicate capture group name\");\n }\n this.raise(\"Invalid group\");\n }\n }",
"get keyName() {\n const prefix = this.guildIDs ? this.guildIDs.join(',') : 'global';\n return `${prefix}:${this.commandName}`;\n }",
"function influxKey(key, type) {\n var k = key.split(',');\n\n var name = k.shift();\n var tags = k;\n\n return name + '.' + type + (tags.length > 0 ? ',' + tags.join(',') : '')\n}",
"facetFieldName(type, field, cf) {\n const multi = ( cf['multi'] || ( cf['resolve'] === 'multi' ) );\n return [ type, field, multi ? 'facetmulti' : 'facet' ].join('_');\n }",
"getKey(idx) {\n if (idx >= 0 && idx < this.state.records.length) {\n return this.state.records[idx].key;\n }\n return '';\n }",
"function key(network, channel) {\n return network + \"|||\" + channel;\n}",
"getFilters(key, appliedFilters) {\n let filters = [];\n //let appliedFilters = Object.assign({}, this.state.appliedFilters);\n return Object.keys(appliedFilters).map(k => { \n let next = appliedFilters[k];\n if (next && next.willFilter && next.willFilter.length > 0 ) {\n let will = next.willFilter.indexOf(key);\n if (will >= 0) return appliedFilters[k];\n }\n });\n }",
"group (name) {\n var me = `${this.visualType}-${this.model.uid}`,\n group = this.visualParent.getPaperGroup(me);\n if (name && name !== this.visualType) return this.paper().childGroup(group, name);\n else return group;\n }",
"function dwscripts_getUniqueSBGroupName(paramObj, serverBehaviorName)\n{\n var groupName = \"\";\n var groupNames = dwscripts.getSBGroupNames(serverBehaviorName);\n\n if (groupNames.length)\n {\n if (groupNames.length == 1)\n {\n groupName = groupNames[0];\n }\n else\n {\n //if subType or dataSource given, resolve ties by filtering using them\n if (paramObj)\n {\n var matchGroups = new Array();\n for (var i=0; i<groupNames.length; i++)\n {\n //if no dataSource or it matches, and no subType or it matches, keep groupName\n if (\n (\n (!paramObj.MM_dataSource && !dw.getExtDataValue(groupNames[i],\"dataSource\")) ||\n (paramObj.MM_dataSource && dw.getExtDataValue(groupNames[i],\"dataSource\") == paramObj.MM_dataSource)\n )\n &&\n (\n (!paramObj.MM_subType && !dw.getExtDataValue(groupNames[i],\"subType\")) ||\n (paramObj.MM_subType && dw.getExtDataValue(groupNames[i],\"subType\") == paramObj.MM_subType)\n )\n )\n {\n matchGroups.push(groupNames[i]);\n }\n }\n\n if (!matchGroups.length && paramObj.MM_subType)\n {\n for (var i=0; i<groupNames.length; i++)\n {\n //if no dataSource or it matches, and no subType, keep groupName\n if (\n (\n (!paramObj.MM_dataSource && !dw.getExtDataValue(groupNames[i],\"dataSource\")) ||\n (paramObj.MM_dataSource && dw.getExtDataValue(groupNames[i],\"dataSource\") == paramObj.MM_dataSource)\n )\n && !dw.getExtDataValue(groupNames[i],\"subType\")\n )\n {\n matchGroups.push(groupNames[i]);\n break;\n }\n }\n }\n\n if (!matchGroups.length && paramObj.MM_dataSource)\n {\n //if no dataSource, keep groupName\n for (var i=0; i<groupNames.length; i++)\n {\n if (!dw.getExtDataValue(groupNames[i],\"dataSource\"))\n {\n matchGroups.push(groupNames[i]);\n break;\n }\n }\n }\n\n //if anything left after filtering, use that\n if (matchGroups.length)\n {\n groupName = matchGroups[0];\n }\n }\n }\n }\n\n return groupName;\n}",
"isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prevent element from initializing properties when it's upgrade disabled. | _initializeProperties() {
if (this.hasAttribute(DISABLED_ATTR)) {
this.__isUpgradeDisabled = true;
} else {
super._initializeProperties();
}
} | [
"onDisabled() {\n this.updateInvalid();\n }",
"function storeOriginalDisabledProperty(element) {\n //capture original disabled property value\n if (element.data('original-disabled') === undefined) {\n element.data(\"original-disabled\", element.prop(\"disabled\"));\n }\n}",
"wakeUp () {\n this.setProperty('isSleeping', false)\n }",
"set disabled(value) {\n const isDisabled = Boolean(value);\n if (this._disabled == isDisabled)\n return;\n this._disabled = isDisabled;\n this._safelySetAttribute('disabled', isDisabled);\n this.setAttribute('aria-disabled', isDisabled);\n // The `tabindex` attribute does not provide a way to fully remove\n // focusability from an element.\n // Elements with `tabindex=-1` can still be focused with\n // a mouse or by calling `focus()`.\n // To make sure an element is disabled and not focusable, remove the\n // `tabindex` attribute.\n if (isDisabled) {\n this.removeAttribute('tabindex');\n // If the focus is currently on this element, unfocus it by\n // calling the `HTMLElement.blur()` method.\n if (document.activeElement === this)\n this.blur();\n } else {\n this.setAttribute('tabindex', '0');\n }\n }",
"function skipHydrate(obj) {\r\n return vueDemi.isVue2\r\n ? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...\r\n /* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj\r\n : Object.defineProperty(obj, skipHydrateSymbol, {});\r\n}",
"function preventInit(feature) {\n\t\t\tif (!args || !args.disable) return false;\n\t\t\treturn args.disable.indexOf(feature) != -1\n\t\t}",
"disableInteractions() {\n this.setState({\n disableGetLink: true,\n disableNodeRemove: true,\n disableAddMarker: true,\n disableReset: true,\n disableDragMarker: true,\n disableNewSeq: true,\n disableLinkRemove: true\n });\n this.forceUpdate();\n }",
"function disableSizeSlider(){\r\n document.querySelector(\"#arr_sz\").disabled = true;\r\n}",
"__disableInput() {\n if (!this.readonly && this.disableTextInput) {\n this.$.display.set('readonly', true);\n }\n }",
"disablePlugin() {\n this.settings = {};\n this.hiddenColumns = [];\n this.lastSelectedColumn = -1;\n\n this.hot.render();\n super.disablePlugin();\n this.resetCellsMeta();\n }",
"static disable() {\n LightObjects.lightObjects = [];\n }",
"function disableOtherElement() {\n //Back, home page, learn and speaker icons are disabled\n document.getElementsByClassName('backContainer')[0].setAttribute('disabled',\n 'true');\n document.getElementsByClassName('homePageContainer')[0].setAttribute(\n 'disabled','true');\n document.getElementsByClassName('learnContainer')[0].setAttribute('disabled',\n 'true');\n document.getElementById('speaker').setAttribute('disabled','true');\n\n //Decrease the opacity of header elements\n document.getElementsByClassName('levelHeader')[0].style.opacity = 0.5;\n var images = document.getElementsByClassName(\n 'levelHeader')[0].getElementsByTagName('img');\n\n //Also remove the pointer for header icons\n for(var i=0;i<images.length;i++) {\n images[i].style.cursor = 'default';\n }\n\n //Deacrease opacity for all elements\n document.getElementsByClassName('leftPanelContainer')[0].style.opacity = 0.5;\n document.getElementsByClassName('questionElement')[0].style.opacity = 0.5;\n document.getElementById('answerInputElement').setAttribute('disabled','true');\n document.getElementById('item_'+currentItem.itemId).setAttribute('draggable',\n 'false');\n}",
"enable_disableMutation(){\n\t\tvar i = Math.floor(Math.random() * this.genes.length)\n\n\t\t//we can only use an available gene\n\t\tif (this.genes[i] != null) {\n\t\t\tthis.genes[i].enabled = !this.genes[i].enabled\n\t\t} else {\n\t\t\tthis.enable_disableMutation()\n\t\t}\n\t}",
"updateAriaAttrs () {\n if (!this.aria || this.isHeadless || !isCallable(this.el.setAttribute)) return;\n\n this.el.setAttribute('aria-required', this.isRequired ? 'true' : 'false');\n this.el.setAttribute('aria-invalid', this.flags.invalid ? 'true' : 'false');\n }",
"_freezeAsyncOldProps() {\n if (!this.oldAsyncProps && this.oldProps) {\n // 1. inherit all synchronous props from oldProps\n // 2. reconfigure the async prop descriptors to fixed values\n this.oldAsyncProps = Object.create(this.oldProps);\n\n for (const propName in this.asyncProps) {\n Object.defineProperty(this.oldAsyncProps, propName, {\n enumerable: true,\n value: this.oldProps[propName]\n });\n }\n }\n }",
"constructor() { \n \n ComDayCqCompatCodeupgradeImplUpgradeTaskIgnoreListProperties.initialize(this);\n }",
"function checkElementNotDisabled(element) {\r\n if (element.disabled) {\r\n throw {statusCode: 12, value: {message: \"Cannot operate on disabled element\"}};\r\n }\r\n}",
"function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}",
"disable_style() {\n this.enabledStyles.pop();\n }",
"_suppressFocusableElements() {\n if (!this.state.isSample || this.isEmbedded) {\n return;\n }\n const rootEls = [];\n for (const selector of this.sampleDataTargets) {\n rootEls.push(...this.el.querySelectorAll(`:scope ${selector}`));\n }\n const focusableEls = new Set(rootEls);\n for (const rootEl of rootEls) {\n rootEl.classList.add('o_sample_data_disabled');\n for (const focusableEl of rootEl.querySelectorAll(FOCUSABLE_ELEMENTS)) {\n focusableEls.add(focusableEl);\n }\n }\n for (const focusableEl of focusableEls) {\n focusableEl.setAttribute('tabindex', -1);\n if (focusableEl.classList.contains('dropdown-item')) {\n // Tells Bootstrap to ignore the dropdown item in keynav\n focusableEl.classList.add('disabled');\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An action icon (e.g., "edit") is clicked next to entry | function onEntryAction(evt) {
if ($(this).hasClass("edit")) {
zdPage.navigate("edit/existing/" + $(this).data("entry-id"));
//window.open("/" + zdPage.getLang() + "/edit/existing/" + $(this).data("entry-id"));
}
} | [
"function on_edit_button_click(){\n\t\tif ($(this).text()=='Edit'){\n\t\t\t$(\"#middle\").find(\"button.edit\").text('Edit')\n\t\t\t\t.siblings('span').hide()\n\t\t\t\t.siblings('span.value').show();\n\n\t\t\t$(this).siblings('span').show()\n\t\t \t\t\t .siblings('span.value').hide();\n\t\t\t$(this).text('Cancel');\n\t\t} else {\n\t\t\t$(this).siblings('span').hide().siblings('span.value').show();\n\t\t\t$(this).text('Edit');\n\t\t}\n}",
"function _iconClickEvent() {\n\n\t\t_toggleVisibility();\n\n\t\t// Turn of file watching when not using it\n\t\tif (false === visible) {\n\t\t\ttailDomain.exec(\"quitTail\")\n\t\t\t\t.done(function () {\n\t\t\t\t\tconsole.log(\"[brackets-tail-node] quitTail done event\");\n\t\t\t\t}).fail(function (err) {\n\t\t\t\t\tconsole.error(\"[brackets-tail-node] quitTail error event\", err);\n\t\t\t\t});\n\t\t}\n\t}",
"function menuEditClick() {\n Data.Edit.Open = !Data.Edit.Open;\n setEditMenuPosition();\n\n if (Data.Edit.Open) {\n if (Data.Edit.LastMode)\n Data.Edit.Mode = Data.Edit.LastMode;\n } else {\n Data.Edit.LastMode = Data.Edit.Mode;\n Data.Edit.Mode = EditModes.Off;\n }\n updateMenu();\n\n if (Data.Edit.Open && Data.Controls.Open) {\n Data.Controls.Open = false;\n setControlsPosition();\n }\n}",
"function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}",
"function editElement(event){\n\t\t\t\t\tclickedItem.innerHTML = textBox.value;\n\t\t\t\t}",
"function addIconClickListener(callBack) {\n browserAction.onClicked.addListener(callBack);\n}",
"deleteIconAdd(cell, row){\n\treturn (<actionDiv><deleteDiv> <a href = 'javaScript:void(0)' onClick= {(e) => {currentObj.deleteTableRow(cell, row, this)}} ><img src=\"http://localhost/img/deleteIcon.png\" /></a></deleteDiv></actionDiv>)\n}",
"function menuTooltipClick() {\n Data.Edit.Mode = EditModes.Notes;\n updateMenu();\n}",
"function performActions() {\n\n // prepare event data\n event_data = $.integrate( entry_data, event_data );\n event_data.content = content_elem;\n event_data.entry = entry_elem;\n delete event_data.actions;\n\n // perform menu entry actions\n if ( entry_data.actions )\n if ( typeof ( entry_data.actions ) === 'function' )\n entry_data.actions( $.clone( event_data ), self );\n else\n entry_data.actions.forEach( action => $.action( action ) );\n\n // perform callback for clicked menu entry\n self.onclick && $.action( [ self.onclick, $.clone( event_data ), self ] );\n\n }",
"function makeEditButton(cls, pk, title, options={}) {\n return makeIconButton('fa-edit icon-blue', cls, pk, title, options);\n}",
"function hoverActions () {\n row = arguments[0];\n icon = [];\n for (var i=1; i<arguments.length; i++)\n this.icon.push(arguments[i]);\n $(\".\" + row).mouseenter( function() {\n var id = $(this).attr(\"id\").toString().replace(/row_/i, \"\");\n if ( $('#edit-modal').length ) {\n $(\"#edit_\"+id).click(function(){\n getData(id, function(data) {\n for(key in data) {\n if ($('#edit-modal input[name='+key+']').length )\n $('#edit-modal input[name='+key+']').val(data[key]);\n else\n $('#edit-modal textarea[name='+key+']').val(data[key]);\n }\n $('input[name=\"id\"]').val(id);\n });\n });\n $(\"#delete_\"+id).click( function(){\n var sum = $(this).parent().parent().parent().find('h4').text();\n $(\"#confirmDelete\").data(\"id\", id );\n $(\"#confirmDelete .btn-danger\").text(\"Delete \" + sum);\n });\n }\n }).mouseleave( function() {\n // Nothing to do.\n });\n}",
"_addClickAction(options) {\n const $action = this.addFooterAction({\n id: options.id,\n html: `<a href=\"#\">${options.text}</a>`,\n });\n\n $action.click(ev => {\n ev.preventDefault();\n ev.stopPropagation();\n\n this.model.loadData(options.loadKey);\n });\n }",
"function handleCustomAction(entry) {\n\t\t\tif(entry.entry_method.template != \"visit\" && (\n\t\t\t\t\tentry.entry_method.method_type == \"Ask a question\" ||\n\t\t\t\t\tentry.entry_method.method_type == \"Allow question or tracking\" ||\n\t\t\t\t\tentry.entry_method.config5 ||\n\t\t\t\t\tentry.entry_method.config6\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tif(entry.entry_method.config5 !== null) {\n\t\t\t\t\thandleMultipleChoiceQuestionEntry(entry);\n\t\t\t\t} else {\n\t\t\t\t\thandleQuestionEntry(entry);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandleClickEntry(entry);\n\t\t\t}\n\t\t}",
"function gripClick() {\n Data.Menu.Open = !Data.Menu.Open;\n setMenuPosition();\n\n if (!Data.Menu.Open && Data.Controls.Open) {\n Data.Controls.Open = false;\n setControlsPosition();\n }\n\n if (!Data.Menu.Open && Data.Edit.Open) {\n Data.Edit.Open = false;\n setEditMenuPosition();\n\n Data.Edit.LastMode = Data.Edit.Mode;\n Data.Edit.Mode = EditModes.Off;\n updateMenu();\n }\n}",
"function menuTextClick() {\n Data.Edit.Mode = EditModes.Text;\n updateMenu();\n}",
"function menuHighlightClick() {\n Data.Edit.Mode = EditModes.Highlight;\n updateMenu();\n}",
"function showIconRightOrWrongOpen() {\r\n showIconRightOrWrongQ6();\r\n}",
"function rtGuiClick() { rtGuiAdd(this.id); }",
"function showIconAddMenu() {\n var apps = FPI.apps.all, i, bundle, sel, name;\n clearinnerHTML(appList);\n showHideElement(appList, 'block');\n appList.appendChild(createDOMElement('li', 'Disable Edit', 'name', 'Edit'));\n\n for (i = 0; i < apps.length; i++) {\n bundle = apps[i].bundle;\n sel = FPI.bundle[bundle];\n name = sel.name;\n appList.appendChild(createDOMElement('li', name, 'name', bundle));\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
approve Property Registration on the network | async approvePropertyRegistration(ctx, propertyId) {
// Verify the CLient is an registar or not
let cid = new ClientIdentity(ctx.stub);
let mspID = cid.getMSPID();
if (mspID !== "registrarMSP") {
throw new Error('You are not authorized to invoke this fuction');
}
// Create a new composite key for the property Request
const requestKey = Request.makeKey([propertyId]);
// Fetch Request with given propertyId from blockchain
let existingRequest = await ctx.requestList
.getRequest(requestKey)
.catch(err => console.log('Provided property Id is not valid!'));
// Make sure Property request already exist.
if (existingRequest === undefined) {
throw new Error('Invalid property Id: ' + propertyId + '. No Property with this ID exists.');
} else {
// Create a new composite key for the Property Registration
const propertyKey = Property.makeKey([propertyId]);
// Fetch Property with given PropertyID from blockchain
let existingProperty = await ctx.propertyList
.getProperty(propertyKey)
.catch(err => console.log('Provided propertyId is unique!'));
// Make sure Property does not already exist.
if (existingProperty !== undefined) {
throw new Error('Invalid propertyId: ' + propertyId + '. A Property with this property ID already exists.');
} else {
// Create a Property object to be stored in blockchain
let propertyObject = {
propertyId: propertyId,
owner: existingRequest.owner,
price: existingRequest.price,
status: existingRequest.status,
createdAt: new Date(),
updatedAt: new Date(),
};
// Create a new instance of Property model and save it to blockchain
let newPropertyObject = Property.createInstance(propertyObject);
await ctx.propertyList.addProperty(newPropertyObject);
// Return value of new Property Object
return newPropertyObject;
}
}
} | [
"async propertyRegistrationRequest(ctx, propertyId, price, status, name, aadharNumber){\r\n\r\n\t\tconst userKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.user',[name, aadharNumber]);\r\n\r\n\t\tconst requestKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.request',[propertyId]);\r\n\r\n\t\tlet userBuffer = await ctx.stub.getState(userKey).catch(err => console.log(err));\r\n\r\n\t\tif(userBuffer.length === 0){\r\n\t\t\tthrow new Error(\"User isn't registered\");\r\n\t\t}\r\n\r\n\t\tif(price < 0){\r\n\t\t\tthrow new Error(\"Price cannot be negative\");\r\n\t\t}\r\n\r\n\t\tlet requestBuffer = await ctx.stub.getState(requestKey).catch(err => console.log(err));\r\n\r\n\t\tif(requestBuffer.length !== 0){\r\n\t\t\tthrow new Error(\"Request already exists\");\r\n\t\t}\r\n\r\n\t\tlet userObject = JSON.parse(userBuffer.toString());\r\n\t\t\r\n\t\tlet newPropertyRegistrationRequest = {\r\n\t\t\tpropertyId:propertyId,\r\n\t\t\towner:userKey,\r\n\t\t\tprice:price,\r\n\t\t\tstatus:status\r\n\t\t};\r\n\r\n\t\tlet dataBuffer = Buffer.from(JSON.stringify(newPropertyRegistrationRequest));\r\n\t\tawait ctx.stub.putState(requestKey,dataBuffer);\r\n\t\treturn newPropertyRegistrationRequest;\r\n\t}",
"async updatePropertyStatus(ctx, propertyId, name, aadharNumber, status){\r\n\r\n\t\tconst userKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.user',[name, aadharNumber]);\r\n\r\n\t\tlet userBuffer = await ctx.stub.getState(userKey).catch(err => console.log(err));\r\n\r\n\t\tif(userBuffer.length === 0){\r\n\t\t\tthrow new Error(\"User isn't registered\");\r\n\t\t}\r\n\r\n\t\tconst propertyKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.property',[propertyId]);\r\n\r\n\t\tlet propertyBuffer = await ctx.stub.getState(propertyKey).catch(err => console.log(err));\r\n\r\n\t\tif(propertyBuffer.length === 0){\r\n\t\t\tthrow new Error(\"Property isn't registered\");\r\n\t\t}\r\n\r\n\t\tlet propertyObject = JSON.parse(propertyBuffer.toString());\r\n\r\n\t\tif(propertyObject['owner'] !== userKey){\r\n\t\t\tthrow new Error(\"User isn't owner of this property\");\r\n\t\t}\r\n\r\n\t\tpropertyObject['status'] = status;\r\n\r\n\t\tlet dataBuffer = Buffer.from(JSON.stringify(propertyObject));\r\n\r\n\t\tawait ctx.stub.putState(propertyKey,dataBuffer);\r\n\r\n\t\treturn propertyObject;\r\n\r\n\t}",
"function testPublishSupplement(){\n let _id = \"12345\";//Math.floor((Math.random() * 1000) + 1);\n let _args = ['{\"Owner\": \"studentEid\", \"University\":\"ntua\",\"Authorized\":[],\"Id\":\"'+_id+'\"}' ];\n let _enrollAttr = [{name:'typeOfUser',value:'University'},{name:\"eID\",value:\"ntua\"}];\n let _invAttr = ['typeOfUser','eID'];\n let req = {\n // Name (hash) required for invoke\n chaincodeID: basic.config.chaincodeID,\n // Function to trigger\n fcn: \"publish\",\n // Parameters for the invoke function\n args: _args,\n //pass explicit attributes to teh query\n attrs: _invAttr\n };\n basic.enrollAndRegisterUsers(\"ntuaTestUser\",_enrollAttr)\n .then(user => {\n basic.invoke(user,req).then(res=> {console.log(res);\n process.exit(0);\n }).catch(err =>{\n console.log(err);\n process.exit(1);\n });\n }).catch(err =>{\n console.log(err);\n });\n}",
"function stateSetApprover() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n var uid = 0;\n\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n if (typeof w2ui.stateChangeForm.record.ApproverName == \"object\" && w2ui.stateChangeForm.record.ApproverName != null) {\n if (w2ui.stateChangeForm.record.ApproverName.length > 0) {\n uid = w2ui.stateChangeForm.record.ApproverName[0].UID;\n }\n }\n if (uid == 0) {\n w2ui.stateChangeForm.error('ERROR: You must select a valid user');\n return;\n }\n si.ApproverUID = uid;\n si.Reason = \"\";\n var x = document.getElementById(\"smApproverReason\");\n if (x != null) {\n si.Reason = x.value;\n }\n if (si.Reason.length < 2) {\n w2ui.stateChangeForm.error('ERROR: You must supply a reason');\n return;\n }\n finishStateChange(si,\"setapprover\");\n}",
"function fillPromoRegisterFromCreateProfile() {\n\t$('#emailIdPromoCode').val($(\"#emailIdChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#confrmEmailIdChkOut\").val());\n\t$('#passwordPromoCode').val($(\"#passwordChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeChkOut\").val());\n\t$('#promoCodeDiscount1').val($(\"#promoCodeDiscount2\").val());\n\tif ($('#chkOptInEnhCreatProf').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhCreatProfPromo\").prop('checked', false);\n\t}\n\tclearFormField(\"createAccountBoxChkOut\");\n\t$(\"#createAccountBoxChkOut\").hide();\n\tclearIntervalApp(chkRegisterBtnCount);\n}",
"SET_ACTIF_ADMINISTRATOR(state,payload){\n state.administrator = payload;\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}",
"_approveLoan(val){\n return true;\n }",
"function finishRegistration() {\n if(!addressChosen) {\n alert(\"Please unlock your Ethereum address\");\n return;\n }\n\n if(state != 1) {\n alert(\"Please wait until Registration Phase\");\n return;\n }\n\n if(myvotingAddr.totalregistered() < 3) {\n alert(\"Election cannot begin until there is 3 or more registered voters\");\n return;\n }\n\n\n web3.personal.unlockAccount(addr,password);\n\n res = myvotingAddr.finishRegistrationPhase.sendTransaction({from:web3.eth.accounts[accountindex], gas: 4200000});\n document.getElementById(\"finishRegistration\").innerHTML = \"Waiting for Ethereum to confirm that Registration has finished\";\n\n //txlist(\"Finish Registration Phase: \" + res);\n}",
"function Entitlement() {}",
"static async postNewProperty(req, res) {\n\t\tconst { price, state, city, address, type } = req.body;\n\t\tlet { rows } = await queryExecutor(selectUserByEmail, [req.user.userEmail])\n\t\tconst owner = rows[0].id;\n\t\tif (!req.files.image) {\n\t\t\treturn res.status(400).json({\n\t\t\t\tstatus: res.statusCode,\n\t\t\t\terror: 'No image file selected'\n\t\t\t})\n\t\t}\n\t\tconst propertyPhoto = req.files.image.path;\n\t\tcloudinary.uploader.upload(propertyPhoto, async (result, error) => {\n\t\t\tif (error) {\n\t\t\t\treturn res.status(400).json({\n\t\t\t\t\tstatus: res.statusCode,\n\t\t\t\t\terror: error\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst newProperty = [owner, price, state, city, address, type, moment().format(), result.url]\n\t\t\tconst { rows } = await queryExecutor(postNewProperty, newProperty)\n\t\t\tconst [results] = rows\n\t\t\treturn res.status(201).json({\n\t\t\t\tstatus: res.statusCode,\n\t\t\t\tmessage: 'New property ad posted successfuly',\n\t\t\t\tdata: results\n\t\t\t});\n\t\t});\n\t}",
"function addPerm(cb) { \n patchRsc('ictrlREST.json', ictrlA, function () {\n console.log('ACCESS to iControl REST API: ictrlUser');\n cb(); \n });\n}",
"_handlePrivacyRequest () {\n const privacyMode = this.preferencesController.getFeatureFlags().privacyMode\n if (!privacyMode) {\n this.platform && this.platform.sendMessage({\n action: 'approve-legacy-provider-request',\n selectedAddress: this.publicConfigStore.getState().selectedAddress,\n }, { active: true })\n this.publicConfigStore.emit('update', this.publicConfigStore.getState())\n }\n }",
"applyDisapproval () {\n this.update({\n 'data.class.disapproval': this.data.data.class.disapproval + 1\n })\n }",
"function fillAdditionalInfoFromPromoRegister() {\n\t$('#emailIdAddInfoChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#mobileNoAddInfoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeAddInfoChkOut').val($(\"#zipCodePromoCode\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', false);\n\t}\n\t$(\"#additional_info_box\").show();\n\tvalidateAdditionalInfo();\n}",
"function pushRegistration()\n{\tif(frmUrl.txtBoxAppId.text!==\"\"&&frmUrl.txtBoxSenderID.text!==\"\"&&frmUrl.txtBoxUrl.text!==\"\"){\n KMSPROP.kmsServerUrl=frmUrl.txtBoxUrl.text;\n KMSPROP.appId=frmUrl.txtBoxAppId.text;\n KMSPROP.senderID=frmUrl.txtBoxSenderID.text;\n\t}\n else{\n alert(\"The URL, APPID and SenderId Should not be Empty\");\n return;\n }\n\tkony.print(\"\\n\\n----in pushRegister----\\n\");\n\t//subsFrom=from;\n\tisDeleteAudience=false;\n\tvar devName = kony.os.deviceInfo().name;\n//\talert(\"devName\" + devName);\n\tkony.application.showLoadingScreen(\"sknLoading\",\"please wait..\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\tif(devName==\"android\")\n\t{\n\t\tcallbackAndroidSetCallbacks();\n\t\tcallbackAndroidRegister();\n\t}else if((devName==\"iPhone\")||(devName==\"iPhone Simulator\")||(devName==\"iPad\")||(devName==\"iPad Simulator\"))\n\t{\n\t\tcallbackiPhoneSetCallbacks();\n\t\tcallbackiPhoneRegister();\n\t}\n}",
"function createDeviceAssignment(axios$$1, payload) {\n return restAuthPost(axios$$1, 'assignments/', payload);\n }",
"async function sendUpdatedWebapiPermission(){\n var beforeWebapiHasPermission = webapiHasPermission;\n var newWebapiHasPermission = checkWebapiHasPermission();\n\n // if something has changed\n if (beforeWebapiHasPermission != newWebapiHasPermission){\n\n\n // case: webapi was deactivated, but now is \"granted\" \n if ((newWebapiHasPermission == 'default')|| (newWebapiHasPermission == true)){\n setTargetUiAvailability('webapi', true);\n console.log('Activating webapi');\n }\n // case: webapi was active, but now is \"denied\" \n else if (newWebapiHasPermission == false) {\n setTargetUiAvailability('webapi', false);\n console.log('Deactivating webapi'); \n }\n\n }\n\n}",
"addProviderAndPubstatus() {\n let providerNode = this.xmlHandler.getNode(this.providerXpath)\n let pubStatusNode = this.xmlHandler.getNode(this.pubStatusXpath)\n\n if (!providerNode || !providerNode.singleNodeValue) {\n this.xmlHandler.createNodes(this.providerXpath)\n providerNode = this.xmlHandler.getNode(this.providerXpath)\n }\n\n if (!pubStatusNode || !pubStatusNode.singleNodeValue) {\n this.xmlHandler.createNodes(this.pubStatusXpath)\n pubStatusNode = this.xmlHandler.getNode(this.pubStatusXpath)\n }\n\n this.xmlHandler.setNodeValue(providerNode, this.config.provider || 'writer')\n this.xmlHandler.setNodeValue(pubStatusNode, this.config.pubStatus || 'imext:draft')\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a promise with all the products in the catalog | function searchAllProducts() {
let all_products = new Promise(function(resolve, reject) {
setTimeout(function() {
if(catalog.length > 0) {
resolve(catalog);
}
else {
reject("Catalog empty.");
}
}, 1000);
});
return all_products;
} | [
"function getAllProducts () {\r\n return db.query(`SELECT * from products`).then(result => {\r\n return result.rows\r\n })\r\n}",
"function getProducts() {\n var params = getParams();\n params[\"categoryID\"] = $scope.categoryId;\n categoryApiService.getProductsByCategoryId(params).$promise.then(function(response) {\n var result = response.result || [];\n $scope.productsList = result;\n });\n }",
"function getAllProducts(onResultsLoaded) {\n connection.query('SELECT * FROM products', function (err, res) {\n if (err) throw err;\n onResultsLoaded(res);\n })\n}",
"function loadAllProductInShop() {\n Product.getProductLive({ SearchText: '' })\n .then(function (res) {\n $scope.products = res.data;\n });\n }",
"async function getProductsForCartHistory() {\n\ttry {\n\t\tconst { rows } = await client.query(`\n\t\tSELECT title, description, image, \"imageDescription\"\n\t\tFROM products;`);\n\t\treturn rows;\n\t} catch (error) {\n\t\tthrow error;\n\t}\n}",
"findProducts() {\n var self = this;\n var products = [];\n\n self.initShoppingCart();\n self.req.session.shoppingCart.forEach(function(elem) {\n var product = { productId : elem.productId, quantity : elem.quantity };\n products.push(product);\n });\n\n return self.res.status(200).json(products);\n }",
"async function getProductList() {\n\n await fetch('http://52.26.193.201:3000/products/list')\n .then(response => response.json())\n .then(response => setProductList([...response]))\n }",
"async getAllProducts() {\n try {\n const eventref = firebase.database().ref('Products');\n const snapshot = await eventref.once('value');\n const value = snapshot.val();\n this.result = value;\n\n // Perist data in localStorage\n this.persistData();\n\n }\n catch (error) {\n console.log(`Product Model:${error}`);\n }\n }",
"static async list(req, res) {\n const variations = _.filter(\n req.product.variations,\n variation => !variation.deleted,\n );\n\n return res.products_with_additional_prices(variations);\n }",
"function getProducts(order, callback) {\n const date = moment(order.dataValues.createdAt).format('LLLL');\n order.date = date;\n\n const { items } = order.dataValues.cart;\n const productIds = Object.keys(items);\n\n models.Product.findAll({\n attributes: ['id', 'title'],\n where: { id: productIds }\n })\n .then(products => {\n let productsObject = {};\n products.forEach(product => {\n productsObject[product.id] = product.title;\n });\n order.items = generateArray(productsObject, items);\n callback();\n }) // END .then(products => {\n .catch(err => callback(err));\n} // END (order, callback) => {",
"function requestProducts(req, res){\n Product.find({}, function(err, response){\n res.send(JSON.stringify(response));\n });\n}",
"function refreshProductList() {\n loadProducts()\n .then(function (results) {\n vm.products = results;\n });\n }",
"function viewProducts(){\n\tconnection.query('SELECT * FROM products', function(err,res){\n\t\tif (err) throw err;\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tconsole.log('ID: ' + res[i].id + '| sku: ' + res[i].sku +' | name: ' + res[i].product_name + \" | Price: $\" + res[i].price + \" | Quantity: \" + res[i].stock_quantity);\n\t\t};\n\t\tconsole.log('\\n');\n\t\tmanagerView();\n\t});\n}",
"function inventoryBuckets(env, fc, productList, options) {\n return new Promise((resolve, reject) => {\n /*\n {\n \"productId\": product.id,\n \"mapping\" : {},\n \"quantity\" : product.quantity * deal.quantity,\n \"wmf\": deal.defaultWhId,\n \"dealId\": deal._id\n } \n */\n var config = _getConfig(env);\n\n var skuList = [];\n\n productList.map(p => {\n if (p.mapping && p.mapping.sku) {\n skuList.push(p.mapping.sku);\n }\n });\n\n var walmartProductPromise = new Promise((resolve, reject) => {\n Promise.all(productList.map(p => {\n return new Promise((_resolve, _reject) => {\n\n var url = `${config.basePath}/Product/Information/${config.MerchantId}/${p.mapping.productId}`;\n\n _fire(config, url, 'GET', null).then(result => {\n _resolve(result);\n }).catch(e => {\n _reject(e);\n });\n\n });\n })).then(walmartProducts => {\n if (walmartProducts && walmartProducts.length) {\n resolve(walmartProducts);\n } else {\n reject(new Error(`Could not get walmart products....`));\n }\n }).catch(e => reject(e));\n });\n\n\n var volumetricPromise = new Promise((resolve, reject) => {\n Promise.all(productList.map(p => {\n return new Promise((_resolve, _reject) => {\n\n const url = `${config.frontApi}/VolumetricPricing/${config.MerchantId}`;\n\n const options = {\n query: {\n productid: productId,\n storeId: fc.partner.locationId\n }\n }\n\n\n _fire(config, url, 'GET', options).then(result => {\n _resolve(result);\n }).catch(e => {\n _resolve();\n });\n //Here add productid to the response;\n });\n })).then(volumes => {\n resolve();\n }).catch(e => reject(e));\n });\n\n Promise.all([walmartProductPromise, volumetricPromise]).then(result => {\n\n var walmartProductList = result[0];\n var volumeList = result[1];\n var sortedGroup = {};\n\n if (!walmartProductList || !walmartProductList.length) {\n reject(new Error(`Could not get walmart product list.....`));\n return;\n }\n //Convert to bucket format;\n productList.map(p => {\n\n // var walmartProduct = _.find(walmartProductList, { \"Product.ProductId\": parseInt(p.mapping.productId) });\n\n var walmartProduct = _.find(walmartProductList, (pr => {\n if (pr.Product.ProductId === parseInt(p.mapping.productId)) {\n return true;\n }\n }));\n\n if (walmartProduct) {\n\n if (!sortedGroup[p.whId]) {\n\n sortedGroup[p.whId] = [];\n\n sortedGroup[p.whId].push({\n \"productId\": p.productId,\n \"totalQty\": 0,\n \"snapShots\": [{\n whId: p.whId,\n productId: p.productId,\n mappedProductId: walmartProduct.Product.ProductId,\n mrp: walmartProduct.Product.MRP,\n transferPrice: walmartProduct.Product.WebPrice,\n stock: parseInt(walmartProduct.Product.Inventory),\n onHold: 0,\n key: walmartProduct.Product.MRP,\n snapShotIds: []\n }],\n \"buckets\": {},\n \"bucketKeys\": []\n });\n\n } else {\n //if wmf key exists , then check if in that wmf this productId exists; If not then add;\n var exisiting = _.find(sortedGroup[p.whId], { productId: p.productId, whId: p.whId });\n\n if (!exisiting) {\n sortedGroup[p.whId].push({\n \"productId\": p.productId,\n \"totalQty\": 0,\n \"snapShots\": [{\n whId: p.whId,\n productId: p.productId,\n mappedProductId: walmartProduct.Product.ProductId,\n mrp: walmartProduct.Product.MRP,\n transferPrice: walmartProduct.Product.WebPrice,\n stock: parseInt(walmartProduct.Product.Inventory),\n onHold: 0,\n key: walmartProduct.Product.MRP,\n snapShotIds: []\n }],\n \"buckets\": {},\n \"bucketKeys\": []\n });\n }\n\n }\n\n }\n });\n\n Object.keys(sortedGroup).map(whId => {\n var whGroup = sortedGroup[whId]; // List of product snapshots;\n whGroup.map(product => {\n product.totalQty = _.sumBy(product.snapShots, \"stock\");\n var group = _.groupBy(product.snapShots, \"key\");\n product.buckets = group;\n Object.keys(product.buckets).map(mrpKey => {\n var _list = product.buckets[mrpKey];\n var count = _.sumBy(_list, \"stock\");\n product.buckets[mrpKey] = {\n \"whId\": _list[0].whId,\n \"productId\": _list[0].productId,\n \"mappedProductId\": _list[0].mappedProductId,\n \"mrp\": _list[0].mrp,\n \"transferPrice\": _list[0].transferPrice,\n \"stock\": count,\n \"onHold\": 0,\n \"snapShotIds\": []\n }\n })\n /* product.buckets[product.key] = {\n \"whId\": _list[0].whId,\n \"productId\": _list[0].productId,\n \"mappedProductId\": walmartProduct.Product.ProductId,\n \"mrp\": _list[0].mrp,\n \"transferPrice\": _list[0].WebPrice,\n \"stock\": count,\n \"onHold\": 0,\n \"snapShotIds\": []\n } */\n product.bucketKeys = Object.keys(group);\n delete product.snapShots;\n });\n\n })\n\n if (options && options.bucketsOnly) {\n resolve({ buckets: sortedGroup });\n } else {\n var products = walmartProductList.map(p => p.Product);\n resolve({ buckets: sortedGroup, productList: products });\n }\n\n }).catch(e => reject(e));\n\n // Sample response format to send;\n /* var mock = {\n \"WMF3\": [\n {\n productId: \"PR10964\",\n totalQty: 10,\n snapShots: [],\n buckets: {\n \"10_Walmart Offer\": {\n whId: \"WMF3\",\n productId: \"PR10964\",\n mrp: 60,\n transferPrice: _list[0].WebPrice,\n stock: 10,\n onHold: 0,\n snapShotIds: []\n }\n },\n bucketKeys: [\"10_Walmart Offer\"]\n }\n ]\n }; */\n });\n}",
"function listProducts()\n{\n connection.query(\"SELECT * FROM products\", function(err, res)\n {\n if (err) throw err;\n console.log(\"You can select from these items\");\n for(i=0;i<res.length;i++)\n {\n console.log('Item ID ' + res[i].item_id + ' Product:' + res[i].product_name + ' Price: ' + res[i].price);\n }\n startOrder();\n })\n}",
"function getAllProducts(parent, args) {\n if (args.inStock) {\n return productList.filter(product => product.inventory_count > 0);\n } else {\n return productList\n }\n}",
"function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }",
"function getProducts() {\n $.ajax({\n url: \"files/productlist.json\",\n dataType: 'json',\n success: function(data) {\n var product =\"\";\n\n $.each(data, function(key, value) { // Execute for each set of data\n product = Object.values(value);\n productlist.push(product);\n }); \n },\n error(xhr, status, error) { // Function for error message and error handling\n console.log(error);\n }\n })\n }",
"static async getStoreInventory() {\n const storeInventory = storage.get(\"products\").value()\n return storeInventory\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subtracts value of each new purchase from budget total | deductBudget() {
let price = parseInt(costClothing.value, 10);
runningBudget -= price;
updateBudget();
} | [
"function _adjust_campaign_budget(my_tot_cost) {\n var today = new Date();\n // Accounting for December\n var eom = (today.getMonth() == 11) ? new Date(today.getFullYear()+1,0,1) : \n new Date(today.getFullYear(),today.getMonth()+1,1);\n var days_left = Math.round((eom-today)/1000/60/60/24);\n var days_spent = today.getDate();\n var run_rate = Math.round(my_tot_cost/days_spent*SIG_FIGS)/SIG_FIGS;\n var projected_total = my_tot_cost + (run_rate * days_left);\n var perc_over = Math.round(((MONTHLY_BUDGET-projected_total)/projected_total)*SIG_FIGS)/SIG_FIGS; \n _change_spend(perc_over,my_tot_cost);\n}",
"calculateDownPayment() { return this.getVariable().getPercentDown() * this.getAsset().getValue() }",
"bankSalery(){\n if( this.bankLoan > 0 ){\n let deduction = (this.payBalance * 0.10) \n this.payBalance = this.payBalance - deduction\n if(deduction > this.bankLoan){\n this.bankBalance = this.bankBalance + (deduction - this.bankLoan)\n this.bankLoan = 0\n } else {\n this.bankLoan = this.bankLoan - deduction\n }\n }\n this.bankBalance = this.bankBalance + this.payBalance \n this.payBalance = 0\n }",
"function billTotal(subTotal){\nreturn subTotal + (subTotal * .15) + (subTotal * .095);\n}",
"function calcAmount(cost, discount) {\n return cost - discount;\n}",
"function giveChange(total) {\n let output = {};\n const totalCents = total * 100;\n //get dollars\n const dollars = Math.floor(totalCents / 100);\n output[\"dollars\"] = dollars;\n //getting remaining cents after removing dollars\n let remainder = totalCents - dollars * 100;\n //get quarters\n const quarters = Math.floor(remainder / 25);\n output[\"quarters\"] = quarters;\n //getting remaining cents after removing quarters\n remainder = remainder - quarters * 25;\n //getting dimes\n const dimes = Math.floor(remainder / 10);\n output[\"dimes\"] = dimes;\n //getting remaining cents after removing dimes\n remainder = remainder - dimes * 10;\n //getting nickles\n const nickles = Math.floor(remainder / 5);\n output[\"nickles\"] = nickles;\n //get remaining cents after removing nickles\n remainder = remainder - nickles * 5;\n //assining whats left to pennies\n output[\"pennies\"] = remainder;\n return output;\n}",
"removeDiscount() {\n var price = PriceList.beverages[this.beverageType];\n this.condiments.forEach(condiment => price += PriceList.Options[condiment]);\n this.beveragePrice = price;\n this.discount = 0;\n }",
"function Decrease() {\n if (quantity > 0) {\n quantity--;\n if (quantity === 0) {\n totalPrice = 0;\n }\n totalPrice = price * quantity;\n }\n totalPrice < 99\n ? (document.getElementById(\"totalPrice\").innerHTML =\n totalPrice + ShippingCost)\n : (document.getElementById(\"totalPrice\").innerHTML = totalPrice);\n document.getElementById(\"result\").innerHTML = quantity;\n document.getElementById(\"quantity\").innerHTML = quantity;\n}",
"function getRefund() {\n const tempVal = Math.min(credits - taxBill, 1000);\n const refund = tempVal + withholdings;\n return refund;\n }",
"function withdraw (account, amount) {\n account.balance -= amount;\n}",
"function payResources() {\n var i, listResources = Variable.findByName(gm, 'resources'),\n budgetDescriptor = Variable.findByName(gm, 'budget'),\n budgetInstance = budgetDescriptor.getInstance(self),\n resourceDescriptor, resourceInstance,\n sumSalary = 0;\n for (i = 0; i < listResources.items.size(); i++) {\n resourceDescriptor = listResources.items.get(i);\n resourceInstance = resourceDescriptor.getInstance(self);\n if (resourceInstance.getActive() == true) {\n sumSalary += parseInt(resourceDescriptor.getProperty('salary'));\n }\n }\n budgetInstance.setValue(budgetInstance.getValue() - sumSalary);\n}",
"function updateCustomerCharge() {\n let grandTotal = $(\"#grandtotal\").val();\n let customerGive = $(\"#customer-give\").val();\n let customerTakeBack = 0;\n\n if (Number(customerGive) < Number(grandTotal)) {\n customerTakeBack = TextGetter.get(\"insufficient_payment\");\n } else {\n customerTakeBack = Number(customerGive) - Number(grandTotal);\n }\n\n $(\"#customer-take-back\").val(customerTakeBack);\n }",
"function updateTotalTable() {\r\n let price = 0;\r\n let discount = 0;\r\n for (let i = 0; i < this.itemsInCart.length; i++) {\r\n price += this.itemsInCart[i].price.display * this.itemsInCart[i].qty;\r\n discount += this.itemsInCart[i].discount;\r\n }\r\n const totalPriceAfterDiscount = ((discount / 100) * price);\r\n const totalCost = (price - totalPriceAfterDiscount);\r\n console.log(totalCost);\r\n document.getElementById('totalItemPrice').innerHTML = '$' + price;\r\n document.getElementById('totalDiscount').innerHTML = '-' + discount + '%';\r\n\r\n document.getElementById('totalPrice').innerHTML = '$' + totalCost;\r\n\r\n}",
"function updateData(payerObj, pointSpent) {\r\n data[payerObj.payer] -= pointSpent;\r\n}",
"totalBill() {\n let billclass = this;\n _.map(this.diners, function(index) {\n let indvTotal = index.total + index.tax + index.tip;\n billclass.tBill.push(indvTotal);\n });\n billclass.tBill = _.sum(billclass.tBill);\n }",
"function hireaddbal() {\n sum = 0;\n master.hireitems.forEach(function (item) {\n sum += Math.floor(item.multi * item.quan * master.imp.balmulti);\n });\n addbal(sum);\n}",
"function calculateTotalAmount()\n{\n\tvar tableProductLength = $(\"#addSubExpensesTable tbody tr\").length;\n\tvar totalAmount = 0;\n\tfor(x = 0; x < tableProductLength; x++) {\n\t\tvar tr = $(\"#addSubExpensesTable tbody tr\")[x];\n\t\tvar count = $(tr).attr('id');\n\t\tcount = count.substring(3);\n\t\t\t\t\t\n\t\ttotalAmount = Number(totalAmount) + Number($(\"#subExpensesAmount\"+count).val());\n\n\n\t} // /for\n\n\ttotalAmount = totalAmount.toFixed(2);\n\n\t// sub total\n\t$(\"#totalAmount\").val(totalAmount);\n\t$(\"#totalAmountValue\").val(totalAmount);\n\t\n}",
"function getPV(current_cashflow, growth_rate_1, growth_rate_2, discount_rate){\n var pv = 0\n var temp = current_cashflow\n var sum = 0\n for(var i = 0; i < 10; i++){\n var discountFactor = 1 / (1 + discount_rate) ** (i + 1)\n //Before Discount\n if(i < 3)\n temp = temp * growth_rate_1 \n else\n temp = temp * growth_rate_2 \n // console.log(\"temp\", i+1, \": \", temp);\n //After discount\n sum += temp * discountFactor\n // console.log(\"discount\", i+1, \": \", discountFactor);\n // console.log(\"sum \",i+1, \": \",sum)\n }\n pv = sum\n return pv\n}",
"function handleDecrease() {\n if (selectedAmount > 1) setSelectedAmount(selectedAmount - 1);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
After calling this, if `this.point` != null, the next range is a point. Otherwise, it's a regular range, covered by `this.active`. | next() {
let from = this.to,
wasPoint = this.point
this.point = null
let trackOpen = this.openStart < 0 ? [] : null
for (;;) {
let a = this.minActive
if (
a > -1 &&
(this.activeTo[a] - this.cursor.from ||
this.active[a].endSide - this.cursor.startSide) < 0
) {
if (this.activeTo[a] > from) {
this.to = this.activeTo[a]
this.endSide = this.active[a].endSide
break
}
this.removeActive(a)
if (trackOpen) remove(trackOpen, a)
} else if (!this.cursor.value) {
this.to = this.endSide = 1000000000 /* C.Far */
break
} else if (this.cursor.from > from) {
this.to = this.cursor.from
this.endSide = this.cursor.startSide
break
} else {
let nextVal = this.cursor.value
if (!nextVal.point) {
// Opening a range
this.addActive(trackOpen)
this.cursor.next()
} else if (
wasPoint &&
this.cursor.to == this.to &&
this.cursor.from < this.cursor.to
) {
// Ignore any non-empty points that end precisely at the end of the prev point
this.cursor.next()
} else {
// New point
this.point = nextVal
this.pointFrom = this.cursor.from
this.pointRank = this.cursor.rank
this.to = this.cursor.to
this.endSide = nextVal.endSide
this.cursor.next()
this.forward(this.to, this.endSide)
break
}
}
}
if (trackOpen) {
this.openStart = 0
for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
this.openStart++
}
} | [
"next() {\n let from = this.to;\n this.point = null;\n let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0;\n for (;;) {\n let a = this.minActive;\n if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {\n if (this.activeTo[a] > from) {\n this.to = this.activeTo[a];\n this.endSide = this.active[a].endSide;\n break;\n }\n this.removeActive(a);\n if (trackOpen)\n remove(trackOpen, a);\n }\n else if (!this.cursor.value) {\n this.to = this.endSide = Far;\n break;\n }\n else if (this.cursor.from > from) {\n this.to = this.cursor.from;\n this.endSide = this.cursor.startSide;\n break;\n }\n else {\n let nextVal = this.cursor.value;\n if (!nextVal.point) { // Opening a range\n this.addActive(trackOpen);\n this.cursor.next();\n }\n else { // New point\n this.point = nextVal;\n this.pointFrom = this.cursor.from;\n this.pointRank = this.cursor.rank;\n this.to = this.cursor.to;\n this.endSide = nextVal.endSide;\n if (this.cursor.from < from)\n trackExtra = 1;\n this.cursor.next();\n if (this.to > from)\n this.forward(this.to, this.endSide);\n break;\n }\n }\n }\n if (trackOpen) {\n let openStart = 0;\n while (openStart < trackOpen.length && trackOpen[openStart] < from)\n openStart++;\n this.openStart = openStart + trackExtra;\n }\n }",
"*points(range) {\n yield [range.anchor, 'anchor'];\n yield [range.focus, 'focus'];\n }",
"equals(range, another) {\n return Point.equals(range.anchor, another.anchor) && Point.equals(range.focus, another.focus);\n }",
"static isRange(obj) {\n return obj instanceof Range;\n }",
"_carouselPointActiver() {\r\n const i = Math.ceil(this.currentSlide / this.slideItems);\r\n this.activePoint = i;\r\n this.cdr.markForCheck();\r\n }",
"function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}",
"function isPointBetween(point, min, max) {\n if(point > min && point < max)\n return true;\n\n return false;\n}",
"isEnd(editor, point, at) {\n var end = Editor.end(editor, at);\n return Point.equals(point, end);\n }",
"function check_point(p) {\n if (p.x < 0 || p.x > 9) {\n return false;\n } else if (p.y < 0 || p.y > 9) {\n return false;\n } else if (spielfeld[p.y][p.x]) {\n //console.log(\"point already in use:\", p);\n return false;\n } else {\n //console.log(\"point ok:\", p);\n return true;\n }\n}",
"_validateYRange() {\n return this.currentYRange[1] >= this.currentYRange[0];\n }",
"includes(range, target) {\n if (Range.isRange(target)) {\n if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {\n return true;\n }\n\n var [rs, re] = Range.edges(range);\n var [ts, te] = Range.edges(target);\n return Point.isBefore(rs, ts) && Point.isAfter(re, te);\n }\n\n var [start, end] = Range.edges(range);\n var isAfterStart = false;\n var isBeforeEnd = false;\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0;\n isBeforeEnd = Point.compare(target, end) <= 0;\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0;\n isBeforeEnd = Path.compare(target, end.path) <= 0;\n }\n\n return isAfterStart && isBeforeEnd;\n }",
"isStart(editor, point, at) {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false;\n }\n\n var start = Editor.start(editor, at);\n return Point.equals(point, start);\n }",
"isSingleCell() {\n return this.fromRow == this.toRow && this.fromCell == this.toCell;\n }",
"function sliderClick(slider, point) {\n\tif (insideBox([slider.x,slider.y,slider.x+slider.width,slider.y+slider.height], point)) {\n\t\tslider.active = !slider.active;\n\t\t//console.log(\"clicked\");\n\t\treturn true;\n\t}\n\telse {\n\t\tvar divX = slider.width*1/5;\n\t\tif (slider.active) {\n\t\t\tdivX = divX*3;\n\t\t}\n\t\tif (insideBox([slider.x+divX,slider.y-slider.height/3,slider.x+divX+slider.width*1.3/5, slider.y+slider.height*5/3], point)) {\n\t\t\tslider.active = !slider.active;\n\t\t\treturn true;\n\t\t}\n\t}\t\n\treturn false;\n}",
"checkRange() {\n if (!this.target)\n return;\n if (this.timeToNextAttack < 0)\n return;\n const dist = this.target.position.distanceTo(this.bot.entity.position);\n if (dist > this.viewDistance) {\n this.stop();\n return;\n }\n const inRange = dist <= this.attackRange;\n if (!this.wasInRange && inRange)\n this.timeToNextAttack = 0;\n this.wasInRange = inRange;\n }",
"inRangeIdea (num, start, end) {\n let startRange\n let endRange\n if (!end) {\n startRange = 0\n endRange = start\n } else if (start > end) {\n startRange = end\n endRange = start\n } else {\n startRange = start\n endRange = end\n }\n return this.checkRangeIdea(num, startRange, endRange)\n }",
"function isInRange(pos, start, end) {\n if (typeof pos != 'number') {\n // Assume it is a cursor position. Get the line number.\n pos = pos.line;\n }\n if (start instanceof Array) {\n return inArray(pos, start);\n } else {\n if (end) {\n return pos >= start && pos <= end;\n } else {\n return pos == start;\n }\n }\n }",
"isAfter(point, another) {\n return Point.compare(point, another) === 1;\n }",
"map(mapping) {\n let from = mapping.mapPos(this.from), to = mapping.mapPos(this.to);\n return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enter a parse tree produced by Java9ParserelementValueList. | enterElementValueList(ctx) {
} | [
"enterElementValuePairList(ctx) {\n\t}",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\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 }",
"exitElementValueList(ctx) {\n\t}",
"visitList_values_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"lesx_parseElement() {\n var startPos = this.start,\n startLoc = this.startLoc;\n\n this.next();\n\n return this.lesx_parseElementAt(startPos, startLoc);\n }",
"fillElements() {\n this.replaceTokens(this.tags, CD.params());\n }",
"function AddValueinLi() {\n li.append(document.createTextNode(input.value));\n}",
"visitIn_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error) {\n errors.push({ error: error });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}",
"function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error, offset, lngth) {\n errors.push({ error: error, offset: offset, length: lngth });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n }",
"function createAVL() {\n root = null;\n var inputArray = document.getElementById(\"inputArray\").value.split(\",\");\n for (let i = 0; i < inputArray.length; i++) { // convert sstring array to number array\n inputArray[i] = parseInt(inputArray[i]);\n }\n\n // Create a root node and tree\n for (let value of inputArray) {\n root = insertValue(root, value);\n }\n\n document.getElementById(\"onorderTraverse\").innerText = inorderTraversal(root, []);\n document.getElementById(\"preOrderTraverse\").innerText = preOrderTraversal(root, []);\n}",
"addChildren(valuesAdded) {\n this.children.push(new Node('()' + this.val, 'right'));\n valuesAdded.push('()' + this.val);\n this.children.push(new Node('(' + this.val + ')', 'right'));\n valuesAdded.push('(' + this.val + ')');\n this.children.push(new Node(this.val + '()', 'right'));\n valuesAdded.push(this.val + '()');\n }",
"function expressionToTree(exp) {\n \"use strict\";\n\n // get rid of spaces on the front of the expression\n var i = 0;\n\n while (1) {\n if (exp[i] === \"(\") {\n // we're dealing with a list\n break;\n } else if (exp[i] === \" \") {\n //do nothing\n } else {\n if (-1 !== exp.search(/\\(|\\)/)) {\n throw \"expression that didn't start with ( has either ( or ) in it\";\n }\n return exp.slice(i);\n }\n i++;\n }\n\n // at this point, we know we're dealing with a list\n var array_to_return = [];\n var start;\n var level = 0;\n var state = \"in_between\";\n\n\n // at this point, we know we're dealing with a list\n for (i++; i < exp.length; i++) {\n switch (state) {\n case \"in_between\":\n switch (exp[i]) {\n case \"(\":\n start = i;\n state = \"in_list\";\n break;\n case \")\":\n return array_to_return;\n case \" \":\n break;\n default:\n start = i;\n state = \"in_token\";\n }\n break;\n case \"in_token\":\n switch (exp[i]) {\n case \")\":\n array_to_return.push(exp.slice(start, i));\n return array_to_return;\n case \" \":\n array_to_return.push(exp.slice(start, i));\n state = \"in_between\";\n break;\n case \"(\":\n array_to_return.push(exp.slice(start, i));\n start = i;\n state = \"in_list\";\n break;\n }\n break;\n case \"in_list\":\n switch (exp[i]) {\n case \"(\":\n level++;\n break;\n case \")\":\n if (level === 0) {\n array_to_return.push(expressionToTree(exp.slice(start, i + 1)));\n state = \"in_between\";\n } else if (level > 0) {\n level--;\n } else {\n throw \"misformed list\";\n }\n break;\n }\n break;\n default:\n throw \"in a weird state\";\n }\n }\n throw \"misformed list\";\n}",
"function createBlocksForAST(ast, workspace) {\n\tconst parse_node = (node) => {\n\t\t\n\t\tconst node_meta = lpe_babel.types.NODE_FIELDS[node.type];\n\t\t\n\t\tlet block = workspace.newBlock(TYPE_PREFIX + node.type);\n\t\tblock.babel_node = node;\n\t\tnode.blockly_block = block;\n\t\t\n\t\tblock.initSvg();\n\t\tblock.render();\n\n\t\tif(typeof node_meta.value !== 'undefined') {\n\t\t\tblock.getField(\"value\").setValue(node.value);\n\t\t} else {\n\t\t\t// Go through the inputs\n\t\t\tfor(const field_name in node_meta) {\n\t\t\t\tconst field_meta = node_meta[field_name];\n\n\t\t\t\t// Check if this is a chaining input\n\t\t\t\tif(!field_meta.validate) {\n\t\t\t\t\tconsole.log(\"Error: field can't be validated:\");\n\t\t\t\t\tconsole.log(field_meta);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(field_meta.validate.chainOf) {\n\n\t\t\t\t\t// Decide if this is a series of nodes or a limited selection of nodes\n\t\t\t\t\tif(field_meta.validate.chainOf[0].type === 'array') {\n\t\n\t\t\t\t\t\tlet node_list = node[field_name];\n\n\t\t\t\t\t\tif(node_list && node_list.length > 0) {\n\t\t\t\t\t\t\t// Transform list to tree\n\t\t\t\t\t\t\tfor(let i = node_list.length-1; i > 0; i--) {\n\t\t\t\t\t\t\t\tnode_list[i-1].next = node_list[i];\n\t\t\t\t\t\t\t\t//node_list.pop();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tblockly_tools.setAsFirstStatement(parse_node(node_list[0]), block, field_name);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblock.getField(field_name).setValue(node[field_name]);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//console.log(field.validate.chainOf)\n\t\t\t\t} else if (field_meta.validate.oneOfNodeTypes) {\n\t\t\t\t if(node[field_name]) {\n\t\t\t\t\t blockly_tools.setAsInput(parse_node(node[field_name]), block, field_name)\n\t\t\t\t }\n\t\t\t\t} else if (field_meta.validate.type && field_meta.validate.type !== 'string') {\n\t\t\t\t\tif(node[field_name]) {\n\t\t\t\t\t blockly_tools.setAsInput(parse_node(node[field_name]), block, field_name)\n\t\t\t\t }\n\t\t\t\t} else {\n\t\t\t\t\tblock.getField(field_name).setValue(node[field_name]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(node.next) {\n\t\t\tblockly_tools.setAsNext(parse_node(node.next), block)\n\t\t}\n \n\t\treturn block;\n\t}\n\t\n\tif(ast.program) {\n\t return parse_node(ast.program);\n\t} else if(ast instanceof Array) {\n\t let parsedNodes = ast.map(parse_node);\n\t return parsedNodes;\n\t} else {\n\t return parse_node(ast);\n\t}\n\t\n}",
"function NumberNode(val) {\n this.push(val);\n}",
"function itemlist() {\n var no = document.getElementById(\"items\");\n var option = no.options[no.selectedIndex].value;\n var list = document.getElementById(\"list\"); \n list.innerHTML=''; \n list.appendChild(document.createTextNode(\"Item Name: Item Value:\"));\n //list.appendChild(document.createTextNode(\"Item Value:\"));\n\tfor (var i=0; i<option; i++){\n\t var input_label = document.createElement(\"INPUT\");\n\t var input_value = document.createElement(\"INPUT\"); \n\t input_label.setAttribute(\"type\", \"text\");\n\t input_label.setAttribute(\"class\", \"name\");\n\t input_value.setAttribute(\"type\", \"number\");\n\t input_value.setAttribute(\"class\", \"values\");\n\t list.appendChild(document.createElement(\"BR\"));\n\t list.appendChild(document.createTextNode(i+1+'. \\t'));\n\t list.appendChild(input_label);\n\t list.appendChild(input_value); \n\t} \t\t\n}",
"get inputlist() {\n return this.dom.firstChild.childNodes;\n }",
"function list (builder, node) {\n\tfinishPending (builder);\n\n\tvar key = node [1];\n\tvar sub = subBuilder (builder);\n\n\tdispatch.nodes (sub, builder.dispatch, node, 2, node.length);\n\n\tvar template = getTemplate (sub);\n\tappendNode (builder, spec.listNode (key, template));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fungsi string index of unrtuk mengetahui urutan indexnya | function indexoff(){
var isi = "saya beajar di rumah";
console.log(isi.indexOf("beajar"));
} | [
"function last(){\n\tvar isi = \"saya beajar di rumah beajar\";\n\tconsole.log(isi.lastIndexOf(\"beajar\",5)); //nilai angka berfungsi sebagai startnya di index\n}",
"function getJouerParIndex(index) {\n let JoueurID = `#Joueur_${index}`;\n return $(JoueurID).val();\n}",
"function findWordIndex(word) {\n\t\tfor (var i = 1; i <= 3; i++) {\n\t\t\tfor (var j = 0; j < 16; j++) {\n\t\t\t\tvar menu_item = \"#\" + i + \"_\" + j + \"\";\n\t\t\t\t// might be item.target.text\n\t\t\t\tif($(menu_item).text() === word) {\n\t\t\t\t\t// return menu_item;\n\t\t\t\t\treturn j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// return \"#none\";\n\t\treturn -1;\n\t}",
"getPositionStringForIndex (index) {\n let { row, column } = this.getCoordinates(index)\n const number = Math.abs(row - 7) + 1\n const letter = String.fromCharCode(97 + column)\n return `${letter}${number}`\n }",
"function myIndexOf(string, searchTerm) {}",
"getIndexForPositionString (positionString = 'a1') {\n const { row, column } = this.getCoordinatesForPositionString(positionString)\n let index = Math.abs(column - 8) + (row * 8)\n index = Math.abs(index - 64)\n return index\n }",
"function getIndexPage(numberString) {\n\tvar number = numberString.split(\"/\");\n\treturn number[0];\n}",
"function secondIndexOf(s1, s2) {\n // Use indexOf twice.\n // const s1Low = s1.toLowerCase();\n // const s2Low = s2.toLowerCase();\n const indexOfFirst = s1.indexOf(s2); \n // console.log(`The index of the first \"${s2}\" from the beginning is ${indexOfFirst}`); \n // console.log(`The index of the secound \"${s2}\" is ${s1.indexOf(s2, (indexOfFirst + 1))}`); \n const a = s1.indexOf(s2, (indexOfFirst + 1));\n console.log(a);\n}",
"getIndexOfFirstWord() {\n let indexFirstWord = -1;\n\n this.recordingData.forEach((word, index) => {\n if (word[1] == -1) {\n indexFirstWord = index;\n return;\n }\n });\n\n return indexFirstWord;\n }",
"function returnACharacter(string, index) {\n return string[index];\n}",
"function printedToRealIdxInStr(pStr, pIdx)\n{\n\tif (typeof(pStr) != \"string\")\n\t\treturn -1;\n\tif ((pIdx < 0) || (pIdx >= pStr.length))\n\t\treturn -1;\n\n\t// Store the character at the given index if the string didn't have attribute codes.\n\t// Also, to help ensure this returns the correct index, get a substring with several\n\t// characters starting at the given index to match a word within the string\n\tvar strWithoutAttrCodes = strip_ctrl(pStr);\n\tvar substr_len = 5;\n\tvar substrWithoutAttrCodes = strWithoutAttrCodes.substr(pIdx, substr_len);\n\tvar printableCharAtIdx = strWithoutAttrCodes.charAt(pIdx);\n\t// Iterate through pStr until we find that character and return that index.\n\tvar realIdx = 0;\n\tfor (var i = 0; i < pStr.length; ++i)\n\t{\n\t\t// tempStr is the string to compare with substrWithoutAttrCodes\n\t\tvar tempStr = strip_ctrl(pStr.substr(i)).substr(0, substr_len);\n\t\tif ((pStr.charAt(i) == printableCharAtIdx) && (tempStr == substrWithoutAttrCodes))\n\t\t{\n\t\t\trealIdx = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn realIdx;\n}",
"sub_to_index( i, j ) {\n\t\tif (i < 0 || i >= this.numRows ) throw \"Subscript i is out of range\"\n\t\tif (j < 0 || j >= this.numColumns) throw \"Subscript j is out of range\"\n\t\t\n\t\t// if reading row/major order (like spoken, used in numpy and torch)\n\t\treturn j + i *this.numColumns\n\t\t\n\t\t// reading column/major order (use in MATLAB)\n\t\t// return i + j *this.numRows\n\t}",
"function getPhraseIndex(arr){\n const phraseIndex = arr.indexOf(chosenPhrase);\n return phraseIndex;\n}",
"function afficher(entrees) {\n //let i = 3;\n // let phrase = \"Ma maison est belle\";\n let tableau = [1, 2, 3, 4, 5];\n for (let i = 0; i <= 10; i++) \n \n// console.log(i + '=' + tableau.charAt(4));\nconsole.log(i + '=' + tableau[i]);\n}",
"_wordToIndex(word) {\n\n word = word.toString();\n\n if(this._wordToIdx[word] === undefined) {\n var idx = this._idxToWord.length;\n this._wordToIdx[word] = idx;\n this._idxToWord[idx] = word;\n\n if(this._normalize) {\n var normWord = word.toLocaleLowerCase();\n if(word != normWord) {\n var idx2 = this._idxToWord.length;\n this._wordToIdx[normWord] = idx2;\n this._idxToWord[idx2] = normWord;\n }\n }\n\n return idx;\n } else {\n return this._wordToIdx[word];\n }\n }",
"function indexFromName(name) {\n if (typeof name === 'string') {\n let ln = name.toLowerCase();\n\n return configurations.findIndex( val => val.name.toLowerCase() === ln );\n }\n // not found\n return -1;\n}",
"function res2iaa(res)\n{\n var i;\n\n for ( i = 0; i < aanames.length; i++ ) {\n if ( res === aanames[i] ) {\n return i;\n }\n }\n return -1;\n}",
"function strWordsIndices(str) {\r\n str = nbsp_to_spaces(str); // replace html characters if found by text characters\r\n var re = /(http|ftp|https):\\/\\/[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?|((([^\\x00-\\x80]+|\\w+)+)?(-|')(([^\\x00-\\x80]+|\\w+)+)?)+|([^\\x00-\\x80]+|\\w+)+/gi; // Match url | words(including non english characters)\r\n return matchIndices(str, re); // return words indices\r\n}",
"function solve(str,idx){\n var left = 1\n var right =0\n var place = str.charAt(idx);\n if (place != '(') {\n return -1;\n };\n for (i=idx+1; i< str.length; i++){\n if (str.charAt(i)==='('){\n left++\n };\n if (str.charAt(i)===')'){\n right++\n };\n if (left===right){\n console.log('index of ' +i);\n return i;\n };\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update month totals array after refund | function updateMonths() {
var tgtMonth = -1;
var i;
//find the index of the month for which order is being refunded
for(i = 0; i < months.length; i++) {
if(orderDate.includes(months[i])) {
tgtMonth = i;
break;
}
}
var diff = monthTotals[tgtMonth] - refund;
if(diff > 0.0) {
monthTotals[tgtMonth] = +diff.toFixed(2);
chrome.storage.local.set({'monthTotals': monthTotals});
}
else {
monthTotals[tgtMonth] = 0.0;
chrome.storage.local.set({'monthTotals': monthTotals});
}
} | [
"function copyMonthTotalsToMaster() {\n var column,\n month,\n range,\n row,\n sheet,\n values,\n spreadsheet,\n sheet;\n \n spreadsheet = SpreadsheetApp.getActiveSpreadsheet();\n sheet = spreadsheet.getActiveSheet();\n \n month = ScriptProperties.getProperty('month');\n column = MONTH_COLUMN_MAP[month];\n values = MONTHLY_SUM.getValues();\n sheet = spreadsheet.setActiveSheet(masterSheet);\n row = 2;\n range = sheet.getRange(row, column);\n\n for (var i = 0, val; (val = values[i]); i++) {\n sheet.getRange(row, column).setValue(val);\n row++;\n }\n}",
"function updateYears() {\r\n var tgtYear = order.outIndex;\r\n var diff = yearTotals[tgtYear] - refund;\r\n if(diff > 0.0) {\r\n yearTotals[tgtYear] = +diff.toFixed(2);\r\n chrome.storage.local.set({'allYearTotals': yearTotals});\r\n }\r\n else {\r\n yearTotals[tgtYear] = 0.0;\r\n chrome.storage.local.set({'allYearTotals': yearTotals});\r\n }\r\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}",
"setMonths(state) {\n let months = [\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\n this.commit(\"setMonths\", months)\n }",
"function addToAnnualTotals(record) {\n for(var field in record.totals) {\n if (record.totals.hasOwnProperty(field)) {\n if (!$scope.annualTotals.hasOwnProperty(field)) {\n $scope.annualTotals[field] = 0;\n }\n $scope.annualTotals[field] += record.totals[field];\n }\n }\n }",
"getFoodMonth(){\n let temp = [];\n let total = 0;\n let today= new Date();\n for(var i = 0; i< this.foodLog.length; i++){\n let then = this.foodLog[i].date;\n if(then.getFullYear() == today.getFullYear() && then.getMonth() == today.getMonth()){\n temp.push(this.foodLog[i]);\n total += this.foodLog[i].calories;\n }\n }\n return {foods: temp, calories: total};\n }",
"listMonthly() {\n const today = new Date();\n return this.trafficRepository.getMonthlyData(dateService.getYearStart(today), dateService.getYearEnd(today))\n .then(data => {\n data = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(1, 12);\n const valuesToAdd = range.filter(x => !data.find(item => item.group === x));\n return data.concat(this.mapEmptyEntries(valuesToAdd));\n });\n }",
"function sumCategAndSubCateg(){\n vm.currentMonth = vm.month.getMonth();\n //console.log( vm.currentMonth);\n //console.log( vm.month);\n\n for(i = 0; i < vm.data.length; i++)\n {\n console.log(\"high\");\n\n dataMonth = new Date(vm.data[i].date).getMonth();\n\n //console.log($scope.currentMonth);\n //console.log(dataMonth);\n\n angular.forEach($scope.categoryDiag, function(value, key) { \n if(value.category == vm.data[i].category & vm.currentMonth == dataMonth){\n value.amount += vm.data[i].amount;\n //console.log(value.amount);\n //console.log(new Date(vm.data[i].date).getMonth());\n }\n });\n\n angular.forEach($scope.subCategoryDiag, function(value, key) { \n if(value.category == vm.data[i].subcategory & vm.currentMonth == dataMonth){\n value.amount += vm.data[i].amount;\n //console.log(value.amount);\n }\n });\n \n }\n\n updateChartData();\n\n\n }",
"recalculateTotals(inventories) {\n this.filteredInventories = inventories.inventories;\n Service.get(this).calculateTotals(1, inventories.inventories);\n }",
"function changeMonth(months){\n Calendar.today = addMonth(Calendar.today, months);\n buildCalendar();\n displayAppointments();\n}",
"function clearTotals() {\n for (var i = 0; i < numOpenHours; i++){\n totals[i] = 0;\n tosserTotals[i] = 0;\n }\n}",
"function resetDailyTotal(campaignId) {\n db.updateById(TABLE, KEY, campaignId, {sales_today: 0})\n}",
"function sumAllInstallments(){\n\tvar instlCount=$(\"#feeInstallments\").val();\n\tfor ( var i = 0; i < instlCount; i++) {\n\t\tvar instlSum=0;\n\t\tfor ( var headCount = 0; headCount < feeHeadCount; headCount++) {\n\t\t\tvar amt= jQuery.trim($(\"#feeHeads_\"+headCount+\"_installments_\"+i+\"_amount\").val());\n\t\n\t\t\tif(!isNaN(amt) && amt.length!=0) {\n\t\t\t\tinstlSum += parseInt(amt);\n\t\t\t}\n }\n\t\t$(\"#inst_col_\"+i+\"_total\").html(instlSum);\n\t}\n\tbindAdminInstallmentDueDatePicker();\n\tvalidateInstallmentsFee();\n}",
"function monthlyReport() {\n\n}",
"totalBill() {\n let billclass = this;\n _.map(this.diners, function(index) {\n let indvTotal = index.total + index.tax + index.tip;\n billclass.tBill.push(indvTotal);\n });\n billclass.tBill = _.sum(billclass.tBill);\n }",
"function setupMonths(){\n for(var i = 0; i < months.length; i++){\n for(var x = months[i].firstDay; x < months[i].lastDay + months[i].firstDay; x++){\n months[i].days.push({cell: {}, todos: [], events:[]});\n }\n }\n}",
"resetUserPayment() {\n Object.keys(this._paidMoney).forEach(key => (this._paidMoney[key] = 0));\n }",
"function update_totals() {\r\n\r\n var shipping_container = software_$('.shipping');\r\n var total_container = software_$('.total');\r\n\r\n // If the shipping container or total container does not exist, then we don't need to\r\n // update totals.\r\n if (!shipping_container.length || !total_container.length) {\r\n return;\r\n }\r\n\r\n // Loop through the recipients in order to calculate the total shipping cost.\r\n\r\n var shipping = 0;\r\n\r\n software_$.each(software.recipients, function(index, recipient) {\r\n shipping += recipient.shipping_cost;\r\n });\r\n\r\n // If the total shipping cost is the same as before, then we don't need to do anything.\r\n if (shipping == software.shipping) {\r\n return;\r\n }\r\n\r\n // Fade out and then fade in new shipping total.\r\n\r\n software.shipping = shipping;\r\n\r\n shipping_container.fadeOut(function () {\r\n shipping_container.html(software.prepare_price({price: shipping}));\r\n shipping_container.fadeIn();\r\n });\r\n\r\n // Fade out and then fade in new total.\r\n\r\n var total = software.total_without_shipping + shipping;\r\n\r\n total_container.fadeOut(function () {\r\n total_container.html(software.prepare_price({price: total}));\r\n total_container.fadeIn();\r\n });\r\n\r\n // Fade out and then fade in new base currency total, if it exists.\r\n\r\n var base_currency_total_container = software_$('.base_currency_total');\r\n\r\n if (base_currency_total_container.length) {\r\n\r\n base_currency_total_container.fadeOut(function () {\r\n\r\n base_currency_total_container.html(software.prepare_price({\r\n symbol: software.base_currency_symbol,\r\n price: total,\r\n base_price: true,\r\n code: software.base_currency_code}));\r\n\r\n base_currency_total_container.fadeIn();\r\n });\r\n }\r\n\r\n // Update hidden field with total, so when the order is submitted, we can check if the\r\n // total has changed from what the customer saw, so we can alert customer. We use\r\n // toFixed(2) in order to just include 2 decimal places because the total might be\r\n // a floating point number with many decimal places.\r\n software_$('input[name=total]').val(total.toFixed(2));\r\n }",
"function getCurrentMonthSalaries() {\n $http.get('/employees/salary')\n .then(function(response) {\n self.currentSalaries = response.data[0].monthly_salaries;\n self.budgetVariance = self.currentBudget - self.currentSalaries;\n });\n } // end function getCurrentMonthSalaries"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads the last file fragment and commits the file. The current file content is changed when this method completes. Use the uploadId value that was passed to the StartUpload method that started the upload session. This method is currently available only on Office 365. | async finishUpload(uploadId, fileOffset, fragment) {
const response = await spPost(File(this, `finishUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`), { body: fragment });
return {
data: response,
file: fileFromServerRelativePath(this, response.ServerRelativeUrl),
};
} | [
"function commitJob(done) {\n if (!req.params.fullUploadPath) {\n return done(new Error(\"Upload path could not be created\"));\n }\n\n async.waterfall([\n async.apply(AppdataJob.findById.bind(AppdataJob), jobId),\n function(job, cb) {\n var fileNamePath = path.join(req.params.fullUploadPath, req.files.file.name);\n // Set the actual file name after the file is stored\n // on disk (different to the original file name)\n job.updateMetadata(\"filePath\", fileNamePath);\n\n // To tell the scheduler that the job can be started\n job.updateMetadata(\"uploadFinished\", true);\n\n // Store the hostnme where this was uploaded so that the correct\n // scheduler can pick this one up. This is to make sure that import\n // also works in setups without a shared location\n job.updateMetadata(\"shipHostname\", os.hostname());\n\n job.save(cb);\n }\n ], done);\n }",
"async continueUpload(uploadId, fileOffset, fragment) {\n let n = await spPost(File(this, `continueUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`), { body: fragment });\n if (typeof n === \"object\") {\n // When OData=verbose the payload has the following shape:\n // { ContinueUpload: \"20971520\" }\n n = n.ContinueUpload;\n }\n return parseFloat(n);\n }",
"function upload() {\n if (! canUpload()) {\n return alert(\"Can't upload right now.\");\n }\n\n // sanity check queued files\n var totalSize = 0;\n for (var i = 0; i < allFiles.length; i++) {\n totalSize += allFiles[i].size;\n }\n if (totalSize > maxUploadSize) {\n return alert(\n 'Sorry, you can only upload ' +\n humanSize(maxUploadSize) +\n ' at a time (you tried to upload ' +\n humanSize(totalSize) +\n ')!'\n );\n }\n\n uploading = true;\n\n // update UI\n var uploadButton = $(\"#upload\");\n uploadButton.text(\"Cancel Upload\");\n\n $(\"#statusText\").show();\n $(\"#selectFiles\").slideUp(200);\n $(\".remove\").fadeOut(200);\n\n // start the upload\n // http://stackoverflow.com/a/8244082\n var request = $.ajax({\n url: \"/upload?json\",\n type: \"POST\",\n contentType: false,\n\n data: getFormData(),\n processData: false,\n\n xhr: function() {\n var req = $.ajaxSettings.xhr();\n\n req.upload.addEventListener(\"progress\", function(e) {\n if (request != uploadRequest) {\n return; // upload was cancelled\n }\n\n if (e.lengthComputable) {\n updateProgress(e.loaded, e.total);\n }\n }, false);\n\n return req;\n },\n\n error: function(xhr, status) {\n if (request !== uploadRequest) {\n return; // upload was cancelled\n }\n\n if (xhr.responseJSON) {\n alert(xhr.responseJSON.error);\n cancelUpload();\n } else {\n // TODO: improve error handling\n console.log(\"Unhandled failure: \" + status + \", status=\" + xhr.status + \", statusText=\" + xhr.statusText);\n alert(\"Sorry, an unexpected error occured.\");\n cancelUpload();\n }\n },\n\n success: function(data) {\n if (request != uploadRequest) {\n return; // upload was cancelled\n }\n\n // TODO: improve error handling\n if (! data.success) {\n return alert(data.error);\n }\n\n if (uploadHistory.enabled()) {\n uploadHistory.addItemToHistory({\n url: data.redirect,\n time: new Date(),\n fileDetails: Object.entries(data.uploaded_files).map(([filename, metadata]) => ({\n filename,\n bytes: metadata.bytes,\n rawUrl: metadata.raw,\n pasteUrl: metadata.paste,\n })),\n });\n }\n\n window.location.href = data.redirect;\n }\n });\n\n uploadRequest = request;\n}",
"async startUpload(uploadId, fragment) {\n let n = await spPost(File(this, `startUpload(uploadId=guid'${uploadId}')`), { body: fragment });\n if (typeof n === \"object\") {\n // When OData=verbose the payload has the following shape:\n // { StartUpload: \"10485760\" }\n n = n.StartUpload;\n }\n return parseFloat(n);\n }",
"static upload(uploadTokenId, fileData, resume = false, finalChunk = true, resumeAt = -1){\n\t\tlet kparams = {};\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\tlet kfiles = {};\n\t\tkfiles.fileData = fileData;\n\t\tkparams.resume = resume;\n\t\tkparams.finalChunk = finalChunk;\n\t\tkparams.resumeAt = resumeAt;\n\t\treturn new kaltura.RequestBuilder('uploadtoken', 'upload', kparams, kfiles);\n\t}",
"function uploadFile(file) {\n const storageRef = firebase.storage().ref('uploads/' + file.name);\n const task = storageRef.put(file);\n\n task.on('state_changed',\n function progress(snap) {\n var progress = (snap.bytesTransferred / snap.totalBytes) * 100;\n uploadProgress.value = progress\n },\n\n function error(err) {\n console.error(err);\n },\n\n function complete() {\n task.snapshot.ref.getDownloadURL().then(function (downloadURL) {\n analysedImage.src = downloadURL;\n });\n const storedPath = task.snapshot.ref.fullPath;\n // Create request to vision\n submitToVision(storedPath);\n\n // Clear input and progress\n uploadProgress.removeAttribute('value');\n fileInput.value = \"\";\n }\n )\n}",
"function appendToFileOverwritingLastBlock(file, initContent, content) {\n let blockSizeInBytes = 16;\n let fileSizeInBytes = 0;\n if (fs.existsSync(file)) {\n fileSizeInBytes = fs.statSync(file)[\"size\"];\n } else {\n fs.closeSync(fs.openSync(file, 'w'));\n content = Buffer.concat([initContent, content]);\n }\n\n let pos = 0;\n let bytesWrote;\n let start = Math.max(0, fileSizeInBytes - blockSizeInBytes);\n let length = Buffer.byteLength(content);\n let fd = fs.openSync(file, 'r+');\n do {\n bytesWrote = tryWriteSync(fd, content, pos, length, start);\n pos += bytesWrote;\n start = null;\n } while (bytesWrote !== 0 && pos < length);\n\n fs.closeSync(fd);\n}",
"function uploadDocumentAttachment() {\n console.log(\"uploadDocumentAttachment() started\");\n current.requestAttachmentUpload(function(response) {\n console.log(\"uploadDocumentAttachment() response is \" + JSON.stringify(response));\n loadDocuments();\n })\n}",
"_uploadFile(upload, file) {\n const formData = new FormData();\n\n // Copy the keys from our upload instructions into the form data\n for (const key in upload.fields) {\n formData.append(key, upload.fields[key]);\n }\n\n // AWS ignores all fields in the request after the file field, so all other\n // fields must appear before the file.\n formData.append('file', file);\n\n // Now we can upload the file\n fetch(upload.url, {\n method: 'post',\n body: formData\n }).then((response) => {\n if (response.ok) {\n this._finalizeFileUpload(upload, file);\n } else {\n this.options.onError(new AssetUploaderError(\"There was an error uploading the file. Please try again.\"));\n }\n });\n }",
"function uploadDone()\r\n{\r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n\tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar docview = objAjax.getDocViewId();\r\n\tif (docview==132)\r\n\t{\r\n\t\tshowProductOverview(null);\r\n\t}\r\n\telse if (docview==2406 || docview==2409)\r\n\t{\r\n\t\ttabSelectionAction(null, 'fitevaloverview.do', 'view', '100', '100')\r\n\t}\r\n\telse if (docview==4007)\r\n\t{\r\n\t\ttabSelectionAction(null, 'sampleeval.do', 'view', '4000', '4000');\r\n\t}\r\n\r\n}",
"upload(e){\n if(e.target.files.length) this.handleFile(e.target.files[0])\n }",
"function upload() {\n\n isCanceled = false;\n indexNumbers = [];\n space = undefined;\n progress = 0;\n let path = $('#file-chooser').val();\n if (validatePath(path) & validateKey.call($('#space-key')) & validateTitle.call($('#space-title'))) {\n space = {\n name: $('#space-title').val(),\n key: $('#space-key').val()\n };\n setUploadMessage(i18n.PREPARING_FOR_UPLOAD, \"generic\");\n createDialog();\n if (AJS.$('#radioButtonUpdate').prop(\"checked\")) {\n\n } else if (AJS.$('#radioButtonClone').prop(\"checked\")) {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, cloneToOldSpace, error);\n } else {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, deleteOldSpace, error);\n }\n\n }\n }",
"function uploadDone(name, myRId) {\r\n var frame = frames[name];\r\n if (frame) {\r\n var ret = frame.document.getElementsByTagName(\"body\")[0].innerHTML;\r\n if (ret.length) {\r\n alert(ret);\r\n frame.document.getElementsByTagName(\"body\")[0].innerHTML = \"\";\r\n showRecordView(myRId);\r\n }\r\n }\r\n }",
"function saveAssetContent(successCallback) {\n $.PercBlockUI();\n var assetEditor = $.PercCreateNewAssetDialogData.assetEditor;\n $contentFrameElem(\"#perc-content-edit-sys_workflowid\").val(assetEditor.workflowId);\n var path = assetEditor.url;\n path = path.split(\"?\")[0];\n var fid = assetEditor.legacyFolderId;\n path = path + \"?sys_folderid=\" + fid + \"&sys_asset_folderid=\" + fid;\n $contentFrameElem(\"#perc-content-form\").attr(\"action\", path);\n //call all the pre submit handlers if nothing returns flase, submit the form.\n var dosubmit = true;\n $.each($.PercContentPreSubmitHandlers.getHandlers(),function(){\n if(!this()){\n dosubmit = false;\n }\n });\n if(!dosubmit)\n {\n $.unblockUI();\n return;\n }\n //We are done processing the handlers, as we are submitting the form, clear all handlers.\n $.PercContentPreSubmitHandlers.clearHandlers();\n $(\"#create-new-asset-content-frame\").contents().find(\"#perc-content-form\").submit();\n //Unbind the function to avoid an acumulation of calls to the same function\n $(\"#create-new-asset-content-frame\").unbind('load', saveAssetResponse).load(saveAssetResponse)\n }",
"async setContentChunked(file, progress, chunkSize = 10485760) {\n if (!isFunc(progress)) {\n progress = () => null;\n }\n const fileSize = (file === null || file === void 0 ? void 0 : file.size) || file.length;\n const totalBlocks = parseInt((fileSize / chunkSize).toString(), 10) + ((fileSize % chunkSize === 0) ? 1 : 0);\n const uploadId = getGUID();\n const fileRef = File(this).using(CancelAction(() => {\n return File(fileRef).cancelUpload(uploadId);\n }));\n // report that we are starting\n progress({ uploadId, blockNumber: 1, chunkSize, currentPointer: 0, fileSize, stage: \"starting\", totalBlocks });\n let currentPointer = await fileRef.startUpload(uploadId, file.slice(0, chunkSize));\n // skip the first and last blocks\n for (let i = 2; i < totalBlocks; i++) {\n progress({ uploadId, blockNumber: i, chunkSize, currentPointer, fileSize, stage: \"continue\", totalBlocks });\n currentPointer = await fileRef.continueUpload(uploadId, currentPointer, file.slice(currentPointer, currentPointer + chunkSize));\n }\n progress({ uploadId, blockNumber: totalBlocks, chunkSize, currentPointer, fileSize, stage: \"finishing\", totalBlocks });\n return fileRef.finishUpload(uploadId, currentPointer, file.slice(currentPointer));\n }",
"async function saveHistoryFile (transferData: TransferData) {\n let data = JSON.parse(storage.getItem('data'))\n let transfers = data[HISTORY_FOLDER_NAME][HISTORY_FILE_NAME]\n let id = transferData.transferId ? transferData.transferId : transferData.receivingId\n if (!id) throw new Error('Missing id in transferData')\n if (transfers) {\n transfers[id] = {\n ...transfers[id],\n ...transferData\n }\n } else {\n transfers = {\n [id]: transferData\n }\n }\n\n // update the send file with new content\n data[HISTORY_FOLDER_NAME][HISTORY_FILE_NAME] = transfers\n storage.setItem('data', JSON.stringify(data))\n}",
"function uploadProg() {\r\n\r\n // The fileUpload input box (hidden) declared in grid_main.html\r\n // is used to select the file. We just click the 'chose file' button\r\n // contained in that input element. When we automatically click the \r\n // input element below, we execute uploadFileContents() routine.\r\n //\r\n var upelem = document.getElementById('fileUpload');\r\n upelem.click();\r\n}",
"handleUpload() {\n if (!this.bShowUploadSection) {\n this.bShowUploadSection = true;\n this.sLabelUpload = 'Collapse Upload Section';\n this.uIconName = 'utility:down';\n }\n else {\n this.bShowUploadSection = false;\n this.sLabelUpload = 'Expand Upload Section';\n this.uIconName = 'utility:right';\n }\n }",
"function handleDeleteUpload() {\n setFiles([])\n deleteFile(document)\n handleDocumentDelete(document)\n fileInputField.current.value = null\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Here is how the email feature works. We move the bitcoins to be sent over to a new random bitcoin address and email the recipient the a code containing the private key matching the bitcoin address. The recipient can then move the bitcoins to their own bitcoin address. So the whole process actually requires two bitcoin transactions. The code sent by email is an encrypted message (encrypted using the recipients email address) which contains: To: email of recipient From: email of sender Amount: BTC amount being sent Date: date and time in UTC of when the send was initiated Message: an optional message from the sender to the recipient Redeem: the private key encrypted with a password provided by the sender or if no password was provided then encrypted with the recipients email address Recover: the private key encrypted with a private key owned by the sender, used if the recipient does not redeem and the sender wants to recover the bitcoins To redeem the recipient just needs to provide the code they were emailed and also a password if the sender chose to add one. The email of the recipient needed to decrypt the above message will already be known from the EZWallet info. To recover the sender just needs to provide the code and the email of the recipient. If the sender added a password to redeem, it is not required to be recalled. The private key needed to decrypt the Recover field of the above message will already be in the senders EZWallet. If the sender does not add a password then anyone who intercepts the email can redeem the bitcoins. If the recipient redeems the bitcoins first, the email will not be of use to anyone intercepting it. Adding a password should be highly recommended, even though it adds some inconvience of having to tell the recipient the password by phone. | function homeMakeEmailTx(){
var to, from, amount, date, message, rawCode, rand, key, bita, pw
var k1, redeem, recover, code
to = removeWhiteSpace($('#homeSendToEmail').val().toLowerCase())
if (to == ''){ alert('To Email must be given.'); return null; }
from = G.email
amount = parseFloat(removeWhiteSpace($('#homeSendAmount').val()))
if (isNaN(amount)){ alert('Amount must be given.'); return null;}
date = new Date().toUTCString()
message = trimWhiteSpace($('#homeSendMessage').val())
pw = trimWhiteSpace($('#homeSendPassword').val())
// create the raw code string:
rawCode = "\
To: "+to+"\n\
From: "+from+"\n\
Amount: "+amount+"\n\
Date: "+date+"\n\
Message: "+message+"\n\
"
// pick a random string
rand = randomHex32()
// create the key using hash of the rawCode and random number so that if anyone
// changes the rawCode in transit, the key cannot be found; thus preventing someone
// from fooling the recipient by changing the info in the rawCode
key = hex2hexKey(hash256(rawCode+rand))
// convert to bitcoin address
bita = key2bitAdd(key)
if (pw == ''){ pw = to }
k1 = seed2key(Seed.main, 0)
redeem = AESencrypt(rand, pw)
recover = AESencrypt(rand, k1)
rawCode = rawCode + "\
redeem: "+redeem+"\n\
recover: "+recover+"\n\
rand: "+rand+"\n\
"
// encrypt the rawCode using the recipients email
code = AESencrypt(rawCode, to)
// alert(rawCode)
// alert(bita)
// alert(code)
code = code.match(/.{1,40}/g).join('\n')
// $('#homeSendCodeForm').show()
$('#debugSendCode').val(code)
$('#homeSendCode').val(code)
$('#homeSendCode').select()
// $('#homeSendForm').hide()
$('#homeSendTo').val(bita)
//alert($('#homeSendTo').val())
return {to:to, sender: from, code: code} //code = transaction code.
} | [
"'mobileRecoverPasswordEmail'(email) {\n Email.send({\n to: email,\n from: \"kupongoteam@kupongo.com\",\n subject: \"Password recovery\",\n html: /*link this to mobile Reset.js page */ \"Link to reset page\",\n });\n }",
"static async inviteUsers(company_id, user_emails) {\n\t\t// find company\n\t\tlet company = await models.Company.findByPk(company_id)\n\t\t// generate random hash\n\t\tlet hash = generator.getRandomString(40)\n\t\t// save hash to db\n\t\tawait models.InviteHash.create({ hash, company_id })\n\n\t\t// send email\n\t\tconst mg = mailgun({ apiKey: 'key-f25a884c247378aa8dd34083fe6e4b28', domain: 'sandbox454409b9d64449f7b661a00c48d6a721.mailgun.org' })\n\t\tconst data = {\n\t\t\tfrom: '<me@samples.mailgun.org>',\n\t\t\tto: user_emails,\n\t\t\tsubject: 'Hello',\n\t\t\ttext: `Dear user you have been invited in ${company.name} <a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>`\n\t\t}\n\t\tmg.messages().send(data, function(error, body) {\n\t\t\tconsole.log(body)\n\t\t})\n\n\t\treturn true\n\n\t\t// // Generate test SMTP service account from ethereal.email\n\t\t// let testAccount = await nodemailer.createTestAccount()\n\t\t// // create reusable transporter object using the default SMTP transport\n\t\t// let transporter = nodemailer.createTransport({\n\t\t// \thost: 'smtp.ethereal.email',\n\t\t// \tport: 587,\n\t\t// \tsecure: false, // true for 465, false for other ports\n\t\t// \tauth: {\n\t\t// \t\tuser: testAccount.user, // generated ethereal user\n\t\t// \t\tpass: testAccount.pass // generated ethereal password\n\t\t// \t}\n\t\t// })\n\n\t\t// send mail with defined transport object\n\t\t// let info = await transporter.sendMail({\n\t\t// \tfrom: '\"Fred Foo 👻\" <foo@example.com>', // sender address\n\t\t// \tto: user_emails, // list of receivers\n\t\t// \tsubject: `Invitation from ${company.name}`, // Subject line\n\t\t// \ttext: `Dear user you have been invited in ${company.name}`, // plain text body\n\t\t// \thtml: `<a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>` // html body\n\t\t// })\n\n\t\t// return nodemailer.getTestMessageUrl(info)\n\t}",
"function _sendEmail() {\n\t\t\t}",
"transferEther(amount, receiverAddress, senderPrivateKey) {\n const senderAddress = `0x${this.getAddressFromPrivateKey(senderPrivateKey).toString('hex')}`\n return this.getNonce(senderAddress).then(nonce => {\n const transaction = {\n from: senderAddress,\n to: receiverAddress,\n value: amount,\n gas: 21000,\n gasPrice: this.gasPrice,\n nonce: nonce,\n privateKey: senderPrivateKey\n }\n const signedTransaction = this.signTransaction(transaction)\n return this.sendSignedTransaction(signedTransaction)\n })\n }",
"sendEmail(sendBody) {\n return API.post(\"emailto\", \"/emailto\", {\n body: sendBody\n });\n }",
"function shovelToBitcoin(message) {\n console.log(`shoveling to bitcoin ${message}`);\n datacash.send({\n data: [\"0x6d02\", message],\n cash: { key: wallet.wif }\n });\n //TODO:should raise event saying that tx was sent\n}",
"*_mailGenerator(args) {\n let { config: template, name: templateName } = args.selectedTemplate;\n let { message, templateVars } = args;\n const { callback } = template;\n\n if (callback && typeof callback === 'function') {\n let userVars = yield Promise.resolve(callback(args.user));\n userVars = this._validateUserVars(userVars);\n templateVars = Object.assign(templateVars, userVars);\n }\n\n let pathPlainText = template.pathPlainText;\n let pathHtml = template.pathHtml;\n let extra = template.extra || {};\n let cachedTemplate = (this.cache[templateName] =\n this.cache[templateName] || {});\n\n // Load plain-text version\n if (!cachedTemplate['text']) {\n let plainTextEmail = yield this._loadEmailTemplate(pathPlainText);\n plainTextEmail = plainTextEmail.toString('utf8');\n cachedTemplate['text'] = plainTextEmail;\n }\n\n // Compile plain-text template\n message.text = Mustache.render(cachedTemplate['text'], templateVars);\n\n // Load html version if available\n if (pathHtml) {\n if (!cachedTemplate['html']) {\n let htmlEmail = yield this._loadEmailTemplate(pathHtml);\n cachedTemplate['html'] = htmlEmail.toString('utf8');\n }\n // Add processed HTML to the message object\n message.html = Mustache.render(cachedTemplate['html'], templateVars);\n }\n\n // Append any `extra` properties from config\n message = Object.assign(message, extra || {});\n\n // Initialize mailcomposer with message\n const composer = this.mailcomposer(message);\n\n // Create MIME string\n const mimeString = yield new Promise((resolve, reject) => {\n composer.build((error, message) => {\n if (error) reject(error);\n resolve(message);\n });\n });\n\n // Assemble payload object for Mailgun\n const payload = {\n to: message.to,\n message: mimeString.toString('utf8')\n };\n\n return new Promise((resolve, reject) => {\n this.mailgun.messages().sendMime(payload, (error, body) => {\n if (error) reject(error);\n resolve(body);\n });\n });\n }",
"function transferFromImportedToEZWallet(fee, callback){\r\n var iAddrs = []\r\n for(var k in ImportedKeys){\r\n iAddrs.push(k)\r\n }\r\n function sTransactionCallback (data){\r\n if(data != null)advancedSentTx (data);\r\n if (callback != null){\r\n callback(data)\r\n\r\n }\r\n }\r\n function createTransfer(totalAmt){\r\n var firstAddy, secondAddy;\r\n for(var k in Keys){\r\n if(firstAddy == null){ firstAddy = k; continue;}\r\n if(secondAddy == null){ secondAddy = k; break;}\r\n }\r\n totalAmt -= fee\r\n if (totalAmt <= 0){\r\n alert(\"Not enough confirmed bitcoins.\")\r\n return\r\n }\r\n var transObj = makeTxObjBase (iAddrs.join(\" \"), firstAddy+\" \"+totalAmt, secondAddy, fee, true)\r\n if(transObj == null){\r\n sTransactionCallback (null)\r\n return;\r\n }\r\n sendTransaction (transObj, sTransactionCallback)\r\n }\r\n\r\n function unspentCallback(d){\r\n var totalAmt = 0\r\n for( var k in d){\r\n if (d[k].address != null){\r\n if(d[k].block > 0){\r\n totalAmt += d[k].value\r\n }\r\n }\r\n }\r\n createTransfer(totalAmt)\r\n }\r\n function getPrivateKeySpentInfo(){\r\n getUnspentBalance(iAddrs, unspentCallback)\r\n }\r\n updateAllSpentInfo(getPrivateKeySpentInfo)\r\n }",
"function sendRoomInvite(recipients, roomID, invitationCode) {\n\n // create link\n const link = `${process.env.DOMAIN}/join-room/${invitationCode}/${roomID}`;\n\n // set mail options\n const mailOptions = {\n from: 'hi@klourly.com', // sender address\n to: recipients, // list of receivers\n subject: 'Room Invite', // Subject line\n text: `A user has invited you to join a room: ${link}`,\n html: `<b>Hello there,<br> click <a href=${link}> here to join room</a></b>` // html body\n };\n\n // send mail\n transporter.sendMail(mailOptions, (error, response) => {\n if(error) console.log(error);\n else console.log('Message sent');\n });\n}",
"sendPremine(data, stamp, keypair)\n {\n //create and sign message\n var message = new Message(data, stamp);\n message.sign(keypair.secretKey);\n\n //encode\n message = message.toHex();\n\n //trigger receive as if we are seeing a new message\n this.receive(message);\n }",
"function sendEmail(usermail){\r\n\r\n \r\n const accessToken = oAuth2Client.getAccessToken();\r\n // to generate accessTokens every time\r\n\r\n // create reusable transporter object\r\n let transporter = nodemailer.createTransport({\r\n service: 'gmail',\r\n auth: {\r\n type: 'OAuth2',\r\n user: usermail,\r\n clientId: CLIENT_ID,\r\n clientSecret: CLIENT_SECRET,\r\n refreshToken: REFRESH_TOKEN,\r\n accessToken: accessToken\r\n }\r\n });\r\n\r\n \r\n // send mail with defined transport object\r\n // mail options to know to,subject, text to sent\r\n let mailOptions = {\r\n from: usermail,\r\n to : 'avinashkethireddy2001@gmail.com', // destination email id\r\n subject: 'Sending via GMAIL API TESTING ',\r\n text: 'Hi Avinash, I think its working !'\r\n };\r\n\r\n // Delivering the message object using the sendMail() method of your previously created transporter\r\n transporter.sendMail(mailOptions, function(err, data) {\r\n if (err) {\r\n console.log(\"Error \" + err);\r\n } else {\r\n console.log(\"Email sent successfully\");\r\n }\r\n });\r\n \r\n}",
"function sendEmail() {\n const mailOption = {\n to: toEmail,\n from: fromEmail,\n subject: `Change detected in ${urlToCheck}`,\n html: `Change detected in <a href=\"${urlToCheck}\"> ${urlToCheck} </a> `,\n };\n transporter.sendMail(mailOption, function (error, info) {\n if (error) {\n console.log(error);\n } else {\n console.log('Email sent: ' + info.response);\n }\n });\n}",
"async function mySendMail( ticker ){\n const result = await transporter.sendMail({\n from: '\"fred <small>👻 </small>\" <knows@amail.com>',\n to: 'homegreen18@gmail.com',\n replyTo: '\"my ghost email shadow who nobody\" <knows@amail.com>',\n subject: 'doing stuff sayiong people coffe',\n html: ticker\n });\n }",
"function sendemail(){\t\n\t\n\t\t// make ajax request to post data to server; get the promise object for this API\n\t\tvar request = WmsPost.newAjaxRequest('/wms/x-services/email/producer', formToJSON());\n\t\n\t\t// register a function to get called when the data is resolved\n\t\trequest.done(function(data,status,xhr){\n\t\t\t//console.log(\"Email sent successfully!\");\n\t\t\tlocation.href = \"emailthankyou.html\";\n\t\t});\n\n\t\t// register the failure function\n\t\trequest.fail(function(xhr,status,error){\n\t\t\t//console.error(\"The following error occured: \"+ status, error);\n\t\t\talert(\"Problem occured while sending email: \" + error);\n\t\t});\n\n\t}",
"forgotPassword(req, res) {\n const we = req.we,\n email = req.body.email;\n\n res.locals.emailSend = false;\n res.locals.messages = [];\n res.locals.user = req.body.user;\n\n if (req.method !== 'POST') return res.ok();\n\n if (!res.locals.user) res.locals.user = {};\n res.locals.formAction = '/auth/forgot-password';\n\n if (!email) {\n return res.badRequest('auth.forgot-password.field.email.required');\n }\n\n we.db.models.user\n .findOne({ where: { email: email }})\n .then( (user)=> {\n if (!user) {\n return res.badRequest('auth.forgot-password.user.not-found', {\n email\n });\n }\n\n if (user.blocked) {\n we.log.warn('auth.user.blocked.on.forgotPassword', {\n id: user.id\n });\n return res.badRequest('auth.forgot-password.user.not-found', {\n id: user.id\n });\n }\n\n we.db.models.authtoken\n .create({\n userId: user.id, tokenType: 'resetPassword'\n })\n .nodeify( (err, token)=> {\n if (err) return res.queryError(err);\n\n if (we.plugins['we-plugin-email']) {\n const options = {\n to: user.email\n };\n\n user = user.toJSON();\n\n if (!user.displayName) {\n user.displayName = user.username;\n }\n\n const templateVariables = {\n userId: user.id,\n name: user.username,\n displayName: (user.displayName || user.fullName),\n siteName: we.config.appName,\n siteUrl: we.config.hostname,\n resetPasswordUrl: token.getResetUrl(),\n token: token.token\n };\n\n if (we.systemSettings) {\n if (we.systemSettings.siteName) {\n templateVariables.siteName = we.systemSettings.siteName;\n }\n }\n\n we.email\n .sendEmail('AuthResetPasswordEmail', options, templateVariables, (err , emailResp)=> {\n if (err) {\n we.log.error('Error on send email AuthResetPasswordEmail', {\n err, emailResp\n });\n return res.serverError();\n }\n we.log.verbose('AuthResetPasswordEmail: Email resp:', {\n emailResp\n });\n });\n\n res.locals.emailSend = true\n }\n\n res.addMessage('success', 'auth.forgot-password.email.send');\n res.ok();\n });\n })\n .catch(res.queryError)\n }",
"async function main(to, from) {\n\n const list = await listunspent();\n\n const addresses = new Set();\n const utxosSortedByAddress = list.reduce( (accumulator, utxo) => {\n const address = utxo.address;\n addresses.add(address);\n if (!accumulator[address]) {\n accumulator[address] = [];\n }\n accumulator[address].push(utxo);\n return accumulator;\n }, {});\n\n const addressArray = Array.from(addresses);\n\n if (addressArray.length === 0) {\n console.log('No UTXOs found with 10 or more confirmations.');\n process.exit(0);\n }\n\n let sendFrom = from ? from : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'sendFrom',\n message: `Select an address to migrate:`,\n choices: addressArray,\n default: addressArray[0]\n },\n ]);\n sendFrom = response.sendFrom;\n }\n const utxoArray = utxosSortedByAddress[sendFrom];\n\n let sendTo = to ? to : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n name: 'sendTo',\n message: `Enter address to send to:`\n },\n ]);\n sendTo = response.sendTo;\n if (!sendTo) {\n console.log('Send To address cannot be blank.');\n process.exit(0);\n }\n }\n\n if (!from || !to) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'list',\n name: 'confirm',\n message: `Migrate ${utxoArray.length} UTXOs from ${sendFrom} to ${sendTo}?`,\n choices: ['Continue', 'Cancel']\n },\n ]);\n if (confirm === 'Cancel') {\n console.log('Aborted by user.');\n process.exit(0);\n }\n }\n\n utxoArray.forEach( async (utxo) => {\n const amount = Math.round(utxo.amount * 100000000);\n const minUtxoSize = argv.minUtxoSize ? argv.minUtxoSize : 100000000;\n if (amount > minUtxoSize) {\n const fee = 10000;\n const sendAmount = (amount - fee) / 100000000;\n const send = {};\n send[sendTo] = sendAmount;\n console.log(`Creating txn to send ${sendAmount} from ${sendFrom} to ${sendTo}`);\n let rawTxn = await createrawtransaction([utxo], send).catch((err) => {\n console.log('createrawtransaction Error.', err);\n console.log('Error creating raw transaction with utxo:', utxo);\n process.exit(0);\n });\n const signedTxn = await signrawtransaction(rawTxn).catch((err) => {\n console.log('signrawtransaction',err);\n console.log('Error signing raw transaction:', rawTxn);\n process.exit(0);\n });\n const txid = await sendrawtransaction(signedTxn.hex).catch((err) => {\n console.log('sendrawtransaction', err);\n console.log('Error sending signed transaction hex:', signedTxn);\n process.exit(0);\n });\n console.log(`Sent ${utxo.amount} to ${sendTo}. txid: ${txid}`);\n }\n });\n\n}",
"async function makeSimpleTx() {\n await t.wait(erc20.transfer(userAFunnel, userAAmount, overrides),\n 'erc20 transfer');\n\n // User A Deposit Token.\n const userADepositToken = new Deposit({\n token: 1,\n owner: userA,\n blockNumber: utils.bigNumberify(await t.getBlockNumber()).add(1),\n value: userAAmount,\n });\n const userADepositTokenTx = await t.wait(contract.deposit(userA, erc20.address, overrides),\n 'token deposit', Fuel.errors);\n\n // Set fee stipulations.\n let feeToken = 1;\n let fee = opts.signatureFee || utils.parseEther('.000012');\n let noFee = utils.bigNumberify(fee).lte(0);\n\n // Build the transaction in question.\n return await tx.Transaction({\n override: true,\n chainId: 0,\n witnesses: [\n userAWallet,\n ],\n metadata: [\n tx.MetadataDeposit({\n blockNumber: userADepositToken.properties.blockNumber().get(),\n token: userADepositToken.properties.token().get(),\n }),\n ],\n data: [\n userADepositToken.keccak256(),\n ],\n inputs: [\n tx.InputDeposit({\n owner: userADepositToken.properties\n .owner().get(),\n }),\n ],\n signatureFeeToken: feeToken,\n signatureFee: fee,\n signatureFeeOutputIndex: noFee ? null : 0,\n outputs: [\n tx.OutputTransfer({\n noshift: true,\n token: '0x01',\n owner: producer,\n amount: utils.parseEther('1000.00'),\n }),\n ],\n contract,\n });\n }",
"walletSetup(seed) {\n\n const root = Hdkey.fromMasterSeed(seed);\n const masterPrivateKey = root.privateKey.toString('hex');\n\n const addrNode = root.derive(\"m/44'/60'/0'/0/0\"); //line 1\n const pubKey = EthUtil.privateToPublic(addrNode._privateKey);\n const addr = EthUtil.publicToAddress(pubKey).toString('hex');\n const address = EthUtil.toChecksumAddress(addr);\n const key = {\n 'root': root,\n 'masterPrivateKey': masterPrivateKey,\n 'addrNode': addrNode,\n 'pubKey': pubKey,\n 'addr': addr,\n 'address': address\n };\n const hexPrivateKey = EthUtil.bufferToHex(addrNode._privateKey)\n this.props.setKeys(masterPrivateKey, address, hexPrivateKey);\n\n this.props.navigation.navigate('HomeScreen');\n /*\n If using ethereumjs-wallet instead do after line 1:\n const address = addrNode.getWallet().getChecksumAddressString();\n */\n }",
"function send_email(your_email,your_password,to_email, subject, content)\n{\n\n\t// Set up the connection to the administrator's email account\n\tvar transporter = nodemailer.createTransport({\n\t service: 'gmail',\n\t auth: {\n\t\tuser: your_email,\n\t\tpass: your_password\n\t }\n\t});\n\n\t// Customize the email as required\n\tvar mailOptions = {\n\t from: your_email,\n\t to: to_email,\n\t subject: subject,\n\t text: content\n\t};\n\n\t// Send an email\n\ttransporter.sendMail(mailOptions, function(error, info){\n\t if (error) {\n\t\tconsole.log(error);\n\t } else {\n\t\tconsole.log('Email sent: ' + info.response);\n\t }\n\t});\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.