query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Pairfantasyland/traverse :: Applicative f => Pair a b ~> (TypeRep f, b > f c) > f (Pair a c) . . `traverse (_) (f) (Pair (x) (y))` is equivalent to . `map (Pair (x)) (f (y))`. . . ```javascript . > S.traverse (Array) (S.words) (Pair (123) ('foo bar baz')) . [Pair (123) ('foo'), Pair (123) ('bar'), Pair (123) ('baz')] . ```
function Pair$prototype$traverse(typeRep, f) { return Z.map (Pair (this.fst), f (this.snd)); }
[ "function Array$prototype$traverse(typeRep, f) {\n var xs = this;\n function go(idx, n) {\n switch (n) {\n case 0: return of(typeRep, []);\n case 2: return lift2(pair, f(xs[idx]), f(xs[idx + 1]));\n default:\n var m = Math.floor(n / 4) * 2;\n return lift2(concat_, go(idx, m), go(idx + m, n - m));\n }\n }\n return this.length % 2 === 1 ?\n lift2(concat_, map(Array$of, f(this[0])), go(1, this.length - 1)) :\n go(0, this.length);\n }", "function Array$prototype$traverse(typeRep, f) {\n var xs = this;\n function go(idx, n) {\n switch (n) {\n case 0: return of (typeRep, []);\n case 2: return lift2 (pair, f (xs[idx]), f (xs[idx + 1]));\n default:\n var m = Math.floor (n / 4) * 2;\n return lift2 (concat_, go (idx, m), go (idx + m, n - m));\n }\n }\n return this.length % 2 === 1 ?\n lift2 (concat_, map (Array$of, f (this[0])), go (1, this.length - 1)) :\n go (0, this.length);\n }", "traverse(T, f) {\n\t\t// Applicative u, Traversable t => t a ~> (TypeRep u, a -> u b) -> u (t b)\n\t\treturn T.of(AJS.of(f(this.value).value))\n\t}", "function Object$prototype$traverse(typeRep, f) {\n var self = this;\n return (Object.keys (this)).reduce (function(applicative, k) {\n function set(o) {\n return function(v) {\n var singleton = {}; singleton[k] = v;\n return Object$prototype$concat.call (o, singleton);\n };\n }\n return lift2 (set, applicative, f (self[k]));\n }, of (typeRep, {}));\n }", "function Object$prototype$traverse(typeRep, f) {\n var self = this;\n return Object.keys(this).reduce(function(applicative, k) {\n function set(o) {\n return function(v) {\n var singleton = {}; singleton[k] = v;\n return Object$prototype$concat.call(o, singleton);\n };\n }\n return lift2(set, applicative, f(self[k]));\n }, of(typeRep, {}));\n }", "function Object$prototype$traverse(typeRep, f) {\n var self = this;\n return Object.keys(this).reduce(function(applicative, k) {\n function set(o) { return function(v) { o[k] = v; return o; }; }\n return lift2(set, applicative, f(self[k]));\n }, of(typeRep, {}));\n }", "function traverse(typeRep, f, traversable) {\n return Traversable.methods.traverse(traversable)(typeRep, f);\n }", "function traverse(node, f) { //tar två arg. en node lista och en funktion\n f(node.value) //du vill att funktionen appliseras på varje listitem. Kalla på funk och ge den listan som argument.\n if(node.next){ //i listan finns två keys. Value och next.\n traverse(node.next, f) //finns keyN next så kalla på funktionen igen med annat argument\n }\n}", "function traverse(T) {\n return (0, function_1.flow)(exports.asTraversal, _.traversalTraverse(T));\n}", "forEach(func){\n for(var o = this; o instanceof Pair; o=o.cdr){\n func(o.car);\n }\n return o;\n }", "function pairWalk(a,b,f)\n{\n\tpath = [];\n\t\n\tfunction rec(a,b,key)\n\t{\n\t\tif (typeof a === 'undefined' || typeof b === 'undefined')\n\t\t\treturn;\n\t\t\n\t\tf(a,b,key,path);\n\t\t\n\t\ta = a[key];\n\t\tb = b[key];\n\t\t\n\t\tif (typeof a !== 'object' || typeof b !== 'object')\n\t\t\treturn;\n\t\t\n\t\tvar keys = _.union(Object.keys(a),Object.keys(b));\n\t\tkeys.map(function(k)\n\t\t{\n\t\t\tpath.push(k);\n\t\t\trec(a,b,k);\n\t\t\tpath.pop();\n\t\t});\n\t}\n\t\n\tvar keys = _.union(Object.keys(a),Object.keys(b));\n\t\n\tkeys.map(function(k)\n\t{\n\t\tpath.push(k);\n\t\trec(a,b,k);\n\t\tpath.pop();\n\t});\n}", "traverse(callback) {\n this.forEach(node => {\n let stack = [node,];\n while (stack.length) {\n const element = stack.pop();\n callback.call(this, element);\n stack = stack.concat(...this.getChildren(element));\n }\n });\n return this;\n }", "function traverse(arr, cb) {\n for (var i = 0; i < arr.length; i++) {\n cb(arr[i], i, arr);\n }\n}", "traverse(fn) {\n fn(this)\n\n const children = Private(this).__children\n for (let i = 0, l = children.length; i < l; i++) {\n children[i].traverse(fn)\n }\n }", "function Left$prototype$traverse(typeRep, f) {\n return Z.of (typeRep, this);\n }", "function traverse(array) {\n for(let index in array){\n if (Array.isArray(array[index])) {\n traverse.call(this,array[index]);\n } else {\n this.push(array[index]);\n }\n }\n}", "traverse(callback, onDuplicate = false) {\n const data = (onDuplicate === true) ? this.clone(true) : this;\n this.traverser(data.output, callback);\n return data;\n }", "function get_pairs (text) {\n\n}", "function Nothing$prototype$traverse(typeRep, f) {\n return Z.of (typeRep, this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that input number is less than a max. If the value is undefined or not capable of being parsed into an integer pass validation
function validateMax(field_value, max) { if (field_value === undefined || field_value === null) { return true; } var int = parseInt(field_value); if (isNaN(int)) { return true; } return int <= max; }
[ "function check_int(val, min, max) {\n assert.ok(typeof(val) == 'number' && val >= min && val <= max && Math.floor(val) === val, \"not a number in the required range\");\n}", "function intCheck(n,min,max,name){if(n<min||n>max||n!==mathfloor(n)){throw Error(bignumberError+(name||\"Argument\")+(typeof n==\"number\"?n<min||n>max?\" out of range: \":\" not an integer: \":\" not a primitive number: \")+String(n))}}// Assumes finite n.", "function intValidatorWithErrors( n, min, max, caller, name ) { // 7005\n if ( n < min || n > max || n != truncate(n) ) { // 7006\n raise( caller, ( name || 'decimal places' ) + // 7007\n ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); // 7008\n } // 7009\n // 7010\n return true; // 7011\n } // 7012", "function numberValidation(input) {\n let name = input.id\n let value = parseFloat(input.value)\n let min = parseFloat(input.min)\n let max = parseFloat(input.max)\n if (!(value >= min && value <= max)) { return `${name} not in range (${input.min}, ${input.max})` }\n else return \"valid\"\n}", "function intCheck(n, min, max, name) {\n if (n < min || n > max || n !== mathfloor(n)) {\n throw Error\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\n : ' not a primitive number: ') + String(n));\n }\n }", "function intCheck(n, min, max, name) {\n if (n < min || n > max || n !== (n < 0 ? mathceil(n) : mathfloor(n))) {\n throw Error\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\n : ' not a primitive number: ') + n);\n }\n }", "function isValidResultLimitNum(num) {\n return isPositiveInteger(num)\n}", "function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== (n < 0 ? mathceil(n) : mathfloor(n))) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + n);\r\n }\r\n }", "function validateInput (input, regex, min, max) {\n if (regex.test(input) && parseInt(input) > min && parseInt(input) < max) {\n return true;\n } else if (isNaN(parseInt(input)) && regex.test(input) && input.length > min && input.length < max) {\n return true;\n } else {\n return false;\n }\n}", "function valid_limit(value) {\n if (value < 0) return false;\n return true;\n}", "function validInput(input) {\n return isInteger(input) && input > 0\n}", "function verifyInputValue(input){\n return((input > 0) && (input <= 10) && (Number.isInteger(input)));\n}", "function validateIntegerRange(val, minVal, maxVal) {\n if (!validateInteger(val))\n return false;\n return ((val >= minVal) && (val <= maxVal));\n}", "function validateIntInRangeOrUndefined(name, min, max, value, isDuration = true) {\n if (value === undefined) {\n return;\n }\n if (!Number.isInteger(value) || value < min || value > max) {\n const seconds = isDuration ? ' seconds' : '';\n throw new Error(`${name}: Must be an int between ${min} and ${max}${seconds} (inclusive); received ${value}.`);\n }\n}", "function validate (number, min, max) {\n // if no range is provided, just check if it is an integer\n if (!min || !max) return isInteger(number);\n // otherwise, validate range parameters\n if (validate(min) && validate(max)) {\n // throw error if number is not in range\n if (number < min || number > max || !isInteger(number)) {\n throw Error('number argument not in range');\n } else {\n return true;\n }\n }\n return false;\n }", "function validMaxMin(min , max){\n try{\n let _min = parseInt(min),_max = parseInt(max);\n return _min < _max; \n }\n catch{\n return false;\n }\n}", "function validateLimitValue (limit) {\n var regex = /^[1-9]+\\d*$/s;\n return regex.test(limit);\n}", "function validateNumberInput(input){\n\tif(isNaN(+input))\n\t{\n\t\tgenerateError(\"Please enter a number!\");\n\t\treturn false;\n\t}\n\tvar num=Number(input); //get an int value from text input\n\tif(num<0||num>200)\n\t{\n\t\tgenerateError(\"Please enter a number between 0-200!\");\n\t\treturn false;\n\t}\n\treturn num;\t\t\n\n}", "function check_integer(which_int, min, max){\n\tvar temp_int = which_int.split(\" \");\n\t\n\tif (temp_int.length > 1){\n\t\treturn false;\n\t}\n\t\t\n\tif (isNaN(which_int) || which_int == \"\"){\t// if it is not an integer\t\t\t\t\n\t\treturn false;\n\t}\n\t\n\tif (which_int.charAt(0) == \"0\" && which_int.length > 1){\t// when the value start with 0\t\n\t\treturn false;\n\t}\n\t\n\tif (arguments.length == 3){\n\t\tif (parseInt(which_int) < min || parseInt(which_int) > max){\t// if it is not in the range\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if the postal address is required and if so is filled out check if business address is filled out
checkAddressReady(){ if(this.state.postal===1 && this.checkBAddress() && this.checkPAddress()){ return true; } else if(this.state.postal===0 && this.checkBAddress()){ return true; } else { return false; } }
[ "function validateAddress(){\n var res = false\n if (myForm.F00000035h.toLowerCase() !== \"berlin\"){\n return false;\n }else if (myForm.F00000035h.toLowerCase() == \"berlin\") {\n if (myForm.bzrnr != '') {\n res = true;\n }\n }else{\n res = false\n } \n\treturn res;\n}", "function validateAddress(){\n var res = false\n if (myForm.transaction){\n if (myForm.F00000035h.toLowerCase() !== \"berlin\"){\n return false;\n }else if (myForm.F00000035h.toLowerCase() == \"berlin\") {\n if (myForm.bzrnr != '') {\n var adr = callbzrinfo();\n myForm.bzrnameh = adr.bzrname;\n myForm.otnameh = adr.otname;\n res = true;\n }\n }else{\n res = false\n }\n } \n\treturn res;\n}", "addressDataIsValid() {\n return (this.props.address &&\n this.props.address.header &&\n this.props.address.line1 &&\n this.props.address.line2 &&\n this.props.address.phoneNum);\n }", "function checkAddressRequiredValues(doc) {\n return prop('street', doc) && prop('city', doc) && prop('state', doc) && prop('zip', doc)\n}", "function checkPostaladdress()\n{\n indicator1.postal = validate(document.getElementById(\"postaladdress\"), regPostaladdress, warningPostaladdress);\n clearErrorInSection1();\n}", "function validateAddress() {\n var validateOrder;\n var address;\n var validateResponse;\n var errorMsg;\n var res = null;\n var message = '';\n var orderNo = params.orderno.value;\n validateOrder = dw.order.OrderMgr.getOrder(orderNo.toString());\n if (validateOrder) {\n var shipments = validateOrder.getShipments().iterator();\n while (shipments.hasNext()) {\n var currentShipment = shipments.next();\n address = currentShipment.shippingAddress;\n validateResponse = validateShippingAddress(address);\n if (validateResponse.messages && validateResponse.messages.length > 0) {\n message = 'Unsuccessful. Service response below:';\n res = {\n success: true,\n message: message,\n svcResponse: validateResponse\n };\n } else {\n message = 'Successful. Service response below:';\n res = {\n success: true,\n message: message,\n svcResponse: validateResponse\n };\n }\n }\n } else {\n errorMsg = 'Order not found in Business Manager.';\n res = {\n success: false,\n message: errorMsg\n };\n }\n r.renderJSON(res);\n}", "function validadeInputsByAddress() {\n var valid = false;\n if (stateSelect.val() <= 0) {\n selectInformationAdress(state, 'State selection is required');\n valid = false;\n } else {\n resetSelectInformation(state);\n valid = true;\n }\n\n if (citySelect.val() <= 0) {\n selectInformationAdress(city, 'City selection is required');\n valid = false;\n } else {\n resetSelectInformation(city);\n valid = true;\n }\n\n if (streetInput.val().length >= 200) {\n inputInformationAdress(streetInput, 'Maximum 200 characters');\n valid = false;\n } else if (streetInput.val() == \"\") {\n inputInformationAdress(streetInput, 'Street filling is required');\n valid = false;\n } else {\n resetInputInformation(streetInput);\n valid = true;\n }\n return valid;\n}", "function validatePresenceOfAllOrNoPayerAddressFields(addressFields) {\r\n var resultOfValidation = true;\r\n if(addressFields != null) {\r\n var blankAddressFields = [];\r\n var blankAddressFieldNames = [];\r\n var lengthOfAddressFields = addressFields.length;\r\n for(i = 0; i < lengthOfAddressFields; i++) {\r\n if($(addressFields[i]) != null) {\r\n if($F(addressFields[i]).strip() == '' && $(addressFields[i]).readOnly != true) {\r\n var splits = addressFields[i].split('_');\r\n splits[0] = \"\";\r\n blankAddressFieldNames.push(splits.join(' '));\r\n blankAddressFields.push(addressFields[i]);\r\n }\r\n }\r\n }\r\n var lengthOfBlankAddressFields = blankAddressFields.length;\r\n if(lengthOfBlankAddressFields > 0 && lengthOfBlankAddressFields != lengthOfAddressFields) {\r\n resultOfValidation = false;\r\n alert(\"Please enter the full address or leave all the address fields blank: \" +\r\n blankAddressFieldNames);\r\n $(blankAddressFields.first()).focus();\r\n }\r\n }\r\n return resultOfValidation;\r\n}", "function validateLegalAddress(LA_ADDR,LA_PIN,LA_COUNTRY,LA_STATUS,LA_CITY){\n\n\t$('#LA_PIN_ERROR').text(\"\");\n\t$('#LA_STATUS_ERROR').text(\"\");\n\t$('#LA_COUNTRY_ERROR').text(\"\");\n\t$('#LA_ADDR_ERROR').text(\"\");\n\t$('#LA_CITY_ERROR').text(\"\");\n\n\n\t\n\tif(LA_ADDR===undefined || LA_ADDR===\"\" || LA_ADDR.length>250){\n\t\t\n\t\tif(LA_ADDR.length>250){\n\t\t\t$('#LA_ADDR_ERROR').text(\"Length should not exceed 250 characters.\");\n\t\t\treturn false;\n\t\t}\n\t\telse{\n\t\t\t$('#LA_ADDR_ERROR').text(\"Please fill Address Line 1.\");\n\t\t\treturn false;\n\t\t}\n\t}\n\tif(LA_STATUS===undefined || LA_STATUS===\"\" || LA_STATUS==null){\n\t\t\n\t\t$('#LA_STATUS_ERROR').text(\"Please select Status.\");\n\t\treturn false;\n\t}\n\tif(LA_CITY!=undefined && LA_CITY!=\"\" && LA_CITY!=null){\n\t\tif(/^[A-Za-z]+$/.test(LA_CITY)== false){\n\t\t\t$('#LA_CITY_ERROR').text(\"Please enter the valid City.\");\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tif(LA_PIN===undefined || LA_PIN===\"\" || /^[1-9]{1}[0-9]{5}$/.test(LA_PIN)== false){\n\t\t\n\t\tif(LA_PIN===undefined || LA_PIN===\"\" ){\n\t\t\t$('#LA_PIN_ERROR').text(\"Please enter the Pincode.\");\n\t\t\treturn false;\n\t\t}\n\t\telse{\n\t\t\t$('#LA_PIN_ERROR').text(\"Please enter valid Pincode\");\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t\n\tif(LA_COUNTRY===undefined || LA_COUNTRY===\"\" || LA_COUNTRY==null ){\n\t\t\n\t\t$('#LA_COUNTRY_ERROR').text(\"Please select Country.\");\n\t\treturn false;\n\t}\n\n\t\n\treturn true;\n}", "validateAddress() {\n\t\tif (!this.request.body.address) {\n\t\t\tthrow new Error(\"Address cannot be empty. Please provide a valid address\");\n\t\t}\n\n\t\treturn true;\n\t}", "function user_reminder_new_address() {\n //IF ALL FIELDS OF [NEW ADDRESS] ARE SET\n if ($('#new_street').val() != \"\" &&\n $('#new_zipcode').val() != \"\" &&\n $('#new_city').val() != \"\" &&\n $('#new_unit').val() != \"\" && \n $('#new_state').val() != \"\") {\n //IF NAME, PHONE OR EMAIL ARE NOT SET\n if ($('#first_name').val() == \"\" ||\n $('#last_name').val() == \"\" ||\n $('#telephone').val() == \"\" ||\n $('#email').val() == \"\") {\n //SHOW ALERT\n $('#alert-forgotten').removeClass('hide');\n };\n //true = new address\n check_all_inputs(true);\n }\n}", "function validateAddressInfo() {\r\n\r\n var addressLine1 = $(\"#addressLine1\").val();\r\n var addressLine2 = $(\"#addressLine2\").val();\r\n // var fullAddress = $(\"#addressLine1\").val() + $(\"#addressLine2\").val();\r\n var city = $(\"#city\").val();\r\n var state = $(\"#state\").val();\r\n var zipCode = $(\"#zipCode\").val();\r\n var flag = true;\r\n\r\n if(addressLine1 != \"\"){\r\n\r\n if(addressLine1.length > 70){\r\n $(\"#error-addressLine1\").html(\"<em>Character limit upto 70</em>\");\r\n flag = false;\r\n }\r\n }\r\n if(addressLine2 != \"\"){\r\n\r\n if(addressLine2.length > 50){\r\n $(\"#error-addressLine2\").html(\"<em>Character limit upto 50</em>\");\r\n flag = false;\r\n }\r\n }\r\n if(city != \"\"){\r\n\r\n if(city.length > 30){\r\n $(\"#error-city\").html(\"<em>Invalid City name</em>\");\r\n flag = false;\r\n }\r\n }\r\n if(state != \"\"){\r\n\r\n if(state.length > 30){\r\n $(\"#error-state\").html(\"<em>Invalid State name</em>\");\r\n flag = false;\r\n }\r\n }\r\n if(zipCode != \"\"){\r\n\r\n var validCode = /^[0-9]{6}$/;\r\n\r\n if(!(zipCode.match(validCode))){\r\n $(\"#error-zipCode\").html(\"<em>Invalid Zip Code</em>\");\r\n flag = false;\r\n }\r\n }\r\n\r\n return flag;\r\n}", "function validPostalCode() {\r\n\r\n inputPostalCode.onblur = () => testPostalCodeBlur();\r\n\r\n testPostalCodeFocus();\r\n }", "validateAddressParameter() {\n if (!this.req.body.address) {\n throw new Error('Fill the address parameter')\n }\n\n return true\n }", "function checkUserAddress(onSuccess, onFail) {\n let user = getSessionUser()\n if (user.town === '' || user.town === undefined ||\n user.firstName === '' || user.firstName === undefined ||\n user.lastName === '' || user.lastName === undefined ||\n user.postalCode === '' || user.postalCode === undefined ||\n user.street === '' || user.street === undefined ||\n user.title === '' || user.title === undefined) {\n onFail()\n } else {\n onSuccess()\n }\n}", "function checkAddress() {\n\tgeocoder.getLocations(jQuery(\"#Field01_1\").val(), function(response) {\n if ( response && response.Status.code === 200)\n {\n\t\tvar loc = response.Placemark[0];\n\n\t\tjQuery(\"#Field01_1\").val( loc.address.substr(0,loc.address.lastIndexOf(',')) );\n\t\tjQuery(\"#Field01_2\").val( loc.Point.coordinates[1] );\n\t\tjQuery(\"#Field01_3\").val( loc.Point.coordinates[0] );\n\n\t\t// Get the ZPID and basic home info\n\t\tjQuery.getJSON(ajax+\"/zillow.php?c=?\", {loc:jQuery(\"#Field01_1\").val()}, function(data){\n\t\t jQuery(\"#Field01_4\").val( data.zpid );\n\t\t});\n }\n\t});\n\treturn false;\n }", "function checkaddress()\n{\n var wdf = window.document.forms[0]; // abbreviates window.document.form\n if ((wdf.bestaddress && wdf.bestaddress.checked == false) && (wdf.includeproperty.checked == false)) {\n\tif(wdf.includepaw && wdf.includepaw.checked == false) {\n\t if (wdf.includesubjectphone && wdf.includesubjectphone.checked == false && wdf.includesubjectaddress) {\n\t\twdf.includesubjectaddress.checked = true;\n\t }\n\t if(wdf.subjectaddresscount && wdf.subjectaddresscount.options[0].selected)\n\t\twdf.subjectaddresscount.options[1].selected = true;\n\t}\n\telse {\n\t if (wdf.subjectaddresscount && wdf.includesubjectaddress && wdf.includesubjectaddress.checked == false && wdf.includesubjectphone && wdf.includesubjectphone.checked == false) {\n\t\twdf.subjectaddresscount.options[0].selected = true;\n\t }\n\t else {\n\t\tif(wdf.subjectaddresscount && wdf.subjectaddresscount.options[0].selected)\n\t\t wdf.subjectaddresscount.options[1].selected = true;\n\t }\n\t}\n }\n}", "function validateNewShippingAddress (required) {\n\n document.getElementById(\"shippingAddressInput\").required = required;\n document.getElementById(\"shippingCityInput\").required= required;\n document.getElementById(\"shippingProvinceInput\").required= required;\n document.getElementById(\"shippingCountryInput\").required = required;\n\n }", "requiredPostcodeLookup(field) {\n /*\n if manual area visible, validate manual fields\n if results area visible, validate results\n if search area visible, validate search\n */\n const element = field.closest('.js-postcode-lookup');\n\n const lookupElement = element.querySelector('.ds_address__lookup');\n const resultsElement = element.querySelector('.ds_address__results');\n const manualElement = element.querySelector('.ds_address__manual');\n\n let valid = false;\n\n if (!lookupElement.classList.contains('fully-hidden')) {\n let message = \"Enter a postcode and click 'Find address'\";\n\n // todo: this should be a check for readonly mode\n if (true) {\n message += ', or enter an address manually';\n }\n\n const field = lookupElement.querySelector('.js-postcode-input');\n\n commonForms.toggleFormErrors(field, valid, 'invalid-postcode-lookup', 'Postcode lookup', message);\n commonForms.toggleCurrentErrors(field, valid, 'invalid-postcode-lookup', message);\n } else if (!resultsElement.classList.contains('fully-hidden')) {\n const value = resultsElement.querySelector('.js-results-select').value;\n\n if (!isNaN(+value) && +value > -1) {\n valid = true;\n }\n } else if (!manualElement.classList.contains('fully-hidden')) {\n\n }\n\n // const valid = false;\n return valid;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add value in localStorage(m+ button)
function addValue(){ var sum = parseInt( localStorage.getItem("M+ Values")); var a = parseInt(document.getElementById("calc").value); sum = sum + a; localStorage.setItem("M+ Values",sum); // console.log("sum : " + sum); }
[ "function addData(key, value) {\n localStorage.setItem(key, value);\n }", "function getValue(){\r\n document.getElementById(\"calc\").value=localStorage.getItem(\"M+ Values\");\r\n}", "function saveMoney() {\n localStorage[\"money\"] = money;\n}", "function nineAmSaveBtnClick(e) {\n e.preventDefault;\n localStorage.setItem(\"nineAm\", nineAm.value);\n}", "function saveToLocal() {\n var btnNum = $(this).attr(\"data-num\"); // Gets the \"number\" of the clicked button\n var wire = ('#' + btnNum); // Creates the element id for the text input from the button number\n txtData = $(wire).val(); // Fetches the text/data from the text input\n\n localStorage.setItem('TimeSlot' + btnNum, txtData); // Sets the time slot and data in Local Storage\n\n}", "guardarEnAlm(key, value) {\n localStorage.setItem(key, value);\n }", "function updateLocalStorage() {\n objString = '{\"nextId\": \"' + nextId + '\"}';\n convertObjectToString(root);\n localStorage.setItem(LOCAL_STORAGE, objString);\n }", "function subValue()\r\n{\r\nvar sub=localStorage.getItem(\"M+ Values\");\r\nvar b=parseInt(document.getElementById(\"calc\").value);\r\nsub=sub-b;\r\nlocalStorage.setItem(\"M+ Values\",sub); \r\n//console.log(\"sub \",sub); \r\n}", "function nineAmSaveBtnClick(e) {\n\te.preventDefault;\n\tlocalStorage.setItem(\"nineAm\", nineAm.value);\n}", "function setCurrent(){\n//set ls items\nlocalStorage.setItem('currentMiles',$(this).data('miles'));\nlocalStorage.setItem('currentDate',$(this).data('date'));\n//insert form fields\n$('#editMiles').val(localStorage.getItem('currentMiles'));\n$('#editDate').val(localStorage.getItem('currentDate'));\n}", "addTime(x){\n let current = parseInt(localStorage.getItem('currentTime')) + parseInt(x);\n localStorage.setItem('currentTime', current);\n this.add.text();\n }", "function save(event) {\n var buttonId = event.target.id;\n var eventDesc = $(\"#\" + buttonId)\n .prev()\n .val();\n var eventText = $(\"#\" + buttonId)\n .prev()\n .text(eventDesc)\n .val();\n console.log(eventText);\n localStorage.setItem(buttonId, eventText);\n var localValue = localStorage.getItem(buttonId);\n console.log(localValue);\n console.log(\n $(\"#\" + buttonId)\n .prev()\n .text(localValue)\n );\n }", "function saveReward() {\n localStorage.rewardOption = $('.btn-reward-option label.active').text().replace(/\\s/g, \"\");\n localStorage.rewardInput = $('#rewardInput').val();\n }", "function pushToStorage() {\n var selectedRow = $(this).parent().parent().attr(\"id\");\n var rowId = \"#\"+selectedRow+ \" .taskEntry\";\n var inputText = $(rowId).children().val();\n localStorage.setItem(rowId , inputText);\n }", "LocalStorageSet(){\n localStorage.setItem(this._dataName, this._data);\n }", "function addStorage(){\n $(\".saveBtn\").click(function(){\n let calInputs = $(this).siblings(\".event\").val();\n let inputsLoc = $(this).siblings(\".event\").attr(\"id\");\n localStorage.setItem(inputsLoc,calInputs);\n });\n }", "function setLocal(key, value){\n localStorage.setItem(key, value);\n}", "function setLocalValue(name, value){\n localStorage.setItem(name, value);\n}", "function addToThird() {\n\n var recentURL = localStorage.getItem(\"urlSet\");\n\n localStorage.setItem(\"recent3\", recentURL);\n\n\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create the buffer canvas from the size of the original canvas used for display
function createBufferCanvasFronDisplayCanvas(displayCanvas){ var backgroundCanvas = document.createElement('canvas'); backgroundCanvas.width = displayCanvas.width; backgroundCanvas.height = displayCanvas.height; backgroundCanvas.getContext("2d").fillStyle = "rgb(255,255,255)"; backgroundCanvas.getContext("2d").fillRect (0,0,backgroundCanvas.width,backgroundCanvas.height ); return backgroundCanvas; }
[ "function _modifyCanvasSize() {\n let width, height;\n if (scene.change_canvas_size) {\n let aspect = (scene.left_eye[1] - scene.left_eye[0])\n / (scene.left_eye[3] - scene.left_eye[2]);\n if (aspect > 1) {\n width = Math.min(200, aspect * 150);\n height = width / aspect;\n } else {\n height = Math.min(200, 150 / aspect);\n width = height * aspect;\n }\n } else {\n width = height = 150;\n }\n\n let canvas = $('#' + id + \"_canvas_b\");\n canvas.width(width).height(height); // changes drawing buffer\n canvas.css(\"width\", width); // changes size of canvas\n canvas.css(\"height\", height); // changes size of canvas\n\n canvas = $('#' + id + \"_canvas_c\");\n canvas.width(width).height(height); // changes drawing buffer\n canvas.css(\"width\", width); // changes size of canvas\n canvas.css(\"height\", height); // changes size of canvas\n }", "function resizeCanvasRenderBuffer(canvas) {\n var dpr = window.devicePixelRatio || 1;\n canvas.width = canvas.clientWidth * dpr;\n canvas.height = canvas.clientHeight * dpr;\n}", "function saveToCanvasBuffer() {\n canvasBuffer = ctx.getImageData(0, 0, width, height);\n}", "function resizeCanvasRenderBuffer(canvas) {\n const dpr = window.devicePixelRatio || 1;\n canvas.width = canvas.clientWidth * dpr;\n canvas.height = canvas.clientHeight * dpr;\n}", "_resizeCanvasDrawingBuffer() {\n if (this.autoResizeDrawingBuffer) {\n const dpr = this.useDevicePixelRatio ?\n window.devicePixelRatio || 1 : 1;\n this.canvas.width = this.canvas.clientWidth * dpr;\n this.canvas.height = this.canvas.clientHeight * dpr;\n }\n }", "function getBufferCanvas() {\n return buffer_canvas;\n }", "apply() {\n const g = this.targetCanvas.getContext('2d');\n g.drawImage(this.bufferCanvas, 0, 0);\n }", "function createBlitCanvas(orig) {\n var o = orig.get(0),\n c = document.createElement('canvas');\n c.width = o.width;\n c.height = o.height;\n\n return c;\n }", "function getDrawingBufferSize(canvas) {\n return {\n width: canvas.width,\n height: canvas.height\n };\n}", "createCanvas(){\n this.myCanvasHolder = document.querySelector(\".myPaint\");\n this.width = this.myCanvasHolder.width = document.querySelector(\".content\").offsetWidth;\n this.height = this.myCanvasHolder.height = window.innerHeight*0.9;\n this.ctx = this.myCanvasHolder.getContext(\"2d\");\n this.ctx.width = this.width;\n this.ctx.height = this.height;\n this.isDrawing = false;\n }", "function createCanvas(){\n var c = document.createElement('canvas');\n c.width = (width * cellsize) + ((1 + width) * padding);\n c.height = (height * cellsize) + ((1 + height) * padding);\n return c;\n }", "_resizeCanvasDrawingBuffer() {\n if ( this.autoResizeDrawingBuffer ) {\n resizeGLContext( this.gl, { useDevicePixels: this.useDevicePixels } );\n }\n }", "function set_canvas_size()\n\t{\n\t\tsize.width = 0;\n\t\tsize.height = 0;\n\n\t\tfeed_string( false );\n\t\trender.setSize( size.width, size.height );\n\t}", "function resetSize (destCanvas, srcCanvas, buffer) {\n var newWidth = srcCanvas.width + 2 * buffer\n var newHeight = srcCanvas.height + 2 * buffer\n var newSize = destCanvas.width !== newWidth ||\n destCanvas.height !== newHeight\n\n if (newSize) {\n if (destCanvas.width !== newWidth) destCanvas.width = newWidth\n if (destCanvas.height !== newHeight) destCanvas.height = newHeight\n destCanvas.getContext('2d').translate(buffer, buffer)\n }\n }", "function resizeCanvas() {\n ch = ((h = canvas.height = innerHeight - 32) / 2) | 0;\n cw = ((w = canvas.width = innerWidth) / 2) | 0;\n updateDisplay = true;\n }", "copyCanvas(){\n const newCanvas = document.createElement('canvas');\n newCanvas.id = `frame${this.number}canvas${this.canvasList.length}`;\n \n const prefill = true;\n setCanvas(prefill, newCanvas, this.width, this.height);\n \n //newCanvas.style.opacity = 0.97;\n this.container.appendChild(newCanvas);\n newCanvas.getContext(\"2d\").drawImage(this.currentCanvas, 0, 0);\n this.canvasList.push(newCanvas);\n }", "addSizedCanvas() {\n this.addCanvas(this.windowlet.width, this.windowlet.height - this.windowlet.handleHeight);\n }", "createCanvas () {\n let width = this.texture.width;\n let height = this.texture.height-50;\n if (!this._canvas) {\n this._canvas = document.createElement('canvas');\n\n this._canvas.width = width;\n this._canvas.height = height;\n }\n else {\n this.clearCanvas();\n }\n let ctx = this._canvas.getContext('2d');\n this.camera.render();\n let data = this.texture.readPixels();\n // write the render data\n let rowBytes = width * 4; \n for (let row = 0; row < height; row++) {\n let srow = height - 1 - row;\n let imageData = ctx.createImageData(width, 1);\n let start = srow * width * 4;\n for (let i = 0; i < rowBytes; i++) {\n // if ((i - 3) % 4 == 0) {\n // // cc.log (\"i \" + i + \" data \" + data[start + i]);\n // // imageData.data[i] = 255;\n // } else {\n // imageData.data[i] = data[start + i];\n // }\n imageData.data[i] = data[start + i];\n }\n\n ctx.putImageData(imageData, 0, row);\n }\n return this._canvas;\n }", "function createCanvas(){\n const scale = 0.95;\n const innerWidth = scale*window.innerWidth;\n const innerHeight = scale*window.innerHeight;\n let canvasWidth = ((9/16)*innerWidth < innerHeight) ? innerWidth:(16/9)*innerHeight;\n let canvasHeight = ((9/16)*innerWidth < innerHeight) ? (9/16)*innerWidth:innerHeight;\n if (innerWidth > 840 && innerHeight > 525) {\n canvasWidth = 840;\n canvasHeight = 525;\n }\n const hold = '<canvas id=\"mainCanvas\" height='+canvasHeight+' width='+canvasWidth+'></canvas>';\n document.getElementById(\"canvasHolder\").innerHTML = hold;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the transform to its original values.
Reset() { this.translation = this.originalTranslation.Clone(); this.rotationInRadians = this.originalRotationInRadians; this.scale = this.originalScale.Clone(); this.origin = this.originalOrigin.Clone(); this.dimensions = this.originalDimensions.Clone(); this.isDirty = true; }
[ "resetTransform() {\n this.getContext().setTransform(1, 0, 0, 1, 0, 0);\n }", "function resetTransform() {\n ctx.setTransform(transform);\n}", "resetTransform() {\n if (this.transformInteractor) {\n this.transformInteractor.reset();\n }\n }", "resetTransform() {\n this._targetNode.resetTransform();\n }", "_resetTransform(context) {\r\n\t\tcontext.setTransform(1, 0, 0, 1, 0, 0);\r\n\t}", "reset() {\r\n this.ctx.setTransform(1, 0, 0, 1, 0, 0);\r\n }", "function resetTransform() {\n gfx.ctx.setTransform(gfx.transform);\n}", "resetTransform() {\n this._targetNode.resetTransform();\n this.matrixProperty.set( this._targetNode.matrix.copy() );\n }", "function resetTransform(ctx) {\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n}", "function reset_transform_to_default() {\n x_scale = default_x_scale\n y_scale = default_y_scale\n x_offset = default_x_offset\n y_offset = default_y_offset\n}", "reset () {\n this.set(clone(this._originalValue))\n }", "_resetObjectTransform() {\n const { defaultPosition, defaultRotation } = this._scenery.object;\n\n this._setObjectTargetPositon(...defaultPosition);\n this._object.rotation.set(...defaultRotation);\n }", "function clear() {\n\t transforms = {};\n\t}", "function reset() {\n zoom.translate([0, 0]).scale(1);\n performScaling();\n }", "function clear() {\n transforms = {};\n}", "reset() {\n this.transformType = this.IDENTITY_TRANSFORM;\n\n let i;\n for (i = 0; i < this.cornerLoc.length; i++) {\n this.cornerLoc[i] = i;\n this.cornerOrient[i] = 0;\n }\n\n for (i = 0; i < this.edgeLoc.length; i++) {\n this.edgeLoc[i] = i;\n this.edgeOrient[i] = 0;\n }\n\n for (i = 0; i < this.sideLoc.length; i++) {\n this.sideLoc[i] = i;\n this.sideOrient[i] = 0;\n }\n\n this.fireCubeChanged(new CubeEvent(this, 0, 0, 0));\n }", "reset() {\n this.transform.identity();\n this.velocity.zero();\n this.angularVelocity = 0;\n this.clearForce();\n this.clearTorque();\n this.contacts.clear();\n }", "reset() {\n this.transmuxer.reset();\n }", "function clearTransformStack ()\n{\n if (this._vs_transform) delete (this._vs_transform);\n this._vs_transform = undefined;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render and initialize the clientside People Picker.
function initializePeoplePicker(eleId) { // Create a schema to store picker properties, and set the properties. var schema = {}; schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup'; schema['SearchPrincipalSource'] = 15; schema['ResolvePrincipalSource'] = 15; schema['AllowMultipleValues'] = true; schema['MaximumEntitySuggestions'] = 50; schema['Width'] = '280px'; // Render and initialize the picker. // Pass the ID of the DOM element that contains the picker, an array of initial // PickerEntity objects to set the picker value, and a schema that defines // picker properties. this.SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema); }
[ "function initializePeoplePicker(eleId) {\n // Create a schema to store picker properties, and set the properties.\n var schema = {};\n schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';\n schema['SearchPrincipalSource'] = 15;\n schema['ResolvePrincipalSource'] = 15;\n schema['AllowMultipleValues'] = false;\n schema['MaximumEntitySuggestions'] = 50;\n schema['Width'] = '280px';\n // Render and initialize the picker. \n // Pass the ID of the DOM element that contains the picker, an array of initial\n // PickerEntity objects to set the picker value, and a schema that defines\n // picker properties.\n this.SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema);\n }", "function initializePeoplePicker(eleId) {\n\n try{\n\n // Create a schema to store picker properties, and set the properties.\n\n var schema = {};\n schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';\n schema['SearchPrincipalSource'] = 15;\n schema['ResolvePrincipalSource'] = 15;\n schema['AllowMultipleValues'] = true;\n schema['MaximumEntitySuggestions'] = 50;\n schema['Width'] = '280px';\n // Render and initialize the picker. \n // Pass the ID of the DOM element that contains the picker, an array of initial\n // PickerEntity objects to set the picker value, and a schema that defines\n // picker properties.\n this.SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema);\n\n\n }\n catch(e){\n console.log(e);\n }\n\n\n}", "function initializePeoplePicker(peoplePickerElementId) {\n\n // Create a schema to store picker properties, and set the properties.\n var schema = {};\n //schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';\n schema['PrincipalAccountType'] = 'User';\n schema['SearchPrincipalSource'] = 15;\n schema['ResolvePrincipalSource'] = 15;\n schema['AllowMultipleValues'] = false;\n schema['MaximumEntitySuggestions'] = 50;\n schema['Width'] = '792px';\n\n // Render and initialize the picker. \n // Pass the ID of the DOM element that contains the picker, an array of initial\n // PickerEntity objects to set the picker value, and a schema that defines\n // picker properties.\n //this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);\n SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);\n}", "function initializePeoplePicker(peoplePickerElementId) {\n\n // Create a schema to store picker properties, and set the properties.\n var schema = {};\n schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';\n schema['SearchPrincipalSource'] = 15;\n schema['ResolvePrincipalSource'] = 15;\n schema['AllowMultipleValues'] = true;\n schema['MaximumEntitySuggestions'] = 50;\n schema['Width'] = '280px';\n\n // Render and initialize the picker.\n // Pass the ID of the DOM element that contains the picker, an array of initial\n // PickerEntity objects to set the picker value, and a schema that defines\n // picker properties.\n this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);\n }", "function initializePeoplePicker(peoplePickerElementId) {\n \n // from https://msdn.microsoft.com/en-us/library/jj713593(v=office.15).aspx#code-snippet-2\n\n // Create a schema to store picker properties, and set the properties.\n var schema = {};\n schema.PrincipalAccountType = 'User,DL,SecGroup,SPGroup';\n schema.SearchPrincipalSource = 15;\n schema.ResolvePrincipalSource = 15;\n schema.AllowMultipleValues = false;\n schema.MaximumEntitySuggestions = 50;\n //schema['Width'] = '280px';\n\n // Render and initialize the picker. \n // Pass the ID of the DOM element that contains the picker, an array of initial\n // PickerEntity objects to set the picker value, and a schema that defines\n // picker properties.\n SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema); // removed 'this' object from statement\n \n // add form-control class to people picker input for Bootstrap styling purposes\n $('#emailRecipient_TopSpan').addClass('form-control');\n}", "function initializePeoplePicker(peoplePickerElementId) {\n\n // Create a schema to store picker properties, and set the properties.\n var schema = {\n Id: $scope.schema.Id,\n Title: $scope.schema.Title,\n Hidden: $scope.schema.Hidden,\n IMEMode: null,\n Name: $scope.schema.InternalName,\n Required: $scope.schema.Required,\n Direction: $scope.schema.Direction,\n FieldType: $scope.schema.TypeAsString,\n //Description: $scope.schema.Description, //-> Hace que renderice la descripción otra vez ya que nosotros ya la renderizamos.\n ReadOnlyField: $scope.schema.ReadOnlyField,\n Type: 'User',\n DependentLookup: false,\n AllowMultipleValues: $scope.schema.AllowMultipleValues,\n Presence: $scope.schema.Presence,\n WithPicture: false,\n DefaultRender: true,\n WithPictureDetail: false,\n ListFormUrl: '/_layouts/15/listform.aspx',\n UserDisplayUrl: '/_layouts/15/userdisp.aspx',\n EntitySeparator: ';',\n PictureOnly: false,\n PictureSize: null,\n UserInfoListId: $scope.schema.LookupList,\n SharePointGroupID: $scope.schema.SelectionGroup,\n PrincipalAccountType: 'User,DL,SecGroup,SPGroup',\n SearchPrincipalSource: 15,\n ResolvePrincipalSource: 15/*,\n MaximumEntitySuggestions: 50,\n Width: '280px'*/\n };\n\n\n // Generate the PickerEntities to fill the PeoplePicker\n var pickerEntities = [];\n\n angular.forEach($scope.selectedUserItems, function(user) {\n\n if (user.data !== null) {\n\n var displayName = user.data.Title; //user.data[$scope.schema.LookupField];\n var userName = user.data.Name;\n\n // MSDN .NET PickerEntity members\n /*\n Claim Gets or sets an object that represents whether an entity has the right to claim the specified values.\n Description Gets or sets text in a text box in the browser.\n DisplayText Gets or sets text in the editing control.\n EntityData Gets or sets a data-mapping structure that is defined by the consumer of the PickerEntity class.\n EntityDataElements\n EntityGroupName Group under which this entity is filed in the picker.\n EntityType Gets or sets the name of the entity data type.\n HierarchyIdentifier Gets or sets the identifier of the current picker entity within the hierarchy provider.\n IsResolved Gets or sets a value that indicates whether the entity has been validated.\n Key Gets or sets the identifier of a database record.\n MultipleMatches\n ProviderDisplayName\n ProviderName\n */\n\n var pickerEntity = {\n AutoFillDisplayText: displayName,\n AutoFillKey: userName,\n AutoFillSubDisplayText: '',\n Description: displayName,\n DisplayText: displayName,\n EntityData: {\n ID: user.data.ID\n },\n EntityType: 'User', //-> Para el administrador es ''\n IsResolved: true,\n Key: userName,\n //LocalSearchTerm: 'adminis', //-> Creo que guarda la última búsqueda realizada en el PeoplePicker.\n ProviderDisplayName: '', //-> Ej.: 'Active Directory', 'Tenant', ...\n ProviderName: '', //-> Ej.: 'AD', 'Tenant', ...\n Resolved: true,\n };\n\n pickerEntities.push(pickerEntity);\n\n }\n\n });\n\n\n // Render and initialize the picker.\n // Pass the ID of the DOM element that contains the picker, an array of initial\n // PickerEntity objects to set the picker value, and a schema that defines\n // picker properties.\n this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, pickerEntities, schema);\n\n\n\n // Get the people picker object from the page.\n var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerElementId + '_TopSpan'];\n\n $scope.peoplePicker = peoplePicker;\n\n if (peoplePicker !== void 0 && peoplePicker !== null) {\n\n // Get information about all users.\n //var users = peoplePicker.GetAllUserInfo();\n\n\n // Maps the needed callback functions...\n\n //peoplePicker.OnControlValidateClientScript = function(peoplePickerId, entitiesArray) {};\n\n //peoplePicker.OnValueChangedClientScript = function(peoplePickerId, entitiesArray) {};\n\n peoplePicker.OnUserResolvedClientScript = function(peoplePickerId, entitiesArray) {\n\n //console.log('OnUserResolvedClientScript', peoplePickerId, entitiesArray);\n\n var resolvedValues = [];\n var promises = [];\n\n angular.forEach(entitiesArray, function(entity) {\n\n if (entity.IsResolved) {\n\n if ($scope.schema.AllowMultipleValues || promises.length === 0) {\n\n var entityPromise;\n\n if (entity.EntityData.SPGroupID !== undefined) {\n\n // sharepoint group\n entityPromise = $q.when(resolvedValues.push(entity.EntityData.SPGroupID));\n\n } else if (entity.EntityData.ID !== undefined) {\n\n // previous entity ...\n entityPromise = $q.when(resolvedValues.push(entity.EntityData.ID));\n\n } else {\n\n // resolve entity by key\n entityPromise = SPUtils.getUserInfoByLoginName(entity.Key).then(function(userInfo) {\n\n resolvedValues.push(userInfo.Id);\n return resolvedValues;\n });\n\n }\n\n promises.push(entityPromise);\n\n } else {\n\n // Force to commit the value through the model controller $parsers and $validators pipelines.\n // This way the validators will be launched and the view will be updated.\n $scope.modelCtrl.$setViewValue($scope.modelCtrl.$viewValue);\n }\n }\n });\n\n\n if (promises.length > 0) {\n\n $q.all(promises).then(function() {\n\n updateModel(resolvedValues);\n\n });\n\n } else {\n\n updateModel(resolvedValues);\n }\n };\n\n\n // Set the focus element for the validate\n var editorElement = document.getElementById($scope.peoplePicker.EditorElementId);\n\n if (editorElement) {\n\n editorElement.setAttribute('data-spfield-focus-element', 'true');\n $compile(angular.element(editorElement))($scope);\n\n }\n\n }\n }", "function initializePeoplePicker(eleId, AllowMultipleValues, Width, accountType, callback) {\r\n // Create a schema to store picker properties, and set the properties.\r\n var schema = {};\r\n if (accountType === undefined) {\r\n accountType = \"User\";\r\n } else if (typeof (accountType) === \"object\") {\r\n accountType = accountType.toString()\r\n }\r\n else if (typeof (accountType) != \"string\") {\r\n accountType = \"User\";\r\n }\r\n\r\n if (Width === undefined) {\r\n Width = \"250px\";\r\n }\r\n\r\n // schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';\r\n schema['PrincipalAccountType'] = accountType;\r\n schema['SearchPrincipalSource'] = 15;\r\n schema['ResolvePrincipalSource'] = 15;\r\n schema['AllowMultipleValues'] = AllowMultipleValues;\r\n schema['MaximumEntitySuggestions'] = 50;\r\n schema['Width'] = Width;\r\n // Render and initialize the picker. \r\n // Pass the ID of the DOM element that contains the picker, an array of initial\r\n // PickerEntity objects to set the picker value, and a schema that defines\r\n // picker properties.\r\n window.SPClientPeoplePicker_InitStandaloneControlWrapper(eleId, null, schema);\r\n setTimeout(function(){\r\n callback();\r\n },500);\r\n }", "function createPicker() {\n if (pickerApiLoaded && oauthToken) {\n var view = new google.picker.View(google.picker.ViewId.PRESENTATIONS).\n setMimeTypes('application/vnd.google-apps.presentation');\n var picker = new google.picker.PickerBuilder().\n addView(view).\n setOAuthToken(oauthToken).\n setCallback(pickerCallback).\n build();\n picker.setVisible(true);\n }\n}", "render() {\n //onChange={this._onSelectionChanged.bind(this)}\n return (\n <div>\n {\n this.state.isLoadingPeople ?\n <div>\n <Spinner size={SpinnerSize.xSmall} label='Loading loan officers list ...' ariaLive='assertive' /><br />\n </div>\n :\n <div />\n }\n <NormalPeoplePicker\n onResolveSuggestions={this._onFilterChanged.bind(this)}\n pickerSuggestionsProps={{\n suggestionsHeaderText: 'Team Members',\n noResultsFoundText: 'No results found',\n searchForMoreText: 'Search',\n loadingText: 'Loading pictures...',\n isLoading: this.state.isLoadingPics\n }}\n getTextFromItem={(persona) => persona.primaryText}\n onEmptyInputFocus={this.onEmptyInputFocusHandler.bind(this)}\n onChange={this.props.onChange}\n onGetMoreResults={this._onGetMoreResults.bind(this)}\n className='ms-PeoplePicker normalPicker'\n key='normal-people-picker'\n itemLimit={this.props.itemLimit ? this.props.itemLimit : '1'}\n defaultSelectedItems={this.state.defaultSelectedItems ? this.state.defaultSelectedItems : []}\n disabled={this.state.isLoadingPeople || this.state.isDisableTextBox}\n />\n <br />\n {\n this.state.result &&\n <MessageBar messageBarType={this.state.result.type}>\n {this.state.result.text}\n </MessageBar>\n }\n </div>\n );\n }", "function picker_init() {\n picker_color_render();\n\n picker_layer_toggle();\n}", "function createPicker() {\n if (pickerApiLoaded && oauthToken) {\n var picker = new google.picker.PickerBuilder().addView(google.picker.ViewId.PHOTOS).addView(google.picker.ViewId.PHOTO_UPLOAD).\n //addView(google.picker.ViewId.DOCS_VIDEOS).\n //addView(new google.picker.DocsUploadView()).\n setOAuthToken(oauthToken).setDeveloperKey(developerKey).setCallback(pickerCallback).build();\n picker.setVisible(true);\n }\n }", "function createPicker() {\n if (pickerApiLoaded && oauthToken) {\n var picker = new google.picker.PickerBuilder().\n addView(google.picker.ViewId.DOCS_IMAGES).\n enableFeature(google.picker.Feature.MULTISELECT_ENABLED).\n setOAuthToken(oauthToken).\n setDeveloperKey(developerKey).\n setCallback(pickerCallback).\n build();\n picker.setVisible(true);\n }\n}", "function loadPicker() {\n gapi.load('picker', {'callback': createPicker});\n }", "function loadPicker() {\n gapi.load('picker', {'callback': onPickerApiLoad});\n }", "function createPicker() {\nvar picker = new google.picker.PickerBuilder().\n addView(google.picker.ViewId.DOCUMENTS).\n setCallback(pickerCallback).\n build();\npicker.setVisible(true);\n}", "function createPicker() {\nvar picker = new google.picker.PickerBuilder().\n addView(google.picker.ViewId.DOCUMENTS).\n setCallback(pickerCallback).\n build();\n picker.setVisible(true);\n}", "function createPicker() {\n if (pickerApiLoaded && oauthToken) {\n var view = new google.picker.View(google.picker.ViewId.DOCS);\n view.setMimeTypes(typeFile);\n var picker = new google.picker.PickerBuilder()\n .enableFeature(google.picker.Feature.NAV_HIDDEN)\n .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)\n .setAppId(appId)\n .setOAuthToken(oauthToken)\n .addView(view)\n .addView(new google.picker.DocsUploadView())\n .setDeveloperKey(developerKey)\n .setCallback(pickerCallback)\n .build();\n picker.setVisible(true);\n }\n }", "function createPicker() {\n var picker = new google.picker.PickerBuilder().\n addView(google.picker.ViewId.DOCUMENTS).\n setCallback(pickerCallback).\n build();\n picker.setVisible(true);\n}", "function onPickerApiLoad() {\n pickerApiLoaded = true;\n createPicker();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flushes the zindexes. This is a fairly expensive operation, thas's why the info is buffered.
_flushUpdateZIndexOfChilden() { const _this = this; // Iterate over a clone: const _buffer = this.cloneObject(this._updateZIndexOfChildrenBuffer); this._updateZIndexOfChildrenBuffer = []; _buffer .map(_viewId => { const _view = _this.__views[_viewId]; const _isRootView = _viewId === null; const _viewOrder = _isRootView ? _this.__viewsZOrder : _view.viewsZOrder; if (_viewOrder instanceof Array) { return _viewOrder; } else { return null; } }) .filter(_viewOrder => { return _viewOrder !== null; }) .map(_viewOrder => { let _zIndex = -1; return _viewOrder .map(_viewId => { const _view = _this.__views[_viewId]; const _elemId = _view.elemId; if (_elemId) { _zIndex += 1; return [_elemId, _zIndex]; } else { return null; } }) .filter(_item => { return _item !== null; }); }) .forEach(_elemZIndexes => { _elemZIndexes.forEach(([_elemId, _zIndex]) => { ELEM.setStyle(_elemId, 'z-index', _zIndex, true); }); }); }
[ "function _clearIndexes() {\n $.each(_indexList, function (indexName, index) {\n index.fileInfos = [];\n });\n }", "_flush() {\n const centralDirectoryOffset = this._offset;\n let centralDirectorySize = 0;\n for (const i in this._files)\n this._writeCentralDirectoryHeader(this._files[i]);\n centralDirectorySize = this._offset - centralDirectoryOffset;\n this._writeEndOfCentralDirectory(\n centralDirectoryOffset,\n centralDirectorySize,\n );\n // Once this buffer is out, we're done with the output stream\n this.output.end();\n }", "function flush() {\n // flush all caches\n Object.keys(cache).forEach(function(name) {\n // dump the buffer if present\n if (cache[name].size)\n cache[name].func(cache[name].buf.join('\\n'));\n\n // clear the buffer\n cache[name].buf.length = 0;\n cache[name].size = 0;\n });\n}", "function compact()\n\t\t{\n\t\t\t// compacting operates on index order\n\t\t\tif (!_options.ordered)\n\t\t\t\tthrow \"Attempted to compact an unordered index: '\" + signature() + \"'.\";\n\n\t\t\t// tracing calls to this method as it is expensive\n\t\t\tjOrder.log(\"Compacting index '\" + signature() + \"'.\");\n\t\t\t\n\t\t\t// remove orphan entries\n\t\t\tfor (idx in _order)\n\t\t\t\tif (!(_order[idx].rowId in _flat))\n\t\t\t\t\t_order.splice(idx, 1);\n\t\t}", "function clearSturebyIndexes(cacheDir) {\n return Promise.all([\n indexes.fileShaIndex(cacheDir),\n indexes.imgFingerIndex(cacheDir),\n indexes.facesIndex(cacheDir),\n indexes.facesCropIndex(cacheDir),\n indexes.importedTimesIndex(cacheDir)\n ].map(index => index.clear()));\n}", "function reindex()\n\t\t{\n\t\t\tfor (var name in _indexes)\n\t\t\t\t_indexes[name].rebuild();\n\t\t}", "processQueuedIndexes() {\n if (! this.isSchemaAttached) return;\n\n for (var i = 0; i < this.toBeAttached.length; i++) {\n this.processIndex(this.toBeAttached[i]);\n }\n //clear the queue\n this._toBeAttached.length = 0;\n }", "function flushBuffer() {\n refresh(buffer);\n buffer = [];\n }", "function refreshIndex(_index){\n\talgolia.deleteByQuery(\"\", function(err) {\n\t\tif (!err) {\n\t\t\tconsole.log('success deleting all');\n\t\t}\n\t\talgolia.saveObjects(_index, function(err, content) {\n\t\t\tif (!err) {\n\t\t\t\tconsole.log('success indexing all');\n\t\t\t}\n\t\t\tconsole.log(content);\n\t\t});\n\t});\n}", "_flush() {\n // Did we write the headers already? If not, start there.\n if (!this._wroteHeader) this._writeLocalFileHeader();\n\n // Is anything buffered? If so, flush it out to output stream and recurse.\n if (this._buffers) {\n for (const i in this._buffers) this._deflate.write(this._buffers[i]);\n this._buffers = [];\n }\n\n // Are we done writing to this file? Flush the deflated stream,\n // which triggers writing file descriptor.\n if (!this.writable) this._deflate.end();\n }", "function updateZIndices() {\n for (var i = 0; i < displayed.length; i++) {\n DOM.style(\"#\" + divIds[displayed[i]], \"zIndex\", divCollection.divBaseZIndex + i + \"\");\n }\n }", "function syncIndexes()\n {\n // This function handles the query finishing\n function finish(err)\n {\n if (err)\n {\n console.error(err);\n }\n\n setTimeout(syncIndexes, self.options.indexSynchronizationInterval * 1000);\n }\n\n // First, we remove any old query profiles\n self.querySet.removeOldQueryProfiles();\n\n // Save before, because the synchronize step can take a long time,\n // and we don't want to lose all the query profiles gathered so far\n self.saveOptimizerData(function (err)\n {\n if (err)\n {\n return finish(err);\n }\n\n try\n {\n // Perform the synchronization. Internally, this triggers the random sampling of your database.\n self.synchronizeIndexes(function (err)\n {\n if (err)\n {\n return finish(err);\n }\n\n // Also save after, so that we don't lose any of the cached sampling statitics gathered during the first step.\n self.saveOptimizerData(function (err)\n {\n if (err)\n {\n return finish(err);\n }\n\n return finish();\n });\n });\n }\n catch(err)\n {\n return finish(err);\n }\n });\n }", "updateZIndices()\n {\n for (let i = 0; i < this.windows.length; i++)\n {\n this.windows[i].element.style.zIndex = Z_INDEX_OFFSET + i\n }\n }", "function reindexObjects() {\n\n for (var objectIndex = 0, objectCount = type_metaData.type_objects.length;\n objectIndex < objectCount;\n objectIndex++) {\n\n var object = type_metaData.type_objects[objectIndex];\n object.index = objectIndex;\n\n }\n\n }", "function saveIndex() {\n const START = '🏗 ' + chalk.yellow(`Saving index files...`);\n const END = '👍 ' + chalk.green(`done saving`);\n console.log('');\n console.log(START);\n console.time(END);\n\n fileTree.write(_cache);\n console.timeEnd(END);\n}", "updateChunks(){if(this._trace)this._trace.push({type:\"updateChunks\"});this._removeInvalidatedChunks();this._addChunksFromTransactions();this._createInitialChunk();}", "flushBuffers() {\n this._xBuffer.flush();\n }", "clearDeletedIndexes () {\n // We iterate in reverse on the presumption (following the unit tests) that KO's diff engine\n // processes diffs (esp. deletes) monotonically ascending i.e. from index 0 -> N.\n for (let i = this.indexesToDelete.length - 1; i >= 0; --i) {\n this.firstLastNodesList.splice(this.indexesToDelete[i], 1);\n }\n this.indexesToDelete = [];\n }", "static update_z_indexes(){\n let z_index=0;\n for(let l of layers){\n if(l.map.setZIndex) l.map.setZIndex(++z_index);\n else l.create_map_level();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Animation instance / "beforeshow" event handler for each submenu of the MenuBar instance, used to setup certain style properties before the menu is animated.
function onSubmenuBeforeShow(p_sType, p_sArgs) { var oBody, oElement, oShadow, oUL; if (this.parent) { oElement = this.element; /* Get a reference to the Menu's shadow element and set its "height" property to "0px" to syncronize it with the height of the Menu instance. */ oShadow = oElement.lastChild; oShadow.style.height = "0px"; /* Stop the Animation instance if it is currently animating a Menu. */ if (oAnim && oAnim.isAnimated()) { oAnim.stop(); oAnim = null; } /* Set the body element's "overflow" property to "hidden" to clip the display of its negatively positioned <ul> element. */ oBody = this.body; // Check if the menu is a submenu of a submenu. if (this.parent && !(this.parent instanceof YAHOO.widget.MenuBarItem)) { /* There is a bug in gecko-based browsers where an element whose "position" property is set to "absolute" and "overflow" property is set to "hidden" will not render at the correct width when its offsetParent's "position" property is also set to "absolute." It is possible to work around this bug by specifying a value for the width property in addition to overflow. */ if (ua.gecko) { oBody.style.width = oBody.clientWidth + "px"; } /* Set a width on the submenu to prevent its width from growing when the animation is complete. */ if (ua.ie == 7) { oElement.style.width = oElement.clientWidth + "px"; } } oBody.style.overflow = "hidden"; /* Set the <ul> element's "marginTop" property to a negative value so that the Menu's height collapses. */ oUL = oBody.getElementsByTagName("ul")[0]; oUL.style.marginTop = ("-" + oUL.offsetHeight + "px"); } }
[ "function onAnimationComplete(p_sType, p_aArgs, p_oShadow) {\n\n\t\tvar oBody = this.body,\n\t\t\t\toUL = oBody.getElementsByTagName(\"ul\")[0];\n\n\t\tif (p_oShadow) {\n\t\t\n\t\t\t\tp_oShadow.style.height = this.element.offsetHeight + \"px\";\n\t\t\n\t\t}\n\n\n\t\toUL.style.marginTop = \"\";\n\t\toBody.style.overflow = \"\";\n\t\t\n\n\t\t// Check if the menu is a submenu of a submenu.\n\n\t\tif (this.parent && \n\t\t\t\t!(this.parent instanceof YAHOO.widget.MenuBarItem)) {\n\n\n\t\t\t\t// Clear widths set by the \"beforeshow\" event handler\n\n\t\t\t\tif (ua.gecko) {\n\t\t\t\t\n\t\t\t\t\t\toBody.style.width = \"\";\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (ua.ie == 7) {\n\n\t\t\t\t\t\tthis.element.style.width = \"\";\n\n\t\t\t\t}\n\t\t\n\t\t}\n\t\t\n}", "function onSubmenuShow(p_sType, p_sArgs) {\n\n\t\tvar oElement,\n\t\t\t\toShadow,\n\t\t\t\toUL;\n\n\t\tif (this.parent) {\n\n\t\t\t\toElement = this.element;\n\t\t\t\toShadow = oElement.lastChild;\n\t\t\t\toUL = this.body.getElementsByTagName(\"ul\")[0];\n\t\t\n\n\t\t\t\t/*\n\t\t\t\t\t\t Animate the <ul> element's \"marginTop\" style \n\t\t\t\t\t\t property to a value of 0.\n\t\t\t\t*/\n\n\t\t\t\toAnim = new YAHOO.util.Anim(oUL, \n\t\t\t\t\t\t{ marginTop: { to: 0 } },\n\t\t\t\t\t\t.5, YAHOO.util.Easing.easeOut);\n\n\n\t\t\t\toAnim.onStart.subscribe(function () {\n\n\t\t\t\t\t\toShadow.style.height = \"100%\";\n\t\t\t\t\n\t\t\t\t});\n\n\n\t\t\t\toAnim.animate();\n\n\n\t\t\t\t/*\n\t\t\t\t\t\tSubscribe to the Anim instance's \"tween\" event for \n\t\t\t\t\t\tIE to syncronize the size and position of a \n\t\t\t\t\t\tsubmenu's shadow and iframe shim (if it exists) \n\t\t\t\t\t\twith its changing height.\n\t\t\t\t*/\n\n\t\t\t\tif (YAHOO.env.ua.ie) {\n\t\t\t\t\t\t\n\t\t\t\t\t\toShadow.style.height = oElement.offsetHeight + \"px\";\n\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\tSubscribe to the Anim instance's \"tween\"\n\t\t\t\t\t\t\t\tevent, passing a reference Menu's shadow \n\t\t\t\t\t\t\t\telement and making the scope of the event \n\t\t\t\t\t\t\t\tlistener the Menu instance.\n\t\t\t\t\t\t*/\n\n\t\t\t\t\t\toAnim.onTween.subscribe(onTween, oShadow, this);\n\n\t\t\t\t}\n\n\n\t\t\t\t/*\n\t\t\t\t\t\tSubscribe to the Anim instance's \"complete\" event,\n\t\t\t\t\t\tpassing a reference Menu's shadow element and making \n\t\t\t\t\t\tthe scope of the event listener the Menu instance.\n\t\t\t\t*/\n\n\t\t\t\toAnim.onComplete.subscribe(onAnimationComplete, oShadow, this);\n\t\t\n\t\t}\n\n}", "function initMenuAnimation() {\n var menu_li = document.getElementById(\"menu_top\").children;\n var l = menu_li.length;\n for (var i = 0; i < l; i++) {\n menu_li[i].li_index = i;\n menu_li[i].onmouseenter = function (e) {\n var current_hr = e.target.getElementsByTagName('hr')[0];\n var current_index = e.target.li_index;\n var classN = \"anm_menu_init \";\n if (menuIndex != -1) {\n classN += (current_index > menuIndex) ? \"fle\" : \"flr\";\n }\n current_hr.className = classN;\n for (var i = 0; i < menu_li.length; i++) {\n if (i != menuIndex && i != current_index) {\n menu_li[i].getElementsByTagName('hr')[0].className = \"\";\n }\n }\n menuIndex = current_index;\n };\n menu_li[i].onmouseleave = function (e) {\n setTimeout(function () {\n var current_hr = e.target.getElementsByTagName('hr')[0];\n var current_index = e.target.li_index;\n var classN = \"anm_menu_fade \";\n if (current_index == menuIndex) {\n menuIndex = -1;\n }\n else if (menuIndex != -1) {\n classN += (current_index < menuIndex) ? \"flr\" : \"fle\";\n }\n current_hr.className = classN;\n }, 10);\n };\n }\n }", "function setupMenuAnimation(p_oMenu) {\r\nif(!p_oMenu.animationSetup) {\r\nvar aItems = p_oMenu.getItemGroups();\r\nif(aItems && aItems[0]) {\r\nvar i = aItems[0].length - 1;\r\nvar oSubmenu;\r\ndo {\r\noSubmenu = p_oMenu.getItem(i).cfg.getProperty(\"submenu\");\r\nif(oSubmenu) {\r\noSubmenu.beforeShowEvent.subscribe(onMenuBeforeShow, oSubmenu, true);\r\noSubmenu.showEvent.subscribe(onMenuShow, oSubmenu, true);\r\n}\r\n}\r\nwhile(i--);\r\n}\r\np_oMenu.animationSetup = true;\r\n}\r\n}", "initMenu() {\n let menuGroups = this._items.map(menuGroup => {\n let items = menuGroup.map(menuItem => {\n let item = HTMLBuilder.li(\"\", \"menu-item\");\n item.html(menuItem.label);\n\n if (menuItem.action) {\n item.data(\"action\", menuItem.action)\n .click(e => {\n if (!item.hasClass(\"disabled\")) {\n this.controller.doAction(menuItem.action);\n this.closeAll();\n }\n });\n\n let shortcut = this.controller.shortcutCommands[menuItem.action];\n if (shortcut) {\n HTMLBuilder.span(\"\", \"hint\")\n .html(convertShortcut(shortcut))\n .appendTo(item);\n }\n }\n\n if (menuItem.submenu) {\n let submenu = new this.constructor(this, item, menuItem.submenu);\n item.addClass(\"has-submenu\").mouseenter(e => {\n if (!item.hasClass(\"disabled\")) {\n this.openSubmenu(submenu);\n }\n });\n this._submenus.push(submenu);\n }\n\n item.mouseenter(e => {\n if (this._activeSubmenu && item !== this._activeSubmenu.parentItem) {\n this.closeSubmenus();\n }\n });\n\n this.makeItem(item, menuItem);\n\n return item;\n });\n return HTMLBuilder.make(\"ul.menu-group\").append(items);\n });\n\n this._menu = HTMLBuilder.div(`submenu ${this.constructor.menuClass}`, menuGroups);\n\n // make sure submenus appear after the main menu\n this.attach();\n this._submenus.forEach(submenu => {\n submenu.attach();\n });\n }", "function menuBarInit()\n {\n \n this.mbarStyleNormal = _mbarStyleNormal;\n this.mbarStyleHover = _mbarStyleHover;\n this.mbarStyleSelect = _mbarStyleSelect;\n this.border = _border;\n this.borderTopStyle = _borderTopStyle;\n this.borderLeftStyle = _borderLeftStyle;\n this.borderRightStyle = _borderRightStyle;\n this.borderBottomStyle = _borderBottomStyle;\n this.wrapOption = _wrapOption;\n this.linkStyle = _linkStyle;\n \n menuRoot = document.createElement('DIV');\n menuRoot.setAttribute('id','s'+this.id);\n menuRoot.setAttribute('parentid','x');\n menuRoot.setAttribute('className','mainmenu');\n \n //menuRoot.attachEvent ('onmouseover', menuFocusHook);\n\n //menuRoot.attachEvent ('onmouseover', menuFocusHookComboHide);\n \n oTbl= document.createElement('TABLE');\n oTr = oTbl.insertRow();\n oTr.setAttribute(\"id\",\"t0\"); \n menuRoot.appendChild(oTbl);\n \n document.body.appendChild(menuRoot);\n oTbl.border=0;\n oTbl.cellPadding=0;\n oTbl.cellSpacing=1;\n oTbl.bgColor='#FFFFFF';\n \n // Create a div with ID menu CHILDREN Container\n\n menuChildren = document.createElement('DIV');\n menuChildren.id='menuchildren';\n //menuChildren.attachEvent ('onfocusin', menuFocusHook);\n //menuChildren.attachEvent ('onfocusout', menuFocusHook1);\n document.body.appendChild(menuChildren);\n return;\n }", "initMenus() {\n // Highlights expand/collapse works on click\n super.listener( this.highlightsTitle, 'click', ( e ) => {\n e.preventDefault()\n\n this.highlightsList.slideToggle()\n this.$element.toggleClass( 'open' )\n } )\n }", "initMenuScrollbarTransitions() {\n const T11G = 't11g';\n\n // transitionstart event emulation for Chrome.\n document.querySelectorAll('ol.menu li').forEach(e => {\n const ol = e.querySelector('ol');\n if (!ol) return;\n\n e.addEventListener('mouseenter', _ => ol.clientHeight === 0 && ol.classList.add(T11G));\n e.addEventListener('mouseleave', _ => ol.classList.add(T11G));\n });\n\n document.querySelectorAll('ol.menu > li ol').forEach(e => {\n e.addEventListener('transitionend', _ => e.classList.remove(T11G));\n\n // Prevent window scrolling whilst over submenu.\n e.addEventListener('wheel', (event) => {\n if (e.clientHeight + e.scrollTop + event.deltaY > e.scrollHeight) {\n e.scrollTop = e.scrollHeight;\n\n event.preventDefault();\n } else if (e.scrollTop + event.deltaY < 0) {\n e.scrollTop = 0;\n\n event.preventDefault();\n }\n\n // Forbid parent from handling event.\n event.stopPropagation();\n });\n });\n }", "function onSubmenuShow() {\n\n\t\tvar oIFrame, oElement, nOffsetWidth;\n\n\t\t/* Keep the left-most submenu against the left edge of the browser viewport */\n\t\tif (this.id == \"evo\") {\n\t\t\tYAHOO.util.Dom.setX(this.element, 0);\n\t\t\toIFrame = this.iframe; \n\t\t\tif (oIFrame) {\n\t\t\t\tYAHOO.util.Dom.setX(oIFrame, 0);\n\t\t\t}\n\t\t\tthis.cfg.setProperty(\"x\", 0, true);\n\t\t}\n\n\t\t/*\n\t\t * Need to set the width for submenus of submenus in IE to prevent the mouseout \n\t\t * event from firing prematurely when the user mouses off of a MenuItem's \n\t\t * text node.\n\t\t */\n\t\tif ((this.id == \"filemenu\" || this.id == \"editmenu\") && YAHOO.env.ua.ie) {\n\n\t\t\toElement = this.element;\n\t\t\tnOffsetWidth = oElement.offsetWidth;\n\t\n\t\t\t/*\n\t\t\t * Measuring the difference of the offsetWidth before and after\n\t\t\t * setting the \"width\" style attribute allows us to compute the \n\t\t\t * about of padding and borders applied to the element, which in \n\t\t\t * turn allows us to set the \"width\" property correctly.\n\t\t\t */\n\t\t\toElement.style.width = nOffsetWidth + \"px\";\n\t\t\toElement.style.width = (nOffsetWidth - (oElement.offsetWidth - nOffsetWidth)) + \"px\";\n\t\t}\n\t}", "function animMenuItems( $area ) {\n\t\t\t\tvar $menu = $area.find('ul.grve-menu'),\n\t\t\t\t\t$firstLevel = $menu.find('li.grve-first-level'),\n\t\t\t\t\titemLength = $firstLevel.length,\n\t\t\t\t\tcount = -1,\n\t\t\t\t\tcounter;\n\n\t\t\t\tif( itemLength > 0 && !startTimer ){\n\t\t\t\t\tstartTimer = true;\n\t\t\t\t\tcounter = setInterval(function(){\n\t\t\t\t\t\ttimer($firstLevel);\n\t\t\t\t\t}, 200);\n\t\t\t\t}\n\n\t\t\t\tfunction timer($menuItem){\n\t\t\t\t\tcount += 1;\n\t\t\t\t\tif (count >= itemLength) {\n\t\t\t\t\t\tclearInterval(counter);\n\t\t\t\t\t\tstartTimer = false;\n\t\t\t\t\t}\n\t\t\t\t\t$menuItem.eq(count).addClass('show');\n\t\t\t\t}\n\t\t\t}", "function initTekNavSubmenu() {\n\n\t$j('.nav-primary .current-page-ancestor.menu-item-has-children .sub-menu, .nav-primary .current-menu-item.menu-item-has-children .sub-menu').animate( {'left': 0, 'opacity': 1}, 250 );\n\tif( $j('.nav-primary .current-page-ancestor.menu-item-has-children .sub-menu, .nav-primary .current-menu-item.menu-item-has-children .sub-menu').length ) {\n\t\n\t\t$j('.nav-primary .current-page-ancestor.menu-item-has-children, .nav-primary .current-menu-item.menu-item-has-children').addClass('current-submenu');\n\t\n\t}\n\telse {\n\t\n\t\t$j('.nav-primary .menu-primary > .menu-item:first-child').addClass('current-submenu');\n\t\tgetSubmenu('.nav-primary .menu-primary > .menu-item:first-child');\n\t\t\n\t}\t//end if( $j('.nav-primary .current-page-ancestor.menu-item-has-children .sub-menu, .nav-primary .current-menu-item.menu-item-has-children .sub-menu').length )\n\t$j('.nav-primary .menu-item-has-children').click( function(e) {\n\t\n\t\tif (!$j(this).hasClass('current-submenu')) {\n\t\t\n\t\t\te.preventDefault();\n\t\t\tgetSubmenu(this);\n\t\t\n\t\t}\t//end if (!$j(this).hasClass('current-submenu'))\n\t\n\t});\t//end $j('.nav-primary .menu-item-has-children').click( function(e)\n\t\n}\t//end function initTekNavSubmenu()", "function eventListenerMenuBar() {\n const menuBarLinks = document.querySelectorAll(\"#events .menubar ul li\");\n menuBarLinks.forEach(link => {\n link.addEventListener(\"click\", handleMenuBar);\n });\n menuBarLinks[0].classList.add(\"active\");\n}", "function configureMenus() {\n // variable to hold current window state - small, medium, or large\n var windowState = 'large';\n \n // check intital width of the screen, respond with appropriate menu\n var sw = document.body.clientWidth;\n if (sw < 980) {\n smMenu();\n } else if (sw >= 980) {\n lgMenu();\n // $('.hasSubMenu').stop().mouseenter(function() {\n // $(this).animate({\n // \"background\": 'white'},\n // 400, function() {\n // $(this).find('.divSubNavWrapper').show();\n // });\n\n // }).mouseleave(function(event) {\n // /* Act on the event */\n // $('.divSubNavWrapper').hide();\n // $(this).stop();\n // });\n } \n \n // take care of resizing the window\n $(window).resize(function() {\n var sw = document.body.clientWidth;\n if (sw < 980 && windowState != 'small') {\n smMenu();\n }\n if (sw > 980 && windowState != 'large') {\n lgMenu();\n // $('.hasSubMenu').stop().mouseenter(function() {\n // $(this).animate({\n // \"background\": 'white'},\n // 400, function() {\n // $(this).find('.divSubNavWrapper').show();\n // });\n\n // }).mouseleave(function(event) {\n // /* Act on the event */\n // $('.divSubNavWrapper').hide();\n // $(this).stop();\n // });\n } \n });\n\n\n \n\n function smMenu() {\n // since we may be switching from another menu, reset the menu first\n //unbind click and touch events \n $('.divMenuToggle').off('click');\n // $('.hasSubMenu').off('mouseenter mouseleave');\n // $('.topMenu h3').off('click touchstart');\n $('html').off('touchstart');\n $('.hasSubMenu a').off('click');\n $('#mainNav').off('touchstart');\n //reset the menu in case it's being resized from a medium screen \n // remove any expanded menus\n $('.expand').removeClass('expand');\n // $('.menuToggle').remove();\n //now that the menu is reset, add the toggle and reinitialize the indicator\n // $('.topMenu').before('<div class=\"menuToggle\"><a href=\"#\">menu<span class=\"indicator\">+</span></a></div>');\n // append the + indicator\n // $('.topMenu h3').append('<span class=\"indicator\">+</span>');\n \n // wire up clicks and changing the various menu states\n //we'll use clicks instead of touch in case a smaller screen has a pointer device\n //first, let's deal with the menu toggle\n // $('.menuToggle a').click(function() {\n // //expand the menu\n // $('.topMenu').toggleClass('expand');\n // // figure out whether the indicator should be changed to + or -\n // var newValue = $(this).find('span.indicator').text() == '+' ? '-' : '+';\n // // set the new value of the indicator\n // $(this).find('span.indicator').text(newValue);\n // });\n $('.divMenuToggle').click(function() {\n //expand the menu\n $('.ulPrimaryNav').toggleClass('expand');\n $(this).find('.spn1').toggleClass('spnLine1');\n $(this).find('.spn2').toggleClass('spnLine2').toggleClass('spnCross');\n // figure out whether the indicator should be changed to + or -\n // set the new value of the indicator\n // $(this).find('span.indicator').text(newValue);\n });\n\n\n \n\n\n $(\".hasSubMenu > a\").click(function(e) {\n e.preventDefault();\n //find the current submenu\n var currentItem = $(this).siblings('.divSubNavWrapper');\n //remove the expand class from other submenus to close any currently open submenus\n $('.divSubNavWrapper').not(currentItem).removeClass('expand');\n //change the indicator of any closed submenus\n //open the selected submenu\n if (currentItem.hasClass('expand')) {\n currentItem.removeClass('expand')\n } else {\n currentItem.addClass('expand')\n };\n // currentItem.toggleClass('expand');\n //change the selected submenu indicator\n });\n //indicate current window state\n windowState = 'small';\n }\n \n \n \n function lgMenu() {\n //largely what we'll do here is simple remove functionality that\n //may be left behind by other screen sizes\n //at this size the menu will function as a pure-css driven dropdown\n //advances in touch screen are beginning to make us re-think\n //this approach\n // unbind click and touch events \n // $('.menuToggle a').off('click');\n // $('.topMenu h3').off('click touchstart');\n $('html').off('touchstart');\n $('#mainNav').off('touchstart');\n \n // remove any expanded submenus\n $('.ulPrimaryNav').find('.hasSubMenu').removeClass('expand');\n \n // remove the span tags inside the menu\n // $('.topMenu h3').find('span.indicator').remove();\n \n // remove the \"menu\" element\n // $('.menuToggle').remove();\n\n \n\n $('.ulPrimaryNav').removeClass('expand');\n $('.divMenuToggle').find('.spn1').removeClass('spnLine1');\n $('.divMenuToggle').find('.spn2').removeClass('spnLine2').addClass('spnCross');\n \n // $('.hasSubMenu').stop().on('mouseenter', function(event) {\n // $(this).animate({\n // \"background\": 'white'},\n // 400, function() {\n // $(this).find('.divSubNavWrapper').show();\n // });\n // });\n // $('.hasSubMenu').stop().on('mouseleave', function(event) {\n // $('.divSubNavWrapper').hide();\n // $(this).stop();\n // });\n $('.hasSubMenu').stop().mouseenter(function() {\n $(this).animate({\n \"background\": 'white'},\n 400, function() {\n $(this).find('.divSubNavWrapper').show();\n });\n }).mouseleave(function(event) {\n /* Act on the event */\n $('.divSubNavWrapper').hide();\n $(this).stop();\n });\n //indicate current window state\n windowState = 'large';\n }\n}", "function setSubmenuStyles(submenu, maxHeight, margins) {\n submenu.style.maxHeight = maxHeight + 'px'\n submenu.style.marginTop = margins\n submenu.style.marginBottom = margins\n}", "addSubMenuListeners() {\n const items = this.querySelectorAll('cr-menu-item[sub-menu]');\n items.forEach((menuItem) => {\n const subMenuId = menuItem.getAttribute('sub-menu');\n if (subMenuId) {\n const subMenu = document.querySelector(subMenuId);\n if (subMenu) {\n this.showingEvents_.add(subMenu, 'activate', this);\n }\n }\n });\n }", "_init() {\n this.$element.find('[data-submenu]').not('.is-active').slideUp(0);//.find('a').css('padding-left', '1rem');\n this.$element.attr({\n 'role': 'menu',\n 'aria-multiselectable': this.options.multiOpen\n });\n\n this.$menuLinks = this.$element.find('.is-accordion-submenu-parent');\n this.$menuLinks.each(function(){\n var linkId = this.id || Foundation.GetYoDigits(6, 'acc-menu-link'),\n $elem = $(this),\n $sub = $elem.children('[data-submenu]'),\n subId = $sub[0].id || Foundation.GetYoDigits(6, 'acc-menu'),\n isActive = $sub.hasClass('is-active');\n $elem.attr({\n 'aria-controls': subId,\n 'aria-expanded': isActive,\n 'role': 'menuitem',\n 'id': linkId\n });\n $sub.attr({\n 'aria-labelledby': linkId,\n 'aria-hidden': !isActive,\n 'role': 'menu',\n 'id': subId\n });\n });\n var initPanes = this.$element.find('.is-active');\n if(initPanes.length){\n var _this = this;\n initPanes.each(function(){\n _this.down($(this));\n });\n }\n this._events();\n }", "changeMenuStyle () {\n let pageOffset = window.pageYOffset;\n let menuItem = 0;\n this.toHideSkills();\n if (pageOffset >= this.oOffsets['#home'] && pageOffset < this.oOffsets['#whoiam']) {\n menuItem = 0;\n } else if (pageOffset >= this.oOffsets['#whoiam'] && pageOffset < this.oOffsets['#workexperience']) {\n this.toShowSkills();\n menuItem = 1;\n } else if (pageOffset >= this.oOffsets['#workexperience'] && pageOffset < this.oOffsets['#aboutme']) {\n menuItem = 2;\n } else if (pageOffset >= this.oOffsets['#aboutme'] && pageOffset < this.oOffsets['#contact']) {\n menuItem = 3;\n } else {\n menuItem = 4;\n }\n\n if ( this.activate === true) {\n this.aMenuItems.forEach( \n (item) => item.classList.remove('active') \n )\n this.aMenuItems[menuItem].classList.add('active');\n }\n \n this.activate = true;\n }", "_setupSubmenus() {\n this._anchors.each((i, anchor) => {\n anchor = $(anchor);\n if (anchor.next('ul').length) {\n // prevent default behaviour (use link just to navigate)\n// \tlet anchorChild = anchor.children('a');\n// anchorChild.click(function (ev) {\n// ev.preventDefault();\n// });\n\n // add `before` and `after` text\n let anchorTitle = anchor.text();\n let anchorLink = anchor.attr('data-url');\n anchor.html('<a href=\"'+ anchorLink +'\">' + anchorTitle + '</a> <i class=\"fa fa-caret-right right_icon\"></i>');\n\n // add a back button\n if (this.options.showBackLink) {\n let backLink = $('<a href class=\"slide-menu-control mobile-nav__link mobile-nav__link--top-level\" data-action=\"back\">' + anchorTitle + '</a>');\n backLink.html('<i class=\"fa fa-caret-left left_icon\"></i>' + backLink.text() + this.options.backLinkAfter);\n anchor.next('ul').prepend($('<li>').append(backLink));\n }\n }\n });\n }", "rebuildMenuStart() {\n this._rebuildingMenu = true;\n this._rebuildingMenuRes = {};\n this._mainLabel = {};\n\n this.disconnectSignals(false);\n\n let oldItems = this.menu._getMenuItems();\n for (let item in oldItems){\n oldItems[item].destroy();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This funtion will choose random time this will animate the mole up and down
function popOut(){ //picking up random time const time= Math.random()*1300 +400; //this hole var is new and independent from above hole variable const hole = pickRandomHole(holes); //CSS will animate its child animate with class mole(.hole.up .mole) it will animate its top value from 0 to 100 hole.classList.add('up'); // this will make a mole to slice down at a random time setTimeout(function(){ hole.classList.remove('up'); //if time out is false call popout again, to show another mole at a different hole, which means if a person is able to hit the mole at a random time(calculated above) then call popout function again else end the game. if(!timeUp) popOut(); }, time); }
[ "function molePopUp() {\r\n // Generate a random time and hole div\r\n const time = randomInterval(200, 1000);\r\n const hole = randomHole(holes);\r\n // Pop the molue up on the selected hole\r\n hole.classList.add(\"up\");\r\n // Based on the random time\r\n // Remove the up class from the mole - and if time is not up\r\n // Keep running the function\r\n setTimeout(() => {\r\n hole.classList.remove(\"up\");\r\n if (!timeUp) molePopUp();\r\n // Stop our timer if the time is up\r\n if (timeUp) gameOver();\r\n }, time);\r\n}", "function randomMoleAppear() {\n var random = Math.floor(Math.random() * 10)\n\n $('.mole').eq(random).addClass('image')\n\n // mole timeout is set to 9ms, mole will disappear\n function removeMole() {\n $('.mole').eq(random).removeClass('image')\n }\n setTimeout(removeMole, 900)\n }", "function peep() {\n // Get a random time, passing min/max time.\n const time = randomTime(200, 1000);\n // Get a random 'hole' using all of the 'holes'.\n const hole = randomHole(holes);\n // Animate in the mole. Add a class to pop it up.\n hole.classList.add('up');\n // The time the mole spends popped up.\n setTimeout(() => {\n // Hide the mole. Remove the class that pops it up.\n hole.classList.remove('up');\n // If the time is not up, pop up another mole, peep().\n if (!timeUp) peep();\n }, time); // Duration, random 'time'.\n}", "function showMoles() {\n // Select random time and hole\n const time = randomTime(300, 1500);\n const hole = randomHole(holes);\n // Show the mole\n hole.classList.add('up');\n // Hide the mole after a certain amount of time\n setTimeout(() => {\n hole.classList.remove('up');\n // If not out of time, show another mole\n if (!timeDone) showMoles();\n }, time);\n}", "function play() {\n /* seconds variable determines how long the mole stays raised for.\n (any ms value from 0 to 500) */\n let seconds = Math.floor(Math.random()*1000) + 500;\n \n // first IF statement only fires when no moles have been raised yet\n if(moleToRaise == false) {\n moleToRaise = holes[getRandomInt(holes.length-1)];\n \n /* else if current mole hasn't been hovered over, lower it and raise another mole.\n then call play function again */\n } else {\n clearInterval(timer);\n moleToRaise.classList.remove(\"up\");\n moleToRaise = holes[getRandomInt(holes.length-1)];\n }\n moleToRaise.classList.add(\"up\");\n timer = setInterval(play, seconds);\n }", "function generateRandomSwim()\n\t\t{\n\t\t\tlet randomTimerDuration = RandomSwimInterval_Min + Math.floor((1 + RandomSwimInterval_Max - RandomSwimInterval_Min) * Math.random());\n\t\t\tcurrentRandomTimer = window.setTimeout(doRandomSwim, randomTimerDuration);\n\t\t} // end generateRandomSwim()", "function setDelay(i) {\r\n\r\n // random sequence of holes with an animate and sound of moles\r\n setTimeout(function() {\r\n var randomHole = Math.floor(Math.random() * 6);\r\n randomChosenHole = holeHumber[randomHole];\r\n animateMole(randomChosenHole);\r\n playSoundOfMole(randomChosenHole);\r\n click();\r\n }, i * 3000);\r\n\r\n // after the last appearance of moles for the restart of a game\r\n setTimeout(function() {\r\n startAgain();\r\n $(\"img\").remove();\r\n var lastAction = 55.458; // i(the bigger var i) + var coefficient(acceleration coefficient for the appearance of moles)\r\n }, 55.458 * 3000);\r\n\r\n}", "function animateMoles(){\n //check what moles were already moving in last frame and reschedule their movement in this frame\n molesState.forEach((state, id) => {\n if (state != 0) {\n switch(state){\n case 1: //mole is going up\n moveMole(id, 1);\n break;\n case -1: //mole is going down\n moveMole(id, -1);\n break;\n }\n }\n });\n}", "function makeDynamicTimeDigitMovement3() {\n\n // NOTE: makeDynamicTimeDigitMovement3 just OFFESTS RUNNERS immediately!\n\n // Offset time-digits immediately very rarely !\n var bOffsetImmediately = Math.random() > 0.99;\n\n if (bOffsetImmediately === true) {\n\n var shakeX;\n var shakeY;\n var rndDigitsOffsetX;\n var rndDigitsOffsetY;\n\n for (var i = 0; i < animGS.runners.length; i++) {\n\n shakeX = calcRndGenMinMax(0, animGS.startingTimeTopLeftOffset);\n shakeY = calcRndGenMinMax(0, animGS.startingTimeTopLeftOffset);\n\n rndDigitsOffsetX = shakeX * Math.random() * (Math.random() > Math.random() ? 1 : -1);\n rndDigitsOffsetY = shakeY * Math.random() * (Math.random() > Math.random() ? 1 : -1);\n\n animGS.runners[i].runnerX += rndDigitsOffsetX;\n animGS.runners[i].runnerY += rndDigitsOffsetY;\n }\n }\n\n return;\n }", "function moles_up() {\n\n const hole = random_hole(holes);\n\n // making the mole popping up by triggering the css file \"up\"\n hole.classList.add('up');\n\n // setting time for making the mole going down and disappearing\n setTimeout(() => {\n hole.classList.remove('up');\n // until the variable \"time_UP\" is false it will carry on\n if (!time_up) {\n\n moles_up();\n }\n\n }, interval);\n\n // update the user table timeout\n setTimeout(() => users_table(), 20500);\n\n // update the user score and saving it into the session store\n setTimeout(() => update_user_score(), 21000);\n}", "function animationLengthTime(){\n return Math.floor(Math.random() * (2000 - 1000) ) + 1000;\n}", "function popoutAvatar(){\nconst time = Math.random() * (800 - 400) + 400;\nconst hole = pickupRandomHole();\nhole.classList.add('up');\nsetTimeout(function(){\n if (!timeUp) popoutAvatar();\n hole.classList.remove('up');\n},time)\n}", "function moveMole() {\n // this runs the function \"randomSquare\" run every half second...\n timerId = setInterval(randomSquare, 500)\n}", "function frame() {\n\tlet firstTarget = createTarget();\n\trandomize(firstTarget);\n\tsetInterval(randomize, 950, firstTarget); //this is where I control the speed of the target\n\t// console.log(firstTarget);\n}", "function generateRandomMovement(){\n if (run == true){\n randomTime = Math.random();\n timeoutBetweenMovement = randomTime * 3000 + 2000; // so moveBomb runs bewteen 3-6s\n setTimeout(moveBomb, timeoutBetweenMovement);\n }\n}", "function show() {\n const time = randomTime(500, 1000); // .5 seconds and 1 second\n const hill = randomMoleHill(moleHills);\n hill.classList.add(\"pop\"); // add class of pop (and all of it's properties) to anything with a class of hill. This will allow the moles to come out of their hills.\n setTimeout(() => { // setTimeout is the function used to get the moles to go away. if setTimeout wasnt there, they moles would just stay out of their hills.\n hill.classList.remove(\"pop\"); // we remove the class of pop\n if (!timesUp) show(); // if time is not up then we will run show() again. If timesUp is true, we they will stop popping up\n }, time);\n }", "function peep() {\n const time = randomTime(300, 1000); // Get a random time between .3sec to 1sec\n const hole = randomHole(holes); // Get random hole\n\n hole.classList.add('up'); // Add a class \"up\" to the \"hole\" element in DOM\n\n // Set a timeout for the duration of moles popping up\n setTimeout(() => { \n hole.classList.remove('up'); // Remove class \"up\" from the \"hole\" element in DOM\n if(!timeUp) peep(); // If time is not done keep moles popping up\n }, time);\n}", "function bonusTimer() {\n $('.bonuses').append($('<div>').addClass('timer').css({\n left: Math.floor((Math.random() * 100) + 1) + '%',\n }))\n }", "function randomMushroom() {\n if (stopAutoMoveAnimate == false){\n let interval = randomIntInclusive(9,50)*100;\n // speed up mushroom\n if (score > 600) {\n // mushroomSpeed += score/5000;\n mushroomSpeed += 0.2\n if (mushroomSpeed >= 5){\n interval = randomIntInclusive(7,30)*100\n }\n if (score > 2000){\n interval = randomIntInclusive(7,18)*100\n }\n }\n console.log(mushroomSpeed)\n console.log(interval)\n setTimeout(function() {\n if (mushroomGo == true) {\n randomMushroom();\n mushroomTroup.push(new Mushroom(mushroomSpeed));\n }\n }, interval);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Definition for type : VelocityControllerRND
function VelocityControllerRND(name, root) { this.name = name; this.root = (root === null)? this : root; this.ready = false; this.bus = (root === null)? new EventEmitter() : this.root.bus; this.build(name); }
[ "get angularVelocity() {}", "get velocity() {}", "get targetVelocity() {}", "set targetVelocity(value) {}", "setVelocity(vel) {\r\n this.velocity = vel;\r\n }", "function VirtualActuator() {\r\n}", "addAngularVelocity (angularVelocity) {}", "get relativeVelocity() {}", "function Velocity(){\n\n\tvelocity = velocity + Acceleration()*deltatime;\n\t/*if(velocity > 0.0005 || throttle > 0.0){\n\t}\n\telse{\n\t\tvelocity = 0;\n\t}*/\n\n\treturn velocity;\n\n}", "constructor()\n {\n this.velocity = createVector(0, 0);\n this.position = createVector(width/2, height/2);\n }", "cmdVel() {\n return new ROSLIB.Topic({\n ros: this.socket,\n name: '/cmd_vel_mux/input/web',\n messageType: 'geometry_msgs/Twist'\n });\n }", "GetAngularVelocity() {\n return this.m_angularVelocity;\n }", "constructor() {\n this.position = { x: 100, y: 100 };\n this.velocity = { x: 10, y: 0 };\n }", "function RTcontroller()\n\t{\n\t\tvar $=this;\n\t\t$.state={ up:0,down:0,left:0,right:0,def:0,jump:0,att:0 };\n\t\t$.config=null;\n\t\t$.child=[];\n\t\t$.sync=true;\n\t\t$.seq=null;\n\t\t$.t=0;\n\t}", "change_velocity(value) {\n this.velocity += value\n }", "function Controller () {}", "setVelocity({ velocity: velocity }) {\n // Vectors are always copied when we don't want their value to be overwritten by a calculation.\n // This is an quirk of p5.Vector implementation.\n this._velocity = velocity.copy();\n }", "function getVelocity() {\n\t\treturn velocity;\n }", "updateVelocity() {\n\n\t\tconst diff = utils.calculateAngleBetweenDirections(this.targetedAngle, this.visibleAngle)\n\t\t\n\t\tthis.velocity = this.velocity * 0.5 + diff * 2\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to instanciate and setup PointerLockControls
function initControls() { controls = new THREE.PointerLockControls( camera, renderer.domElement); var geometry = new THREE.CircleBufferGeometry( 0.005, 32 ); var material = new THREE.MeshBasicMaterial( { color: 0xaaaaaa } ); reticle = new THREE.Mesh( geometry, material ); reticle.position.set( 0, 0, -1 ); // or whatever distance you want scene.add( controls.getObject() ); // required zwhen the camera has a child controls.getObject().add( reticle ); // add event listener to show/hide a UI (e.g. the game's menu) controls.addEventListener( 'lock', function () { if (loading) return; blocker.style.display = "none"; instructions.innerHTML = ""; } ); controls.addEventListener( 'unlock', function () { if (loading) return; blocker.style.display = "block"; instructions.innerHTML = "Paused"; } ); listenForPlayerMovement(); }
[ "function createPointerLockControls() {\n\n\t// create blocker and instruction divs\n\tjQuery('<div/>', {\n\t id: 'blocker',\n\t}).insertBefore('canvas');\n\n\tjQuery('<div id=\"instructions\"><span style=\"font-size:40px\">Click to play</span><br />(W, A, S, D = Move, SPACE = Jump, MOUSE = Look around)</div>', {\n\t}).appendTo('#blocker');\n\n\t// get blocker and instruction divs\n\tvar blocker = document.getElementById( 'blocker' );\n\tvar instructions = document.getElementById( 'instructions' );\n\n\t// PointerLock Requirements\n\tvar havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;\n\n\tif ( havePointerLock ) {\n\t\tvar element = document.body;\n\n\t\tvar pointerlockchange = function ( event ) {\n\n\t\t\tif ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) {\n\n\t\t\t\tGame.controlsEnabled = true;\n\t\t\t\tGame.controls.enabled = true;\n\t\t\t\tblocker.style.display = 'none';\n\n\t\t\t} else {\n\n\t\t\t\tGame.controlsEnabled = false;\n\t\t\t\tGame.controls.enabled = false;\n\t\t\t\tblocker.style.display = 'block';\n\t\t\t\tinstructions.style.display = '';\n\t\t\t}\n\n\t\t};\n\n\t\tvar pointerlockerror = function ( event ) {\n\t\t\tinstructions.style.display = '';\n\t\t};\n\n\t\t// Hook pointer lock state change events\n\t\tdocument.addEventListener( 'pointerlockchange', pointerlockchange, false );\n\t\tdocument.addEventListener( 'mozpointerlockchange', pointerlockchange, false );\n\t\tdocument.addEventListener( 'webkitpointerlockchange', pointerlockchange, false );\n\n\t\tdocument.addEventListener( 'pointerlockerror', pointerlockerror, false );\n\t\tdocument.addEventListener( 'mozpointerlockerror', pointerlockerror, false );\n\t\tdocument.addEventListener( 'webkitpointerlockerror', pointerlockerror, false );\n\n\t\tinstructions.addEventListener( 'click', function ( event ) {\n\n\t\t\tinstructions.style.display = 'none';\n\t\t\telement.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;\n\t\t\telement.requestPointerLock();\n\n\t\t}, false );\n\n\t} else {\n\n\t\tinstructions.innerHTML = 'Your browser doesn\\'t seem to support Pointer Lock API';\n\n\t}\n}", "function setupPointerLock() {\n\n // register the callback when a pointerlock event occurs\n document.addEventListener('pointerlockchange', changeCallback, false);\n document.addEventListener('mozpointerlockchange', changeCallback, false);\n document.addEventListener('webkitpointerlockchange', changeCallback, false);\n\n // when element is clicked, we're going to request a\n // pointerlock\n $(\"#pointerLock\").click(function () {\n var canvas = $(\"#pointerLock\").get()[0];\n canvas.requestPointerLock = canvas.requestPointerLock ||\n canvas.mozRequestPointerLock ||\n canvas.webkitRequestPointerLock;\n\n\n // Ask the browser to lock the pointer)\n canvas.requestPointerLock();\n });\n}", "function setPointerLock() {\n console.log(\"Attempted to lock pointer\");\n stage.requestPointerLock();\n }", "function InitLockElements( gs:GameState )\n{\n\tif( lockInsts.Count > 0 )\n\t\t// already done \n\t\treturn;\n\n\tvar lockPrefab = layout.FindElement('locked');\n\n\tif( lockPrefab == null )\n\t{\n\t\tDebug.LogError('Could not find locked layout element');\n\t\treturn;\n\t}\n\n\tvar lockSize = layout.GetElementSize( lockPrefab );\n\n\tfor( var i = 1; i < gs.GetNumSongs(); i++ )\n\t{\n\t\t// find the location of the song button\n\t\tvar songElm = layout.FindElement( 'Song'+(i+1) );\n\t\tif( songElm == null )\n\t\t\tDebug.LogError('could not find song'+(i+1) );\n\t\tvar topLeft = layout.GetElementTopLeft( songElm );\n\t\tvar pos = Vector3( topLeft.x + lockSize.x/2, topLeft.y - lockSize.y/2,\n\t\t\tlockPrefab.transform.position.z);\n\t\tvar inst = Instantiate( lockPrefab, pos, lockPrefab.transform.rotation );\n\t\tlockInsts.Add( inst );\n\t}\n}", "createLockWidget() {\n new Auth0Lock(\n AUTH_CONFIG.clientId,\n AUTH_CONFIG.domain,\n Object.assign(\n {\n rememberLastLogin: false,\n closable: false,\n container: 'preview'\n },\n this.mapEditOptionsToLockOptions()\n )\n ).show();\n }", "_InitLockedGate(){\n this._BuildBaseGate();\n this._baseGate.name = \"lock\";\n this._lockedGate.add(this._baseGate);\n //builds and positions the lock that appears with the game\n this._lock = this._GenerateLock();\n this._lock.position.y = 80;\n this._refractor = this._GenerateRefractivePlane();\n this._refractor.position.y = 400;\n\n this._lockedGate.add(this._lock);\n this._lockedGate.add(this._refractor);\n }", "function createControls() {\n controls = new OrbitControls(camera, container);\n}", "_onpointerlockchange() {\n this._pointerLocked = window.document.pointerLockElement === this.canvas;\n }", "initPointerState() {\n this.pointerState.node = null;\n this.pointerState.ctrl = false;\n this.pointerState.shift = false;\n this.pointerState.range = null;\n this.pointerState.primaryButton = true;\n }", "initMapControls() {\n // add controls\n const scalebar = this.createScaleBar();\n this.sidebar = this.createSidebar();\n this.map.addControl(this.sidebar);\n this.map.addControl(scalebar);\n }", "function setupLock() {\n var $lock = $(\"<div class = 'lock'></div>\"); // create the container\n // create 3 buttons and add them to the container\n for (let i = 0; i < 3; i++) {\n var $lockBtn = $(`<div class = 'lock-btn' id = 'lock-btn-${i}'>0</div>`);\n $lockBtn.click(changeCode); // connect function\n $lock.append($lockBtn);\n }\n $body.append($lock.hide()); // add it to the body and hide it\n}", "function InitLockElements()\n{\n\tif( lockInsts.length > 0 )\n\t\t// already done \n\t\treturn;\n\n\tvar lockPrefab = layout.FindElement('locked');\n\n\tif( lockPrefab == null )\n\t{\n\t\tDebug.LogError('Could not find locked layout element');\n\t\treturn;\n\t}\n\n\tvar lockSize = layout.GetElementSize( lockPrefab );\n\n\t// TEMP TEMP hard coding 4 stars, 5 levels\n\tfor( var i = 0; i < 5; i++ )\n\t{\n\t\t// find the location of the star\n\t\tvar starobj = layout.FindElement( 'level'+i );\n\t\tif( starobj == null )\n\t\t\tDebug.LogError('could not find level'+i );\n\t\t//var topLeft = layout.GetElementTopLeft( starobj );\n\t\t//var pos = Vector3( topLeft.x + lockSize.x/2, topLeft.y - lockSize.y/2,\n\t\t\t//lockPrefab.transform.position.z);\n\t\tvar pos = starobj.transform.position;\n\t\tpos.z -= 0.1;\t// make sure we're in front\n\t\tvar inst = Instantiate( lockPrefab, pos, lockPrefab.transform.rotation );\n\t\tlockInsts.Push( inst );\n\t}\n\n\t// hide the prefab\n\tlockPrefab.GetComponent(Renderer).enabled = false;\n}", "requestPointerLock() {\n if (this.pointerLockState === false) {\n return;\n }\n if (!window.engine || !window.engine.renderer) {\n return;\n }\n engine.renderer.domElement.requestPointerLock();\n }", "function setupControl() {\n // Create the DIV to hold the control and call the CenterControl()\n // constructor passing in this DIV.\n let centerControlDiv = document.createElement(\"div\");\n centerControlDiv.id = \"control-panel\";\n centerControlDiv.index = 1;\n map.controls[google.maps.ControlPosition.TOP_LEFT].push(centerControlDiv);\n\n // Create global controls\n currentControl = ShowControl(centerControlDiv, showAllMarkers, show_all_title);\n ShowControl(centerControlDiv, showFutureEvents, upcoming_only_title);\n\n toggleControlHighlight(null, currentControl);\n}", "requestPointerLock() {\n if (this.pointerLockState === false) {\n return;\n }\n if (!window.engine || !window.engine.renderer) {\n return;\n }\n engine.renderer.domElement.requestPointerLock();\n }", "static lockPointer() {\n const canvas = EngineToolbox.getCanvas();\n if (!canvas || document.pointerLockElement === canvas) {\n return;\n }\n document.addEventListener(\n \"pointerlockchange\",\n Input._lockChangeAlert,\n false\n );\n canvas.requestPointerLock();\n }", "setupControls() {\n let controls = {\n 'direction': {\n 'UP': 0,\n 'DOWN': 0,\n 'LEFT': 0,\n 'RIGHT': 0,\n 'BEARING': '',\n 'BEARING_LAST': '',\n 'DEGREES': 0,\n 'DEGREES_LAST': 0,\n 'TIMESTAMP': 0\n },\n 'direction_secondary': {\n 'UP': 0,\n 'DOWN': 0,\n 'LEFT': 0,\n 'RIGHT': 0,\n 'BEARING': '',\n 'DEGREES': 0,\n 'BEARING_LAST': '',\n 'DEGREES_LAST': 0,\n 'TIMESTAMP': 0\n },\n 'buttons': {},\n 'pointer': {\n 'M1': 0,\n 'M2': 0,\n 'M3': 0,\n 'M4': 0,\n 'M5': 0,\n 'BEARING': '',\n 'BEARING_DEGREES': 0,\n 'ANGLE': 0,\n 'TIMESTAMP': 0\n },\n 'position': {},\n 'interaction': {},\n 'gamepad': {},\n 'keys': {\n 'UP': [],\n 'DOWN': [],\n 'LEFT': [],\n 'RIGHT': [],\n }\n }\n for (let i=1; i<=16; i++) {\n controls.buttons['B'+i] = 0;\n controls.keys['B'+i] = [];\n }\n\n controls.interaction.buffer = '';\n controls.interaction.pressed = '';\n controls.interaction.last = '';\n controls.interaction.device = '';\n\n return controls;\n }", "function DWInitControls(){\n\tvar controls = null;\n\t//check if already created\n\tif (DW) {\n\t\tcontrols = DW.controls;\n\t\tif (!controls){\n\t\t\tcontrols = new DWControls;\n\t\t}\n\t\tDW.controls = controls;\n\t}\n}", "function connectControls() {\n wasdControl();\n touchControl();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
6. Creating another function called vehicle with age parameter
function vehicle(y, z, age) { let vehicleType; let vehicleAge; if (z === 1) { vehicleType = 'car'; } else if (z === 2) { vehicleType = 'motorbike'; } if (age === 0) { vehicleAge = 'new'; } else { vehicleAge = 'used'; } console.log("a " + y + " " + vehicleAge + " " + vehicleType); }
[ "function vehicule(age) {\r\n\r\n}", "function calculateDogAge(age){\n}", "function vehicle(color, code, age) {\r\n let vehicleAge = \"\";\r\n if (age > 1) { vehicleAge = \"used\"; } else { vehicleAge = \"new\"; }\r\n if (code === 1) {\r\n console.log(\"a\", color, vehicleAge, \"car\");\r\n }\r\n else if (code === 2) { console.log(\"a\", color, vehicleAge, \"motorbike\"); }\r\n else { console.log(\"This is not a vehicle\"); }\r\n}", "function calculateDogAge() {}", "function vehicle(blue, M, C, age) {\n return (blue + age + C)\n}", "function newVehicle(color, category, age) {\n if (age <= 4) {\n age = \"new\";\n } else {\n age = \"used\";\n }\n console.log(\"a \" + color + \" \" + age + \" \" + myListOfVehicles[3]);\n}", "function vehicle(age){\n return \"blue\"+age;\n}", "function vehicle(color,code,age){ \n \n if(code==1 && age <= 2){\n console.log (\"a new \" + color + \" car\");\n }else if ( code==1 && age > 2){\n console.log (\"a \" + color + \" used car\");\n }else if (code==2 && age<=2){\n console.log (\"a new \" + color + \" motorbike\") ; \n }else if ( code==2 && age > 2) {\n console.log(\"a \" + color + \" used motorbike\")\n }else if (code==3 && age<=2){\n console.log (\"a new \" + color + \" bike\") ; \n }else if ( code==3 && age > 2) {\n console.log(\"a \" + color + \" used bike\")\n } else {\n console.log (\"the code must be 1 or 2\");\n }\n }", "function vehicle(color, code, age) {\r\n if (code === 1 && age === 5) {\r\n console.log(\"a\", color, \"used car\");\r\n } else if (code === 2 && age === 0) {\r\n console.log(\"a\", color, \"motorbike\")\r\n\r\n }\r\n}", "function vehicle(color, code, age) {\n if (code === 1 && age === 0) {\n console.log(\"a \", color, \" new motorbike\");\n } else if (code === 1 && age !== 0) {\n console.log(\"a \", color, \" used motorbike\");\n } else if (code === 2 && age === 0) {\n console.log(\"a \", color, \" new car\");\n } else {\n console.log(\"a \", color, \" used car \");\n }\n}", "function vehicle(color, code, age) {\n if (code === 1) {\n if (age >= 5) {\n return console.log(\"a \", color, \" used car\");\n } else {\n return console.log(\"a \", color, \" recent car\");\n } \n } else {\n return console.log(\"a \", color, \" motorbike\")\n };\n}", "function getDogAge(age){\n return age * 7;\n}", "function getAge() {\n return 24;\n}", "function yearsUntilRetirement (year,name){\n var age = myAge (year);\n var retirementAge = 67 - age;\n console.log( name + ' ' + ' will retire in' + ' ' + retirementAge +' ' + 'years time' )\n }", "function retirement(retirementAge) {\n var a = ' years until retirement';\n return function (yearOfBirth) {\n var age = 2016 - yearOfBirth;\n console.log(retirementAge - age + a);\n }\n}", "function ageCalc(birthYear) {\n age = 2019 - birthYear;\n return age;\n}", "function Person(initialAge){\n // Add some more code to run some checks on initialAge\n if(initialAge<0){\n console.log(\"Age is not valid, setting age to 0.\")\n this.age=0;\n }else{\n this.age=initialAge; \n }\n this.amIOld=function(){\n // Do some computations in here and print out the correct statement to the console\n if(this.age<13){\n console.log(\"You are young.\")\n }else if(this.age>17){\n console.log(\"You are old.\")\n }else{\n console.log(\"You are a teenager. \")\n }\n\n };\n this.yearPasses=function(){\n // Increment the age of the person in here\n this.age++; \n };\n}", "function calculateAge(personName){\n var currentYear = 2018;\n return currentYear - personName.birthYear; \n}", "function Person(initialAge) {\n this.age = initialAge\n // Add some more code to run some checks on initialAge\n if(initialAge <= 0) {\n console.log(\"Age is not valid, setting age to 0.\")\n this.age = 0 \n }\n this.amIOld = function() {\n // Do some computations in here and print out the correct statement to the console\n if (this.age >= 18) {\n console.log(\"You are old.\");\n } else if (this.age >= 13 && this.age < 18) {\n console.log(\"You are a teenager.\");\n } else if (this.age < 13) {\n console.log(\"You are young.\");\n }\n };\n this.yearPasses = function() {\n this.age++;\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Below function calls all relevant functions when a user clicks a card, thus making a move
function makeMove(){ $(".card").click(function(e){ showCardSymbol($(e.target)); addToCardCheck($(e.target)); if (cardCheck.length === 2) { checkMatches(); } congratsMessage(); }); }
[ "function turnCard(e){\n // store the moves element in a variable\n let clickedCard = e.target;\n if (clickedCard.classList.contains('card')) {\n if (clickedCard.className === \"card open show\") {\n moves -= 1;\n }\n if (firstClick) {\n stopwatch.start();\n firstClick = false;\n }\n if (openCards.length >= 1) {\n moves++;\n movesCounter.innerText = `${moves} moves`;\n }\n }\n if (clickedCard.classList.contains('hide') && openCards.length<2) {\n clickedCard.className = 'card open show';\n openCards.push(clickedCard);\n }\n if (openCards.length == 2 && openCards !== \"undefined\"){\n match();\n }\n}", "function cardClick() {\n\tif (clickedCards.length === 2 || matchedCards.includes(this.id)) {\n\t\treturn;\n\t}\n\tif(clickedCards.length === 0 || this.id != clickedCards[0].id){\n\n\t\tif(timeTrigger){\n\t\t\ttimerStart();\n\t\t\ttimeTrigger = false;\n\t\t}\n\t\tthis.classList.add('show', 'open');\n\t\tclickedCards.push(event.target);\n\t\tdetermineAction();\n\t}\n\telse {\n\t\treturn;\n\t}\n\tsetRating(moves);\n}", "function handleCardClick() {\n cardClickBehaviour(this);\n }", "function moveCardToTableau(pile, event) { //tableau pile \r\n if (!isSelected) { //isSelected == false\r\n // can only select cards from the tableau and talon\r\n if (\r\n pile.classList.contains(\"tableau-pile\") ||\r\n pile.classList.contains(\"talon-pile\")\r\n ) {\r\n var card = event.target; //card div\r\n if (card && card.classList.contains(\"up\")) {\r\n card.classList.add(\"selected\");\r\n var cardSiblings = findSiblings(card);\r\n for (i = 0; i < cardSiblings.length; i++) {\r\n cardSiblings[i].classList.add(\"selected\");\r\n }\r\n isSelected = true;\r\n }\r\n }\r\n } else {\r\n var cardsSelected = document.querySelectorAll(\".card.selected\"); // source find by .selected\r\n var cardDestination = pile.lastChild; // dest card found by when this card clicked\r\n // find parent pile of the first selected card\r\n var parentPile = cardsSelected[0].closest(\".tableau-pile,.talon-pile\");\r\n // console.log(cardsSelected, parentPile);\r\n var validMove = false;\r\n\r\n if (pile.classList.contains(\"tableau-pile\")) {\r\n validMove = validTableauMove(cardsSelected[0], cardDestination);\r\n } \r\n else if (pile.classList.contains(\"foundations-pile\")) {\r\n // Check foundation pile of the correct suit, despite which foundation pile is clicked\r\n pile = document.querySelector(\r\n \".pile.foundations-pile.\" + cardsSelected[0].getAttribute(\"data-suit\")\r\n ); //finding type of suit in pile \r\n cardDestination = pile.lastChild;\r\n validMove = validFoundationMove(cardsSelected[0], cardDestination);\r\n } else {\r\n // invalid move\r\n // console.log('invalid move')\r\n // TODO: possible error feedback (red flash/sound, etc)\r\n }\r\n\r\n \r\n if (validMove) {\r\n // Score 10 points when moving to a foundation\r\n if(pile.classList.contains(\"foundations-pile\")) {\r\n addToScore(SCOREFOUNDATION);\r\n }\r\n\r\n // Score 5 points when moving from the talon pile\r\n if(parentPile.classList.contains(\"talon-pile\")) {\r\n addToScore(SCORETALON);\r\n }\r\n\r\n // remove cardSelected from the old parent pile\r\n for (i = 0; i < cardsSelected.length; i++) {\r\n parentPile.removeChild(cardsSelected[i]);\r\n }\r\n // open the last card left in that pile (if any)\r\n if (parentPile.lastChild) {\r\n if(!parentPile.lastChild.classList.contains(\"up\")) {\r\n // New card turned face up, add 5 to score\r\n addToScore(SCORETABLEAU);\r\n }\r\n parentPile.lastChild.classList.add(\"up\");\r\n }\r\n // add cardSelected to the end of the new pile\r\n for (i = 0; i < cardsSelected.length; i++) {\r\n pile.appendChild(cardsSelected[i]);\r\n }\r\n }\r\n clearSelected();\r\n }\r\n}", "cardSelected(cardPos,row){\n //let c=null;\n if(cardPos==\"\"){//A face down card was clicked on\n this.solview.displayMessage(\"That card is currently not flipped up\");\n return;\n }\n \n let card=null;\n //alert(\"cardpos=\"+cardPos);\n if(cardPos==\"empty\"){\n card = new Card(\"s\",\"k\");\n }\n else{\n card=this.find(cardPos,row);\n }\n //let card=this.find(cardPos,row);\n if(card==null){//Null card error\n this.solview.displayMessage(\"Error cannot find chosen card\")\n return;\n }\n else{\n if(!this.placing){\n let value=0;\n let j=0;\n //Find pos of card to make changes to selected row\n if(row==\"row1\"){\n for(var i =cardPos; i<this.row1.length; i++){\n j=++i;\n i--;\n if(i==this.row1.length-1){\n break;\n }\n if(this.row1[i].getSValue() != +this.row1[j].getSValue() + +1){\n alert(\"Move fail\");\n this.solview.displayMessage(\"That card cannot be moved\");\n return;\n }\n }\n }\n else if(row==\"row2\"){\n for(var i =cardPos; i<this.row2.length; i++){\n j=++i;\n i--;\n if(i==this.row2.length-1){\n break;\n }\n if(this.row2[i].getSValue() != +this.row2[j].getSValue() + +1){\n alert(\"Move fail\");\n this.solview.displayMessage(\"That card cannot be moved\");\n return;\n }\n }\n }\n else if(row==\"row3\"){\n for(var i =cardPos; i<this.row3.length; i++){\n j=++i;\n i--;\n if(i==this.row3.length-1){\n break;\n }\n if(this.row3[i].getSValue() != +this.row3[j].getSValue() + +1){\n alert(\"Move fail\");\n this.solview.displayMessage(\"That card cannot be moved\");\n return;\n }\n }\n }\n else if(row==\"row4\"){\n for(var i =cardPos; i<this.row4.length; i++){\n j=++i;\n i--;\n if(i==this.row4.length-1){\n break;\n }\n if(this.row4[i].getSValue() != +this.row4[j].getSValue() + +1){\n alert(\"Move fail\");\n this.solview.displayMessage(\"That card cannot be moved\");\n return;\n }\n }\n }\n else if(row==\"row5\"){\n for(var i =cardPos; i<this.row5.length; i++){\n j=++i;\n i--;\n if(i==this.row5.length-1){\n break;\n }\n if(this.row5[i].getSValue() != +this.row5[j].getSValue() + +1){\n alert(\"Move fail\");\n this.solview.displayMessage(\"That card cannot be moved\");\n return;\n }\n }\n }\n else if(row==\"row6\"){\n for(var i =cardPos; i<this.row6.length; i++){\n j=++i;\n i--;\n if(i==this.row6.length-1){\n break;\n }\n if(this.row6[i].getSValue() != +this.row6[j].getSValue() + +1){\n alert(\"Move fail\");\n this.solview.displayMessage(\"That card cannot be moved\");\n return;\n }\n }\n }\n \n this.actionRow=row\n this.placing=true;\n this.actionPos=cardPos;\n this.solview.displayMessage(\"Select row to place cards at\");\n \n return;\n }else{\n /*\n * Section for determining if the move is legal\n * \n */\n //Boolean to determine if we are making a legal move currently false for testing\n let movable=false;\n let value=card.getSValue();\n \n if(cardPos==\"empty\"){\n movable=true;\n }\n else{\n //Run checks to make sure the move that we are making is legal\n if(this.actionRow==\"row1\"){\n if(this.row1[this.actionPos].getSValue() == (+card.getSValue() - +1)){movable=true;}else{movable=false;}\n }\n else if(this.actionRow==\"row2\"){\n if(this.row2[this.actionPos].getSValue() == (+card.getSValue() - +1)){movable=true;}else{movable=false;}\n }\n else if(this.actionRow==\"row3\"){\n if(this.row3[this.actionPos].getSValue() == (+card.getSValue() - +1)){movable=true;}else{movable=false;}\n }\n else if(this.actionRow==\"row4\"){\n if(this.row4[this.actionPos].getSValue() == (+card.getSValue() - +1)){movable=true;}else{movable=false;}\n }\n else if(this.actionRow==\"row5\"){\n if(this.row5[this.actionPos].getSValue() == (+card.getSValue() - +1)){movable=true;}else{movable=false;}\n }\n else if(this.actionRow==\"row6\"){\n if(this.row6[this.actionPos].getSValue() == (+card.getSValue() - +1) ){movable=true;}else{movable=false;}\n } \n }\n \n if(!movable){//if the move that we are making is not legal\n this.solview.displayMessage(\"Illeagal move select cards to move again\");\n this.actionRow=null;\n this.actionPos=-1;\n this.placing=false;\n return;\n }\n \n let mrow=new Array();\n \n if(this.actionRow==\"row1\"){\n for(var i=this.actionPos; i<this.row1.length; i++){\n mrow.push(this.row1[i]);\n //this.solview.addCard(this.row1[i],row);\n //this.solview.removeCard(this.row1[i],this.actionRow);\n }\n this.row1.splice(this.actionPos);\n this.solview.displayRow(this.row1, 1);\n }else if(this.actionRow==\"row2\"){\n for(var i=this.actionPos; i<this.row2.length; i++){\n mrow.push(this.row2[i]);\n //this.solview.removeCard(this.row2[i],this.actionRow);\n }\n this.row2.splice(this.actionPos);\n this.solview.displayRow(this.row2, 2);\n }else if(this.actionRow==\"row3\"){\n for(var i=this.actionPos; i<this.row3.length; i++){\n mrow.push(this.row3[i]);\n //this.solview.removeCard(this.row3[i],this.actionRow);\n }\n this.row3.splice(this.actionPos);\n this.solview.displayRow(this.row3, 3);\n }else if(this.actionRow==\"row4\"){\n for(var i=this.actionPos; i<this.row4.length; i++){\n mrow.push(this.row4[i]);\n //this.solview.removeCard(this.row4[i],this.actionRow);\n }\n this.row4.splice(this.actionPos);\n this.solview.displayRow(this.row4, 4);\n }else if(this.actionRow==\"row5\"){\n for(var i=this.actionPos; i<this.row5.length; i++){\n mrow.push(this.row5[i]);\n // this.solview.removeCard(this.row5[i],this.actionRow);\n }\n this.row5.splice(this.actionPos);\n this.solview.displayRow(this.row5, 5);\n }else if(this.actionRow==\"row6\"){\n for(var i=this.actionPos; i<this.row6.length; i++){\n mrow.push(this.row6[i]);\n //this.solview.removeCard(this.row6[i],this.actionRow);\n }\n this.row6.splice(this.actionPos);\n this.solview.displayRow(this.row6, 6);\n }\n \n if(row==\"row1\"){\n for(var i=0; i<mrow.length; i++){\n this.row1.push(mrow[i]);\n this.solview.addCard(mrow[i],row);\n }\n }\n if(row==\"row2\"){\n for(var i=0; i<mrow.length; i++){\n this.row2.push(mrow[i]);\n this.solview.addCard(mrow[i],row);\n }\n }\n if(row==\"row3\"){\n for(var i=0; i<mrow.length; i++){\n this.row3.push(mrow[i]);\n this.solview.addCard(mrow[i],row);\n }\n }\n if(row==\"row4\"){\n for(var i=0; i<mrow.length; i++){\n this.row4.push(mrow[i]);\n this.solview.addCard(mrow[i],row);\n }\n }\n if(row==\"row5\"){\n for(var i=0; i<mrow.length; i++){\n this.row5.push(mrow[i]);\n this.solview.addCard(mrow[i],row);\n }\n }\n if(row==\"row6\"){\n for(var i=0; i<mrow.length; i++){\n this.row6.push(mrow[i]);\n this.solview.addCard(mrow[i],row);\n }\n }\n \n \n setTimeout(()=>{\n this.checkFlips();\n this.actionRow=null;\n this.placing=false;\n if(this.row1.length>=13){this.removeCards(this.row1);}\n if(this.row2.length>=13){this.removeCards(this.row2);}\n if(this.row3.length>=13){this.removeCards(this.row3);}\n if(this.row4.length>=13){this.removeCards(this.row4);}\n if(this.row5.length>=13){this.removeCards(this.row5);}\n if(this.row6.length>=13){this.removeCards(this.row6);}\n \n if(this.checkWin()){\n this.solview.displayMessage(\"Congratulations you cleared all the cards!!!\");\n }\n else{\n this.solview.displayMessage(\"Select cards to have moved\");\n \n this.solview.displayRow(this.row1, 1);\n this.solview.displayRow(this.row2, 2);\n this.solview.displayRow(this.row3, 3);\n this.solview.displayRow(this.row4, 4);\n this.solview.displayRow(this.row5, 5);\n this.solview.displayRow(this.row6, 6); \n }\n },1800);\n\n \n }\n }\n \n return;\n }", "cardOnClickEvent(card, e) {\n // [TODO] Introduce a dialogue window to allow players to choose which action\n // they'd like to use the card for (bank it, play it)\n switch (card.type) {\n case \"money\":\n this.game.network.moveCardFromHandToBank(card);\n break;\n case \"property\":\n this.game.network.moveCardFromHandToProperties(card);\n break;\n case \"action\":\n this.game.network.moveCardFromHandToDiscard(card);\n break;\n }\n }", "function Card_OnClick(e, args)\n\t{\t\n\t\tselectedcard = GameScene.items[ArrayFindIndexByName(GameScene.items, args[0])];\n\n\t\t//can't select after 2 are in use\n\t\tif (numcardsselected >= 2)\n\t\t\treturn;\n\t\t//can't select same card twice\n\t\tif (selectedcard == lastselectedcard)\n\t\t\treturn;\n\n\t\tif (selectedcard.IsFront == false)\n\t\t\tselectedcard.IsFront = true;\n\t\t\t\n\t\tUpdateCardDrawingList(selectedcard);\n\t\tnumcardsselected ++;\n\t\tif (numcardsselected == 1)\n\t\t{\n\t\t\tlastselectedcard = selectedcard;\n\t\t}\n\t\tif (numcardsselected == 2)\n\t\t{\n\t\t\t//pause inputs until lose/win animations are done\n\t\t\tMouseInputPaused = true;\n\t\t\t\n\t\t\tif (selectedcard.cardvalue == lastselectedcard.cardvalue)\n\t\t\t{\n\t\t\t\tAddCardWinGraphic(selectedcard);\n\t\t\t\tAddCardWinGraphic(lastselectedcard);\n\t\t\t\tsetTimeout(\"ClearMatchCardAnimation(true)\", CLEARCARDANIMATION_TIMEOUT);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsetTimeout(\"ClearMatchCardAnimation(false)\", CLEARCARDANIMATION_TIMEOUT);\n\t\t\t}\n\t\t}\n\t}", "function manipulateCard(event) {\n\t// Check if there is any card already clicked\n\tif (firstClickedElement === null){\n\n\t\t// No card clicked yet => store its value (class) into firstCard variable\n\t\tfirstCard = event.target.lastElementChild.getAttribute('class');\n\n\t\t// Show the card\n\t\tshowCard(event);\n\n\t\t// Get the element of the first clicked card\n\t\tfirstClickedElement = document.querySelector('.clicked');\n\n\t} else if (firstCard === event.target.lastElementChild.getAttribute('class')) {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Since 2nd card matches the first one => change cards status to \"card match\" (both cards remain with their face up) -> with a short delay\n\t\tchangeCardsStatus(event, 'card match');\n\n\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\tother2Cards();\n\t\t\n\t\t// Increase number of matched cards\n\t\tcellNo = cellNo + 2;\n\n\t} else {\n\t\t// Show the second clicked card\n\t\tshowCard(event);\n\n\t\t// Set the 2 clicked cards attributes to wrong class -> with a short delay\n\t\tchangeCardsStatus(event, 'card open show wrong');\n\n\t\t// Set the 2 clicked cards attributes to its defaults -> with a short delay\n\t\tsetTimeout(function(){\n\t\t\tchangeCardsStatus(event, 'card');\n\n\t\t\t// Reinitialize to null (a new pair of clicks begins)\n\t\t\tother2Cards();\n\t\t}, 300);\n\t}\n}", "function cardClick() {\n deck.find('.card').on('click', function () {\n //Ignores and exits if it already has the show or matched class\n if ($(this).hasClass('show') || $(this).hasClass('match')) {\n return true;\n }\n\n //Capture html for icon and add open show class to show selected card\n let card = \"\";\n card = $(this).html();\n $(this).addClass('open show');\n\n //Adding element to array object \n cards_select.push(card);\n\n //Verify selection\n if (cards_select.length > 1) {\n\n //Successful or Unsuccessful\n if (card === cards_select[0] && cards_select.length === 2) {\n setTimeout(function () {\n deck.find('.open').addClass('open show match');\n }, wait / 2);\n match++;\n } else {\n setTimeout(function () {\n deck.find('.open').removeClass('open show');\n }, wait / 2);\n }\n cards_select = [];\n num_move++;\n starRating(num_move);\n moves.html(num_move);\n }\n\n //Match all the cards to win the game\n if (match_total === match) {\n cards_select = [];\n match = 0;\n starRating(num_move);\n setTimeout(function () {\n gameWon(num_move, final_score);\n });\n }\n });\n }", "function cardClicked(evt){\n //Checks whether the user has clicked a card\n if(evt.target.className == 'card')\n {\n score += 1;\n scoreCard.innerText = score.toString();\n // Changing from moves to move for the first move\n if(score == 1){\n \n scoreCard.nextSibling.textContent = \" Move\";\n }\n else{\n scoreCard.nextSibling.textContent = \" Moves\";\n }\n // Setting the card information to the variable card1\n if (!card1){\n card1 = evt.target;\n card1.classList.add('show');\n card1.classList.add('open');\n }\n // Setting the card information to the variable card2 when there is any card opened\n else{\n card2 = evt.target;\n card2.classList.add('show');\n card2.classList.add('open');\n }\n // Checking the logic only when the two cards are opened\n if(card1&&card2)\n { \n // Checking whether the two cards have the same symbol\n // Incrementing the successMoves counter\n if(card1.firstChild.className == card2.firstChild.className){\n successMoves += 1;\n card1.classList.remove('open');\n card1.classList.add('match');\n card2.classList.remove('open');\n card2.classList.add('match'); \n card1 = null;\n card2 = null; \n }\n // Incrementing the unsuccessMoves coutnter\n // Executes when the two cards are not matched\n else{\n unsuccessMoves += 1;\n setTimeout(function(){\n card1.classList.remove('open', 'show');\n card2.classList.remove('open', 'show');\n card1 = null;\n card2 = null;\n }, 200);\n }\n } \n }\n displayRating(successMoves, unsuccessMoves); \n}", "function move_card(direction){\n\n $( \".card_row\" ).removeClass( \"slide_up_fade_2\" ).removeAttr( \"data-check-visibility\" );\n\n if ( direction == \"right\" ){\n\n // move right\n // toggle right\n $( \"._on_card\" ).removeClass( \"_on_card\" ).next().addClass( \"_on_card\" ).prev().prev().insertAfter( \"._on_card\" );\n\n $( \"._on_tab\" ).removeClass( \"_on_tab\" ).next().addClass( \"_on_tab\" ).prev().prev().insertAfter( \"._on_tab\" );\n\n\n } if ( direction == \"left\" ){\n\n // move left\n $( \"._on_card\" ).removeClass( \"_on_card\" ).prev().addClass( \"_on_card\" ).next().next().insertBefore( \"._on_card\" );\n\n\n $( \"._on_tab\" ).removeClass( \"_on_tab\" ).prev().addClass( \"_on_tab\" ).next().next().insertBefore( \"._on_tab\" );\n\n }\n\n\n\n\n\n} // end of move_card", "function cardClick() {\n if(running){\n if(!this.classList.contains(\"open\")) {\n flipCard(this);\n openCards.push(this);\n }\n if(openCards.length === numInSets) {\n updateMoves();\n if(cardsMatch(openCards)) {\n matched();\n }\n else {\n setTimeout(noMatch, 800);\n running = false; // no selecting cards until the current set flips back over\n }\n }\n }\n}", "bindCardActions() {\n this.cards.forEach((card) => {\n card.addEventListener('click', this.triggerMove);\n });\n }", "function bindClickEvent() {\n cardDeck.cards.forEach(card => {\n card.node.addEventListener(\"click\", (e) => {\n if (isClosingCard || card.isOpened() || card.isMatched()) {\n return;\n }\n \n card.open();\n \n if (state.isMatching) {\n if (state.matchingCard.getValue() === card.getValue()) {\n \n card.match()\n state.matchingCard.match();\n \n if (cardDeck.cards.filter(x => x.isMatched()).length === cardDeck.cards.length) {\n state.isGameOver = true;\n saveState();\n updateScreenMode(true);\n return;\n }\n \n state.isMatching = false;\n state.matchingCard = null;\n increaseMoveCounter();\n saveState();\n } else {\n isClosingCard = true;\n window.setTimeout(function() {\n card.closeCard()\n if (state.matchingCard !== null) {\n state.matchingCard.closeCard()\n }\n \n increaseMoveCounter();\n \n state.isMatching = false;\n state.matchingCard = null;\n saveState();\n isClosingCard = false;\n }, 500);\n }\n } else {\n state.isMatching = true;\n state.matchingCard = card;\n saveState();\n }\n }, false);\n });\n }", "function cardPressed(event){\n var i = event.target.i;\n\n\t if (frontCards[i].alpha == 0)\n\t return;\n\n if(baseGame.isGameActive()){\n\n if(cards[i].done == false){\n\n\t baseGame.setGameActive(false);\n\n frontCards[i].alpha = 0;\n cards[i].alpha = 1;\n whiteCards[i].alpha = 1;\n\n var bigScale = cards[i].defaultScaleX + 0.1*cards[i].defaultScaleX;\n var normalScale = cards[i].defaultScaleX;\n\n cards[i].scaleX = 0.5*normalScale;\n cards[i].scaleY = 0.5*normalScale;\n\n Tween.get(cards[i]).to({scaleX:bigScale},150).play(Tween.get(cards[i]).to({scaleY:bigScale},150));\n Tween.get(items[i]).wait(150).call(function(){\n Tween.get(cards[i]).to({scaleX:normalScale},50).play(Tween.get(cards[i]).to({scaleY:normalScale},50));\n });\n\n\t\t\t\tif(click == 0){\n click = 1;\n\t\t\t\t\tpreviousItem = i;\n\t\t\t\t\tif(newXML.items[i].getSound() != \"\"){\n\t\t\t\t\t\tPFSound.playWithCallback(\"sound\"+i,function() {\n\t\t\t\t\t\t\tbaseGame.setGameActive(true);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbaseGame.setGameActive(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tclick = 0;\n\t\t\t\t\tif(cards[previousItem].identifier == cards[i].identifier && previousItem != i){\n\t\t\t\t\t\t//Play card sound\n\t\t\t\t\t\tcards[i].done = true;\n\t\t\t\t\t\tcards[previousItem].done = true;\n\n\t\t\t\t\t\tif (newXML.items[i].getSound2() != \"\") {\n\t\t\t\t\t\t\tPFSound.playWithCallback(\"sound2\"+i,function() {\n\t\t\t\t\t\t\t\tplayOkSound(function() {\n\t\t\t\t\t\t\t\t\tcheckEndGame(folder);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayOkSound(function() {\n\t\t\t\t\t\t\t\tcheckEndGame(folder);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t//Play wrong sound\n\t\t\t\t\t\tplayWrongSound(function() {\n\t\t\t\t\t\t\tTween.get(items[i]).wait(5).call(function(){\n\t\t\t\t\t\t\t\thideCards(i);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n }\n }\n }", "function clickOn() {\n openedCards[0].click(cardToggle);\n}", "triggerMove() {\n const cardIsHidden = !this.classList.contains('open');\n\n if (cardIsHidden) {\n if (isTheFirstMove() === 'true') initGameCounters();\n CardActions.pickCard(this);\n CardActions.compareCards();\n }\n }", "function placeCard() {}", "function cardActions(clickTrackerObject,currentCard,counterObject){\n if(clickTrackerObject.clickNumber===0){\n actionFirstCardPick(currentCard, clickTrackerObject);\n }\n\n else if(clickTrackerObject.clickNumber===1){\n\n if(currentCard.classList.contains(clickTrackerObject.card.classList[0])&& currentCard!==clickTrackerObject.card){\n actionCardMatch(currentCard,clickTrackerObject,counterObject);\n }\n else {\n actionCardMismatch(currentCard,clickTrackerObject);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function animates the icon container element for the navbar it takes a direction as an arguement to dictate if the animation is adding or removing the element
animateIcons(direction){ if(direction === "in"){ const navIcons = document.getElementById("nav_icons"); navIcons.classList.remove("hide_icons"); navIcons.classList.add("reveal_icons"); } else{ const navIcons = document.getElementById("nav_icons"); navIcons.classList.remove("reveal_icons"); navIcons.classList.add("hide_icons"); } }
[ "function mobileNavAni() {\n $(\"#mobileNav\").slideDown();\n $(\"#menuClick\").css(\"visibility\", \"hidden\");\n $(\"#icon1\").animate({\n right: \"50%\",\n \"margin-right\": \"115px\",\n top: mobileTop\n }, 1000);\n $(\"#icon2\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"45px\"\n }, 1100);\n $(\"#icon3\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"-25px\"\n }, 1150);\n $(\"#icon4\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"-95px\"\n }, 1250);\n $(\"#icon5\").animate({\n right: \"50%\",\n top: mobileTop,\n \"margin-right\": \"-165px\"\n }, 1350);\n }", "animateElements(direction){\n if(direction === \"in\"){\n this.animateName(\"in\");\n this.animatePicture(\"in\");\n this.animateIcons(\"in\");\n this.animateLinks(\"in\");\n this.animateArrow(\"in\");\n }\n else{\n this.animateName();\n this.animatePicture();\n this.animateIcons();\n this.animateLinks();\n this.animateArrow();\n }\n }", "function addClass(){\n navbar.classList.toggle('active');\n //Changing the icon by following the conditions above.\n if(navbar.classList != 'navbar'){\n icon.className = 'fas fa-times';\n }\n else{\n icon.className = 'fas fa-bars';\n }\n}", "function removeNavigation() {\n $imNext.stop().animate({right: '-50px'}, 300);\n $imPrev.stop().animate({left: '-50px'}, 300);\n }", "function add_navigation(){\r\n\t\tif(list_elem_count==0){\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tvar icon_markup2 = '<div class=\"icon2\" id=\"icon_wrapper\"><svg x=\"0px\" y=\"0px\" width=\"24.3px\" height=\"23.2px\" viewBox=\"0 0 24.3 23.2\" enable-background=\"new 0 0 24.3 23.2\" xml:space=\"preserve\"><polygon class=\"arrow\" fill=\"#ffffff\" points=\"'+ svg_arrow_icon +'\"></svg></div>';\r\n\t\t\r\n $('#2nav .vertab').after(icon_markup2);\r\n $('#2nav .icon2').eq(0).addClass('current_nav');\r\n\t}", "function animateMenuHeader() {\n $('.animMe').delay(400)\n .queue(function (goNext) {\n $(this).css({\n 'padding-right':'4rem'\n\n });\n goNext()\n }\n );\n }", "function initElementsAnimation() {\n if ($(\".animated\").length > 0) {\n $(\".animated\").each(function() {\n var $this = $(this);\n $this.appear(function() {\n $this.addClass(\"go\");\n }, {\n accX: 0,\n accY: -200\n });\n })\n };\n}", "function animation() {\n\n if (Npos == 60) { // une fois atteint la hauteur souhaitée,\n clearInterval(Nrun); // arrêt du Nrun, donc de l'appel de animation\n }\n else { // tant que la hauteur souhaitée n'est pas atteinte\n Npos = Npos+6; // la variable augment de 6px\n Nopacity = Nopacity + 0.1; // la variable augment de 0,1\n navbar.css('top',-60+Npos+'px');\n navbar.css('opacity', Nopacity); // ce qui est répercuté sur l'objet\n }\n}", "function animateLucyIcon() {\n if (keepAnimatingLucyIcon) {\n chrome.browserAction.setIcon({path:\"mic-animated-\" + currentLucyIconFrame + \".png\"});\n if (currentLucyIconFrame++ >= maxLucyIconFrame) {\n currentLucyIconFrame = minLucyIconFrame;\n }\n\n // switch to next frame of icon every .2 seconds\n window.setTimeout(animateLucyIcon, 200);\n }\n}", "function changeIcon(navItem, action) {\n if(action == \"enter\"){\n navItem.firstChild.classList.remove(openIcon);\n navItem.firstChild.classList.add(closeIcon);\n }\n else{\n navItem.firstChild.classList.add(openIcon);\n navItem.firstChild.classList.remove(closeIcon);\n }\n}", "function iconAnimationBackward(){\n setNavRotate(state => ({\n ...state,\n value: 0,\n }));\n }", "_enableAnimation() {\n this.isAnimatable = true;\n toggleClass(this.navEl, 'no-animation', !this.isAnimatable);\n }", "function showIconList(){\r\n\t$('#showIconButton').css('display', 'none');\r\n\t$('#selectIconMenu').css('marginBottom', '-133px');\r\n\t$('#selectIconMenu').animate({marginLeft: '-20px'});\r\n}", "function initIconWithTextAnimation(){\n\t\"use strict\";\n\tif($j('.q_icon_animation').length > 0 && $j('.no_animation_on_touch').length === 0){\n\t\t$j('.q_icon_animation').each(function(){\n\t\t\t$j(this).appear(function() {\n\t\t\t\t$j(this).addClass('q_show_animation');\n\t\t\t},{accX: 0, accY: -200});\t\n\t\t});\t\n\t}\n}", "animateLinks(direction){\n const navLinks = document.getElementsByClassName(\"nav_link\");\n\n //iterate through every navlink animation (1-3) and add them to the link classes\n let x = 1;\n\n if(direction === \"in\"){\n for (let link of navLinks) {\n link.classList.remove(\"link_slide_out\" + x);\n link.classList.add(\"link_slide_in\" + x);\n x += 1;\n }\n }\n else{\n for (let link of navLinks) {\n link.classList.remove(\"link_slide_in\" + x);\n link.classList.add(\"link_slide_out\" + x);\n x += 1;\n }\n }\n\n }", "animateName(direction){\n if(direction === \"in\"){\n const nameContainer = document.getElementById(\"name_container\");\n nameContainer.style.pointerEvents = \"none\";\n nameContainer.classList.remove(\"name_bounce_out\");\n nameContainer.classList.add(\"name_bounce_in\");\n }\n else{\n const nameContainer = document.getElementById(\"name_container\");\n nameContainer.classList.remove(\"name_bounce_in\");\n nameContainer.classList.add(\"name_bounce_out\");\n }\n }", "function _handleNavIconClick () {\n this.$el.find('.nav-list').toggleClass('show');\n }", "function navArrowVisibility(){\n // console.log('in navArrowVisibility');\n if(currentStep != stepIDs[stepIDs.length-1]){\n $('#projectTitleBar .fa-angle-right').css('visibility', 'visible');\n // console.log('making right nav visible');\n }else{\n $('#projectTitleBar .fa-angle-right').css('visibility', 'hidden');\n }\n $('#projectTitleBar .fa-angle-left').css('visibility', 'visible'); \n }", "function add_navigation() {\n if (list_elem_count == 0) {\n return false;\n }\n\n var pag_markup = '<div class=\"navigation_container\"><ul class=\"clearfix\" id=\"navigation\">';\n var icon_markup = '<div class=\"icon\" id=\"icon_wrapper\"><svg x=\"0px\" y=\"0px\" width=\"24.3px\" height=\"23.2px\" viewBox=\"0 0 24.3 23.2\" enable-background=\"new 0 0 24.3 23.2\" xml:space=\"preserve\"><polygon class=\"arrow\" fill=\"#ffffff\" points=\"' + svg_arrow_icon + '\"></svg></div>';\n\n for (var i = 1; i <= list_elem_count; i++) {\n pag_markup = pag_markup + '<li>' + icon_markup + '</li>';\n };\n\n $('#steps').after(pag_markup + '</div>');\n $('#navigation li').eq(0).addClass('current_nav');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize Javascript variables that correspond to items in the body. Also initialize $window.
function initializeVariables() { $window = $(window); $pageHead = $("#pageHead"); $storyFrame = $("#storyFrame"); storyFrame = $storyFrame[0]; $backArrow = $("#backArrow"); $nextArrow = $("#nextArrow"); newtabLink = $("#newtabLink")[0]; $slideDropdown = $("#slideDropdown"); slideDropdown = $slideDropdown[0]; $slideTotal = $("#slideTotal"); }
[ "function init() {\n initializeVariables();\n initializeHtmlElements();\n}", "function _initScrollVars()\n {\n var elem_body_obj = $('body');\n wizmo.store(\"var_viewport_scroll_t\", elem_body_obj.scrollTop());\n wizmo.store(\"var_viewport_scroll_l\", elem_body_obj.scrollLeft());\n }", "initializeElements () {\n this.$els = {\n window,\n body: document.body\n }\n }", "function init() {\n\t\t$(function () {\n\t\t\tinitHandlers();\n\t\t\tinitEnhancers();\n\t\t});\n\t}", "function _BindGlobals(){\r\n\t\t\r\n\t\tif(typeof window.$$ !== \"undefined\"){\r\n\t\t\t_Original$$ = window.$$;\r\n\t\t}\r\n\t\t\r\n\t\twindow.$$ = _Penguin;\r\n\t\twindow.Penguin = _Penguin;\r\n\t\t\r\n\t}", "function init() {\r\n\t// Get the template views from the server to better separate views from model\r\n\t// They're loaded before the document is actually ready for better performance\r\n\tvar signInTemplate = $(\"<div>\").load(\"templates/signIn.html\");\r\n\tvar signUpTemplate = $(\"<div>\").load(\"templates/signUp.html\");\r\n\r\n\t// Get the properties according to the URL's \"lan\" parameter\r\n\tloadProperties(language);\r\n\r\n\t$(document).ready(function() {\r\n\t\t// Populate the templates according to the configuration and URL data\r\n\t\tpopulateBasePage();\r\n\t\tsignInTemplate = populateSignInTemplate(signInTemplate);\r\n\t\tsignUpTemplate = populateSignUpTemplate(signUpTemplate);\r\n\r\n\t\t// Put the templates in the document\r\n\t\t$(\"#wrap\").append(signInTemplate);\r\n\t\t$(\"#wrap\").append(signUpTemplate);\r\n\r\n\t\t// Prepare the modals to close when the required conditions are met\r\n\t\tprepareModals();\r\n\t});\r\n}", "init() {\n self = this;\n\n // A page can't be manipulated safely until the document is \"ready.\"\n // jQuery detects this state of readiness for you.\n // http://learn.jquery.com/using-jquery-core/document-ready/\n $(document).ready(self.ready);\n }", "function initScripts() {\n breakpoint();\n lazyload();\n heroSlider();\n categoriesMobile();\n asideLeftMobile();\n scrollRevealInit();\n seoSpoiler();\n mobileMenuOverflowScroll();\n}", "init() {\n const windowScrollAndSize = { ...getWindowSize(), ...getWindowScroll() };\n this.elementsWithEffectsMap = this.getElementsWithEffects();\n this.initDocument();\n this.propagateScroll(windowScrollAndSize);\n this.registerNextAF();\n }", "function initScopeVariables() {\n\n\t\t}", "function _initDimensionVars()\n {\n var docElem = document.documentElement;\n store(\"var_document_client_w\", docElem.clientWidth);\n store(\"var_document_client_h\", docElem.clientHeight);\n store(\"var_window_outer_w\", window.outerWidth);\n store(\"var_window_outer_h\", window.outerHeight);\n store(\"var_window_screen_w\", screen.width);\n store(\"var_window_screen_h\", screen.height);\n }", "init() {\n // Read the DOM to find all the templates, and make them available to the code\n $('.js_template').each((__, $el) => {\n const namespaceElements = $el.id.split('_');\n const id = namespaceElements.pop();\n\n // remove the prefix \"template\" that MUST be added to have clean HTML ids\n namespaceElements.shift();\n const namespace = getTemplateNamespace(namespaceElements);\n namespace[id] = new DOMTemplate($el.id);\n });\n }", "function initialize() {\n body = document.querySelector('body');\n triggers = document.querySelectorAll('[data-balloon]');\n html_toolips = document.querySelectorAll('[data-balloon-html-content]');\n generateHTMLTooltips();\n bindEvents();\n }", "function prepareGlobalValues() {\n // '$(id)' is an alias for 'document.getElementById(id)'. It is defined\n // in //resources/ash/common/util.js. If this function is not exposed\n // via the global object, it would not be available to tests that inject\n // JavaScript directly into the renderer.\n window.$ = $;\n\n // Expose MultiTapDetector class on window for tests to set static methods.\n window.MultiTapDetector = MultiTapDetector;\n\n // TODO(crbug.com/1229130) - Remove the necessity for these global objects.\n if (window.cr == undefined) {\n window.cr = {};\n }\n if (window.cr.ui == undefined) {\n window.cr.ui = {};\n }\n if (window.cr.ui.login == undefined) {\n window.cr.ui.login = {};\n }\n\n // Expose some values in the global object that are needed by OOBE.\n window.cr.ui.Oobe = Oobe;\n window.Oobe = Oobe;\n}", "function formal_body_onload_init() {\n // add server side elements with buttons, actions, etc\n formal_adorn_server_side_elements();\n}", "function init() {\n\n // Detect the viewport\n breakpoint.refresh_value();\n\n // Pick and set the carousel element.\n _set_element();\n\n // Fetch content for the carousel.\n _fetch();\n\n }", "initialize() {\n this.settings = {};\n this.scripts = [];\n }", "function initUI() {\r\n createTopBar();\r\n root.append(mainPanel); // TODO JADE\r\n makeSidebar();\r\n METADATA_EDITOR.init(); // initialize different parts of the editor\r\n LOCATION_HISTORY.init();\r\n THUMBNAIL_EDITOR.init();\r\n MEDIA_EDITOR.init();\r\n }", "function init(){\r\n\t\tgetUrlParameters();\r\n\t\tgetAPIKeys();\r\n\t\tbrowserDetect();\r\n\t\tmiscSetup();\r\n\t\tinitCollapse();\r\n\t\tupdateMeasurements();\r\n\t\tbindings();\r\n\t\tsameHeight();\r\n\t\taddCaptions();\r\n\t\tlightboxSetup();\r\n\t\tapplyEllipsis();\r\n\t\trandomBGImage();\r\n\t\tvideoBackgrounds();\r\n\r\n\t\tif(s.windowWidth <= s.breakpoints.xs){ /*[1]*/\r\n\t\t\t$('.wc-mobile-default-collapse').collapse('hide'); \r\n\t\t}\r\n\r\n\t\tif(!s.breakpointChecks.md){ /*[2]*/\r\n\t\t\t$('.wc-mobile-collapse-box').addClass('collapse');\r\n\t\t}\r\n\r\n\t\taddCSS('.wc-lightbox img{max-height:'+Math.floor((s.windowHeight * 0.9)) +'px;}'); /*[3]*/\r\n\r\n\t\tif(s.urlParameters['hc'] === '1'){ /*[4]*/\r\n\t\t\thighContrast();\r\n\t\t}\r\n\r\n\t\t$.publish('dom.newElements'); /*[5]*/\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load the staff list file
function findStaffList(ListFile){ //console.log("Looking for filename: "+filename); if (fs.existsSync(ListFile)){ console.log("found staff file"); let rawdata = fs.readFileSync(ListFile); //console.log("raw data: "+rawdatamuddy); stafflist = JSON.parse(rawdata); //console.log("parsed data: "+JSON.stringify(muddypoints, null, 2)); //console.log(muddypoints.points.length+" stored server points sets loaded"); return stafflist; } else { console.log("no staff file found"); var pointsArray = []; stafflist = { aberuid: pointsArray, }; let data = JSON.stringify(stafflist, null, 2); //null, 2 for formating fs.writeFileSync(StaffListFile, data); return stafflist; } }
[ "function loadWillList() {\n\twillList = JSON.parse(fs.readFileSync(willListFullPath, 'utf8'));\n}", "function loadData() {\n var fileContent = fs.readFileSync('./data.json');\n members = JSON.parse(fileContent);\n}", "function loadStudents() {\n var empty = \"[]\";\n readFile(\"students.txt\", empty, function(err, data) {\n students = JSON.parse(data)\n });\n}", "function loadWikiList() {\n\twikiList = JSON.parse(localStorage.wikiList || \"[]\");\n}", "function loadFiles(){\n\tmakeArrayFromXML(completedXmlLoad, newItemList);\n}", "loadMasterAcctList() {\n let acctData = path.join(this.cwd, this.USER_DATA, this.ACCT_MASTERLIST);\n this.masterAccountList = JSON.parse(fs.readFileSync(acctData));\n }", "function loadPicklist(picklist_index, path) {\n let csv_file = fs.readFileSync(path).toString();\n // splits file be \"\\n\", the new line character\n let picklist_teams = csv_file.split(\"\\n\");\n // gets the picklist title from teams\n // splice automatically removes the title from the list of things\n let picklist_title = picklist_teams.splice(0,1)[0];\n $(\"#picklist-title-\" + picklist_index).text(picklist_title);\n // adds it to the picklists object\n picklists[picklist_index] = picklist_teams;\n createPicklistTable(picklist_index);\n}", "function loadFile(){\n\tvar questions = [\n\t\t{\n\t\t\tname: 'fileName',\n\t\t\ttype: 'input',\n\t\t\tmessage: 'Enter a file to load, otherwise a default file (eList.txt) will be loaded\\n',\n\t\t\tvalidate: function (fileName) {\n\t\t\t\tif(fileName.indexOf('.txt') > -1) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else if ( fileName == ''){\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn console.log('\\nPlease enter a valid .txt file or blank\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t];\n\n\tinquirer.prompt(questions).then(function(response) {\n\t\t// Set the file name to user input\n\t\tif(response.fileName != ''){\n\t\t\tm_list_name = response.fileName;\n\t\t} else {\n\t\t\tm_list_name = 'eList.txt';\n\t\t}\n\n\t\tconsole.log('Initializing employee list from ' + m_list_name + '...');\n\t\t// Load employee list from m_list_name\n\t\tfs.readFile(m_list_name, function(err, data) {\n\t\t if(err){\n\t\t \tconsole.log(\"Error reading file: \" + err);\n\t\t \tloadFile();\n\t\t } else {\n\t\t\t var array = data.toString().split(\"\\n\");\n\t\t\t \n\t\t\t var i = 0;\n\t\t\t for(i; i < array.length; i++) {\n\t\t\t m_employee_array.push(array[i]);\n\t\t\t }\n\n\t\t\t\tm_total_people = m_employee_array.length;\n\t\t\t\tconsole.log(\"Done!\");\n\t\t\t\tsortArray();\n\t\t\t\tshowMenu();\n\t\t }\n\t\t});\n\t});\n}", "function loadReminders(cb) {\n fs.readFile(reminderFile(), 'utf8', (err, data) => {\n if(err) {\n if(err.code == 'ENOENT') {\n clearReminders()\n cb()\n } else cb(err)\n }\n else {\n clearReminders()\n let d = archieml.load(data)\n for(let i = 0;i < d.reminders.length;i++) {\n addReminder(d.reminders[i])\n }\n cb()\n }\n })\n}", "function loadWordlists() {\n let wordlists = {}\n const files = fs.readdirSync('./data/');\n\n // loop over each file & import each json file\n for (file in files) {\n file = files[file];\n const language = file.slice(0, 2);\n wordlists[language] = require(`./data/${file}`);\n }\n return wordlists;\n}", "function load_teams(){ //Load the Teams list to the teams object\n\tvar teams = require(\"./prof_walnut/teams.json\");\n}", "function FeedStaffList() {\n\n listOfStaff[0] = [\"John\", \"Center\", \"Assistant\", \"./res/employee/John_Center.png\", \"Policies Update due\", \"Profile changes to validate\", \"Profile changes to validate\", \"Security Training due\"];\n listOfStaff[1] = [\"Jessica\", \"Pineapple\", \"DAS III\", \"./res/employee/Jessica_Pineapple.png\", \"Security Training Due\", \"TB test due\"];\n listOfStaff[2] = [\"Maria\", \"Hive\", \"DAS II\", \"./res/employee/Maria_Hive.png\", \"Probation ends in 2 weeks\"];\n listOfStaff[3] = [\"Douglas\", \"Vault\", \"Assistant\", \"./res/employee/Douglas_Vault.png\", \"Policies Update due\", \"Profile changes to validate\"];\n listOfStaff[4] = [\"Paul\", \"Thunder\", \"DAS III\", \"./res/employee/Paul_Thunder.png\", \"Security Training Due\", \"TB test due\"];\n listOfStaff[5] = [\"Emeline\", \"Theater\", \"DAS II\", \"./res/employee/Emeline_Theater.png\", \"Probation ends in 2 weeks\"];\n\n\n}", "function loadNotesData() {\n // loads through each file in manifest\n for (let data_id in manifest_notes) {\n let file_name = manifest_notes[data_id]; // 5-135935359979.json (the second # is just for getting rid of duplicates)\n if (fs.existsSync(\"./data/notes/\" + file_name)) {\n let data_point = JSON.parse(fs.readFileSync(\"./data/notes/\" + file_name));\n let dp_match = data_point[\"match\"];\n // finds what teams are in the data\n for (let team_index in schedule[dp_match]) {\n let team_name = schedule[dp_match][team_index];\n if (notes_data[team_name] === undefined) { notes_data[team_name] = []; }\n notes_data[team_name].push([data_point[team_index.toString()], data_point[\"match\"]]);\n }\n }\n }\n}", "function loadNaughtyList(){\n let myInterface = readline.createInterface({\n input: fs.createReadStream(NAUGHTY_LIST_FILE)\n });\n\n myInterface.on('line', (line) => {\n naughtyList.push(line);\n });\n}", "function readFile(){\n\tvar data = fs.readFileSync(\"restaurantList.txt\");\n\tresArr = JSON.parse(data.toString());\n}", "function loadWordList(fileName, list, extractFunc, filterFunc) {\n var parser, value;\n\n parser = csv({ trim: true }, function(err, data) {\n //console.log(\"Words record: \" + JSON.stringify(data));\n data.forEach(function(record) {\n if (!filterFunc || filterFunc(record)) {\n value = extractFunc(record);\n //console.log(\"List add: \" + value);\n list.push(value);\n }\n });\n });\n\n var input = fs.createReadStream(fileName);\n input.pipe(parser); \n}", "function loadEvents()\n{\n\t// Prepares a variable to store the text from the file\n\tvar text = readTextFile( \"scripts/Events.txt\" );\n\t\n\t// Splits the text file into individual lines, storing\n\t// these values in an array\n\teventByLine = text.split( \"\\n\" );\n}", "load() {\n \n fs.readFile('employeeStore.json', (err, data) => { \n if (err) throw err;\n let employeeStore = JSON.parse(data);\n console.log('Current contents of employee file' + '\\n'); \n console.log(employeeStore);\n });\n }", "function loadUsers() {\n fs.readdir(usersFilePath, function(err, files) {\n if (err) {\n // failed to read the dir. Maybe logout error?\n }\n else {\n files.forEach(function(file) {\n var nick = file.split(\".\")[0];\n userDict[nick] = {};\n });\n loadSayings(); // go ahead an do an inital load for the sayings\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Example query to get one individual species.
async function example_query_get_one_species(queryResolver) { const query = { get: { species: { // Query for "species" entity. args: { name: "Hutt", // Gets the one species that matches this name. }, }, }, }; const result = await miniql(query, queryResolver, {}); // Invokes MiniQL. console.log(JSON.stringify(result, null, 4)); // Displays the query result. }
[ "async function getVillagerBySpecies(req, res){\n\tconst species = req.params.species;\n\tconsole.log(species);\n\tawait con.query(`SELECT * FROM ${collection} WHERE species = \"${species}\"`, (err, result, fields) => { \n\t\tif (err) throw err;\n\t\tres.json(result);\n\t\t// console.log(result);\n\t});\n\n}", "getInnuendoSpecies() {\n return axios({\n method: \"get\",\n url: address + \"app/api/v1.0/species/\",\n\n })\n }", "async function example_query_get_one_species_with_nested_entity_lookup(queryResolver) {\n\n const query = {\n get: {\n species: { // Query for \"species\" entity.\n args: {\n name: \"Hutt\", // Gets the one species that matches this name.\n },\n resolve: {\n homeworld: { // Resolves the homeworld of the species as a nested lookup.\n },\n },\n },\n },\n };\n\n const result = await miniql(query, queryResolver, {}); // Invokes MiniQL.\n console.log(JSON.stringify(result, null, 4)); // Displays the query result.\n}", "static async selectId(id)\n {\n const species = await Species.getId(id);\n return species;\n }", "async function example_query_get_all_species_with_nested_entity_lookup(queryResolver) {\n\n const query = {\n get: {\n species: { // Query for \"species\" entity.\n\n // No arguments gets all entities.\n\n resolve: {\n homeworld: { // Resolves the homeworld of each species as a nested lookup.\n },\n },\n },\n },\n };\n\n const result = await miniql(query, queryResolver, {}); // Invokes MiniQL.\n console.log(JSON.stringify(result, null, 4)); // Displays the query result.\n}", "async getSpecies (algorithm) {\n try {\n const res = await api().get(`/algorithm/${algorithm}/species`)\n return Array.isArray(res.data) ? res.data : []\n } catch (e) {\n return []\n }\n }", "function makeSpeciesQuery(val){\n\t\n\t\t var QueryMESATask = new QueryTask({\n\t\t\t\t\turl: \"https://services1.arcgis.com/7iJyYTjCtKsZS1LR/arcgis/rest/services/Public_Town_MESA_Spp_List/FeatureServer/1\"\n\t\t\t\t\t});\n\t\tvar params = new Query({\n returnGeometry: false,\n outFields: [\"TOWN\",\"Most_Recent_Observation\",\"Taxonomic_Group\", \"MESA_Status\", \"OBJECTID\"]\n });\n params.where =\"CommonName = '\"+val+\"'\";\n\t\t\tQueryMESATask \n\t\t\t.execute(params)\n\t\t\t.then(showResults)\n\t\t \n function showResults(response) {\n var firstResult = []; //all the towns for the definition query\n\t\t\t\tvar secondResult= []; //this is an bunch of objects that hold town and observed date\n\t\t\t\tvar thirdResult= []; //this is objectStore for the towns that are selected to show in the towns dropdown\n\t\t\t\t\n var resultCount = response.features.length;\n for (var i = 0; i < resultCount; i++) {\n var featureAttributes = response.features[i].attributes;\n\t\t\t\t\tfirstResult.push(\"'\"+featureAttributes.Town+\"'\");\t\t\t\n\t\t\t\t\tsecondResult.push({town:featureAttributes.Town.toProperCase(), observed: featureAttributes.Most_Recent_Observation});\n\t\t\t\t\tthirdResult.push({id:featureAttributes.OBJECTID, name: featureAttributes.Town.toProperCase()});\t\n }\n\t\t\t\tdocument.getElementById(\"infoSpotOne\").innerHTML = \"<b>Taxonomic Group:</b> \" + featureAttributes.Taxonomic_Group;\n\t\t\t\tdocument.getElementById(\"infoSpotThree\").innerHTML = \"<br /><b>MESA Status:</b> \" + MESA_Formatter(featureAttributes.MESA_Status);\n\t\t\t\t\n\t\t\t\t var NewTownStore = new Memory({idProperty : \"name\", data : thirdResult});\n\t\t\t\t townSelect.set('store', NewTownStore)\n\t\t\t\t\n\t\t MESAtowns.definitionExpression = \"TOWN IN (\" +firstResult.toString()+ \")\"; //first result definition expression for the map\n\t\t\t\ttownsWithASpecies(secondResult); //second result to make the SpeciesInATown grid\n\t } \n\t\t}", "async function example_query_get_all_species_with_nested_entity_lookup(queryResolver) {\n\n const query = {\n get: {\n planet: { // Query for \"planet\" entity.\n \n // No arguments gets all entities.\n\n resolve: {\n species: { // Gets all the species related to to each planet.\n },\n },\n },\n },\n };\n\n const result = await miniql(query, queryResolver, {}); // Invokes MiniQL.\n console.log(JSON.stringify(result, null, 4)); // Displays the query result.\n}", "function getSpeciesS(cell) {\n return cell.speciesS;\n}", "function getAllSpeciesFromDB() {\n\n var species = [];\n\n $.get('api/getallbirds', function(data){\n data.data.forEach(function(bird){\n var parsed = JSON.parse(bird);\n let scientificName = parsed.scientificName;\n // Strip first descriptor if he's included in scientificName\n var indexOfParenthesis = scientificName.indexOf(\"(\")\n if (indexOfParenthesis !== -1) {\n scientificName = scientificName.substr(0, indexOfParenthesis).trim();\n }\n let speciesObject = {\n scientificName: scientificName,\n id: parsed.id\n };\n species.push(speciesObject);\n });\n console.log(species);\n });\n return species;\n}", "function getSpeciesTypeDetail(uuid) {\r\n return get('/speciestype/detail', { uuid: uuid }).then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}", "function getSpeciesName() {\n return $('#species-name').val();\n }", "function hydrateSpecies() {\n //TODO: ajax query\n //fixte\n return getAllSpeciesFromDB();\n }", "function getAnimals() {\n return db(\"animals\").select('*')\n}", "function getFilterBySpecies(speciesId = null, topPIC = null) {\r\n return post('/livestock/getfilterbyspecies', { speciesId: speciesId, topPIC: topPIC }).then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}", "function getById(req,res,next){\n\n\t// Add check that request is for specified parent plant resource\n\n\t// Use the Variety model to find the variety we want\n\tVariety.findById(req.params.variety_id, function(err, variety){\n\t\tif (err) throw err;\n\t\tres.status(200).json(variety);\n\t})\n}", "function getAllPeople(specie) {\n return getSpecies(specie)\n .then(table => {\n // console.log(table.people)\n return table.people\n })\n}", "function getSpeciesById(id) {\r\n\tmodule.getResourceById('species',id,function(data) {\r\n\t\t//Logging the response data on console and assigning it to a DOM element. Below code in the function can be changed as per the requirement.\r\n\t\tconsole.log(\"getSpeciesById data\", data);\r\n\t\tvar stringData=JSON.stringify(data, undefined, 4);\r\n\t\tdocument.getElementById(\"species\").innerHTML = stringData;\r\n\t});\r\n}", "function getEOLspeciesID(speciesName) {\n return fetch(\n `https://eol.org/api/search/1.0.json?q=${speciesName}&page=1&key=`\n )\n .then(function(response) {\n return response.json();\n })\n .then(function(response) {\n return response.results[0].id;\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the maximum frequency for a concrete sensor.
setMaximumSupportedFrequency(frequency) { this.max_frequency_ = frequency; }
[ "setMaximumSupportedFrequency(frequency) {\n this.maxFrequency_ = frequency;\n }", "function YMotor_set_frequency(newval)\n { var rest_val;\n rest_val = String(Math.round(newval * 65536.0));\n return this._setAttr('frequency',rest_val);\n }", "function YPwmOutput_set_frequency(newval)\n { var rest_val;\n rest_val = String(Math.round(newval * 65536.0));\n return this._setAttr('frequency',rest_val);\n }", "setFrequency(aFrequency) {\n this.frequency = aFrequency;\n }", "set frequency(f) {\n\t\tthis.vcos[this.currVoice].frequency = f;\n\t}", "function setFrequency() {\n radio.frequency = (radio.range.low + radio.range.high)/2;\n}", "setFrequency() {\r\n\r\n this.frequency = [];\r\n for (let i = 0; i < this.fftSize / 2; i++) {\r\n this.frequency[i] = i * this.sampleRate / this.fftSize;\r\n }\r\n }", "set maximumPossiblePressure(value) {}", "setMinimumSupportedFrequency(frequency) {\n this.minFrequency_ = frequency;\n }", "function setFrequency() {\n radio.frequency=(radio.range.low + radio.range.high) / 2;\n}", "function initFrequencySelector(onSlideEndCallback) {\n $('#' + self.frameId + '_frequencySelector').attr('value', defaultFrequency);\n updateFreqText(defaultFrequency);\n\n $('#' + self.frameId + '_frequencySelector').rangeslider({\n polyfill: false,\n onSlide: function (position, value) {\n value = updateFreqText(value);\n },\n onSlideEnd: function (position, newValue) {\n newValue = updateFreqText(newValue);\n\n // Prepare the basic subscriptions options.\n const subOptions = {};\n if (newValue !== 'Unlimited') {\n subOptions['maxFrequency'] = newValue;\n }\n\n // Trigger the callback.\n onSlideEndCallback(subOptions);\n }\n });\n\n function updateFreqText(value) {\n if (value === MAX_FREQ_VALUE) {\n value = 'Unlimited';\n }\n $('#' + self.frameId + '_freqText').text(value + ' updates/second');\n return value;\n }\n }", "setLfoFrequency( frequency ) {\n this.lfo.frequency.setTargetAtTime( frequency, this.audioContext.currentTime, PARAMETER_CHANGE_TIME_CONSTANT );\n }", "function setFrequency(){\n radio.frequency = (radio.range.low + radio.range.high)/2\n}", "set_logFrequency(newval) {\n this.liveFunc.set_logFrequency(newval);\n return YAPI_SUCCESS;\n }", "static set processorFrequency(value) {}", "set _max(value) {\n Helper.UpdateInputAttribute(this, \"max\", value);\n }", "setMaxSpeed(newMaxSpeed) {\n var self = this;\n self.__maxSpeed = newMaxSpeed;\n }", "function changeFreq(_osc, _freq){\n _osc.freq(_freq);\n}", "set maxAutoTicks(value) {\n this.maxAutoTicksProperty = value;\n this.notifyPropertyChanged(constants_1.PROPERTY.MAX_AUTO_TICKS);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check the uipanel for userspecified settings
function getUserSettings() { return setUIPanelSettings(); }
[ "_validatePanel() {\n const hasPanelConfig = this.config.panel && (this.config.panel.icon || this.config.panel.header);\n if (!hasPanelConfig) {\n console.warn('Missing panel header and icon, please specify at least one of them.');\n }\n }", "function settingsValidation() {\n\n if (settings.get(\"OPTION_ID\") && settings.get(\"MAIN_TABLE\") && settings.get(\"MAIN_PK_FIELD\") && settings.get(\"SPC_TABLE\") && settings.get(\"SPC_PK_FIELD\")) {\n return true;\n } else {\n eventEmmitter.emit(\"message\", \"Unable to Process Action Due to Settings Configuration Incomplete. Please Launch Settings.\");\n \n return false;\n }\n\n}", "function _checkPreview(settings){\n\t\tif($.isEmptyObject(settings.tips)){\n\t\t\tdisabledItem(settings.toolbarContainer.find('.f_preview'));\n\t\t}else{\n\t\t\tenabledItem(settings.toolbarContainer.find('.f_preview'));\n\t\t}\n\t}", "function checkSettings () {\n// If no setting found\n settings.defaultSettings(true)\n // Apply them\n applySettings()\n // Set theme\n setTheme(settings.mobySettings.Theme)\n}", "function checkOpts() {\n for (var i = 0; i < $scope.opts.length; i++) {\n if ($scope.opts[i].toLowerCase() == $scope.ua) {\n $element.show();\n return false;\n }\n }\n }", "function checkSettings() {\n var portalLevel = -1;\n var leadCheck = false;\n switch(autoTrimpSettings.AutoPortal.selected) {\n case \"Off\":\n break;\n case \"Custom\":\n portalLevel = autoTrimpSettings.CustomAutoPortal.value + 1;\n leadCheck = autoTrimpSettings.HeliumHourChallenge.selected == \"Lead\" ? true:false;\n break;\n case \"Balance\":\n portalLevel = 41;\n break;\n case \"Electricity\":\n portalLevel = 82;\n break;\n case \"Crushed\":\n portalLevel = 126;\n break;\n case \"Nom\":\n portalLevel = 146;\n break;\n case \"Toxicity\":\n portalLevel = 166;\n break;\n case \"Lead\":\n portalLevel = 181;\n break;\n case \"Watch\":\n portalLevel = 181;\n break;\n case \"Corrupted\":\n portalLevel = 191;\n break;\n case \"Daily\":\n\t portalLevel = 9998;\n\t var stopDaily = 0;\n\t if (game.global.challengeActive == \"Daily\") {\n\t stopDaily = (hiderwindow <= 0.02) ? \"stopIt\" : 0;\n\t }\n\t if (stopDaily == \"stopIt\") {\n\t\t viewPortalUpgrades(); abandonChallenge(); confirmAbandonChallenge(); cancelTooltip();\n\t }\n\t if (game.global.challengeActive != \"Daily\") {\n\t portalLevel = (hiderwindow <= 0.01) ? game.global.world : 9999;\n break;\n\t }\n }\n if(portalLevel == -1)\n return portalLevel;\n if(autoTrimpSettings.VoidMaps.value >= portalLevel)\n tooltip('confirm', null, 'update', 'WARNING: Your void maps are set to complete after your autoPortal, and therefore will not be done at all! Please Change Your Settings Now. This Box Will Not Go away Until You do. Remember you can choose \\'Custom\\' autoPortal along with challenges for complete control over when you portal. <br><br> Estimated autoPortal level: ' + portalLevel , 'cancelTooltip()', 'Void Maps Conflict');\n if((leadCheck || game.global.challengeActive == 'Lead') && (autoTrimpSettings.VoidMaps.value % 2 == 0 && portalLevel < 182))\n tooltip('confirm', null, 'update', 'WARNING: Voidmaps run during Lead on an Even zone do not receive the 2x Helium Bonus for Odd zones, and are also tougher. You should probably fix this.', 'cancelTooltip()', 'Lead Challenge Void Maps');\n return portalLevel;\n}", "function verifySettingsExistence(){\n var settings = $(document.getElementById('settingsBox'));\n settings.remove();}", "function validateAllPanels() {\n\n if (validGeneral() && validImage () && validParent () )\n return true;\n else\n return false;\n }", "function loadSettings() {\n var currentUser = users[currentUserIndex];\n console.log(currentUser);\n\n // UI updates\n\n var settingsForm = document.getElementById('settingsForm');\n settingsForm.elements['accessibility'].checked = currentUser.accessibility;\n settingsForm.elements['learner'].checked = currentUser.learner;\n settingsForm.elements['locationMonitoring'].checked = currentUser.locationMonitoring;\n settingsForm.elements['speedWarning'].checked = currentUser.speedWarning;\n\n // Update info text\n document.getElementById('userInfo').innerHTML = currentUser.name + ' - ' + currentUser.phone + ' - ' + currentUser.address;\n\n // Update actual settings\n runSettings();\n}", "function invokeSettingsCheck(msg) {\r\n var mods;\r\n cb.settings[\"mods\"];\r\n if (msg[\"user\"] == cb.room_slug) {\r\n // Broadcaster.\r\n invokeSettings(msg, \"model\");\r\n } else if (cbjs.arrayContains(mod_users, msg[\"user\"])) {\r\n // Mod.\r\n invokeSettings(msg, \"mod\");\r\n } else if (cbjs.arrayContains(fan_users, msg[\"user\"])) {\r\n // Fan.\r\n invokeSettings(msg, \"fan\");\r\n }\r\n}", "function checkSettings() {\n // set scope variables for all drawer items\n $scope.featured = (mobileSettings.drawerFeaturedDisabled) ? false : true;\n $scope.categories = (mobileSettings.drawerCategoriesDisabled) ? false : true;\n $scope.map = (mobileSettings.drawerMapDisabled) ? false : true;\n $scope.create = (mobileSettings.drawerCreateDisabled) ? false : true;\n $scope.checkin = (mobileSettings.drawerCheckInDisabled) ? false : true;\n $scope.mytickets = (mobileSettings.drawerMyTicketsDisabled) ? false : true;\n $scope.friends = (mobileSettings.drawerFriendsDisabled) ? false : true;\n $scope.notifications = (mobileSettings.drawerNotificationsDisabled) ? false : true;\n $scope.crowdsurf = (mobileSettings.drawerCrowdSurfDisabled) ? false : true;\n $scope.help = (mobileSettings.drawerHelpDisabled) ? false : true;\n $scope.logout = (mobileSettings.drawerLogoutDisabled) ? false : true;\n $scope.avatar = (mobileSettings.drawerSearchDisabled) ? false : true;\n $scope.searchable = (mobileSettings.drawerAvatarDisabled) ? false : true;\n }", "function checkSettings(){\n\tlog(\"commencing settings check\");\n\tvar errors = new Array();\n\tif (settings.cols % 1 != 0 || settings.cols < 1){\n\t\terrors.push(\"cols settings incorrect. cols: \"+ settings.cols +\" (settings.cols % 1 != 0 || settings.cols < 1\");\n\t}\n\tif (settings.rows % 1 != 0 || settings.rows < 1){\n\t\terrors.push(\"rows settings incorrect. rows: \"+ settings.rows +\" (settings.rows % 1 != 0 || settings.rows < 1)\");\n\t}\n\tif (settings.mines % 1 != 0 || settings.mines < 1 || (settings.mines >= settings.rows * settings.cols) ){\n\t\terrors.push(\"mines settings incorrect. mines: \"+ settings.mines +\" (settings.mines % 1 != 0 || settings.mines < 1 || (settings.mines >= settings.rows * settings.cols)\");\n\t}\n\t// to-do: check difficulty\n\t// to-do: only check rows, cols, mines if no difficulty is set and vice versa\n\tif (errors.length > 0) {\n\t\tif (settings.debug == true) {\n\t\t\tlog(\"Settings check failed!\",\"error\");\n\t\t\tfor (e in errors){\n\t\t\t\tlog(errors[e],\"error\");\n\t\t\t}\n\t\t}\n\t\treturn errors;\n\t}\n\telse {\n\t\tlog(\"Settings check successful\");\n\t\treturn true;\n\t}\n}", "function validateAllPanels() {\n \n if (validDetails() && validDescription() && validImage() && validAttribute() && validInventory() && validListPrice() && validAdvanced() && validVendor() )\n return true;\n else\n return false;\n \n \n }", "function confirmSettingsAndShowGmailPanel() {\n populateGmail();\n const assignSettingsButton =\n document.querySelector('#gmail-settings-icon img:not([hidden])');\n assignSettingsButton.click();\n}", "function checkSettings() {\r\n var errors = [];\r\n for (var key in settings) {\r\n if (!settings[key]) {\r\n errors.push(settings[key]);\r\n }\r\n }\r\n ieVersion() && errors.push(\"NO IE 7\");\r\n return errors;\r\n }", "function checkPlatforms(){\n var profile;\n \n api.getUser(function(err, res){\n if (err) console.log(err);\n profile = res.profile;\n if (!profile){\n document.querySelector('#settings_reminder').style.display = 'block';\n } \n });\n }", "_canOpen() {\n return !this._panelOpen && !this.disabled && this.options?.length > 0;\n }", "function checkConfigs() {\r\n\r\n // fix bad mode setting\r\n var modes = [\"alert\", \"message\", \"modal\", \"redirect\"];\r\n if ($.inArray(configs.mode, modes) == -1) {\r\n configs.mode = \"alert\";\r\n }\r\n\r\n // fix missed title\r\n if ($.trim(configs.title) == \"\") {\r\n configs.title = \"هشدار\";\r\n }\r\n\r\n // fix missed message\r\n if ($.trim(configs.message) == \"\") {\r\n\r\n if (configs.mode == \"modal\") {\r\n configs.message = ModalDefaultMessage();\r\n }\r\n else if (configs.mode == \"message\") {\r\n configs.message = MessageDefaultMessage();\r\n }\r\n else if (configs.mode == \"alert\") {\r\n configs.message = \"مرورگر شما قدیمی و غیر ایمن است . لطفا آن را بروز کنید\";\r\n }\r\n }\r\n\r\n // fix missed links\r\n if ($.trim(configs.links) == \"\") {\r\n configs.links = DefaultLinks();\r\n }\r\n\r\n // fix missed container for [ message ] mode\r\n if (configs.mode == \"message\" && $.trim(configs.container) == \"\") {\r\n configs.container = \"BrowserWarningMessage\";\r\n }\r\n if (configs.mode == \"message\" && $(\"#\" + configs.container).length == 0) {\r\n $('body').prepend(\"<div id='\" + configs.container + \"'></div>\");\r\n }\r\n\r\n // fix bad boolean as showCloseButton\r\n if (typeof configs.showCloseButton != \"boolean\") {\r\n configs.showCloseButton = true;\r\n }\r\n\r\n // change to [ alert ] mode if [ redirect ] mode url is missed\r\n if (configs.mode == \"redirect\" && $.trim(configs.redirectToUrl) == \"\") {\r\n configs.mode = \"alert\";\r\n }\r\n\r\n }", "function hClickOnButtonSettings(){\n //storage check\n if (typeof(Storage) !== \"undefined\") { // Code for localStorage/sessionStorage.\n b_StorageAvailable = true;\n } else b_StorageAvailable = false;// Sorry! No Web Storage support..\n\n if (b_StorageAvailable)\n $(\".settings-container\").css('z-index', 2); /*show settings-window */\n else alert(o_Language.settingsUnavaluable);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
register a catch functor
catch(func) { this.catchFunctions.push(func); return this; }
[ "catch( fn ) {\n\t\tthis.catchFn = fn;\n\t\treturn( this );\n\t}", "function register(err, handler){\n\thandlersMap[err.name] = handler;\n}", "function _try_catch (f) {\n return function () {\n try {\n f.apply(this, arguments);\n } catch (e) {\n console.error(e);\n }\n };\n}", "function raise(type) {\n make_error_handler(type)() }", "_registerHandlers(target, becameInvalid, becameValid) {\n this.on('becameInvalid', target, becameInvalid);\n this.on('becameValid', target, becameValid);\n }", "_registerHandlers(target, becameInvalid, becameValid) {\n this.on('becameInvalid', target, becameInvalid);\n this.on('becameValid', target, becameValid);\n }", "configureErrorHandler() {\n process.on('uncaughtException', (error) => {\n logger.debug('Uncaught Exception', 'An Uncaught Exception was throwed', {\n error\n });\n console.log(error);\n });\n\n this.server.on('restifyError', errorHandler.handle.bind(errorHandler));\n }", "function exceptionHandler(){\n\n\tvar me = this;\n\n\tme.error = function(msg){\n\n\t\tthrow new Error(msg);\n\t};\n}", "static set actionOnDotNetUnhandledException(value) {}", "function _wrap(next) {\n return function(fn) {\n return function(err) {\n if (err) { next.err.call(this, err); return; }\n try { fn.apply(this, arguments); }\n catch (e) { next.err.call(this, e); }\n };\n };\n }", "static level(l) {\n let handlerName = `handler${l}`\n\n if (CGIError.handler) {\n process.removeListener('uncaughtException', CGIError.handler)\n }\n if (CGIError[handlerName]) {\n CGIError.handler = CGIError[handlerName]\n process.on('uncaughtException', CGIError.handler)\n }\n else {\n CGIError.handler = CGIError.handler0\n }\n }", "function add_finally_hook(fn, name) {\n\tname = name || 'default';\n\tvar hooks = get_chain(this.finally_hooks, name);\n\thooks.push(fn);\n}", "function _cwrap(next) {\n return function(fn) {\n return function(err) {\n try { fn.apply(this, arguments); }\n catch (e) { next.err.call(this, e); }\n };\n };\n }", "function register(event) { return function(fun) {\n return this.on(event, fun) }}", "function sc_errorHookSet( h ) {\n __sc_errorHook = h;\n}", "function addError() {}", "bindConnectorEvents () {\n try {\n let evt\n evt = 'ERROR'\n this.register({\n connector: CONNECTORS.KAFKA,\n cb: this.kafkaError,\n evt\n })\n this.register({\n connector: CONNECTORS.REDIS,\n cb: this.redisError,\n evt\n })\n this.register({\n connector: CONNECTORS.SOCKET,\n cb: this.socketError,\n evt\n })\n this.register({\n connector: CONNECTORS.DB,\n cb: this.databaseError,\n evt\n })\n } catch (e) {\n console.log(e)\n }\n }", "function make_error_handler(type) { return function(ev) {\n promise.flush(type, 'failed').fail(type, ev) }}", "function tryCatch(fn, obj, arg) { // 60\n try { // 61\n return { type: \"normal\", arg: fn.call(obj, arg) }; // 62\n } catch (err) { // 63\n return { type: \"throw\", arg: err }; // 64\n } // 65\n } // 66" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the textContent If the element is not yet created, store the value and apply it when the element is created
set textContent(text) { if (this.#el) this.#el.textContent = text; else this.#textContent = text; }
[ "set textContent(value) {\n this.nodeValue = value;\n }", "set textContent(value) {\n // Mutation Observation is performed by CharacterData.\n this.nodeValue = value;\n }", "function setContent(element, text){\n\telement.textContent = text;\n}", "setText(text) {\r\n this.text.innerHTML = text;\r\n }", "set(text, contentNum, selector) {\n var el = $(contentSetter.selectorPrefix + (selector || '')).contents()[contentNum];\n if (el) el.textContent = text;\n }", "setValue(value) {\n this.element.innerText = value;\n }", "set _textWhenEmpty(aValue) {\n if (this._emptyTextNode) {\n this._emptyTextNode.setAttribute(\"value\", aValue);\n }\n this._emptyTextValue = aValue;\n this._showEmptyText();\n }", "appendingText(){\r\n this.container = document.querySelector(this.selector);\r\n this.container.innerText = this.text;\r\n }", "function setText(element,value){\n\telement.innerText = value;\n\telement.textContent = value;\n}", "function setTextContent(node, text) {\n node[0].children[0].data = text;\n}", "function fillText(content, element ) {\n\n element.text(content);\n\n}", "text(el, value) {\n return setGet(el, 'innerText', value);\n }", "set innerText(text) {\n if (this.#el) this.#el.innerText = text;\n else this.#innerText = text;\n }", "function setElementText(elem, text)\n {\n logDebug(\"setElementText: \", elem, \", \", text) ;\n //elem.firstChild.nodeValue = text;\n replaceChildNodes(elem,text);\n return elem ;\n }", "text(newTxt){\n this.elements.forEach(element => {\n element.innerText = newTxt\n })\n return this\n }", "function setTextContent(node, value) {\n if (isCommentNode(node)) {\n node.data = value;\n } else if (isTextNode(node)) {\n node.value = value;\n } else {\n var tn = newTextNode(value);\n tn.parentNode = node;\n node.childNodes = [tn];\n }\n}", "function setElementText(elem, text)\n {\n logDebug(\"setElementText: \", elem, \", \", text) ;\n replaceChildNodes(elem,text) ;\n return elem ;\n }", "setText(text) {\n if (text !== this.getText()) {\n if (this._editor) {\n this._editor.setText(text);\n } else {\n this._value = text;\n }\n }\n }", "_syncTextBoxContentOnInitialization() {\n const that = this;\n let value;\n\n if (that.value === '') {\n value = that.innerHTML;\n }\n else {\n value = that.value;\n }\n\n if (that.displayMode === 'escaped') {\n if (value.match(/\\r\\n|\\n\\r|\\n|\\r|\\s|\\t|\\f|\\r/g)) {\n that.value = that._initializationValue = value;\n that.$.input.value = that._toEscapedDisplayMode(value);\n }\n else {\n that.value = that._initializationValue = that._toDefaultDisplayMode(value);\n that.$.input.value = value;\n }\n\n return;\n }\n\n that.$.input.value = that.value = that._initializationValue = value;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
As efficiently as possible, decorate the comment object with .precedingNode, .enclosingNode, and/or .followingNode properties, at least one of which is guaranteed to be defined.
function decorateComment(node, comment) { var childNodes = getSortedChildNodes(node); // Time to dust off the old binary search robes and wizard hat. var left = 0, right = childNodes.length; while (left < right) { var middle = (left + right) >> 1; var child = childNodes[middle]; if (comparePos(child.loc.start, comment.loc.start) <= 0 && comparePos(comment.loc.end, child.loc.end) <= 0) { // The comment is completely contained by this child node. decorateComment(comment.enclosingNode = child, comment); return; // Abandon the binary search at this level. } if (comparePos(child.loc.end, comment.loc.start) <= 0) { // This child node falls completely before the comment. // Because we will never consider this node or any nodes // before it again, this node must be the closest preceding // node we have encountered so far. var precedingNode = child; left = middle + 1; continue; } if (comparePos(comment.loc.end, child.loc.start) <= 0) { // This child node falls completely after the comment. // Because we will never consider this node or any nodes after // it again, this node must be the closest following node we // have encountered so far. var followingNode = child; right = middle; continue; } throw new Error("Comment location overlaps with node location"); } if (precedingNode) { comment.precedingNode = precedingNode; } if (followingNode) { comment.followingNode = followingNode; } }
[ "function decorateComment(node, comment) {\n var childNodes = getSortedChildNodes(node);\n\n // Time to dust off the old binary search robes and wizard hat.\n var left = 0, right = childNodes.length;\n while (left < right) {\n var middle = (left + right) >> 1;\n var child = childNodes[middle];\n\n if (comparePos(child.loc.start, comment.loc.start) <= 0 &&\n comparePos(comment.loc.end, child.loc.end) <= 0) {\n // The comment is completely contained by this child node.\n decorateComment(comment.enclosingNode = child, comment);\n return; // Abandon the binary search at this level.\n }\n\n if (comparePos(child.loc.end, comment.loc.start) <= 0) {\n // This child node falls completely before the comment.\n // Because we will never consider this node or any nodes\n // before it again, this node must be the closest preceding\n // node we have encountered so far.\n var precedingNode = child;\n left = middle + 1;\n continue;\n }\n\n if (comparePos(comment.loc.end, child.loc.start) <= 0) {\n // This child node falls completely after the comment.\n // Because we will never consider this node or any nodes after\n // it again, this node must be the closest following node we\n // have encountered so far.\n var followingNode = child;\n right = middle;\n continue;\n }\n\n throw new Error(\"Comment location overlaps with node location\");\n }\n\n if (precedingNode) {\n comment.precedingNode = precedingNode;\n }\n\n if (followingNode) {\n comment.followingNode = followingNode;\n }\n}", "function decorateComment(node, comment, lines) {\n var childNodes = getSortedChildNodes(node, lines);\n // Time to dust off the old binary search robes and wizard hat.\n var left = 0;\n var right = childNodes && childNodes.length;\n var precedingNode;\n var followingNode;\n while (typeof right === \"number\" && left < right) {\n var middle = (left + right) >> 1;\n var child = childNodes[middle];\n if (util.comparePos(child.loc.start, comment.loc.start) <= 0 &&\n util.comparePos(comment.loc.end, child.loc.end) <= 0) {\n // The comment is completely contained by this child node.\n decorateComment((comment.enclosingNode = child), comment, lines);\n return; // Abandon the binary search at this level.\n }\n if (util.comparePos(child.loc.end, comment.loc.start) <= 0) {\n // This child node falls completely before the comment.\n // Because we will never consider this node or any nodes\n // before it again, this node must be the closest preceding\n // node we have encountered so far.\n precedingNode = child;\n left = middle + 1;\n continue;\n }\n if (util.comparePos(comment.loc.end, child.loc.start) <= 0) {\n // This child node falls completely after the comment.\n // Because we will never consider this node or any nodes after\n // it again, this node must be the closest following node we\n // have encountered so far.\n followingNode = child;\n right = middle;\n continue;\n }\n throw new Error(\"Comment location overlaps with node location\");\n }\n if (precedingNode) {\n comment.precedingNode = precedingNode;\n }\n if (followingNode) {\n comment.followingNode = followingNode;\n }\n}", "function decorateComment(node, comment, lines) {\n var childNodes = getSortedChildNodes(node, lines);\n // Time to dust off the old binary search robes and wizard hat.\n var left = 0;\n var right = childNodes && childNodes.length;\n var precedingNode;\n var followingNode;\n while (typeof right === \"number\" && left < right) {\n var middle = (left + right) >> 1;\n var child = childNodes[middle];\n if ((0, util_1.comparePos)(child.loc.start, comment.loc.start) <= 0 &&\n (0, util_1.comparePos)(comment.loc.end, child.loc.end) <= 0) {\n // The comment is completely contained by this child node.\n decorateComment((comment.enclosingNode = child), comment, lines);\n return; // Abandon the binary search at this level.\n }\n if ((0, util_1.comparePos)(child.loc.end, comment.loc.start) <= 0) {\n // This child node falls completely before the comment.\n // Because we will never consider this node or any nodes\n // before it again, this node must be the closest preceding\n // node we have encountered so far.\n precedingNode = child;\n left = middle + 1;\n continue;\n }\n if ((0, util_1.comparePos)(comment.loc.end, child.loc.start) <= 0) {\n // This child node falls completely after the comment.\n // Because we will never consider this node or any nodes after\n // it again, this node must be the closest following node we\n // have encountered so far.\n followingNode = child;\n right = middle;\n continue;\n }\n throw new Error(\"Comment location overlaps with node location\");\n }\n if (precedingNode) {\n comment.precedingNode = precedingNode;\n }\n if (followingNode) {\n comment.followingNode = followingNode;\n }\n}", "function DocCommentNode() {\n}", "function Comment(_node) {\r\n this._node = _node;\r\n}", "function comments(ctx, node) {\n return \"\\\\begin{comment}\\n\".concat(node.data.comment, \"\\n\\\\end{comment}\\n\");\n}", "function emitCommentsOnNotEmittedNode(node) {\n emitLeadingCommentsWorker(node, /*isEmittedNode*/ false);\n }", "function prependPureComment(node) {\n const comments = node.leadingComments || (node.leadingComments = []);\n comments.push({\n type: 'CommentBlock',\n value: '#__PURE__'\n });\n}", "function comment(ctx, node) {\n return '<!--' + node.value + '-->'\n}", "function CommentTree(properties) {\n\tthis.structure = properties;\n}", "function comment() {\n return wrap('comment', and(literal('('), star(and(opt(fws), ccontent)), opt(fws), literal(')'))());\n }", "function createNewCommentOnEvent() {\n let commentHeader = document.createElement(\"div\")\n commentHeader.className = \"alert\";\n commentHeader.innerHTML = window.getSelection();\n commentHeader.absoluteOffsetBottom = passingobject.absoluteOffsetTop + 80;\n commentHeader.id = document.getElementsByClassName(\"alert\").length;\n passingobject.id = commentHeader.id;\n var aboutToChangePositionOffsetTop;\n var commentHeaderPreviousSiblingOffsetBottom;\n console.log(\"Initializing new annotation - ID = \" + passingobject.id + \" / Expected absoluteOffsetTop = \" + passingobject.absoluteOffsetTop + \" / Expected absoluteOffsetBottom = \" + commentHeader.absoluteOffsetBottom);\n\n //position the comment in the margin, before the relevant sibling if one is existing, or directly as a child.\n if (passingobject.lastElementChild == false) {\n commentToInsertBefore = document.getElementById(\"marginright\").childNodes[passingobject.nextComment()];\n console.log(\"The comment following the inserted one is \");\n console.log(document.getElementById(\"marginright\").childNodes[passingobject.nextComment()]);\n document.getElementById(\"marginright\").insertBefore(commentHeader, commentToInsertBefore);\n }\n else {\n console.log(\"Creating commentHeader - I detected that there was not any annotations after this one\")\n document.getElementById(\"marginright\").appendChild(commentHeader);\n }\n\n if (commentHeader.nextSibling) {\n var aboutToChangePositionOffsetTop = commentHeader.nextSibling.offsetTop - 17;\n console.log(\"Detected a next sibling - Saving the next sibling PositionOffsetTop into the dedicated variable : \" + aboutToChangePositionOffsetTop);\n }\n\n if (commentHeader.previousSibling) {\n console.log(\"detected a previous sibling\")\n var commentHeaderPreviousSiblingOffsetBottom = commentHeader.previousSibling.offsetTop + 80;\n }\n ///////////////////////\n // MARGIN DEFINITION\n ///////////////////////\n\n //case 1 - no previous comment, no next comment. margin will be defined from the highlighted text.\n if (typeof commentHeader.previousSibling.offsetTop == 'undefined' && commentHeader.nextSibling === null ) {\n commentHeader.style.margin = passingobject.absoluteOffsetTop + \"px \" + \"0px \" + \"0px \" + \"10px\";\n console.log(\"case 1 - no previous comment, no next comment. margin will be defined from the highlighted text\")\n }\n //case 2 - no previous comment, but existing next comment.\n else if (typeof commentHeader.previousSibling.offsetTop == 'undefined') {\n commentHeader.style.margin = passingobject.absoluteOffsetTop + \"px \" + \"0px \" + \"0px \" + \"10px\";\n console.log(\"case 2 - no previous comment, but existing next comment - amending the margin of next annotation\")\n console.log(commentHeader.nextSibling);\n console.log(\"commentHeader.nextSibling.offsetTop = \" + commentHeader.nextSibling.offsetTop);\n console.log(\"commentHeader.absoluteOffsetBottom = \" + commentHeader.absoluteOffsetBottom);\n let startingZoneNextSibling = aboutToChangePositionOffsetTop - 27;\n //space is evaluated here.\n if (commentHeader.absoluteOffsetBottom >= startingZoneNextSibling)\n {\n console.log(\"The next sibling is too close\")\n commentHeader.style.margin = passingobject.absoluteOffsetTop + \"px \" + \"0px \" + \"0px \" + \"10px\";\n amendPositionNextSiblingClose(commentHeader);\n }\n else\n {\n console.log(\"The next sibling is far enough.\")\n amendPositionNextSiblingFar(commentHeader);\n }\n }\n //case 3 - existing previous comments, no next comments - the expected position of the new annotations\n // is proven to be lower than the previous comment absolute offset bottom)\n else if (commentHeader.nextSibling === null && passingobject.absoluteOffsetTop >= commentHeaderPreviousSiblingOffsetBottom) {\n let commentHeaderMarginSeparatingFromPreviousSibling = passingobject.absoluteOffsetTop - commentHeaderPreviousSiblingOffsetBottom;\n commentHeader.style.margin = commentHeaderMarginSeparatingFromPreviousSibling + \"px \" + \"0px \" + \"0px \" + \"10px\";\n // commentHeader.absoluteOffsetBottom = commentHeaderMarginSeparatingFromPreviousSibling + 80;\n console.log(\"case 3 - existing previous annotations, no next ones, expected position of the new annotation is proven to be lower than the previous comment absolute offset bottom\");\n }\n //case 4 - existing previous comments, no next sibling, the highlighted text is located at a smaller Y coordinate than the bottom of the previous comment.\n else if (commentHeader.nextSibling === null && passingobject.absoluteOffsetTop <= commentHeaderPreviousSiblingOffsetBottom) {\n commentHeader.style.margin = \"10px \" + \"0px \" + \"0px \" + \"10px\";\n commentHeader.absoluteOffsetBottom = comments[commentHeader.previousSibling.id].absoluteOffsetBottom + 10 + 80;\n console.log(\"Case 4 - existing previous comments, no next comments, the highlighted text is located at a smaller Y coordinate than the bottom of the previous comment\");\n console.log(\"We had to amend the absolute offset top it is now \" + commentHeader.offsetTop + \" / we also amend the absolute offset bottom, it is now \" + commentHeader.absoluteOffsetBottom)\n }\n //case 5 - existing previous comments, existing next siblings.\n //2 cases for next sibling :\n //one where the sibling is far enough below. It will need to be repositioned but will stay where it is, not impacting all siblings following him.\n // one where the sibling is less than 90px down below. It will need to move, its distance next siblings will have to be assessed to move them if needed.\n else if (commentHeader.nextSibling && passingobject.absoluteOffsetTop <= comments[commentHeader.previousSibling.id].absoluteOffsetBottom) {\n commentHeader.style.margin = \"10px \" + \"0px \" + \"0px \" + \"10px\";\n commentHeader.absoluteOffsetBottom = comments[commentHeader.previousSibling.id].absoluteOffsetBottom + 10 + 80;\n console.log(\"Case 5 - existing previous annotations, the new annotation overlaps with the previous one\");\n //checking here for the case. To check we get the offsetTop distance of the next sibling.\n //We remove 27 because the next sibling already has moved 17PX. We also want to make sure there is a 10px breathing space.\n let startingZoneNextSibling = commentHeader.nextSibling.offsetTop - 27;\n //space is evaluated here.\n if (commentHeader.absoluteOffsetBottom >= startingZoneNextSibling)\n {\n console.log(\"The next sibling is too close\")\n let commentHeaderMarginSeparatingFromPreviousSibling = passingobject.absoluteOffsetTop - comments[commentHeader.previousSibling.id].absoluteOffsetBottom;\n commentHeader.style.margin = \"10px \" + \"0px \" + \"0px \" + \"10px\";\n commentHeader.prevSiblingOffsetBottom = commentHeaderMarginSeparatingFromPreviousSibling + 80;\n amendPositionNextSiblingClose(commentHeader);\n }\n else\n {\n console.log(\"The next sibling is far enough.\")\n amendPositionNextSiblingFar(commentHeader);\n }\n }\n\n else if (commentHeader.nextSibling && passingobject.absoluteOffsetTop >= comments[commentHeader.previousSibling.id].absoluteOffsetBottom)\n {\n commentHeaderMarginSeparatingFromPreviousSibling = passingobject.absoluteOffsetTop - commentHeaderPreviousSiblingOffsetBottom;\n commentHeader.style.margin = commentHeaderMarginSeparatingFromPreviousSibling + \"px \" + \"0px \" + \"0px \" + \"10px\";\n commentHeader.prevSiblingOffsetBottom = commentHeaderMarginSeparatingFromPreviousSibling + 80;\n let startingZoneNextSibling = aboutToChangePositionOffsetTop - 10;\n console.log(\"case 6 - existing previous annotations, existing next annotations, expected position of the new annotation is proven to be lower than the previous comment absolute offset bottom\");\n //sub case\n if (commentHeader.absoluteOffsetBottom >= startingZoneNextSibling)\n {\n console.log(\"The next sibling is too close\")\n let commentHeaderMarginSeparatingFromPreviousSibling = passingobject.absoluteOffsetTop - comments[commentHeader.previousSibling.id].absoluteOffsetBottom;\n commentHeader.style.margin = commentHeaderMarginSeparatingFromPreviousSibling + \"px \" + \"0px \" + \"0px \" + \"10px\";\n amendPositionNextSiblingClose(commentHeader);\n }\n else\n {\n console.log(\"The next sibling is far enough.\")\n amendPositionNextSiblingFar(commentHeader);\n }\n }\n\n //add a notebox as a child to the element.\n createNewNoteBox();\n\n\n //check if we need toreposition the second next sibling.\n if (commentHeader.nextSibling && commentHeader.nextSibling.nextSibling) {\n console.log(\"Margintop detected for second next sibling is \" + commentHeader.nextSibling.nextSibling.style.marginTop);\n if (parseInt(commentHeader.nextSibling.nextSibling.style.marginTop) >= 80) {\n console.log(\"CALLING THE REPOSITIONING OF SECOND NEXT SIBLING BECAUSE IT IS FAR ENOUGH\")\n positionVariationSecondSibling(commentHeader, aboutToChangePositionOffsetTop);\n }\n else {\n console.log(\"Not calling the repositioning of second next sibling because it is not far enough\")\n }\n }\n\n //save the informations of the comment to an object, with ID, margin, absoluteOffsetBottom, and Content\n\n}", "function comment() {\n return wrap('comment', and(\n literal('('),\n star(and(opt(fws), ccontent)),\n opt(fws),\n literal(')')\n )());\n }", "function comments (ctx, node) {\n return `\\\\begin{comment}\\n${node.data.comment}\\n\\\\end{comment}\\n`\n}", "function patchCommentNodeProto(comment) {\n if (language_1.isUndefined(CommentNodeProto)) {\n CommentNodeProto = faux_1.PatchedNode(comment).prototype;\n }\n language_1.setPrototypeOf(comment, CommentNodeProto);\n}", "_isComment(o) {\n return Boolean(o && o.nodeType === 8)\n }", "function getSurroundingComments(node){var result=[];if(node.comments&&node.comments.length>0){node.comments.forEach(function(comment){if(comment.leading||comment.trailing){result.push(comment);}});}return result;}", "function getSurroundingComments(node){var result=[];if(node.comments && node.comments.length > 0){node.comments.forEach(function(comment){if(comment.leading || comment.trailing){result.push(comment);}});}return result;}", "function comment (ctx, node) {\n return `\\\\begin{comment}\\n${node.value}\\n\\\\end{comment}\\n`\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if the moves list is optimal and returns true/false/undefined
function isOptimal(moves, base) { if (moves && moves.length) { let position = base; const possibilities = {white: true, black: true}; for (let i = 0; i < moves.length; i++) { let move = moves[i]; let bestMove = position && position.s && position.s.length && position.s[0].m; if (move !== bestMove) { if (i % 2 === 0) { possibilities.white = false; } else { possibilities.black = false; } } if (!possibilities.white && !possibilities.black) { return bestMove ? false : undefined; } position = baseIterator.findSubPositionObject(position, move); } } return true; }
[ "function doOptimalMove() {\n var serialized = getSerialized(nodes);\n if (serialized in cache) {\n choice = cache[serialized];\n } else {\n minimax(player, nodes, 0);\n cache[serialized] = choice;\n }\n finishMove(serialized);\n}", "checkAvailableMove() {\n for (let i = 0; i < this.boardSize; i++) {\n if ((this.gameState.board[i] === this.gameState.board[i + 1] && (i + 1) % this.size !== 0) ||\n (this.gameState.board[i] === this.gameState.board[i - 1] && i % this.size !== 0) ||\n this.gameState.board[i] === this.gameState.board[i - this.size] ||\n this.gameState.board[i] === this.gameState.board[i + this.size]) {\n return true;\n }\n } return false;\n }", "hasJump() {\n // Check the moves for every piece belonging to the player\n for (let i = 0; i < this.state.pieces.length; i++) {\n const piece = this.state.pieces[i];\n if (piece.hasPiece && piece.color === this.state.turn) {\n if (this.getAvailableMoves(i).jump) {\n return true;\n }\n }\n }\n return false;\n }", "function checkMoves(){\n if(Moves > 0)\n return 1;\n return 0;\n }", "atLeastOneMove() {\n const color = this.turn;\n for (let i = 0; i < V.size.x; i++) {\n for (let j = 0; j < V.size.y; j++) {\n if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {\n const moves = this.getPotentialMovesFrom([i, j]);\n if (moves.length > 0) {\n for (let k = 0; k < moves.length; k++)\n if (this.filterValid([moves[k]]).length > 0) return true;\n }\n }\n }\n }\n return false;\n }", "function checkPossibleMoves()\n{\n\tif(squares[0].innerHTML && squares[1].innerHTML && squares[2].innerHTML && squares[3].innerHTML &&\n\tsquares[4].innerHTML && squares[5].innerHTML && squares[6].innerHTML && squares[7].innerHTML && squares[8].innerHTML){\n\t\treturn true;\n\t}\n}", "adjustValidMove(stones) {\n this.validMoves = [];\n\n for (let i = 0; i < this.totalValidMoves.length; i++) {\n if (stones - this.totalValidMoves[i] <= 1) {\n this.validMoves.push(this.totalValidMoves[i]);\n return true;\n }\n }\n\n this.validMoves = this.totalValidMoves;\n \n return true;\n }", "function checkForAvailableMoves(c,state,prevState){\n\tfor(var x = 0; x < state.size; x++){\n\t\tfor(var y = 0; y < state.size; y++){\n\t\t\tif(checkMoveValidity(x,y,c,state,prevState)) return true;\n\t\t}\n\t}\n\treturn false;\n}", "function validMove() {\n if(board[jEnd][iEnd].status.id === HoleStatusEnum.EMPTY.id) { // make sure destination is empty\n if(alreadyMoved === Boolean.FALSE) { // can only jump length 1 once, length 2 over other ball multiple times\n if(iStart-1 === iEnd) {\n if(jStart-1 === jEnd){\n return true; // TOP LEFT JUMP\n }\n if(jStart+1 === jEnd){\n return true; // BOTTOM LEFT JUMP\n }\n }\n else if(iStart+1 === iEnd) {\n if(jStart-1 === jEnd){\n return true; // TOP RIGHT JUMP\n }\n if(jStart+1 === jEnd){\n return true; // BOTTOM RIGHT JUMP\n }\n }\n else if(jStart === jEnd) {\n if(iStart-2 === iEnd){\n return true; // LEFT JUMP\n }\n if(iStart+2 === iEnd){\n return true; // RIGHT JUMP\n }\n }\n }\n\n // Jump over another ball, as many times possilbe\n if(iStart-2 === iEnd) {\n if(jStart-2 === jEnd){\n if(board[jStart-1][iStart-1].status.id !== HoleStatusEnum.EMPTY.id) { // ensure jumping over ball\n return true; // TOP LEFT JUMP\n }\n }\n if(jStart+2 === jEnd){\n if(board[jStart+1][iStart-1].status.id !== HoleStatusEnum.EMPTY.id) {\n return true; // BOTTOM LEFT JUMP\n }\n }\n }\n else if(iStart+2 === iEnd) {\n if(jStart-2 === jEnd){\n if(board[jStart-1][iStart+1].status.id !== HoleStatusEnum.EMPTY.id) {\n return true; // TOP RIGHT JUMP\n }\n }\n if(jStart+2 === jEnd){\n if(board[jStart+1][iStart+1].status.id !== HoleStatusEnum.EMPTY.id) {\n return true; // BOTTOM RIGHT JUMP\n }\n }\n }\n else if(jStart === jEnd) {\n if(iStart-4 === iEnd){\n if(board[jStart][iStart-2].status.id !== HoleStatusEnum.EMPTY.id) {\n return true; // LEFT JUMP\n }\n }\n if(iStart+4 === iEnd){\n if(board[jStart][iStart+2].status.id !== HoleStatusEnum.EMPTY.id) {\n return true; // RIGHT JUMP\n }\n }\n }\n }\n console.log(\"Move is not valid\");\n return false;\n}", "function checkOptimum() {\n\n var objectiveRow = matrix[matrix.length - 1];\n for (var i = 0; i < objectiveRow.length; i++) {\n if (objectiveRow[i] < 0) {\n // there are still negative values present\n return false;\n }\n }\n\n return true;\n }", "function hasMoves(){\n for (var x = 0; x < cols; x++){\n for (var y = 0; y < rows; y++){\n if (canJewelMove(x,y)) {\n return true\n }\n }\n }\n return false\n }", "function hasMoves() {\n for (var x = 0; x < cols; ++x) {\n for (var y = 0; y < cols; ++y) {\n if (canJewelMove(x, y)) {\n return true;\n }\n }\n }\n\n return false;\n }", "checkPossibleMove(destination, isEnemyAtDestination) {\n var move = [\n destination[0] - this.position[0], \n destination[1] - this.position[1]\n ];\n\n if (isEnemyAtDestination) {\n return this.checkListForTuple(this.captureMoveSet, move);\n\n } else if (this.position[0] === this.startingRow) {\n\n return this.checkListForTuple(this.firstMoveSet, move);\n \n } else {\n return this.checkListForTuple(this.moveSet, move);\n };\n }", "function hasMandatoryJumps(board, yourPlayerIndex) {\r\n var possibleMoves = [],\r\n delta = {row: -1, col: -1},\r\n row,\r\n col;\r\n\r\n for (row = 0; row < CONSTANT.ROW; row += 1) {\r\n for (col = 0; col < CONSTANT.COLUMN; col += 1) {\r\n delta.row = row;\r\n delta.col = col;\r\n possibleMoves = possibleMoves.concat(\r\n getJumpMoves(board, delta, yourPlayerIndex)\r\n );\r\n }\r\n }\r\n return possibleMoves.length > 0;\r\n }", "checkMines() {\n return (this.minesArray.indexOf(this.guessValue) >= 0) ? true : false; \n }", "function validMove(list,goal,type)\n{\n if(type==\"f\" || type==\"F\")\n for(x in list)\n {\n if($.inArray(goal,MAP[list[x]].fleet_moves))\n return true;\n }\n else if (type==\"a\" || type==\"A\")\n for(x in list)\n {\n if($.inArray(goal,MAP[list[x]].army_moves))\n return true;\n }\n return false;\n}", "function AIfindBestMove(colour) {\n\n var row;\n\n //loop through all columns\n for(var col = 0; col < 7; col++)\n {\n //get the first empty row in the column\n row = checkColumn(col);\n\n //if a best move is found, do not continue searching\n if(columnFull == false)\n {\n\n //Check for 3 up\n if(row > 1)\n {\n //check for 2 upwards, replace aiCol if there is 3 upwards\n if(grid[row-1][col] == colour && grid[row-2][col] == colour)\n {\n\n if(row > 2 && grid[row-3][col] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n }\n //Check for 3 to the right\n //XOOO//\n if(grid[row][col+1] == colour && grid[row][col+2] == colour && grid[row][col+3] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n //Check for 3 to the left\n //OOOX//\n if(grid[row][col-1] == colour && grid[row][col-2] == colour && grid[row][col-3] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n //OOXO//\n if(grid[row][col+1] == colour && grid[row][col-1] == colour && grid[row][col-2] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n //OXOO//\n if(grid[row][col-1] == colour && grid[row][col+1] == colour && grid[row][col+2] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n /////O//\n ////O///\n ///O////\n //X/////\n if (row < 3)\n {\n if(grid[row+1][col+1] == colour && grid[row+2][col+2] == colour && grid[row+3][col+3] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n /////X//\n ////O///\n ///O////\n //O/////\n if (row > 2)\n {\n if(grid[row-1][col-1] == colour && grid[row-2][col-2] == colour && grid[row-3][col-3] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n //O/////\n ///O////\n ////O///\n /////X//\n if (row < 3)\n {\n if(grid[row+1][col-1] == colour && grid[row+2][col-2] == colour && grid[row+3][col-3] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n //X/////\n ///O////\n ////O///\n /////O//\n if (row > 2)\n {\n if(grid[row-1][col+1] == colour && grid[row-2][col+2] == colour && grid[row-3][col+3] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n /////O//\n ////O///\n ///X////\n //O/////\n if(row > 0 && row < 4)\n {\n if(grid[row-1][col-1] == colour && grid[row+1][col+1] == colour && grid[row+2][col+2] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n /////O//\n ////X///\n ///O////\n //O/////\n if(row > 1 && row < 5)\n {\n if(grid[row-1][col-1] == colour && grid[row-2][col-2] == colour && grid[row+1][col+1] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n //O/////\n ///O////\n ////X///\n /////O//\n if(row > 0 && row < 4)\n {\n if(grid[row-1][col+1] == colour && grid[row+1][col-1] == colour && grid[row+2][col-2] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n //O/////\n ///X////\n ////O///\n /////O//\n if(row > 1 && row < 5)\n {\n if(grid[row-1][col+1] == colour && grid[row-2][col+2] == colour && grid[row+1][col-1] == colour)\n {\n aiCol = col;\n bestMove = true;\n return true;\n }\n }\n }\n }\n\n return false;\n }", "isMoveAvailable(possibleMove) {\n if (this.moves[possibleMove] == 0) return true;\n else return false;\n }", "function isWinningMove() {\n var hori = count(0, -1) + count(0, 1) - 1;\n var vert = count(-1, 0) + count(1, 0) - 1;\n var diag = count(1, -1) + count(-1, 1) - 1;\n var antd = count(1, 1) + count(-1, -1) - 1;\n // console.log(\"horizontal: \" + hori);\n // console.log(\"vertical: \" + vert);\n // console.log(\"diagonal: \" + diag);\n // console.log(\"anti-diagonal: \" + antd);\n if (hori >=4 | vert >= 4 | diag >= 4 | antd >= 4) {\n return true;\n }\n else return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
angular ui accordiongroup mod with plus/minus icon
function accordionGroupMod() { return { restrict: "E", transclude: true, scope: { heading: "@", isOpen: "=?" }, template: '<accordion-group is-open="isOpen"><accordion-heading>' + '<i class="glyphicon" ng-class="{\'glyphicon-minus\': isOpen, \'glyphicon-plus\': !isOpen}"'+ 'style="font-size: 60%; vertical-align: 2px; padding-right: 10px;"></i>{{heading}}' + '</accordion-heading><div ng-transclude></div></accordion-group>' }; }
[ "function avAccordionGroup(AV_ACCORDION){\n return {\n restrict: 'A',\n require: '^avAccordion',\n transclude: true,\n replace: true,\n templateUrl: AV_ACCORDION.TEMPLATES.GROUP,\n scope: {\n heading: '@', // Interpolate the heading attribute onto this scope\n popOverContent: '@', // Interpolate the heading attribute onto this scope\n popOverContentHeader: '@', // Interpolate the heading attribute onto this scope\n isOpen: '=?',\n initOpen: '=?',\n isDisabled: '=?'\n },\n link: function (scope, element, attrs, accordionCtrl) {\n\n accordionCtrl.addGroup(scope);\n scope.openClass = attrs.openClass || 'panel-open';\n scope.panelClass = attrs.panelClass || 'panel-default';\n scope.$watch('initOpen', function (value) {\n element.toggleClass(scope.openClass, !!value);\n scope.isOpen = !!scope.initOpen;\n });\n\n scope.toggleOpen = function ($event) {\n if (!scope.isDisabled) {\n if (!$event || $event.which === 32) {\n scope.isOpen = !scope.isOpen;\n }\n }\n };\n\n var id = 'accordion-' + scope.$id + '-' + Math.floor(Math.random() * 10000);\n scope.headingId = id + '-tab';\n scope.panelId = id + '-panel';\n }\n };\n }", "function ObuiAccordionController($scope) {\n \n $scope.oneAtATime = true;\n\n $scope.groups = [\n {\n title: 'Dynamic Group Header - 1',\n content: 'Dynamic Group Body - 1'\n },\n {\n title: 'Dynamic Group Header - 2',\n content: 'Dynamic Group Body - 2'\n }\n ];\n\n $scope.items = ['Item 1', 'Item 2', 'Item 3'];\n\n $scope.addItem = function() {\n var newItemNo = $scope.items.length + 1;\n $scope.items.push('Item ' + newItemNo);\n };\n\n $scope.status = {\n isFirstOpen: true,\n isFirstDisabled: false\n };\n \n // Alert \n \n }", "function ccwAccordion() {\n var directive = {\n bindToController: false, \n controller: Controller,\n restrict: 'A',\n };\n return directive;\n }", "function panelControlCollapse() {\n return {\n restrict: 'A',\n link: function (scope, element, attrs) {\n element.bind('click', function() {\n var parent = angular.element(element).closest('.panel');\n parent.toggleClass('panel-collapsed');\n });\n }\n };\n}", "function add_groupaccordion_toggle() {\n let acc = document.getElementsByClassName(\"groupaccordion\");\n for (let i of acc) {\n i.addEventListener(\"click\", function () {\n this.classList.toggle(\"active\");\n let panel = this.nextElementSibling;\n if (panel.style.display === \"block\") {\n panel.style.display = \"none\";\n } else {\n panel.style.display = \"block\";\n }\n });\n }\n}", "expandAccordion(event) {\n this.expand(event.target)\n }", "function expand(e) {\n if (e.isExpanded && [].indexOf.call(this.items, e.item) === 1) {\n if (e.element.querySelectorAll('.e-accordion').length > 0) {\n return;\n }\n //Initialize Nested Accordion component\n nestAcrdn = new ej.navigations.Accordion({\n expandMode: 'Single',\n items: [\n { header: 'Sensor', content: '#Sensor_features' },\n { header: 'Camera', content: '#Camera_features' },\n { header: 'Video Recording', content: '#Video_Rec_features' },\n ]\n });\n //Render initialized Nested Accordion component\n nestAcrdn.appendTo('#nested_Acc');\n }\n}", "function openAccordionElement($element) {\n\t\t$element.children('.accordion-icon').text('-');\n\t\t$element.next().show(500);\n\t}", "toggleExpandGroup(group) {\n this.toggle.emit({\n type: 'group',\n value: group\n });\n }", "function initializeToolsAccordion() {\r\n var icons = {\r\n header: \"ui-icon-triangle-1-e\",\r\n activeHeader: \"ui-icon-triangle-1-s\"\r\n };\r\n $(\"#custom-tools-accordion\").accordion({\r\n heightStyle: \"content\",\r\n icons: icons,\r\n active: 0 //which panel is open by default\r\n });\r\n $( \"#toggle\" ).button().click(function () {\r\n if ( $( \"#accordion\" ).accordion( \"option\", \"icons\" ) ) {\r\n $( \"#accordion\" ).accordion( \"option\", \"icons\", null );\r\n } else {\r\n $( \"#accordion\" ).accordion( \"option\", \"icons\", icons );\r\n }\r\n });\r\n // $(\".activateSections\").click(function () {\r\n // $(\"#custom-tools-accordion\").accordion({ active: 2});\r\n // });\r\n }", "function expandItem(){\n vm.expanded = !vm.expanded;\n }", "_selectionSummaryAccordian() {\n const cf = this._currentItem;\n\n // dissolveSingle => title not shown if only one item in accordian\n const a = new Accordian({\n onSelect: (id) => this.switchItem(id),\n alwaysOpen: true,\n dissolveSingle: true,\n });\n\n const fs = new FactSet(this._currentItemList);\n for (const fact of this._currentItemList) {\n let factHTML;\n const title = fs.minimallyUniqueLabel(fact);\n if (fact instanceof Fact) {\n factHTML = $(require('../html/fact-details.html')); \n $('.std-label', factHTML).text(fact.getLabelOrName(\"std\", true));\n $('.documentation', factHTML).text(fact.getLabel(\"doc\") || \"\");\n $('tr.concept td', factHTML)\n .find('.text')\n .text(fact.conceptName())\n .attr(\"title\", fact.conceptName())\n .end()\n .find('.clipboard-copy')\n .data('cb-text', fact.conceptName())\n .end();\n $('tr.period td', factHTML)\n .text(fact.periodString());\n if (fact.isNumeric()) {\n $('tr.period td', factHTML).append(\n $(\"<span></span>\") \n .addClass(\"analyse\")\n .text(\"\")\n .click(() => this.analyseDimension(fact, [\"p\"]))\n );\n }\n this._updateEntityIdentifier(fact, factHTML);\n this._updateValue(fact, false, factHTML);\n\n const accuracyTD = $('tr.accuracy td', factHTML).empty().append(fact.readableAccuracy());\n if (!fact.isNumeric() || fact.isNil()) {\n accuracyTD.wrapInner(\"<i></i>\");\n }\n\n const scaleTD = $('tr.scale td', factHTML).empty().append(fact.readableScale());\n if (!fact.isNumeric() || fact.isNil()) {\n scaleTD.wrapInner(\"<i></i>\");\n }\n\n $('#dimensions', factHTML).empty();\n const taxonomyDefinedAspects = fact.aspects().filter(a => a.isTaxonomyDefined());\n if (taxonomyDefinedAspects.length === 0) {\n $('#dimensions-label', factHTML).hide();\n }\n for (const aspect of taxonomyDefinedAspects) {\n const h = $('<div class=\"dimension\"></div>')\n .text(aspect.label() || aspect.name())\n .appendTo($('#dimensions', factHTML));\n if (fact.isNumeric()) {\n h.append(\n $(\"<span></span>\") \n .addClass(\"analyse\")\n .text(\"\")\n .on(\"click\", () => this.analyseDimension(fact, [aspect.name()]))\n )\n }\n const s = $('<div class=\"dimension-value\"></div>')\n .text(aspect.valueLabel())\n .appendTo(h);\n if (aspect.isNil()) {\n s.wrapInner(\"<i></i>\");\n }\n }\n }\n else if (fact instanceof Footnote) {\n factHTML = $(require('../html/footnote-details.html')); \n this._updateValue(fact, false, factHTML);\n }\n a.addCard(\n title,\n factHTML, \n fact.id == cf.id,\n fact.id\n );\n }\n return a;\n }", "function addAccordeon(){\r\n\t\ttry{\r\n\t\t\tvar accBtn = document.getElementsByClassName(\"icon-itaufonts_seta_achatada\");\r\n\t\t\tfor (var i = 0; i < accBtn.length; i++) {\r\n\t\t\t\taccBtn[i].addEventListener(\"click\", function () {\r\n\t\t\t\t\ttoggleClass(this, \"active\"); \r\n\t\t\t\t\ttoggleClass(this.parentNode.parentNode, \"closed\"); \r\n\t\t\t\t\ttoggleClass(this.parentNode.parentNode, \"open\"); \r\n\t\t\t\t\tvar panel = this.parentNode.nextElementSibling;\r\n\t\t\t\t\tif (panel.style.display === \"block\") {\r\n\t\t\t\t\t\tpanel.style.display = \"none\";\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tpanel.style.display = \"block\";\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}catch (e){}\r\n\t}", "function accordionToggleClose(segment) {\n segment.attr('aria-checked','false');\n segment\n .children('i.accordion-arrow')\n .html(\"expand_more\");\n segment\n .parent('li')\n .children('.accordion-content')\n .addClass('collapsed')\n .slideToggle( \"fast\" );\n }", "function expand() {\n if(!expanded){\n setExpanded(true);\n setIcon(\"bi-chevron-up\");\n } else {\n setExpanded(false);\n setIcon(\"bi-chevron-down\");\n }\n }", "function expandAllAccordions(expand_by_click) {\n expand_by_url_param = getParameterByName('expand');\n if (expand_by_click || expand_by_url_param == 'true') {\n $(\".accordion-body\").addClass(\"in\");\n $(\".accordion-toggle\").children(\".icon-plus\").addClass(\"icon-minus\");\n $(\".accordion-toggle\").children(\".icon-minus\").removeClass(\"icon-plus\");\n }\n}", "function accordionToggleOpen(segment) {\n segment\n .attr('aria-checked','true');\n segment\n .children('i.accordion-arrow')\n .html(\"expand_less\");\n segment\n .parent('li')\n .children('.accordion-content')\n .removeClass('collapsed')\n .slideToggle( \"fast\" );\n }", "setSummaryExpandedState(expandButton) {\n expandButton.setAttribute('data-category', 'collapse');\n expandButton.setAttribute('aria-label', '$i18n{FEEDBACK_COLLAPSE_LABEL}');\n expandButton.setAttribute('aria-expanded', 'true');\n this.panels_.hidden = false;\n this.separator_.hidden = false;\n }", "function openAccordion() {\n TweenLite.set(inner, { height: \"auto\" });\n TweenLite.from(inner, 0.2, { height: 0 });\n inner.attr('aria-hidden', 'false'); // toggle aria-hidden\n trigger.attr('aria-expanded', 'true'); // toggle aria-expanded\n triggerArrow.removeClass('typcn-arrow-sorted-down');\n triggerArrow.addClass('typcn-arrow-sorted-up');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unit Ratio Calculation / When queried, the browser returns (most) CSS property values in pixels. Therefore, if an endValue with a unit type of %, em, or rem is animated toward, startValue must be converted from pixels into the same unit type as endValue in order for value manipulation logic (increment/decrement) to proceed. Further, if the startValue was forcefed or transferred from a previous call, startValue may also not be in pixels. Unit conversion logic therefore consists of two steps: 1) Calculating the ratio of %/em/rem/vh/vw relative to pixels 2) Converting startValue into the same unit of measurement as endValue based on these ratios. / Unit conversion ratios are calculated by inserting a sibling node next to the target node, copying over its position property, setting values with the target unit type then comparing the returned pixel value. / Note: Even if only one of these unit types is being animated, all unit ratios are calculated at once since the overhead of batching the SETs and GETs together upfront outweights the potential overhead of layout thrashing caused by requerying for uncalculated ratios for subsequentlyprocessed properties. / Todo: Shift this logic into the calls' first tick instance so that it's synced with RAF.
function calculateUnitRatios () { /************************ Same Ratio Checks ************************/ /* The properties below are used to determine whether the element differs sufficiently from this call's previously iterated element to also differ in its unit conversion ratios. If the properties match up with those of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity, this is done to minimize DOM querying. */ var sameRatioIndicators = { myParent: element.parentNode || document.body, /* GET */ position: CSS.getPropertyValue(element, "position"), /* GET */ fontSize: CSS.getPropertyValue(element, "fontSize") /* GET */ }, /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */ samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)), /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */ sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize); /* Store these ratio indicators call-wide for the next element to compare against. */ callUnitConversionData.lastParent = sameRatioIndicators.myParent; callUnitConversionData.lastPosition = sameRatioIndicators.position; callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize; /*************************** Element-Specific Units ***************************/ /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */ var measurement = 100, unitRatios = {}; if (!sameEmRatio || !samePercentRatio) { var dummy = Data(element).isSVG ? document.createElementNS("http://www.w3.org/2000/svg", "rect") : document.createElement("div"); Velocity.init(dummy); sameRatioIndicators.myParent.appendChild(dummy); /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped. Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */ /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */ $.each([ "overflow", "overflowX", "overflowY" ], function(i, property) { Velocity.CSS.setPropertyValue(dummy, property, "hidden"); }); Velocity.CSS.setPropertyValue(dummy, "position", sameRatioIndicators.position); Velocity.CSS.setPropertyValue(dummy, "fontSize", sameRatioIndicators.fontSize); Velocity.CSS.setPropertyValue(dummy, "boxSizing", "content-box"); /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */ $.each([ "minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height" ], function(i, property) { Velocity.CSS.setPropertyValue(dummy, property, measurement + "%"); }); /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */ Velocity.CSS.setPropertyValue(dummy, "paddingLeft", measurement + "em"); /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */ unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, "width", null, true)) || 1) / measurement; /* GET */ unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, "height", null, true)) || 1) / measurement; /* GET */ unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, "paddingLeft")) || 1) / measurement; /* GET */ sameRatioIndicators.myParent.removeChild(dummy); } else { unitRatios.emToPx = callUnitConversionData.lastEmToPx; unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth; unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight; } /*************************** Element-Agnostic Units ***************************/ /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null, so we calculate it now. */ if (callUnitConversionData.remToPx === null) { /* Default to browsers' default fontSize of 16px in the case of 0. */ callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, "fontSize")) || 16; /* GET */ } /* Similarly, viewport units are %-relative to the window's inner dimensions. */ if (callUnitConversionData.vwToPx === null) { callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */ callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */ } unitRatios.remToPx = callUnitConversionData.remToPx; unitRatios.vwToPx = callUnitConversionData.vwToPx; unitRatios.vhToPx = callUnitConversionData.vhToPx; if (Velocity.debug >= 1) console.log("Unit ratios: " + JSON.stringify(unitRatios), element); return unitRatios; }
[ "function calculateUnitRatios(){ /************************\n Same Ratio Checks\n ************************/ /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */var sameRatioIndicators={myParent:element.parentNode||document.body, /* GET */position:CSS.getPropertyValue(element,\"position\"), /* GET */fontSize:CSS.getPropertyValue(element,\"fontSize\") /* GET */}, /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */samePercentRatio=sameRatioIndicators.position===callUnitConversionData.lastPosition&&sameRatioIndicators.myParent===callUnitConversionData.lastParent, /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */sameEmRatio=sameRatioIndicators.fontSize===callUnitConversionData.lastFontSize; /* Store these ratio indicators call-wide for the next element to compare against. */callUnitConversionData.lastParent=sameRatioIndicators.myParent;callUnitConversionData.lastPosition=sameRatioIndicators.position;callUnitConversionData.lastFontSize=sameRatioIndicators.fontSize; /***************************\n Element-Specific Units\n ***************************/ /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */var measurement=100,unitRatios={};if(!sameEmRatio||!samePercentRatio){var dummy=Data(element).isSVG?document.createElementNS(\"http://www.w3.org/2000/svg\",\"rect\"):document.createElement(\"div\");Velocity.init(dummy);sameRatioIndicators.myParent.appendChild(dummy); /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */ /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */$.each([\"overflow\",\"overflowX\",\"overflowY\"],function(i,property){Velocity.CSS.setPropertyValue(dummy,property,\"hidden\");});Velocity.CSS.setPropertyValue(dummy,\"position\",sameRatioIndicators.position);Velocity.CSS.setPropertyValue(dummy,\"fontSize\",sameRatioIndicators.fontSize);Velocity.CSS.setPropertyValue(dummy,\"boxSizing\",\"content-box\"); /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */$.each([\"minWidth\",\"maxWidth\",\"width\",\"minHeight\",\"maxHeight\",\"height\"],function(i,property){Velocity.CSS.setPropertyValue(dummy,property,measurement+\"%\");}); /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */Velocity.CSS.setPropertyValue(dummy,\"paddingLeft\",measurement+\"em\"); /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */unitRatios.percentToPxWidth=callUnitConversionData.lastPercentToPxWidth=(parseFloat(CSS.getPropertyValue(dummy,\"width\",null,true))||1)/measurement; /* GET */unitRatios.percentToPxHeight=callUnitConversionData.lastPercentToPxHeight=(parseFloat(CSS.getPropertyValue(dummy,\"height\",null,true))||1)/measurement; /* GET */unitRatios.emToPx=callUnitConversionData.lastEmToPx=(parseFloat(CSS.getPropertyValue(dummy,\"paddingLeft\"))||1)/measurement; /* GET */sameRatioIndicators.myParent.removeChild(dummy);}else {unitRatios.emToPx=callUnitConversionData.lastEmToPx;unitRatios.percentToPxWidth=callUnitConversionData.lastPercentToPxWidth;unitRatios.percentToPxHeight=callUnitConversionData.lastPercentToPxHeight;} /***************************\n Element-Agnostic Units\n ***************************/ /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */if(callUnitConversionData.remToPx===null){ /* Default to browsers' default fontSize of 16px in the case of 0. */callUnitConversionData.remToPx=parseFloat(CSS.getPropertyValue(document.body,\"fontSize\"))||16; /* GET */} /* Similarly, viewport units are %-relative to the window's inner dimensions. */if(callUnitConversionData.vwToPx===null){callUnitConversionData.vwToPx=parseFloat(window.innerWidth)/100; /* GET */callUnitConversionData.vhToPx=parseFloat(window.innerHeight)/100; /* GET */}unitRatios.remToPx=callUnitConversionData.remToPx;unitRatios.vwToPx=callUnitConversionData.vwToPx;unitRatios.vhToPx=callUnitConversionData.vhToPx;if(Velocity.debug>=1)console.log(\"Unit ratios: \"+JSON.stringify(unitRatios),element);return unitRatios;}", "function calculateUnitRatios() {\n\n\t\t\t\t\t\t\t\t\t\t/************************\n\t\t\t\t\t\t\t\t\t\t Same Ratio Checks\n\t\t\t\t\t\t\t\t\t\t************************/\n\n\t\t\t\t\t\t\t\t\t\t/* The properties below are used to determine whether the element differs sufficiently from this call's\n\t\t\t\t\t\t\t\t\t\t previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n\t\t\t\t\t\t\t\t\t\t of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n\t\t\t\t\t\t\t\t\t\t this is done to minimize DOM querying. */\n\t\t\t\t\t\t\t\t\t\tvar sameRatioIndicators = {\n\t\t\t\t\t\t\t\t\t\t\t\tmyParent: element.parentNode || document.body,\n\t\t\t\t\t\t\t\t\t\t\t\t/* GET */\n\t\t\t\t\t\t\t\t\t\t\t\tposition: CSS.getPropertyValue(element, \"position\"),\n\t\t\t\t\t\t\t\t\t\t\t\t/* GET */\n\t\t\t\t\t\t\t\t\t\t\t\tfontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t/* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n\t\t\t\t\t\t\t\t\t\t\tsamePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n\t\t\t\t\t\t\t\t\t\t\t/* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n\t\t\t\t\t\t\t\t\t\t\tsameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n\t\t\t\t\t\t\t\t\t\t/* Store these ratio indicators call-wide for the next element to compare against. */\n\t\t\t\t\t\t\t\t\t\tcallUnitConversionData.lastParent = sameRatioIndicators.myParent;\n\t\t\t\t\t\t\t\t\t\tcallUnitConversionData.lastPosition = sameRatioIndicators.position;\n\t\t\t\t\t\t\t\t\t\tcallUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n\t\t\t\t\t\t\t\t\t\t/***************************\n\t\t\t\t\t\t\t\t\t\t Element-Specific Units\n\t\t\t\t\t\t\t\t\t\t***************************/\n\n\t\t\t\t\t\t\t\t\t\t/* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n\t\t\t\t\t\t\t\t\t\t of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n\t\t\t\t\t\t\t\t\t\tvar measurement = 100,\n\t\t\t\t\t\t\t\t\t\t\tunitRatios = {};\n\n\t\t\t\t\t\t\t\t\t\tif (!sameEmRatio || !samePercentRatio) {\n\t\t\t\t\t\t\t\t\t\t\tvar dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n\t\t\t\t\t\t\t\t\t\t\tVelocity.init(dummy);\n\t\t\t\t\t\t\t\t\t\t\tsameRatioIndicators.myParent.appendChild(dummy);\n\n\t\t\t\t\t\t\t\t\t\t\t/* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n\t\t\t\t\t\t\t\t\t\t\t Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n\t\t\t\t\t\t\t\t\t\t\t/* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n\t\t\t\t\t\t\t\t\t\t\t$.each([\"overflow\", \"overflowX\", \"overflowY\"], function(i, property) {\n\t\t\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n\t\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n\t\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n\t\t\t\t\t\t\t\t\t\t\t/* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n\t\t\t\t\t\t\t\t\t\t\t$.each([\"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\"], function(i, property) {\n\t\t\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t/* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n\t\t\t\t\t\t\t\t\t\t\tVelocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n\t\t\t\t\t\t\t\t\t\t\t/* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n\t\t\t\t\t\t\t\t\t\t\tunitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n\t\t\t\t\t\t\t\t\t\t\tunitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n\t\t\t\t\t\t\t\t\t\t\tunitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n\t\t\t\t\t\t\t\t\t\t\tsameRatioIndicators.myParent.removeChild(dummy);\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tunitRatios.emToPx = callUnitConversionData.lastEmToPx;\n\t\t\t\t\t\t\t\t\t\t\tunitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n\t\t\t\t\t\t\t\t\t\t\tunitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t/***************************\n\t\t\t\t\t\t\t\t\t\t Element-Agnostic Units\n\t\t\t\t\t\t\t\t\t\t***************************/\n\n\t\t\t\t\t\t\t\t\t\t/* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n\t\t\t\t\t\t\t\t\t\t once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n\t\t\t\t\t\t\t\t\t\t that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n\t\t\t\t\t\t\t\t\t\t so we calculate it now. */\n\t\t\t\t\t\t\t\t\t\tif (callUnitConversionData.remToPx === null) {\n\t\t\t\t\t\t\t\t\t\t\t/* Default to browsers' default fontSize of 16px in the case of 0. */\n\t\t\t\t\t\t\t\t\t\t\tcallUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t/* Similarly, viewport units are %-relative to the window's inner dimensions. */\n\t\t\t\t\t\t\t\t\t\tif (callUnitConversionData.vwToPx === null) {\n\t\t\t\t\t\t\t\t\t\t\tcallUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n\t\t\t\t\t\t\t\t\t\t\tcallUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tunitRatios.remToPx = callUnitConversionData.remToPx;\n\t\t\t\t\t\t\t\t\t\tunitRatios.vwToPx = callUnitConversionData.vwToPx;\n\t\t\t\t\t\t\t\t\t\tunitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n\t\t\t\t\t\t\t\t\t\tif (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n\t\t\t\t\t\t\t\t\t\treturn unitRatios;\n\t\t\t\t\t\t\t\t\t}", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function updateUnitPositions() {\n var _this_ = this;\n var wh = window.innerHeight;\n for (var i = 0; i < _this_._logics_.length; i++) {\n var _l = _this_._logics_[i];\n for (var j = 0; j < _l.units.length; j++) {\n var _u = _l.units[j];\n var _bcr = _u.el.getBoundingClientRect();\n // Update progress of each unit in a logic.\n _u.progress.px = _this_.baseline.px - (_bcr.top + _u.baseline.px);\n _u.progress.vf = _u.progress.px / wh;\n _u.progress.f = _bcr.height === 0 ? 0 : _u.progress.px / _bcr.height;\n\n if (_l.range) {\n\n if (_l.range[0] <= _u.progress[_l._range_unit_] && _u.progress[_l._range_unit_] <= _l.range[1]) {\n // In range\n\n // NOTE: Review & test required.\n // Editing this part as it should change the flags in edge cases.\n // Not completely removing legacy code as not yet tested.\n // _u._top_edge_rendered_ = false;\n // _u._bot_edge_rendered_ = false;\n _u._top_edge_rendered_ = _l.range[0] === _u.progress[_l._range_unit_] ? true : false;\n _u._bot_edge_rendered_ = _l.range[1] === _u.progress[_l._range_unit_] ? true : false;\n _l.callback.apply(_u, _l.callbackArgs);\n } else {\n // Out of range\n\n if (_u.progress[_l._range_unit_] < _l.range[0]) {\n // Unit locates lower than Scrawler Baseline.\n\n _u._bot_edge_rendered_ = false;\n\n if (_l._range_unit_ === 'px') {\n _u.progress.px = _l.range[0];\n _u.progress.f = _bcr.height === 0 ? 0 : _u.progress.px / _bcr.height;\n } else {\n // === 'f'\n _u.progress.f = _l.range[0];\n _u.progress.px = _bcr.height * _u.progress.f;\n }\n\n _u.progress.vf = _u.progress.px / wh;\n\n if (!_u._top_edge_rendered_) {\n _u._top_edge_rendered_ = true;\n _l.callback.apply(_u, _l.callbackArgs);\n } else {}\n } else {\n // Unit locates higher than Scrawler Baseline.\n\n _u._top_edge_rendered_ = false;\n\n if (_l._range_unit_ === 'px') {\n _u.progress.px = _l.range[1];\n _u.progress.f = _bcr.height === 0 ? 0 : _u.progress.px / _bcr.height;\n } else {\n // === 'f'\n _u.progress.f = _l.range[1];\n _u.progress.px = _bcr.height * _u.progress.f;\n }\n\n _u.progress.vf = _u.progress.px / wh;\n\n if (!_u._bot_edge_rendered_) {\n _u._bot_edge_rendered_ = true;\n _l.callback.apply(_u, _l.callbackArgs);\n } else {}\n }\n }\n } else {\n _l.callback.apply(_u, _l.callbackArgs);\n }\n }\n }\n }", "function measureUpdate(unitSet) {\n let unitsTo = {\n \"length\": \"\",\n \"speed\": \"\",\n \"temperature\": \"\",\n \"volume_flow_rate\": \"\"\n }\n if(unitSet == 'imperial') {\n // Imperial\n // Speed: mile/hour\n // Length: feet\n // Volume Flow Rate: cubic feet/second\n // Temperature: Fahrenheit\n unitsTo.length = 'ft';\n unitsTo.speed = 'm/h';\n unitsTo.temperature = 'F';\n unitsTo.volume_flow_rate = 'ft3/s';\n } else {\n // Metric\n // Speed: metre/second\n // Length: meter\n // Volume Flow Rate: cubic meter/second\n // Temperature: Celsius\n unitsTo.length = 'm';\n unitsTo.speed = 'm/s';\n unitsTo.temperature = 'C';\n unitsTo.volume_flow_rate = 'm3/s';\n }\n let unitBase = 'FT';\n if(unitSet == 'metric') {\n unitBase = 'M';\n }\n\n // Select values of all the items that need to have their units update\n // Height range\n let heightUnit = document.querySelector('.height-wrapper').getAttribute('data-unit');\n let highHeightMeasure = parseInt(document.querySelector('#high-height').textContent);\n let lowHeightMeasure = parseInt(document.querySelector('#low-height').textContent);\n // Convert\n highHeightMeasure = Math.round(convert(highHeightMeasure).from(heightUnit).to(unitsTo.length)*10)/10;\n lowHeightMeasure = Math.round(convert(lowHeightMeasure).from(heightUnit).to(unitsTo.length)*10)/10;\n // Set\n document.querySelector('.height-wrapper').setAttribute('data-unit', unitsTo.length);\n document.querySelector('#high-height').innerHTML = highHeightMeasure;\n document.querySelector('#low-height').innerHTML = lowHeightMeasure;\n // Measurement\n document.querySelector('#height-unit').innerHTML = '';\n document.querySelector('#height-unit').insertAdjacentText('afterbegin', unitBase);\n\n // Flow range\n let rangeFlowUnit = document.querySelector('.range-wrapper').getAttribute('data-unit');\n let highRangeFlowMeasure = parseInt(document.querySelector('#high-range').textContent);\n let lowRangeFlowMeasure = parseInt(document.querySelector('#low-range').textContent);\n // Convert\n highRangeFlowMeasure = Math.round(convert(highRangeFlowMeasure).from(rangeFlowUnit).to(unitsTo.volume_flow_rate));\n lowRangeFlowMeasure = Math.round(convert(lowRangeFlowMeasure).from(rangeFlowUnit).to(unitsTo.volume_flow_rate));\n // Set\n document.querySelector('.range-wrapper').setAttribute('data-unit', unitsTo.volume_flow_rate);\n document.querySelector('#high-range').innerHTML = highRangeFlowMeasure;\n document.querySelector('#low-range').innerHTML = lowRangeFlowMeasure;\n // Measurement\n document.querySelector('#range-unit').innerHTML = '';\n document.querySelector('#range-unit').insertAdjacentText('afterbegin', unitBase);\n document.querySelector('#range-unit').insertAdjacentHTML('beforeend', '<span class=\"superscript\">3</span>');\n document.querySelector('#range-unit').insertAdjacentText('beforeend', '/S');\n\n // Current temp\n let currentTempUnit = document.querySelector('.weather-subtitle').getAttribute('data-unit');\n let currentWaterTempMeasure = document.querySelector('#water-temp').textContent.split('o')[0].split(' ')[1];\n let currentAirTempMeasure = parseInt(document.querySelector('#air-temp').textContent.split('o')[0].split(' ')[1]);\n // Convert\n if(currentWaterTempMeasure !== '-') {\n // Water temp is not a null value\n currentWaterTempMeasure = Math.round(convert(parseInt(currentWaterTempMeasure)).from(currentTempUnit).to(unitsTo.temperature));\n }\n currentAirTempMeasure = Math.round(convert(currentAirTempMeasure).from(currentTempUnit).to(unitsTo.temperature));\n // Set\n document.querySelector('.weather-subtitle').setAttribute('data-unit', unitsTo.temperature);\n // Water\n document.querySelector('#water-temp').innerHTML = '';\n document.querySelector('#water-temp').insertAdjacentText('afterbegin', 'Water: ' + currentWaterTempMeasure);\n document.querySelector('#water-temp').insertAdjacentHTML('beforeend', '<span class=\"degree\">o</span>');\n document.querySelector('#water-temp').insertAdjacentText('beforeend', unitsTo.temperature);\n // Air\n document.querySelector('#air-temp').innerHTML = '';\n document.querySelector('#air-temp').insertAdjacentText('afterbegin', 'Air: ' + currentAirTempMeasure);\n document.querySelector('#air-temp').insertAdjacentHTML('beforeend', '<span class=\"degree\">o</span>');\n document.querySelector('#air-temp').insertAdjacentText('beforeend', unitsTo.temperature);\n\n // Current flow\n let currentFlowUnit = document.querySelector('#current-flow').getAttribute('data-unit');\n let currentFlowMeasure = parseInt(document.querySelector('#current-flow > .container').textContent);\n // Convert\n currentFlowMeasure = Math.round(convert(currentFlowMeasure).from(currentFlowUnit).to(unitsTo.volume_flow_rate));\n // Set\n document.querySelector('#current-flow').setAttribute('data-unit', unitsTo.volume_flow_rate);\n document.querySelector('#current-flow > .container').textContent = currentFlowMeasure;\n}", "_regexUnits(units) {\n const re = this.regex;\n const m = re.exec(units);\n const op = m[2] ? (m[2][0] === '/' ?\n 'div' : (m[2][0] === '*' ? 'multi' : null)) : null;\n const x = m[1] ? m[1].toLowerCase() : null;\n const y = m[3] ? m[3].toLowerCase() : null;\n let ret = {unit: '', factor: 1.0};\n if (!x) return ret;\n if (!(x in this.unitMap)) return ret;\n ret.unit = this.unitMap[x][1];\n ret.factor = ret.factor * this.unitMap[x][0];\n if (y) {\n if (!(y in this.unitMap)) { // TODO: support recursive\n return {unit: '', factor: 1.0};\n }\n switch (op) {\n case 'multi':\n ret.unit = ret.unit + '*' + this.unitMap[y][1];\n ret.factor = ret.factor * this.unitMap[y][0];\n break;\n case 'div':\n ret.unit = ret.unit + '/' + this.unitMap[y][1];\n ret.factor = ret.factor / this.unitMap[y][0];\n break;\n default:\n break;\n }\n }\n return ret;\n }", "function updateUnits() {\n vwCache = {};\n units = {\n px: 1,\n width: Math.max(window.innerWidth || 0, docElm.clientWidth),\n height: Math.max(window.innerHeight || 0, docElm.clientHeight),\n em: getEmValue(),\n rem: getEmValue()\n };\n units.vw = units.width / 100;\n units.vh = units.height / 100;\n units.orientation = units.height > units.width; // If portrait\n units.devicePixelRatio = window.devicePixelRatio || 1;\n units.dpi = 0; // @todo\n units.dppx = 0; // @todo\n units.resolution = 0; // @todo\n }", "set referencePixelsPerUnit(value) {}", "convertUnit() {\n const { first, second } = this.state;\n \n const firstInGram = this.convertToGram(first);\n const secondInGram = this.convertToGram(second);\n\n this.updateFactor((firstInGram / secondInGram))\n }", "function move(elem, start, target, progress, spatialDelta, spatialMagnitude, unit){\n\n var unitString;\n \n switch(unit){\n\n case Unit.PERCENT:\n unitString = \"%\";\n break;\n \n case Unit.PIXEL:\n unitString = \"px\";\n break;\n\n default:\n unitString = \"%\";\n\n }\n \n //console.log(\"Element: \"+elem.id);\n //console.log(\"Start: \"+start.toString());\n //console.log(\"Target: \"+target.toString());\n var vector = new Vector(start, target);\n //console.log(\"Vector: \"+vector.toString());\n var scaled = vector.mult(progress);\n //console.log(\"Progress: \"+progress)\n //console.log(\"Scaled: \"+scaled.toString());\n\n var magnitude = spatialMagnitude(progress);\n //console.log(\"Magnitude: \"+magnitude);\n var offset = spatialDelta(scaled, progress).mult(magnitude);\n //console.log(\"Offset: \"+offset.toString());\n var result = scaled.add(offset);\n //console.log(\"Result: \"+result.toString());\n\n elem.style.left = result.end.x+unitString;\n elem.style.top = result.end.y+unitString;\n}", "function convertUnits(unit, value){\n if (unit === \"inch\") return value * 2.54 + \" centimetres\";\n else if (unit === \"foot\") return value * 30.48 + \" centimetres\";\n else if (unit === \"yard\") return value * 0.91 + \" metres\";\n else if (unit === \"mile\") return value * 1.6 + \" kilometres\";\n else if (unit === \"league\") return value * 4.82 + \" kilometres\";\n else if (unit === \"nautical mile\") return value * 1.85 + \" kilometres\";\n else if (unit === \"acre\") return value * 0.4 + \" hectares\";\n else if (unit === \"ounce\") return value * 28.41 + \" mililitres\";\n else if (unit === \"pint\") return value * 0.56 + \" litres\";\n else if (unit === \"pound\") return value * 0.45 + \" kilograms\";\n else if (unit === \"centimeter\") return value / 2.54 + \" inches\";\n else if (unit === \"meter\") return value / 0.91 + \" yards\";\n else if (unit === \"kilometer\") return value / 1.6 + \" miles \" + value / 4.82 + \" leagues \" + value / 1.85 + \" nautical miles\";\n else if (unit === \"hectare\") return value / 0.4 + \" acres\";\n else if (unit === \"mililitre\") return value / 28.41 + \" ounces\";\n else if (unit === \"litre\") return value / 0.56 + \" pints\";\n else if (unit === \"kilogram\") return value / 0.45 + \" pounds\";\n else console.log(\"Try another unit.\");\n}", "refreshFromPixels() {\n \"use strict\";\n this._unit = Field.pixel2units(this._pixel);\n }", "function changeAttribute(element,startValue=\"0\",endValue,percentage,property,unit=\"\"){\n newValue = ((endValue - startValue) * percentage) + startValue\n element.css(property,newValue + unit)\n}", "refreshFromUnits() {\n \"use strict\";\n this._pixel = Field.units2pixel(this._unit);\n }", "function ValueAndUnit(value,/** defines the unit to store */unit,/** defines a boolean indicating if the value can be negative */negativeValueAllowed){if(unit===void 0){unit=ValueAndUnit.UNITMODE_PIXEL;}if(negativeValueAllowed===void 0){negativeValueAllowed=true;}this.unit=unit;this.negativeValueAllowed=negativeValueAllowed;this._value=1;/**\n * Gets or sets a value indicating that this value will not scale accordingly with adaptive scaling property\n * @see https://doc.babylonjs.com/how_to/gui#adaptive-scaling\n */this.ignoreAdaptiveScaling=false;this._value=value;this._originalUnit=unit;}", "function convert(value, unit) {\n var baseValue = self.unitValues[unit];\n return value / baseValue;\n }", "function _normalizeSpeedUnit(units) {\n\t if (units) {\n\t switch (units.toLowerCase()) {\n\t case \"feetpersecond\":\n\t case \"footsecond\":\n\t case \"ftps\":\n\t case \"ft/s\":\n\t return SpeedUnits.feetPerSecond;\n\t case \"milesperhour\":\n\t case \"mileperhour\":\n\t case \"mph\":\n\t case \"mi/hr\":\n\t case \"mi/h\":\n\t return SpeedUnits.milesPerHour;\n\t case \"knots\":\n\t case \"knot\":\n\t case \"knts\":\n\t case \"knt\":\n\t case \"kn\":\n\t case \"kt\":\n\t return SpeedUnits.knots;\n\t case \"mach\":\n\t case \"m\":\n\t return SpeedUnits.mach;\n\t case \"kilometersperhour\":\n\t case \"kilometresperhour\":\n\t case \"kmperhour\":\n\t case \"kmph\":\n\t case \"km/hr\":\n\t case \"km/h\":\n\t return SpeedUnits.kilometersPerHour;\n\t case \"meterspersecond\":\n\t case \"metrespersecond\":\n\t case \"mps\":\n\t case \"ms\":\n\t case \"m/s\":\n\t default:\n\t return SpeedUnits.metersPerSecond;\n\t }\n\t }\n\t return SpeedUnits.metersPerSecond;\n\t}", "function ensureUnit(val){return val+(Object(min_dash__WEBPACK_IMPORTED_MODULE_0__[\"isNumber\"])(val)?'px':'');}", "function _normalizeAccelerationUnit(units) {\n\t // Convert to metersPerSecondSquared\n\t if (units) {\n\t switch (units.toLowerCase()) {\n\t case \"milespersecondsquared\": // mi/s^2\n\t case \"milepersecondsquared\":\n\t case \"mi/s^2\":\n\t case \"mi/s2\":\n\t return AccelerationUnits.milesPerSecondSquared;\n\t case \"kilometerspersecondsquared\": // km/s^2\n\t case \"kilometrespersecondsquared\":\n\t case \"kilometerpersecondsquared\":\n\t case \"kilometrepersecondsquared\":\n\t case \"km/s^2\":\n\t case \"km/s2\":\n\t return AccelerationUnits.kilometersPerSecondSquared;\n\t case \"knotspersecond\": // knts/s\n\t case \"knotpersecond\":\n\t case \"knts/s\":\n\t case \"kn/s\":\n\t case \"kt/s\":\n\t return AccelerationUnits.knotsPerSecond;\n\t case \"standardgravity\": // g\n\t case \"g\":\n\t return AccelerationUnits.standardGravity;\n\t case \"feetpersecondsquared\": // ft/s^2\n\t case \"footpersecondsquared\":\n\t case \"ft/s^2\":\n\t case \"ft/s2\":\n\t return AccelerationUnits.feetPerSecondSquared;\n\t case \"yardspersecondsquared\": // yds/s^2\n\t case \"yardpersecondsquared\":\n\t case \"yds/s^2\":\n\t case \"yds/s2\":\n\t case \"yd/s^2\":\n\t case \"yd/s2\":\n\t return AccelerationUnits.yardsPerSecondSquared;\n\t case \"milesperhoursecond\": // mi/h/s\n\t case \"mileperhoursecond\":\n\t case \"milesperhourseconds\":\n\t case \"mileperhourseconds\":\n\t case \"mi/h/s\":\n\t return AccelerationUnits.milesPerHourSecond;\n\t case \"kilometersperhoursecond\": // km/h/s\n\t case \"kilometrespersoursecond\":\n\t case \"kilometerperhoursecond\":\n\t case \"kilometrepersoursecond\":\n\t case \"kilometersperhourssecond\":\n\t case \"kilometrespersourssecond\":\n\t case \"kilometerperhourssecond\":\n\t case \"kilometrepersourssecond\":\n\t case \"kmhs\":\n\t case \"km/h/s\":\n\t return AccelerationUnits.kilometersPerHourSecond;\n\t case \"meterspersecondsquared\": // m/s^2\n\t case \"metrespersecondsquared\":\n\t case \"meterpersecondsquared\":\n\t case \"metrepersecondsquared\":\n\t case \"m/s^2\":\n\t case \"m/s2\":\n\t default:\n\t return AccelerationUnits.metersPerSecondSquared;\n\t }\n\t }\n\t return AccelerationUnits.metersPerSecondSquared;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects if the current browser is a Garmin Nuvifone.
function DetectGarminNuvifone() { if (uagent.search(deviceNuvifone) > -1) return true; else return false; }
[ "function DetectGarminNuvifone()\n{\n if (uagent.search(deviceNuvifone) > -1)\n return true;\n else\n return false;\n}", "function isThisLGEBrowser(){\r\n\tvar userAgentString = new String(navigator.userAgent);\r\n\tif (userAgentString != null && userAgentString.search(/LG Browser/) > -1) {\r\n\treturn true;\r\n\t}else{\r\n\t\treturn false;\r\n\t}\r\n}", "function xrxIdentifyCurrentBrowser()\r\n{\r\n var uaString = navigator.userAgent;\r\n return (((uaString != undefined) && (uaString != null)) ? (((uaString = uaString.toLowerCase()).indexOf( \"galio\" ) >= 0) ? \r\n \"FirstGenBrowser\" : ((uaString.indexOf( \"webkit\" ) >= 0) ? \"SecondGenBrowser\" : \"Unknown\" )) : \"No User Agent\" );\r\n}", "function DetectKindle()\n{\n if (uagent.search(deviceKindle) > -1)\n return true;\n else\n return false;\n}", "function DetectKindle()\n {\n if (uagent.search(deviceKindle) > -1)\n return true;\n else\n return false;\n }", "isBrowser() {\n return this.type === PlatformType_1.PlatformType.BROWSER\n || this.type === PlatformType_1.PlatformType.ELECTRON\n || this.type === PlatformType_1.PlatformType.NWJS;\n }", "function ismetaMaskBrowser() {\n if (navigator.userAgent.search(\"Brave\") >= 0) {\n //code goes here\n return true;\n }\n else if (navigator.userAgent.search(\"Chrome\") >= 0) {\n //code goes here\n return true;\n }\n else if (navigator.userAgent.search(\"Firefox\") >= 0) {\n //code goes here\n return true;\n }\n else if (navigator.userAgent.search(\"Edge\") >= 0) {\n //code goes here\n return true;\n }\n else {\n return false;\n }\n}", "function _checkBrowser(){var ua=navigator.userAgent;if(/Arora/.test(ua)?device.arora=!0:/Chrome/.test(ua)?device.chrome=!0:/Epiphany/.test(ua)?device.epiphany=!0:/Firefox/.test(ua)?device.firefox=!0:/AppleWebKit/.test(ua)&&device.iOS?device.mobileSafari=!0:/MSIE (\\d+\\.\\d+);/.test(ua)?(device.ie=!0,device.ieVersion=parseInt(RegExp.$1,10)):/Midori/.test(ua)?device.midori=!0:/Opera/.test(ua)?device.opera=!0:/Safari/.test(ua)?device.safari=!0:/Trident\\/(\\d+\\.\\d+)(.*)rv:(\\d+\\.\\d+)/.test(ua)&&(device.ie=!0,device.trident=!0,device.tridentVersion=parseInt(RegExp.$1,10),device.ieVersion=parseInt(RegExp.$3,10)),\n//Silk gets its own if clause because its ua also contains 'Safari'\n/Silk/.test(ua)&&(device.silk=!0),\n// WebApp mode in iOS\nnavigator.standalone&&(device.webApp=!0),\"undefined\"!=typeof window.cordova&&(device.cordova=!0),\"undefined\"!=typeof process&&\"undefined\"!=typeof require&&(device.node=!0),device.node)try{device.nodeWebkit=\"undefined\"!=typeof require(\"nw.gui\")}catch(error){device.nodeWebkit=!1}if(navigator.isCocoonJS&&(device.cocoonJS=!0),device.cocoonJS)try{device.cocoonJSApp=\"undefined\"!=typeof CocoonJS}catch(error){device.cocoonJSApp=!1}\"undefined\"!=typeof window.ejecta&&(device.ejecta=!0),/Crosswalk/.test(ua)&&(device.crosswalk=!0)}", "function DetectNintendo()\n{\n if (uagent.search(deviceNintendo) > -1 || \n\tuagent.search(deviceWii) > -1 ||\n\tuagent.search(deviceNintendoDs) > -1)\n return true;\n else\n return false;\n}", "function DetectNintendo()\n {\n if (uagent.search(deviceNintendo) > -1 ||\n uagent.search(deviceWii) > -1 ||\n uagent.search(deviceNintendoDs) > -1)\n return true;\n else\n return false;\n }", "function isGecko() {\n var _a, _b;\n var w = window;\n // Based on research in September 2020\n return (countTruthy([\n 'buildID' in navigator,\n 'MozAppearance' in ((_b = (_a = document.documentElement) === null || _a === void 0 ? void 0 : _a.style) !== null && _b !== void 0 ? _b : {}),\n 'MediaRecorderErrorEvent' in w,\n 'mozInnerScreenX' in w,\n 'CSSMozDocumentRule' in w,\n 'CanvasCaptureMediaStream' in w,\n ]) >= 4);\n}", "function uTestBrowserNS()\n{\n return (uBrowserID == uNS);\n}", "isNWJS() {\n return this.type === PlatformType_1.PlatformType.NWJS;\n }", "function detect_browser() {\n var browser = 'unknown';\n if ((!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {\n browser = 'opera';\n } else if (typeof InstallTrigger !== 'undefined') {\n browser = 'firefox';\n } else if (/constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === \"[object SafariRemoteNotification]\"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification))) {\n browser = 'safari';\n } else if (/*@cc_on!@*/false || !!document.documentMode) {\n browser = 'internet-explorer';\n } else if (!(/*@cc_on!@*/false || !!document.documentMode) && !!window.StyleMedia) {\n browser = 'edge';\n } else if (!!window.chrome && !!window.chrome.webstore) {\n browser = 'chrome';\n }\n $('html').addClass('browser-' + browser);\n}", "function checkBrowser() {\n \n\tvar browser=\"\";\n\t// Opera 8.0+\n\tif((!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0)\n\t{\n\t\treturn OPE;\n\t}\n\t\n\t// Firefox 1.0+\n\tif(typeof InstallTrigger !== 'undefined')\n\t{\n\t\treturn FIR\n\t}\n\n // Safari 3.0+ \"[object HTMLElementConstructor]\" \n\tif(Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 || (function (p) { return p.toString() === \"[object SafariRemoteNotification]\"; })(!window['safari'] || safari.pushNotification))\n\t{\n\t\treturn SAF;\n\t}\n\t//Chrome\n\tif((/Chrome/.test(navigator.userAgent)) && (/Google Inc/.test(navigator.vendor)))\n\t{\n\t\treturn CHR;\n\t}\n\t\n\treturn OTH;\n\n}", "function isGecko() {\n var _a;\n // Based on research in September 2020\n return countTruthy([\n 'buildID' in n$2,\n ((_a = d$1.documentElement) === null || _a === void 0 ? void 0 : _a.style) && 'MozAppearance' in d$1.documentElement.style,\n 'MediaRecorderErrorEvent' in w$2,\n 'mozInnerScreenX' in w$2,\n 'CSSMozDocumentRule' in w$2,\n 'CanvasCaptureMediaStream' in w$2,\n ]) >= 4;\n }", "function browserDetection() {\n var userAgent = navigator.userAgent.toLowerCase(); \n var browser;\n if ( userAgent.indexOf('trident') > -1 || userAgent.indexOf('msie') > -1) {\n browser = 'ie';\n } else if ( userAgent.indexOf('edge') > -1 ) {\n browser = 'edge';\n } else if (userAgent.indexOf('safari')!=-1){ \n if (userAgent.indexOf('chrome') > -1){\n browser = 'chrome';\n } else if((userAgent .indexOf('opera') > -1)||(userAgent.indexOf('opr') > -1)){\n browser = 'opera';\n } else {\n browser = 'safari';\n }\n \n } else if (userAgent.indexOf('firefox') !=-1) {\n browser = 'firefox';\n } else {\n browser = 'dont-know'; \n }\n \n return browser;\n }", "function isUA(string) {\n if (!canUseDOM) return false;\n return window.navigator.userAgent.indexOf(string) !== -1;\n}", "function runningInGecko() {\n return navigator.userAgent.indexOf('Gecko/') >= 0;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This module is a function that takes in a food and returns an image url based on the food name It uses "pluralize" and .toLowerCase functions to account for different ways of user entering the food name
function addFoodIcon(food) { switch(pluralize.singular(food.name.toLowerCase())) { case 'apple': return 'apple-1.png'; break; case 'asparagus': return 'asparagus.png'; break; case 'avocado': return 'avocado.png'; break; case 'bacon': return 'bacon.png'; break; case 'banana': return 'banana.png'; break; case 'bean': return 'beans.png'; break; case 'biscuit': return 'biscuit.png'; break; case 'blueberry': return 'blueberries.png'; break; case 'bread': return 'bread-1.png'; break; case 'broccoli': return 'broccoli.png'; break; case 'cabbage': return 'cabbage.png'; break; case 'cake': return 'cake.png'; break; case 'candy': return 'candy.png'; break; case 'carrot': return 'carrot.png'; break; case 'cauliflower': return 'cauliflower.png'; break; case 'cereal': return 'cereals.png'; break; case 'cheese': return 'cheese.png'; break; case 'cherry': return 'cherries.png'; break; case 'chili': return 'chili.png'; break; case 'chips': return 'chips.png'; break; case 'chives': return 'chives.png'; break; case 'green onion': return 'chives.png'; break; case 'chocolate': return 'chocolate.png'; break; case 'coconut': return 'coconut.png'; break; case 'coffee': return 'coffee-2.png'; break; case 'cookie': return 'cookies.png'; break; case 'corn': return 'corn.png'; break; case 'cucumber': return 'cucumber.png'; break; case 'egg': return 'egg.png'; break; case 'fish': return 'fish.png'; break; case 'flour': return 'flour.png'; break; case 'fry': return 'fries.png'; break; case 'garlic': return 'garlic.png'; break; case 'egg': return 'egg.png'; break; case 'grape': return 'grapes.png'; break; case 'ham': return 'ham.png'; break; case 'honey': return 'honey.png'; break; case 'ice cream': return 'ice-cream-12.png'; break; case 'jam': return 'jam-1.png'; break; case 'jelly': return 'jam-1.png'; break; case 'lemon': return 'lemon-1.png'; break; case 'lime': return 'lime.png'; break; case 'milk': return 'milk-1.png'; break; case 'mushroom': return 'mushroom.png'; break; case 'mustard': return 'mustard.png'; break; case 'noodles': return 'noodles.png'; break; case 'oat': return 'oat.png'; break; case 'olive oil': return 'oil.png'; break; case 'vegetable oil': return 'oil.png'; break; case 'oil': return 'oil.png'; break; case 'olive': return 'olive.png'; break; case 'onion': return 'onion.png'; break; case 'orange': return 'orange.png'; break; case 'pancake': return 'pancakes-1.png'; break; case 'pasta': return 'spaguetti.png'; break; case 'peach': return 'peach.png'; break; case 'pear': return 'pear.png'; break; case 'pea': return 'peas.png'; break; case 'pepper': return 'pepper.png'; break; case 'pickle': return 'pickles.png'; break; case 'pie': return 'pie.png'; break; case 'pineapple': return 'pineapple.png'; break; case 'beer': return 'pint.png'; break; case 'pistachio': return 'pistachio.png'; break; case 'pizza': return 'pizza.png'; break; case 'pomegranate': return 'pomegranate.png'; break; case 'potato': return 'potatoes-2.png'; break; case 'pretzel': return 'pretzel.png'; break; case 'pumpkin': return 'pumpkin.png'; break; case 'radish': return 'radish.png'; break; case 'raspberry': return 'raspberry.png'; break; case 'rice': return 'rice.png'; break; case 'brown rice': return 'rice.png'; break; case 'white rice': return 'rice.png'; break; case 'salad': return 'salad.png'; break; case 'lettuce': return 'salad-1.png'; break; case 'spinach': return 'salad-1.png'; break; case 'kale': return 'salad-1.png'; break; case 'salami': return 'salami.png'; break; case 'salmon': return 'salmon.png'; break; case 'sandwich': return 'sandwich.png'; break; case 'sausage': return 'sausage.png'; break; case 'italian sausage': return 'sausage.png'; break; case 'breakfast sausage': return 'sausage.png'; break; case 'steak': return 'steak.png'; break; case 'strawberry': return 'strawberry.png'; break; case 'sushi': return 'sushi-1.png'; break; case 'taco': return 'taco.png'; break; case 'toast': return 'toast.png'; break; case 'tomato': return 'tomato.png'; break; case 'turkey': return 'turkey.png'; break; case 'watermelon': return 'watermelon.png'; break; case 'wrap': return 'wrap.png'; break; case 'chicken': return 'meat.png'; break; case 'chicken breast': return 'meat.png'; break; case 'ketchup': return 'mustard-2.png'; break; case 'ground beef': return 'ham.png'; break; case 'ground turkey': return 'ham.png'; break; case 'ground chicken': return 'ham.png'; break; case 'ground chicken': return 'ham.png'; break; // If a food name is not one of these things, populate it's icon based on category default: if (food.category === 'Vegetables') { return 'salad-1.png'; } else if (food.category === 'Fruits') { return 'apple-1.png' } else if (food.category === 'Meat/Seafood') { return 'meat-1.png' } else if (food.category === 'Grains') { return 'grain.png' } else if (food.category === 'Dairy') { return 'milk.png' } else if (food.category === 'Sugars') { return 'cupcake.png' } return 'food.png' } }
[ "function moodNameToURL(moodName) {\n switch (moodName) {\n case \"happy\":\n return browser.extension.getURL(\"moods/happy.jpg\");\n case \"sad\":\n return browser.extension.getURL(\"moods/sad.jpg\");\n case \"stoic\":\n return browser.extension.getURL(\"moods/stoic.jpg\");\n }\n }", "function getImage(dish) {\n\tvar name = '<img src=\"img/food/',\n\t\tdname = dish.name.toLowerCase(), ename;\n\n\t// Unless it is an elixir, ignore the effect to get a generic image\n\tif (dname.indexOf(\"elixir\") == -1) {\n\t\tename = dname.substring(0, dname.indexOf(' '));\n\t\tif (ename == dish.effect)\n\t\t\tdname = dname.slice(ename.length);\n\t}\n\tname += dname.replace(/\\s/g, ''); // Remove whitespaces\n\treturn name + '.png\"/>';\n}", "function natureNameToURL(natureName) {\n switch (natureName) {\n case \"Waterfall\":\n return browser.extension.getURL(\"nature/waterfall.jpg\");\n case \"Snow\":\n return browser.extension.getURL(\"nature/snow.jpg\");\n case \"Nightfall\":\n return browser.extension.getURL(\"nature/nightfall.jpg\");\n }\n }", "function getImage(city) {\n\n let lowerCity = city.replace(/\\s/g, '').toLowerCase();\n return \"images/\" + lowerCity + \".jpg\";\n\n}", "function displayImage(title, image) {\n if(title.includes(\"Phantom\")) {\n image.src=\"./images/phantom.JPG\";\n } else if (title.includes(\"Harry\")) {\n image.src=\"./images/harrypotter.JPG\";\n } else if (title.includes(\"Aladdin\")) {\n image.src=\"./images/Aladdin.jpg\";\n } else if (title.includes(\"Mormon\")) {\n image.src=\"./images/book-of-mormon.jpg\";\n }else if (title.includes(\"Cats\")) {\n image.src=\"./images/Cats.jpg\";\n }else if (title.includes(\"Charlie\")) {\n image.src=\"./images/Charlie.jpg\";\n }else if (title.includes(\"Chicago\")) {\n image.src=\"./images/Chicago.jpeg\";\n }else if (title.includes(\"Come\")) {\n image.src=\"./images/come-from-away.jpg\";\n }else if (title.includes(\"Frozen\")) {\n image.src=\"./images/Frozen.JPG\";\n }else if (title.includes(\"Hamilton\")) {\n image.src=\"./images/Hamilton.JPG\";\n }else if (title.includes(\"Dolly\")) {\n image.src=\"./images/hello-dolly.jpg\";\n }else if (title.includes(\"Kinky\")) {\n image.src=\"./images/kinky-boots.jpg\";\n }else if (title.includes(\"Les\")) {\n image.src=\"./images/les-mis.jpg\";\n }else if (title.includes(\"Lion\")) {\n image.src=\"./images/lionking.JPG\";\n }else if (title.includes(\"Matilda\")) {\n image.src=\"./images/Matilda.jpg\";\n }else if (title.includes(\"Mean\")) {\n image.src=\"./images/mean-girl.png\";\n }else if (title.includes(\"Saigon\")) {\n image.src=\"./images/miss-saigon.jpg\";\n }else if (title.includes(\"Oklahoma\")) {\n image.src=\"./images/Oklahoma.jpg\";\n }else if (title.includes(\"Pretty\")) {\n image.src=\"./images/pretty-woman.jpg\";\n }else if (title.includes(\"Rock\")) {\n image.src=\"./images/school-of-rock.jpg\";\n }else if (title.includes(\"Wicked\")) {\n image.src=\"./images/wicked.jpg\";\n } else if (title.includes(\"Fair\")) {\n image.src=\"./images/my-fair-lady.jpg\";\n }\n}", "static imageAltForRestaurant(restaurant) {\r\n return (`${restaurant.name}`);\r\n }", "function weather_and_image(name) {\n switch(name) {\n case 'Colorado River ':\n src = 'images/coloradoRiver.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[0] + ' °F';\n return [src, temp];\n case 'Arivaca Lake ':\n src = 'images/arivacaLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[1] + ' °F';\n return [src, temp];\n case 'Dankworth Pond ':\n src = 'images/dankworthPond.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[2] + ' °F';\n return [src, temp];\n case 'Frye Mesa Reservoir ':\n src = 'images/frymesaReservoir.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[2] + ' °F';\n return [src, temp];\n case 'Parker Canyon Lake ':\n src = 'images/parkercanyonLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[3] + ' °F';\n return [src, temp];\n case 'Apache Lake ':\n src = 'images/apacheLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[4] + ' °F';\n return [src, temp];\n case 'Bartlett Lake ':\n src = 'images/bartlettLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[4] + ' °F';\n return [src, temp];\n case 'Canyon Lake ':\n src = 'images/canyonLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[4] + ' °F';\n return [src, temp];\n case 'Lake Pleasant ':\n src = 'images/lakePleasant.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[5] + ' °F';\n return [src, temp];\n case 'Lower Salt River ':\n src = 'images/lowersaltRiver.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[6] + ' °F';\n return [src, temp];\n case 'Roosevelt Lake ':\n src = 'images/rooseveltLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[4] + ' °F';\n return [src, temp];\n case 'Saguaro Lake ':\n src = 'images/saguaroLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[4] + ' °F';\n return [src, temp];\n case 'Tempe Town Lake* ':\n src = 'images/tempetownLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[7] + ' °F';\n return [src, temp];\n case 'Bear Canyon Lake ':\n src = 'images/bearcanyonLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[8] + ' °F';\n return [src, temp];\n case 'Black Canyon Lake ':\n src = 'images/blackcanyonLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[8] + ' °F';\n return [src, temp];\n case 'Chevelon Canyon ':\n src = 'images/chevelonCanyon.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[8] + ' °F';\n return [src, temp];\n case 'Willow Springs Lake ':\n src = 'images/willowspringsLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[8] + ' °F';\n return [src, temp];\n case 'Woods Canyon Lake ':\n src = 'images/woodscanyonLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[8] + ' °F';\n return [src, temp];\n case 'Becker Lake ':\n src = 'images/beckerLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[10] + ' °F';\n return [src, temp];\n case 'Big Lake ':\n src = 'images/bigLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[10] + ' °F';\n return [src, temp];\n case 'Greer Lakes ':\n src = 'images/greerLakes.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[9] + ' °F';\n return [src, temp];\n case 'Carnero Lake':\n src = 'images/carneroLake.jpg';\n temp = 'Current temp: ☀️ ' + weatherinfo[10] + ' °F';\n return [src, temp];\n default:\n src = 'images/apacheLake.jpg';\n temp = 'No weather info';\n return [src, temp];\n }\n}", "function checkPokemonGame_Name(pokemon_game) {\n if (pokemon_game == \"red\")\n return \"images/red.png\";\n else if (pokemon_game == \"blue\")\n return \"images/blue.png\";\n else if (pokemon_game == \"yellow\")\n return \"images/yellow.png\";\n else if (pokemon_game == \"gold\")\n return \"images/gold.png\";\n else if (pokemon_game == \"silver\")\n return \"images/silver.png\";\n else if (pokemon_game == \"crystal\")\n return \"images/crystal.png\";\n else if (pokemon_game == \"ruby\")\n return \"images/ruby.png\";\n else if (pokemon_game == \"sapphire\")\n return \"images/sapphire.png\";\n else if (pokemon_game == \"emerald\")\n return \"images/emerald.png\";\n else if (pokemon_game == \"firered\")\n return \"images/firered.png\";\n else if (pokemon_game == \"leafgreen\")\n return \"images/leafgreen.png\";\n else if (pokemon_game == \"diamond\")\n return \"images/diamond.png\";\n else if (pokemon_game == \"pearl\")\n return \"images/pearl.png\";\n else if (pokemon_game == \"platinum\")\n return \"images/platinum.png\";\n else if (pokemon_game == \"heartgold\")\n return \"images/heartgold.png\";\n else if (pokemon_game == \"soulsilver\")\n return \"images/soulsilver.png\";\n else if (pokemon_game == \"black\")\n return \"images/black.png\";\n else if (pokemon_game == \"white\")\n return \"images/white.png\";\n else if (pokemon_game == \"black-2\")\n return \"images/black-2.png\";\n else if (pokemon_game == \"white-2\")\n return \"images/white-2.png\";\n else\n return null;\n}", "function CreateImgName(longName,ending){\n if(longName.length > 1 ){\n switch(ending){\n case \"Weight\":\n case \"Patrol\":\n longName = longName.slice(0,-2);\n longName = longName.join().replace(/,/g, \" \");\n break;\n case \"Extended\": \n case \"Hammerless\": \n case \"Perosa\": \n case \"Shotgun\": \n case \"Artillerie\": \n case \"Auto\": \n case \"Patrol\": \n case \"SMG\": \n case \"Degtyarev\": \n case \"M1918A2\": \n case \"Revolver\": \n case \"Pistol\": \n case \"Automatic\": \n case \"MkVI\": \n case \"08-15\": \n case \"1903\": \n case \"1915\": \n case \"M1914\": \n case \"M1918\": \n case \"M1870\": \n case \"M1912\": \n case \"1889\": \n longName = longName.join().replace(/,/g, \" \"); \n break;\n default:\n longName = longName.slice(0,-1);\n longName = longName.join().replace(/,/g, \" \");\n }\n }\n return longName;\n}", "function beastNameToURL(beastName) {\n switch (beastName) {\n case \"Frog\":\n return chrome.extension.getURL(\"beasts/frog.jpg\");\n case \"Snake\":\n return chrome.extension.getURL(\"beasts/snake.jpg\");\n case \"Turtle\":\n return chrome.extension.getURL(\"beasts/turtle.jpg\");\n }\n}", "function getImg(house) {\n if (house === \"Hufflepuff\") {\n return \"https://vignette.wikia.nocookie.net/csydes-test/images/e/ee/Hufflepuff_Crest.png/revision/latest?cb=20171101063214\";\n }\n else if (house === \"Gryffindor\") {\n return \"https://pngimage.net/wp-content/uploads/2018/06/gryffindor-crest-png.png\";\n }\n else if (house === \"Ravenclaw\") {\n return \"https://vignette.wikia.nocookie.net/csydes-test/images/2/2b/Ravenclaw_Crest.png/revision/latest?cb=20171101063206\";\n }\n else {\n return \"https://vignette.wikia.nocookie.net/csydes-test/images/4/45/Slytherin_Crest.png/revision/latest?cb=20171101063219\";\n }\n}", "static imageInitialLoadUrlForRestaurant(restaurant) { \n //return (`/responsiveimages/${restaurant.photograph}-medium_0.80x.jpg`);\n return (`/responsiveimages/${restaurant.id}-medium_0.80x.jpg`); \n}", "static imageSourceMediumForRestaurant(restaurant) {\r\n let photo_source = restaurant.photograph;\r\n if (photo_source != undefined){\r\n photo_source = photo_source.replace(\".jpg\", \"\");\r\n photo_source = `/img/${photo_source}-600_medium_2x.jpg 2x, /img/${photo_source}-600_medium_1x.jpg`;\r\n }\r\n return photo_source;\r\n }", "static imageUrlForRestaurant(restaurant, type) {\r\n return (`/img/${type}/${restaurant.photograph||restaurant.id}.jpg`);\r\n }", "static imageUrlForRestaurant(restaurant) {\n let url = `/img/${(restaurant.photograph||restaurant.id)}-medium.jpg`;\n return url;\n }", "static imageUrlForRestaurantS(restaurant) {\r\n if (restaurant.photograph === undefined){\r\n return 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';\r\n }\r\n return (`/img/400_${restaurant.photograph}.jpg`);\r\n }", "static largeImageUrlForRestaurant(restaurant) {\r\n //Photos are named based on Restaurant IDs so use that to find the different sized images\r\n let photoRef = restaurant.id;\r\n return (`/images_sized/${photoRef}-large.jpg`);\r\n }", "static smallImageUrlForRestaurant(restaurant) {\r\n // let smallFile = restaurant.photograph.slice(0, -4) + '-400w' + '.jpg';\r\n let smallFile = restaurant.photograph + '-400w.webp';\r\n return (`/img_converted/${smallFile}`);\r\n }", "function getThumbnailURL(latin_name)\n{\n var url = '';\n if (latin_name !== undefined) {\n// let latinURL = '/species_images/thumbnails/' + latin_name.toLowerCase().replace(\" \", \"_\") + '.jpg';\n if (tax_json[latin_name] !== undefined) {\n url = 'images/' + tax_json[latin_name] + '_110px.jpg'\n }\n }\n return url;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function sends the position of each of the updated element to the controller file so that database can be updated Also this function removes the positionupdated class from the element whose position is updated in database
function saveNewPositions(url){ var positions = []; $('.position-updated').each(function(){ //Sending data-index and data-position attribute value to controller positions.push([$(this).attr('data-index'), $(this).attr('data-position')]); }); $.ajax({ url: url, method: 'POST', dataType: 'text', data: { //update is used just to check in controller file that weather data is send by post method or not update: 1, positions: positions }, success: function(response){ console.log(response); } }); }
[ "function updateWidgetPosition() {\n\t\n\tvar result = [];\n\tvar widgets = $(\".w_container\");\n\t\n\t// Look for the widgets that have changed positions\n\t$.each(widgets, function() {\n\t\tvar $widget = $(this);\n\t\tvar idx = $widget.index();\n\t\tif (idx == parseInt($widget.data(\"pos\")))\n\t\t\treturn;\n\t\t\n\t\tvar obj = {\"widgetId\": $widget.data(\"widgetId\"), \"pos\": idx};\n\t\tresult.push(obj);\n\t\t$widget.data(\"pos\", idx);\n\t});\n\t\n\t// If widgets have changed, save the changes.\n\tif(result.length > 0) {\n\t\t$.ajax({\n\t\t\ttype: 'POST',\n\t\t\turl: applicationRoot + \"updateWidgetPosition\",\n\t\t\tdata: {\"widgets\": JSON.stringify(result) },\n\t\t\tsuccess: function() {\n\t\t\t\tconsole.log(\"Widget position updated successfully.\")\n\t\t\t},\n\t\t\terror: handleAjaxError\n\t\t});\n\t}\n}", "function _updateElementPositions() {\n elements.forEach(function (element) {\n if (element.props.disabled) return;\n\n // check if the element is in view then\n var isInView = (0, _index.isElementInView)(element, windowHeight, scrollY);\n\n // set styles if it is\n if (isInView) _setParallaxStyles(element);\n\n // reset ticking so more animations can be called\n ticking = false;\n });\n }", "function _updateElementPositions() {\n elements.forEach(element => {\n if (element.props.disabled) return;\n\n // check if the element is in view then\n const isInView = isElementInView(element, windowHeight, scrollY);\n\n // set styles if it is\n if (isInView) _setParallaxStyles(element);\n\n // reset ticking so more animations can be called\n ticking = false;\n });\n }", "function updateChevronPositions(element) {\n var id = element.find('.text-edit').attr('name');\n var xValue = parseInt(element.css(\"left\"), 10);\n var yValue = parseInt(element.css(\"top\"), 10);\n for (var i = 0; i < chevronPositions.length; i++) {\n if (id == chevronPositions[i].chevId) {\n if (chevronPositions[i].xVal != xValue) {\n chevronPositions[i].xVal = xValue;\n chevronPositions[i].yVal = yValue;\n chevronPositions[i].chevName = element.find('.text-edit').val();\n positionChanged = true;\n }\n }\n }\n }", "updatePosition() {\r\n this.position = Utils.convertToEntityPosition(this.bmp);\r\n }", "updatePosition() {\n this.position = Utils.convertToEntityPosition(this.bmp);\n }", "function updateTodoListCoordinates($el) { \r\n var Stoppos = $el.position();\r\n var left = parseInt(Stoppos.left);\r\n var top = parseInt(Stoppos.top);\r\n BRW_sendMessage({command: \"changeTodoItemCoordinates\", \"left\": left, \"top\": top});\r\n}", "updatePositions(){\n this.api.get_positions(this.apiPositionListener)\n }", "function update() {\n var scrollTop = element.pageYOffset || element.scrollTop,\n scrollBottom = scrollTop + listHeight;\n\n // Quit if nothing changed.\n if (scrollTop == element.lastTop) return;\n\n element.lastTop = scrollTop;\n\n // One loop to make our changes to the DOM\n for (var i = 0, len = items.length; i < len; i++) {\n var item = items[i];\n\n // Above list viewport\n if (item._offsetTop + item._offsetHeight < scrollTop) {\n item.classList.add('past');\n } else if (item._offsetTop > scrollBottom) {\n item.classList.add('future');\n } else {\n item.classList.remove('past');\n item.classList.remove('future');\n }\n }\n }", "updatePositions() {\r\n $(\"#positions-log\").empty();\r\n this.alpaca.getPositions().then((resp) => {\r\n resp.forEach((position) => {\r\n $(\"#positions-log\").prepend(\r\n `<div class=\"position-inst\">\r\n <p class=\"position-fragment\">${position.symbol}</p>\r\n <p class=\"position-fragment\">${position.qty}</p>\r\n <p class=\"position-fragment\">${position.side}</p>\r\n <p class=\"position-fragment\">${position.unrealized_pl}</p>\r\n </div>`\r\n );\r\n })\r\n })\r\n }", "function recalculatePosition() {\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n scope.position.top += element.prop('offsetHeight');\n }", "function recalculatePosition() {\n\t scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n\t scope.position.top += element.prop('offsetHeight');\n\t }", "function refreshPositions() {\n $(\"#docsTableContent tr\").each(function(index) {\n $(this).find('.position').html((index + 1));\n });\n}", "function recalculatePosition() {\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n scope.position.top += element.prop('offsetHeight');\n }", "function updatePos(pos) {\r\n arrayPos = pos;\r\n id = ('Track-' + pos);\r\n titlediv.attr('id', id + '-title'); \r\n my.track.attr('id', id);\r\n my.resource = 'R-' + arrayPos;\r\n //prevTrack = my.track.prev(\".track\");\r\n //prevTitleDiv = titlediv.prev(\".titlediv\");\r\n //console.log(\"new position assigned: \" + pos);\r\n }", "_update( e, ui ) {\n\n\t\tif ( ui.item.elements !== this.column.get( 'elements' ) ) {\n\t\t\treturn;\n\t\t}\n\t\tlet index = ui.item.index();\n\t\t// resort elements collection\n\t\tthis.column.get( 'elements' ).moveItem( ui.item.indexStart, index );\n\t\t// trigger drop event element\n\t\tui.item.trigger( 'drop', index );\n\t}", "updatePosition() {\n if (this.component) {\n this.component.updatePosition();\n }\n }", "setPosition() {\n this.elements.forEach((data) => {\n data.element.style.top = data.top + \"px\";\n data.element.style.left = data.left + \"px\";\n });\n }", "updatePosition(position) \n {\n this.position = position;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves dropdowns to the Menu.
_moveDropDownsToMenu() { const that = this; for (let i = 0; i < that._containersInBody.length; i++) { const container = that._containersInBody[i]; container.$.unlisten('click'); container.$.unlisten('mouseleave'); container.$.unlisten('mouseout'); container.$.unlisten('mouseover'); container.style.left = ''; container.style.right = ''; container.style.top = ''; container.style.marginLeft = ''; container.style.marginTop = ''; container.menuItemsGroup.appendChild(container); } for (let i = 0; i < that._containers.length; i++) { const container = that._containers[i]; if (that.theme !== '') { container.classList.remove(that.theme); } container.classList.remove('jqx-drop-down-repositioned'); container.removeAttribute('mode'); container.removeAttribute('drop-down-position'); container.removeAttribute('checkboxes'); } }
[ "_moveDropDownsToMenu() {\n const that = this;\n\n for (let i = 0; i < that._containersInBody.length; i++) {\n const container = that._containersInBody[i];\n\n container.$.unlisten('click');\n container.$.unlisten('mouseleave');\n container.$.unlisten('mouseout');\n container.$.unlisten('mouseover');\n\n container.style.left = '';\n container.style.right = '';\n container.style.top = '';\n container.style.marginLeft = '';\n container.style.marginTop = '';\n\n container.menuItemsGroup.appendChild(container);\n }\n\n for (let i = 0; i < that._containers.length; i++) {\n const container = that._containers[i];\n\n if (that.theme !== '') {\n container.classList.remove(that.theme);\n }\n\n container.classList.remove('smart-drop-down-repositioned');\n container.removeAttribute('mode');\n container.removeAttribute('drop-down-position');\n container.removeAttribute('checkboxes');\n container.removeAttribute('right-to-left');\n }\n }", "function moveDropdown () {\n\t if (!elements.$.root.length) return;\n\t $mdTheming(elements.$.scrollContainer);\n\t elements.$.scrollContainer.detach();\n\t elements.$.root.append(elements.$.scrollContainer);\n\t if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);\n\t }", "function moveDropdown() {\n if (!elements.$.root.length) return;\n $mdTheming(elements.$.scrollContainer);\n elements.$.scrollContainer.detach();\n elements.$.root.append(elements.$.scrollContainer);\n if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);\n }", "function moveNotificationsDropdown(){\n $('.sidebar-status .dropdown-toggle').after($('#notifications-dropdown-menu').detach());\n }", "function moveDropdown () {\r\n if (!elements.$.root.length) return;\r\n $mdTheming(elements.$.scrollContainer);\r\n elements.$.scrollContainer.detach();\r\n elements.$.root.append(elements.$.scrollContainer);\r\n if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);\r\n }", "function moveDropdown () {\n if (!elements.$.root.length) return;\n $mdTheming(elements.$.scrollContainer);\n elements.$.scrollContainer.detach();\n elements.$.root.append(elements.$.scrollContainer);\n if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);\n }", "function moveDropdown () { // 18732\n if (!elements.$.root.length) return; // 18733\n $mdTheming(elements.$.scrollContainer); // 18734\n elements.$.scrollContainer.detach(); // 18735\n elements.$.root.append(elements.$.scrollContainer); // 18736\n if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement); // 18737\n } // 18738", "function moveIntoPlace(){\n\t\t$globalNavCont.append( $megaMenu );\n\t\t//$global-nav.after( $megaMenu );\n\t\tfirstClick = false;\n\t}", "function move_elements() {\r\n\t\t\tvar screenSize = checkWindowWidth();\r\n\t\t \r\n\t\t\tif ( screenSize ) {\r\n\t\t\t\t$search_nav.detach();\r\n\t\t\t\t$search_nav.insertBefore('#main-menu .dropdown-all');\r\n\t\t\t \r\n\t\t\t} else {\r\n\t\t\t\t$search_nav.detach();\r\n\t\t\t\t$search_nav.insertBefore('#main-menu > li:first-child');\t\t\t\t\r\n\t\t\t}\r\n\t\t}", "function moveDropdownElmTop()\r\n{\r\n\tif(!isIE)\r\n\t\tpWind.dropdown.elm.scrollTop = pWind.dropdown.elm.selectedIndex * pWind.dropdown.optHeight;\r\n\tpWind.dropdown.elm.focus();\r\n}", "function dropDownsUp() {\n $menuBtn.removeClass(\"open\");\n $navDropdown.removeClass(\"show_nav\");\n $dropdownCurrencies.removeClass(\"drop_currencies\");\n $rateInfo.removeClass(\"drop_info\");\n $flagsContainer.removeClass(\"drop_info\");\n}", "function resetExtraDropdown()\n {\n usingExtraDropdown = false;\n \n var LIsToMove = extraDropdown.children();\n \n mainUL.find(\".extraDropdown\").remove();\n \n mainUL.append(LIsToMove);\n }", "function moveLI()\n {\n mainLIs = mainUL.children().not(\".extraDropdown\");\n \n extraDropdown.prepend(mainLIs.last());\n \n checkLIsFit();\n }", "function shift_user_dropdown() {\n var shift = 195 - $(\".user-link .dropdown\").width();\n $(\".user-link .dropdown-menu\").css(\"margin-left\", \"-\" + shift.toString() + \"px\");\n }", "function moveAllOptions(from, to)\r\n{\r\n selectList(from);\r\n moveOption(from, to);\r\n}", "function dropdownButtonClicked() {\r\n if (dom.dropdownMenu.hasClass(\"dropdown-menu-container--hidden\")) {\r\n dom.dropdownMenu.removeClass(\"dropdown-menu-container--hidden\").addClass(\"dropdown-menu-container--show\");\r\n } else {\r\n dom.dropdownMenu.removeClass(\"dropdown-menu-container--show\").addClass(\"dropdown-menu-container--hidden\");\r\n }\r\n }", "function McDropdownPanel() { }", "onMoveDownClick_() {\n /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close();\n this.languageHelper.moveLanguage(\n this.detailLanguage_.state.language.code, /*upDirection=*/ false);\n settings.recordSettingChange();\n }", "function MoveToSelection() \n {\n \tMoveTheOptions($(\"select[name*='lstNonSelected']\").attr(\"id\"), $(\"select[name*='lstSelected']\").attr(\"id\"));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if all the tracks have been loaded into the map
function tracksDoneLoading(){ return trackLayerGroup.getLayers().length == Object.keys(tracks).length; }
[ "function areAllLoaded(){\n\tvar allDone = true;\n\tfor(var k in playLists){\n\t\tvar loaded = playLists[k].loaded || playLists[k].list.length == 0;\n\t\tallDone = (allDone && loaded);\n\t}\n\treturn allDone;\n}", "is_loaded() {\n for (const g of this.graphs) {\n if (!g.loadedOk) {\n return false;\n }\n }\n\n return true;\n }", "allLoaded() {\r\n if (this._resources.size > 0) {\r\n const resources = Array.from(this._resources.values());\r\n for (let resource of resources) {\r\n if (!resource.loaded) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n else {\r\n return true;\r\n }\r\n }", "mapHasLoaded() {\n\n\t\tthis.isLoaded = true;\n\n\t}", "function checkLoaded() {\n\t\t var i = 0, _confirm = true;\n\t\t for(i; i < playlistLength; i++){\n\t\t\t if(spareSectionArr[i] == undefined || spareSectionArr[i] == null){\n\t\t\t\t _confirm = false;//not loaded found\n\t\t\t\t break; \n\t\t\t }\n\t\t }\n\t\t if(_confirm){\n\t\t\t allLoaded = true;\n\t\t\t //console.log(\"allLoaded = \" + allLoaded);\n\t\t }\n\t }", "function allLoaded() {\n for (var i = 0; i != images.length; ++i) {\n if (!images[i].loaded) return false;\n }\n return true;\n }", "get allGeometryLoaded() {\n return this.currentPhase >= this.m_loadPhaseDefinitions.length;\n }", "function ready() {\n for (var i = 0; i < preloadTiles.length; i++) {\n var state = layerAbove.textureStore().query(preloadTiles[i]);\n if (!state.hasTexture) {\n return false;\n }\n }\n return true;\n}", "checkLoad(){\n let loadObjects = this.loadShaderObj.concat(this.loadModelObj.concat(this.loadTextureObj));\n\n for(let loadObj of loadObjects){\n if(loadObj.getLoaded() === false){\n return false;\n }\n }\n \n return true;\n }", "areResourcesLoaded() {\n const names = Object.keys(this.resources);\n\n return names.every(name => {\n return this.resources[name].loaded;\n });\n }", "isDataLoaded() {\n if (this.state.mealLocations && this.state.dropinLocations && this.state.homebaseLocations) {\n //only checks meals because it takes longest\n if (this.state.mealLocations.length === 111) {\n return true;\n }\n }\n return false;\n }", "allGraphsLoaded() {\n let allLoaded = true;\n\n Object.values(this.graphsLoadedOk).forEach((loaded) => {\n if (! loaded)\n allLoaded = loaded;\n });\n\n return allLoaded;\n }", "function checkLoad(){\n for (var key in assets) {\n if (!c[key].loaded) return false;\n }\n return true;\n }", "get isLoadingMapItems() {\n return this._mapItemsLoader.isLoading;\n }", "get loaded() {\n return Array.from(this._buffers).every(([_, buffer]) => buffer.loaded);\n }", "get allReady() {\n /* Iterate over every player */\n for (let key in this._players) {\n /* Check if player is NOT ready */\n if (!this._players[key].isReady) return false;\n }\n /* Everyone is ready! */\n return true;\n }", "function allPlayersRegistered() {\n // Initialize our registered variable.\n var registered = true;\n \n // Iterate through all flash objects.\n for( id in flashObjects ) {\n // AND the ready flags together.\n registered = (registered && flashObjects[id].ready);\n }\n \n // Return if they all have registered.\n return registered;\n}", "allPlayersReady() {\n\t\tfor (let i = 0; i < this.players.length; i++) {\n\t\t\tif (!this.players[i].ready) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "areAllArtefactsTaken () {\n let areAllArtefactsTaken = true\n\n for (let key in this.players) {\n const player = this.players[key]\n\n areAllArtefactsTaken = areAllArtefactsTaken && (player.takenArtefactsCount === this.spectrum.artefactsToTakeCount)\n }\n\n return areAllArtefactsTaken\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple test for verifying that MOVE is a valid move number
function isValid(move) { return (move > 10 && move < 89 && move % 10 > 0 && move % 10 < 9); }
[ "function verifyMove( state, move ) {\n\tif ( isNaN( move ) )\n\t\treturn false;\n\tif ( state.players[state.currentPlayer].pos == 1 && move >= 7 && move <= 12\n\t\t&& state.board[move] != 0 )\n\t\treturn true;\n\tif ( state.players[state.currentPlayer].pos == 0 && move >= 0 && move <= 5\n\t\t&& state.board[move] != 0 )\n\t\treturn true;\n\treturn false;\n}", "function isValidMove(move){\n //return boolean\n\n\n\n\n\n }", "function isValidMoveValue(moveValue) {\n return (moveValue >= 1) && (moveValue <= 99);\n }", "function isValidMove(move) {\n \n // If the passed in number is beween 0 and 8 (the tic tac toe board),\n // and the spot is empty, return true. If the spot is taken, return false\n if (move >= 0 && move <= 8 && move != -1) {\n if (position[move] == \"\") {\n return true;\n } else {\n console.log(\"That spots taken, try again.\");\n return false;\n }\n } else {\n console.log(\"Please enter a number between 0 and 8\");\n return false;\n }\n}", "function isValidMoveValue(moveValue) {\n return (moveValue >= 1) && (moveValue <= 99);\n}", "function isMoveValueValid(moveValue) {\n return (moveValue >= 1 && moveValue <= 99);\n}", "isValidMove (move) {\n const newPoint = this.currentPoint.pointAfterMove(move)\n if (newPoint == null) return false\n\n return !newPoint.occupied\n }", "check_valid_move(direction){\n if (\n (direction === 'u' || direction === 'U' || direction === 'up')\n && this.poss[0] === 0) {\n return false;\n }else if (\n (direction === 'd' || direction === 'D' || direction === 'down')\n && this.poss[0] === this.field.length) {\n return false;\n }else if (\n (direction === 'r' || direction === 'R' || direction === 'right')\n && this.poss[1] >= this.field[0].length-1) {\n return false;\n }else if (\n (direction === 'l' || direction === 'L' || direction === 'left')\n && this.poss[1] === 0) {\n return false;\n }else {\n return true;\n }\n }", "moveIsValid(coord, steps) {\n // We'll just throw an error if the coordinates or steps are invalid.\n if (!this.verifyCoord(coord)) throw new RangeError(\"Coordinate \\\"\" + coord + \"\\\" is invalid.\");\n if (steps < 0 || steps > 4) throw new RangeError(\"Step count \" + steps.toString() + \" is invalid.\");\n \n // We'll say that no move with inaction is valid.\n if (steps == 0) return false;\n \n // Get the colour of the player on that coordinate\n let player = this.contentsOf(coord);\n if (player == \"n\") throw new Error(\"Invalid move: the cell at coordinate \\\"\" + coord + \"\\\" is empty.\");\n \n // Fetch the appropriate path, and the piece's position along that path.\n let path = {\"o\": this.oPath, \"b\": this.bPath}[player];\n let progress = path.indexOf(coord);\n \n // Throw an error if the piece isn't on the path; this is an incorrect state.\n if (progress == -1) throw new Error(\"Peice coloured \\\"\" + player + \"\\\" at position \\\"\" + coord + \"\\\" is not on its path.\");\n \n // CONDITION 1: If the piece leaves the board exactly, the move is valid.\n if (progress + steps == path.length) return true;\n // CONDITION 2: If the piece leaves the board with too many steps, the move is invalid.\n if (progress + steps > path.length) return false;\n // (since we now know the destination is on the board, let's get what it's landing on:)\n let endCoord = path[progress + steps];\n let destination = this.contentsOf(endCoord);\n // CONDITION 3: If the piece steps onto a friend, the move is invalid.\n if (destination == player) return false;\n // CONDITION 4: If the piece steps onto an enemy on a rosette, the move is invalid.\n if (destination != \"n\" && this.isRosette(endCoord)) return false;\n // All other moves are valid\n return true;\n }", "function isValidMove(x,y){\n\tif (isValidSpot(x,y) == 0) return false;\n\tif ((Math.abs(x-selectedX)==1)&&((Math.abs(y-selectedY)==0))) return true;\n\tif ((Math.abs(x-selectedX)==0)&&((Math.abs(y-selectedY)==1))) return true;\n\treturn false;\n}", "function moveValidate() {\n if (playerMoveList[moveChecker] != simonMoveList[moveChecker]) {\n simonBoard();\n playerMoveList = [];\n wrongMove();\n } else {\n moveChecker++;\n }\n}", "function outOfBound(newMove) {\n if (newMove > 410 || newMove < 10) {\n promptError(\"You shall not pass!\");\n return true;\n } else return false;\n}", "isValidMove(direction) {\r\n try\r\n {\r\n switch (direction)\r\n {\r\n case \"Up\":\r\n return this._data[this._playerRow - 1][this._playerCol] == 0;\r\n case \"Down\":\r\n return this._data[this._playerRow + 1][this._playerCol] == 0;\r\n case \"Right\":\r\n return this._data[this._playerRow][this._playerCol + 1] == 0;\r\n case\"Left\":\r\n return this._data[this._playerRow][this._playerCol - 1] == 0;\r\n default:\r\n var e = new Error();\r\n e.message = \"wrong argument in isValidMove\";\r\n throw e;\r\n }\r\n }\r\n //in case the movement is outside the maze\r\n catch (e)\r\n {\r\n return false;\r\n } \r\n }", "function boardIsValidPosition(board, move) {\n if (!Number.isInteger(move) || move < 1 || move > 9) {\n return false;\n }\n\n let row = getRow(move);\n let col = getCol(move);\n\n if (board[row][col] !== ' ') {\n return false;\n }\n\n return true;\n}", "function validateMove(x, y, piece){\n\tret_code = 0; // Default: return invalid move; change if valid\n\tif(x < 8 && x >= 0 && y < 8 && y >= 0){ // Ensure it's on the board\n\t\tvar color = $(piece).attr('color'); // Store piece color\n\t\tvar tile = $('td#'+getTileId(x, y)); // Store tile ID of square being checked\n\t\t\n\t\t// Check if it's an empty tile\n\t\tif($(tile).children().size() == 0){\n\t\t\tret_code = 1\n\t\t// If not empty, is it occupied by an opponent\n\t\t} else if($(tile).children('img').attr('color') != color){ \n\t\t\tret_code = 2;\n\t\t}\n\t\t\n\t\t/*\n\t\tif(ret_code !== 0 && testForCheck(x, y, piece)){\n\t\t\tret_code = 0;\n\t\t}\n\t\t*/\n\t}\n\treturn ret_code;\n}", "function isValidMove(position) {\n return board.isValidPosition(position) && isUnmarkedPosition(position);\n }", "function isMoveOk(params, debug) {\r\n var stateBeforeMove = params.stateBeforeMove,\r\n turnIndexBeforeMove = params.turnIndexBeforeMove,\r\n move = params.move,\r\n board,\r\n fromDelta,\r\n toDelta,\r\n expectedMove;\r\n\r\n /*********************************************************************\r\n * 1. If the stateBeforeMove is empty, then it should be the first\r\n * move, set the board of stateBeforeMove to be the initial board.\r\n * If the stateBeforeMove is not empty, then the move operations\r\n * array should have a length of 4.\r\n ********************************************************************/\r\n\r\n\r\n if (isEmptyObj(stateBeforeMove)) {\r\n stateBeforeMove.board = getInitialBoard();\r\n }\r\n\r\n // If the move length is not 4, it's illegal\r\n if (move.length !== 4) {\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_MOVE);\r\n }\r\n\r\n /*********************************************************************\r\n * 2. Compare the expected move and the player's move.\r\n ********************************************************************/\r\n try {\r\n /*\r\n * Example move:\r\n * [\r\n * {setTurn: {turnIndex: 1}},\r\n * {set: {key: 'board', value: [\r\n * ['--', 'BM', '--', 'BM', '--', 'BM', '--', 'BM'],\r\n * ['BM', '--', 'BM', '--', 'BM', '--', 'BM', '--'],\r\n * ['--', 'DS', '--', 'BM', '--', 'BM', '--', 'BM'],\r\n * ['BM', '--', 'DS', '--', 'DS', '--', 'DS', '--'],\r\n * ['--', 'DS', '--', 'DS', '--', 'DS', '--', 'DS'],\r\n * ['WM', '--', 'WM', '--', 'WM', '--', 'WM', '--'],\r\n * ['--', 'WM', '--', 'WM', '--', 'WM', '--', 'WM'],\r\n * ['WM', '--', 'WM', '--', 'WM', '--', 'WM', '--']]\r\n * }}\r\n * {set: {key: 'fromDelta', value: {row: 2, col: 1}}}\r\n * {set: {key: 'toDelta', value: {row: 3, col: 0}}}\r\n * ]\r\n */\r\n\r\n board = stateBeforeMove.board;\r\n fromDelta = move[2].set.value;\r\n toDelta = move[3].set.value;\r\n expectedMove =\r\n createMove(board, fromDelta, toDelta, turnIndexBeforeMove);\r\n if (debug) {\r\n console.log(\"Debug\");\r\n console.log(JSON.stringify(move));\r\n console.log(JSON.stringify(expectedMove));\r\n console.log(angular.equals(move, expectedMove));\r\n }\r\n\r\n if (!angular.equals(move, expectedMove)) {\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_MOVE);\r\n }\r\n } catch (e) {\r\n // if there are any exceptions then the move is illegal\r\n// console.log('Erorr: ' + e.message);\r\n switch (e.message) {\r\n case ILLEGAL_CODE.ILLEGAL_MOVE:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_MOVE);\r\n case ILLEGAL_CODE.ILLEGAL_SIMPLE_MOVE:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_SIMPLE_MOVE);\r\n case ILLEGAL_CODE.ILLEGAL_JUMP_MOVE:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_JUMP_MOVE);\r\n case ILLEGAL_CODE.ILLEGAL_DELTA:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_DELTA);\r\n case ILLEGAL_CODE.ILLEGAL_COLOR_CHANGED:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_COLOR_CHANGED);\r\n case ILLEGAL_CODE.ILLEGAL_CROWNED:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_CROWNED);\r\n case ILLEGAL_CODE.ILLEGAL_UNCROWNED:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_UNCROWNED);\r\n case ILLEGAL_CODE.ILLEGAL_IGNORE_MANDATORY_JUMP:\r\n return getIllegalEmailObj(ILLEGAL_CODE\r\n .ILLEGAL_IGNORE_MANDATORY_JUMP);\r\n case ILLEGAL_CODE.ILLEGAL_SET_TURN:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_SET_TURN);\r\n case ILLEGAL_CODE.ILLEGAL_END_MATCH_SCORE:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_END_MATCH_SCORE);\r\n default:\r\n return getIllegalEmailObj(ILLEGAL_CODE.ILLEGAL_CODE);\r\n }\r\n }\r\n\r\n return true;\r\n }", "function validateMove(moveObject, gameBoard) {\n\n\n\tif(moveObject.x < 0 || moveObject.x > 2 || moveObject.y < 0 || moveObject.y >2){\n\t\tthrow 'Invalid move: the coordinates are outside the game board';\n\t} \n\n\telse if (gameBoard[moveObject.y][moveObject.x] !== ' '){\n\t\tthrow 'Invalid move: that spot is already taken'\n\t}\n\treturn moveObject;\n}", "function checkMove() {\n if (move.length > 1) { //this is just for error checking in the code\n\n if (move[0][0] * move[1][0] === -1 || move[0][1] * move[1][1] === -1) {\n //invalid move\n move.pop() //then the last move is removed\n } else {\n snake.speedX = move[1][0];\n snake.speedY = move[1][1];\n move.shift();\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
init properties usually done from the config file text: defualt text string, can be dynamically changed textStyle: css styled text x: x position y: y position
init(properties) { this.text = properties.text || this.text; this.textStyle = properties.textStyle; this.x = properties.x || this.x; this.y = properties.y || this.y; this.visible = true; }
[ "function textStyle()\n{\n if(arguments.length==3) {\n this.font = arguments[0];\n this.text_color = arguments[1];\n this.h_align = arguments[2];\n this.v_align = arguments[3];\n }\n else {\n this.font = \"normal 12pt arial\";\n this.text_color = \"#000000\";\n this.h_align = \"left\";\n this.v_align = \"bottom\";\n }\n}", "constructor(text, x, y, w, h, col){\n this.text = text;\n this.x = x;\n this.y = y;\n this.w = w;\n this.h = h;\n this.textCol = col;\n }", "function setCss(){\n\t\t\t\t\n\t\t//set background css\t\t\n\t\tif(g_options.textpanel_enable_bg == true){\n\t\t\tg_objBG = g_objPanel.children(\".ug-textpanel-bg\");\n\t\t\tg_objBG.fadeTo(0,g_options.textpanel_bg_opacity);\n\t\t\t\n\t\t\tvar objCssBG = {\"background-color\":g_options.textpanel_bg_color};\n\t\t\tobjCssBG = jQuery.extend(objCssBG, g_options.textpanel_bg_css);\n\t\t\t\n\t\t\tg_objBG.css(objCssBG);\n\t\t}\n\t\t\n\t\t\n\t\t//set title css from options\n\t\tif(g_options.textpanel_enable_title == true){\n\t\t\tg_objTitle = g_objTextWrapper.children(\".ug-textpanel-title\");\n\t\t\tvar objCssTitle = {};\n\t\t\t\n\t\t\tif(g_options.textpanel_title_color !== null)\n\t\t\t\tobjCssTitle[\"color\"] = g_options.textpanel_title_color;\n\t\t\t\n\t\t\tif(g_options.textpanel_title_font_family !== null)\n\t\t\t\tobjCssTitle[\"font-family\"] = g_options.textpanel_title_font_family;\n\t\t\t\n\t\t\tif(g_options.textpanel_title_text_align !== null)\n\t\t\t\tobjCssTitle[\"text-align\"] = g_options.textpanel_title_text_align;\n\t\t\t\n\t\t\tif(g_options.textpanel_title_font_size !== null)\n\t\t\t\tobjCssTitle[\"font-size\"] = g_options.textpanel_title_font_size+\"px\";\n\t\t\t\n\t\t\tif(g_options.textpanel_title_bold !== null){\n\t\t\t\t\n\t\t\t\tif(g_options.textpanel_title_bold === true)\n\t\t\t\t\tobjCssTitle[\"font-weight\"] = \"bold\";\n\t\t\t\telse\n\t\t\t\t\tobjCssTitle[\"font-weight\"] = \"normal\";\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t//set additional css\n\t\t\tif(g_options.textpanel_css_title)\n\t\t\t\tobjCssTitle = jQuery.extend(objCssTitle, g_options.textpanel_css_title);\n\t\t\t\n\t\t\tg_objTitle.css(objCssTitle);\n\t\t}\n\t\t\n\t\t//set description css\n\t\tif(g_options.textpanel_enable_description == true){\n\t\t\tg_objDesc = g_objTextWrapper.children(\".ug-textpanel-description\");\n\t\t\t\n\t\t\tvar objCssDesc = {};\n\t\t\t\n\t\t\tif(g_options.textpanel_desc_color !== null)\n\t\t\t\tobjCssDesc[\"color\"] = g_options.textpanel_desc_color;\n\t\t\t\n\t\t\tif(g_options.textpanel_desc_font_family !== null)\n\t\t\t\tobjCssDesc[\"font-family\"] = g_options.textpanel_desc_font_family;\n\t\t\t\n\t\t\tif(g_options.textpanel_desc_text_align !== null)\n\t\t\t\tobjCssDesc[\"text-align\"] = g_options.textpanel_desc_text_align;\n\t\t\t\n\t\t\tif(g_options.textpanel_desc_font_size !== null)\n\t\t\t\tobjCssDesc[\"font-size\"] = g_options.textpanel_desc_font_size+\"px\";\n\t\t\t\n\t\t\tif(g_options.textpanel_desc_bold !== null){\n\t\t\t\t\n\t\t\t\tif(g_options.textpanel_desc_bold === true)\n\t\t\t\t\tobjCssDesc[\"font-weight\"] = \"bold\";\n\t\t\t\telse\n\t\t\t\t\tobjCssDesc[\"font-weight\"] = \"normal\";\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t//set additional css\n\t\t\tif(g_options.textpanel_css_title)\n\t\t\t\tobjCssDesc = jQuery.extend(objCssDesc, g_options.textpanel_css_description);\n\t\t\t\t\n\t\t\tg_objDesc.css(objCssDesc);\n\t\t}\n\t\t\n\t}", "set text(text) {\n assertParameters(arguments, [Number, String]);\n \n this._text = text;\n \n if (!(text in Hexagon.NUMBER_PROPS)) {\n text = 'default';\n }\n \n const {color, textColor, highlight} = Hexagon.NUMBER_PROPS[text];\n this._color = color;\n this._highlight = highlight;\n this._textColor = textColor;\n }", "function initProperties() {\r\n // initialize the property behaviours\r\n jQuery('#size').val(defaultSize);\r\n sizeB = changeB(sizeE,'size');\r\n insertValueB(liftB(function(size){return size+'px'},sizeB),\r\n 'size-example','style','height');\r\n \r\n jQuery('#color').val(defaultColor);\r\n colorB = changeB(colorE,'color');\r\n insertValueB(colorB,'color-example','style','backgroundColor');\r\n \r\n jQuery('#fill').val(defaultFill);\r\n fillB = changeB(fillE,'fill');\r\n insertValueB(fillB,'fill-example','style','backgroundColor');\r\n \r\n my.sizeB = sizeB;\r\n my.colorB = colorB;\r\n my.fillB = fillB;\r\n }", "format() {\n if(this.properties[\"text\"]) {\n this.formattedText = this.addLineBreaks(this.properties[\"text\"], 27);\n }\n }", "text() {\n return styles[text[this.id]];\n }", "setInitialValues(){\n // Get computed styles to get the initial :host{} variable values\n let computedStyles = window.getComputedStyle( this.template.host, null );\n\n if( this.defaultAccentColor ){\n this._styleObj.accentColor = this.defaultAccentColor;\n this._hostStyle.setProperty( CSS_VARIABLES.COLOR_ACCENT, this._styleObj.accentColor );\n } else{\n this._styleObj.accentColor = computedStyles.getPropertyValue( CSS_VARIABLES.COLOR_ACCENT );\n }\n\n if( this.defaultFontSize ){\n if( this.defaultFontUnit ){\n this._styleObj.fontUnit = this.defaultFontUnit;\n this.updateSliderSpecsForUnit();\n } // else leave it to default ( 'px' )\n // Set default font-size (after unit update, to prevent overriding the average of new unit range)\n this._styleObj.fontSize = this.defaultFontSize;\n\n this._hostStyle.setProperty( CSS_VARIABLES.FONT_SIZE, this._styleObj.fontSize + this._styleObj.fontUnit );\n } else{\n // When no font-size specified on input, retrieve font-size and unit from css file\n let fontDeclaration = computedStyles.getPropertyValue( CSS_VARIABLES.FONT_SIZE );\n let fontSizeMatcher = fontDeclaration.match( /\\d+/ );\n // When font-size specified, split the integer-size from text-unit;\n if( fontSizeMatcher ){\n let matchedFontSize = fontSizeMatcher[ 0 ];\n this._styleObj.fontUnit = fontDeclaration.replace( matchedFontSize, '' ).trim();\n if( this._styleObj.fontUnit ){\n this.updateSliderSpecsForUnit();\n }\n this._styleObj.fontSize = matchedFontSize;\n }\n }\n }", "function setupText() {\n textFont(\"Helvetica\");\n textSize(10);\n textStyle(NORMAL);\n}", "function textSettings() {\n // Get the element values\n fsValue = fs.value;\n lhValue = lh.value;\n lwValue = lw.value;\n\n // Set styles with new values\n settingValues = \"font-size:\" + fsValue + \"em;line-height:\" + lhValue + \";padding-left:\" + lwValue + \"em;padding-right:\" + lwValue + \"em;\";\n \n // Store settings\n localStorage.setItem(\"textPad-settings\", settingValues);\n localStorage.setItem(\"textPad-settings-fs\", fsValue);\n localStorage.setItem(\"textPad-settings-lh\", lhValue);\n localStorage.setItem(\"textPad-settings-lw\", lwValue);\n }", "function initText() {\r\n fontLabel.text(\"Font: \");\r\n fontLabel1.text(\"Times New Roman\");\r\n fontLabel.append(fontLabel1);\r\n textSliderPoint.css(\"left\", \"10%\");\r\n timesOption.attr(\"selected\", \"selected\");\r\n textSizeLabel.text(\"Text Size: \");\r\n textSizeLabel1.text(\"12px\");\r\n textSizeLabel.append(textSizeLabel1);\r\n hideAll(textArray);\r\n }", "function createTxtObj() {\n return {\n isDraggable: false,\n line: '',\n font: 'Impact',\n size: 50,\n align: '',\n color: '#fff',\n posX: gCanvas.width / 2,\n posY: gCanvas.height / 2,\n }\n}", "function displayText(text, x, y, properties){\n\tctx.save();\n\tfor(var p in properties){\n\t\tctx[p] = properties[p];\n\t}\n\tctx.fillText(text, x, y);\n\tctx.restore();\n}", "getTextStyle() {\n\t\tlet style = {};\n\n\t\tif (this.props.primary) {\n\t\t\tstyle.color = getColor('white-0');\n\t\t} else if (this.props.secondary) {\n\t\t\tstyle.color = getColor(this.props.hue + '-7', 'graphite-7');\n\t\t} else if (this.props.icon && !this.props.title) {\n\t\t\tstyle.fontSize = 24;\n\t\t\tstyle.fontWeight = 'normal';\n\t\t\tstyle.color = getColor(this.props.hue + '-7', 'graphite-7');\n\t\t} else {\n\t\t\tstyle.color = getColor(this.props.hue + '-6', 'graphite-6');\n\t\t}\n\n\t\treturn [styles.text, style];\n\t}", "constructor(text_struct) {\n super(text_struct);\n this.setAttribute('type', 'TextDynamics');\n\n this.sequence = text_struct.text.toLowerCase();\n this.line = text_struct.line || 0;\n this.glyphs = [];\n\n Vex.Merge(this.render_options, {\n glyph_font_size: 40,\n });\n\n L('New Dynamics Text: ', this.sequence);\n }", "initDefaults(defaults) {\n super.initDefaults({\n text: 'Text Element',\n font: '50px Arial',\n color: '#000',\n padding: false,\n lineHeight: false,\n maxWidth: false,\n shadow: false,\n outline: false,\n textAlign: 'center',\n }.inherit(defaults));\n }", "function setUpText() {\n textImg = createGraphics(width, height);\n textImg.pixelDensity(1);\n textImg.background(255);\n textImg.textStyle(fontStyle);\n textImg.textFont('Roboto');\n textImg.textSize(fontSize);\n textImg.textAlign(CENTER, CENTER);\n textImg.text(type, width / 2, height / 4 + fontSize / 6);\n textImg.loadPixels();\n}", "setup() {\n if (this.theme === 0) {\n this.font = FONT_PLAYFUL;\n } else if (this.theme === 1) {\n this.font = FONT_TERMINAL;\n this.underlineColor = this.textColor;\n this.highlightColor = this.textColor;\n }\n }", "setStyleString(style) {\n this.styleString = style;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
console.log(onlyPeopleOfAge(people)); 03. Underage people
function printUnderagePeople(input) { var result = input.filter(function (item) { return item.age < 18; }); result.forEach(function (item) { console.log(item); }); }
[ "function filterUnderagedPeople(people, ageLimit) {\n \n}", "function getempbyage(){\n let agfactor = company.student.filter((ag)=>{\n return ag.Age >40;\n })\n return agfactor;\n}", "function peopleOfAge(arr) {\n const result = arr.filter(function(str) {\n if (peopleOfAge.age >= 18) {\n return arr;\n }});\n return result;\n}", "function shortPeople(people) {\n return people.filter( p => p.height < 70);\n}", "function ageOfPerson(age) {\n\tif (age >= 16){\n\t\treturn \"Here are the keys!\";\n\t} else {\n\t\treturn \"Sorry, you're too young.\"\n\t}\n\treturn age;\n}", "function doFilter() {\n const olderThan60 = people.results.filter((person) => {\n return person.dob.age > 60;\n });\n console.log('maiores de 60', olderThan60);\n}", "function Exercise1() {\n return users.filter(function(user) {\n return user.age < 18;\n });\n}", "function peopleWithAgeDrink(age) {\n if (age < 14) {\n return 'drink toddy'; \n } else if (age < 18) {\n return 'drink coke';\n } else if (age < 21) {\n return 'drink beer';\n }\n\n return 'drink whisky';\n\n\n }", "function olderPeople(peopleArr, age) {\n return peopleArr.filter((person) => {\n return person.age > age;\n });\n}", "function above(person, age){\n let aboveAge = [];\n person.forEach(element => {\n if(element.age > age)\n {aboveAge.push(element)}\n });\n return aboveAge;\n }", "function peopleWithAgeDrink(old) {\r\n if (old>=21)return \"drink whisky\";\r\n if (old<14)return\"drink toddy\"\r\n if (old<18)return\"drink coke\"\r\n if (old<21)return\"drink beer\"\r\n}", "function whatsMyAge(itsatweet) {\n if (itsatweet.age >= 18) {\n return true;\n }\n return false;\n}", "function showAge(birthYear) {\n let age = 2018 - birthYear;\n console.log(\"Du bist \", age, \"Jahre alt\");\n}", "function olderPeople(peopleArr, age) {\n return peopleArr.filter(function (person) {\n return person.age > age;\n });\n}", "function canIWatch(age){\n if (age > 0 && age < 6) return \"You are not allowed to watch Deadpool after 6.00pm.\";\n else if (age >= 6 && age < 17) return \"You must be accompanied by a guardian who is 21 or older.\";\n else if (age >= 17 && age < 25) return \"You are allowed to watch Deadpool, right after you show some ID.\";\n else if (age >= 25) return \"Yay! You can watch Deadpool with no strings attached!\";\n return \"Invalid age\";\n}", "function ageCal(person)\n{\n return person.died - person.born;\n}", "function arbitraryPractice(people) {\n\n people = people.filter(function(person) {\n\n if (! person.pets.filter(pet => pet.nickNames.length > 0).length) {\n return false;\n }\n\n if (! person.pets.filter(pet => pet.type === 'dog').length) {\n return false;\n }\n\n if (person.age <= 20 ) {\n return false;\n }\n\n return true;\n\n });\n\n var pets = [];\n\n for (let i = 0; i < people.length; i++) {\n for (let j = 0; j < people[i].pets.length; j++) {\n pets.push(`<li>${people[i].pets[j].name}</li>`);\n }\n }\n\n return pets;\n}", "function filterFunction(array) {\n let over40 = array.filter(x => x.age >= 40);\n return over40;\n}", "function maleCodersOverThirty(arr) {\n return arr.filter(n => n.age > 30 )\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List handler for reservation resources
async function list(req, res, next) { try { const reservation = await service.list(); if (reservation) { res.json({ data: reservation }); } next({ status: 404, message: `Reservations cannot be found for this.` }); } catch (err) { console.log(err); next({ status: 500, message: "Something went wrong looking for reservations", }); } }
[ "async function list(req, res) {\n\tconst date = req.query.date;\n\tconst mobile_number = req.query.mobile_number;\n\n\tconst reservations = await service.list(date, mobile_number);\n\n\tconst response = reservations.filter((reservation) => reservation.status !== \"finished\");\n\n\tres.json({ data: response });\n}", "async function list(req, res) {\n if (res.locals.mobile_number) {\n const data = await service.search(res.locals.mobile_number);\n res.status(200).json({ data });\n } else {\n const data = await service.list(res.locals.date);\n const unfinishedReservations = data.filter(\n (reservation) =>\n reservation.status != \"finished\" && reservation.status != \"cancelled\"\n );\n res.status(200).json({ data: unfinishedReservations });\n }\n}", "async function list(req, res) {\n if (req.query.date) {\n const { date } = req.query;\n const reservationsByDate = await reservationsService.list(date);\n res.json({\n data: reservationsByDate,\n });\n } if (res.locals.mobile_number) {\n const found = await reservationsService.search(res.locals.mobile_number);\n res.json({ data: found })\n }\n}", "async function list(req, res, next) {\n try {\n const reservation = await service.list();\n if (reservation) {\n res.status(200).json({ data: reservation });\n } else {\n next({ status: 404, message: `Tables cannot be found.` });\n }\n } catch (err) {\n console.log(err);\n next({\n status: 500,\n message: \"Something went wrong looking for tables\",\n });\n }\n}", "function getReservations() {\n\n\t// empty the reservation list\n\t$('.reservation-list').empty();\n\n\treservationsReference.on('child_added', snapshot => {\n\n\t\t// retrieve the day, name, and key from firebase\n\t\tvar resDay = snapshot.val().day;\n\t\tvar resName = snapshot.val().name;\n\t\tvar resId = snapshot.key;\n\n\t\t// add the values to the handlebars template\n\t\tvar source = $('#reservation-template').html();\n\t\tvar template = Handlebars.compile(source);\n\t\tvar context = {\n\t\t\tname: resName, \n\t\t\tday: resDay,\n\t\t\tid: resId\n\t\t};\n\t\tvar reservationItem = template(context);\n\n\t\t// append the new reservation to the list\n\t\t$('.reservation-list').prepend(reservationItem);\n\n\t});\n}", "function loadReservations() {\n const abortController = new AbortController();\n setReservationsError(null);\n\n listReservations({ date: searchDate }, abortController.signal)\n .then(setReservations)\n .catch(setReservationsError);\n return () => abortController.abort();\n }", "async getReservations() {\n return await Reservation.getReservationsForCustomer(this.id);\n }", "function getRes () { \n\n \n fetch(\"http://localhost:3000/reservations\")\n\n .then(resp => resp.json())\n .then( (resp) => {\n \n allRes =reFormatDates(resp) \n existingRes = filterAll()\n debugger\n avail = getAvail(existingRes)\n displayExisting()\n renderTimeSlots()\n \n })\n }", "async function getUserReservations(req, res, next) {\n try {\n const user = await models.user.findOne({\n where: {\n login: req.params.login,\n },\n });\n const reservations = await user.getReservations({\n where: {\n beginning: {\n [Op.gte]: Date.now(),\n },\n },\n });\n res.send(reservations);\n } catch (e) {\n next(e);\n }\n}", "async list(req, res) {\n const { empresa_id } = req.params;\n\n const data = await this.sedesRepo.findAllByEmpresaId(empresa_id)\n .catch(err => {\n return responses.failure(res, err);\n });\n\n return responses.success(res, `Listed sedes from empresa ${empresa_id}`, data);\n }", "function getResList()\n{\n\tif(fs.existsSync('reservations.json'))\n\t{\n\t\tresData = fs.readFileSync('reservations.json');\n\n\t}\n\telse\n\t{\n\t\t// I used Smith as a placeholder first entry if a new file needs to be created. \n\t\tlet mydate = new Date();\n\t\tmydate = mydate.getFullYear() + \"-\" + mydate.getMonth() + \"-\" + mydate.getDay();\n\t\tresListInfo = [\n\n\t\t\t{\n\t\t\t\tusername: 'Smith',\n\t\t\t\tstartdate: mydate,\n\t\t\t\tstarttime: '0700',\n\t\t\t\thours: 3\n\t\t\t},\n\n\t\t];\t\t\n\t\twriteResList();\n\t\tresData = fs.readFileSync('reservations.json');\n\t}\n\n\tresListInfo = JSON.parse(resData);\n\t//console.log(`Reservation: ${JSON.stringify(resListInfo)}`);\n\treturn resListInfo;\n\n}", "function listReservations(from, to, locationID, authInfo) {\n return {\n Pull_ListReservations_RQ: {\n ...createAuthentication(authInfo),\n DateFrom: from,\n DateTo: to,\n LocationID: locationID\n }\n }\n}", "function list(req, res){\n return HoursList\n .findAll()\n .then(hoursLists => {\n // get hour items for each list and display that with list\n const addedHourItems = hoursLists.map(hoursList => {\n const hoursListInfo = hoursList.dataValues;\n return getHourItems(hoursListInfo.id)\n .then(hourItems => {\n hoursListInfo['hourItems'] = hourItems;\n return hoursListInfo;\n });\n });\n\n Promise\n .all(addedHourItems)\n .then(fullHoursLists => {\n return res.status(200).send(fullHoursLists)\n })\n .catch(error => res.status(400).send(error));\n })\n .catch(error => res.status(400).send(error));\n}", "function realestateobject_list(request, response, next) {\n console.log('List of real estate objects');\n\n pool.query('SELECT * FROM real_estate_objects', (error, results) => {\n if (error) {\n throw error;\n }\n response.status(200).json(results.rows);\n });\n}", "function loadReservations() {\r\n debugger;\r\n API.getReservations()\r\n .then(res =>\r\n setReservations(res.data)\r\n )\r\n .catch(err => console.log(err));\r\n }", "function listRegistrars(req, res, next) {\n res.send(200, req.registrars);\n next();\n}", "async function initResaervationsList() {\n let reservations = await get(\"/reservations/allCustomers\"); // getting the reservations from the database\n\n //Converting the r.date to a readable string\n for (r of reservations) {\n let date = new Date(r.date); // creating a new date object by using the date form the reservation\n date = date.toLocaleDateString('de-DE'); // formatting the date to dd.mm.yyyy\n r.date = date; // setting the date of the reservation to the newly created and formatted date object\n }\n\n // Generating and setting html for the reservationsList\n let reservationItemsHtml = await generateAllReservations(reservations);\n let reservationsList = document.getElementById(\"reservationsList\");\n reservationsList.innerHTML = reservationItemsHtml;\n}", "function listRooms(callback) {\n const LIST_PATH = \"/list\";\n \n ajaxGet(LIST_PATH, callback);\n}", "function contract_list(request, response, next) {\n console.log('List of contracts');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves all page instances for website whose _id is websiteId
function findAllPagesForWebsite(websiteId) { return Page.find({ _website: websiteId }); }
[ "function findAllPagesForWebsite(websiteId) {\n return pageModel.find({_website: websiteId});\n}", "function findPageByWebsiteId(websiteId) {\n ret = [];\n for(var p in pages) {\n if (pages[p].websiteId == websiteId) {\n ret.push(pages[p]);\n }\n }\n return ret;\n }", "function findAllPagesForWebsite(req,res) {\n var websiteId = req.params.websiteId;\n pageModel.findAllPagesForWebsite(websiteId).then(\n function (page) { res.json(page); },\n function (error) { res.statusCode(404).send(error); });\n }", "function findAllPagesForWebsite(req, res) {\n var websiteId = req.params.websiteId;\n pageModel\n .findAllPagesForWebsite(websiteId)\n .then(\n function(pages) {\n res.json(pages);\n },\n function(error){\n res.status(404).send(\"Error finding pages\");\n }\n );\n }", "function findAllWebsites(websiteIds) {\n console.log(\"Have websiteIds in findAllWebsites in model.server: \"+websiteIds);\n\n var deferred = q.defer();\n\n WebsiteModel\n .find({'_id': { $in: websiteIds}}, function(err, websiteObjects) {\n console.log(\"Found website objects in model.server: \"+websiteObjects);\n\n if(err) {\n deferred.abort(err); // reject\n } else {\n deferred.resolve(websiteObjects);\n }\n });\n return deferred.promise;\n }", "function getWebPagesByCampaignID(id, callback) {\n\trest('GET', baseURL + 'web/pages/?campaign=' + id + '&limit=' + limit + '&offset=' + (currentPage() === 1 ? 0 : (currentPage() * limit)), null, callback);\n}", "function findAllWebsitesForUser(userId) {\n return WebsiteModel.find({_user: userId});\n }", "function init() {\n vm.pages = pageService.findPagesByWebsiteId(vm.websiteId);\n }", "function createPage(websiteId, page) {\n page.websiteId = websiteId;\n pages.push(page);\n }", "function init() {\n var promise = PageService.findAllPagesForWebsite(websiteId);\n promise\n .success(function(pages) {\n vm.pages = pages;\n })\n }", "function findWebsiteById(websiteId) {\n return websiteModel.findById(websiteId);\n}", "function findWidgetsByPageId(pageId){\n var widgets = $http.get(\"/api/page/\"+pageId+\"/widget\");\n return widgets;\n }", "function findWidgetsByPageId(pageId) {\n var url = '/api/page/' + pageId + '/widget';\n return $http.get(url);\n }", "function findPageById(pageId) {\n return Page.findById(pageId);\n }", "function findWidgetsByPageId(pageId) {\n // /api/page/:pageId/widget\n return $http.get(\"/api/page/\" + pageId + \"/widget\");\n }", "function findWidgetsByPageId(pageId) {\n return $http.get(parentRoute + pageId + \"/widget\");\n }", "function findWebsiteById(websiteId) {\n return WebsiteModel.findById(websiteId);\n }", "function findWebsiteById(websiteId) {\n return WebsiteModel.findWebsiteById(websiteId);\n }", "function getWebPagesByBrandID(id, callback) {\n\trest('GET', baseURL + 'web/pages/?brand=' + id + '&limit=' + limit + '&offset=' + (currentPage() === 1 ? 0 : (currentPage() * limit)), null, callback);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mouse over threat category
function mouseOverCategory(d) { if (timer_draw) timer_draw.stop(); mouse_hover_active = true; hover_type = 'category'; current_hover = d; var id = d.id; //Draw the edges from threat category to the elements edges_elements.forEach(function (l) { l.opacity = l.target.id === id ? 0.5 : 0; }); //Draw the edges from the threat category to the threats edges_concepts.forEach(function (l) { l.opacity = l.target.id === id ? 0.5 : 0; }); //Draw the ICH circles elements.forEach(function (n) { n.opacity = n.threat_categories.indexOf(id) >= 0 ? 1 : 0.1; }); ICH_num = elements.filter(function (n) { return n.threat_categories.indexOf(id) >= 0; }).length; //Draw connected threat categories threats.forEach(function (n) { n.opacity = n.id === id ? 1 : 0.1; }); //Draw connected threats concepts.forEach(function (n) { n.opacity = n.threat_category === id ? 1 : 0.1; }); //Draw it all drawCanvas(); } //function mouseOverElement
[ "function doCountyMouseOver() {\n this.bringToFront();\n this.setStyle({\n weight: 3\n });\n\n var this_geoid = this.feature.properties['geoid'];\n d3.selectAll(\".bar[geoid='\"+this_geoid+\"']\")\n .classed({'active':true})\n .style(\"opacity\",0.7);\n}", "function catSelector(event) {\n // find object of selected cat and set it as active cat\n activeCat = cats.find(function (x) {\n return x.name === event.target.textContent;\n });\n // clear container of previous cat\n clearHtml();\n // add selected cat to html\n renderCat();\n}", "function catSelector(event) {\r\n // find object of selected cat and set it as active cat\r\n activeCat = cats.find(x => x.name === event.target.textContent);\r\n // clear container of previous cat\r\n clearHtml();\r\n // add selected cat to html\r\n renderCat();\r\n}", "function emphasizeCategory(event)\n {\n // De-emphasize all the categories and emphasize the selected one\n var listItems = document.getElementsByTagName(\"li\");\n for ( var i = 0 ; i < listItems.length ; i++ )\n {\n if ( listItems[i].id.slice(0,17) == \"toneCategoryItem_\" )\n {\n listItems[i].style[\"background-color\"] = \"rgb(238, 238, 238)\";\n listItems[i].style[\"color\"] = \"#000\";\n listItems[i].style[\"font-size\"] = \"1.0em\";\n }\n if ( listItems[i].innerHTML == event.target.innerHTML )\n {\n listItems[i].style[\"background-color\"] = \"#000\";\n listItems[i].style[\"color\"] = \"#FFF\";\n listItems[i].style[\"font-size\"] = \"14px\";\n }\n }\n }", "function selectCategoryClickHandler(ev) {\n selectCategory(ev.target);\n}", "function handleCategoryClick(e) {\t\t\t\t\n\tshowItemsInCategory(e.row.catid,e.row.catname);\n}", "display() {\n let nodes = document.getElementsByTagName(\"SPAN\"), i;\n for (i = 0; i < nodes.length; i++) {\n if (nodes[i]['id']) {\n nodes[i].addEventListener(\"click\", function () {\n Demoshop.Category.treeView.displayCategory(this['id']);\n });\n }\n }\n }", "function handleCategoryClick(e) {\t\t\t\t\n\tshowItemsInCategory(e.row.categoryId,e.row.categoryName);\n}", "function legendHover(evt, info, over) {\n var category = null;\n\n if (over) {\n var pos = $(evt.target).closest('.geo-label').index() - 1;\n category = info.legend[pos].name;\n }\n showCategory(category, info);\n}", "function hoverToDisplaySubCategories() {\r\n // Variables:\r\n\r\n // Item Categories\r\n const categories = document.querySelectorAll(\".category\");\r\n\r\n categories.forEach((category) => {\r\n category.addEventListener(\"click\", function (e) {\r\n console.log(category.nextElementSibling);\r\n category.nextElementSibling.classList.add(\"hovered-show\");\r\n });\r\n\r\n category.nextElementSibling.addEventListener(\"mouseleave\", function (e) {\r\n console.log(category.nextElementSibling);\r\n category.nextElementSibling.classList.remove(\"hovered-show\");\r\n });\r\n });\r\n}", "function handleMouseOver(d) {\n attack_count = attacks_per_state_dict[this.id];\n if (attack_count == undefined) {\n attack_count = 0;\n }\n state_name = this.id.replace(/([A-Z])/g, ' $1');\n d3.select(\"#tooltip\").text(state_name);\n d3.select(\"#tooltip2\").text(\"Documented Attacks: \"+attack_count);\n d3.select(this).attr(\"opacity\", \".6\");\n }", "function select_category(elem) {\n selected['category'] = elem;\n }", "function hoverCategoryItems() {\n let cgrElIdx = -1; // initialize the ordinal numbers of category items\n let actEl = 'category-item--active'; // set active property of item\n \n let cgrPC_Ctn = document.querySelector('.category-pc > .category'); // get element of category container on PC\n let cgrElsCtn = cgrPC_Ctn.querySelector('.category-list'); // get element of category list\n let cgrEls = cgrElsCtn.querySelectorAll('.category-item'); // get element of category items\n\n // remove active property of item \n let removeColor = () => {\n for (let cgrEl of cgrEls) {\n if (cgrEl.classList.contains(actEl)) {\n cgrEl.classList.remove(actEl);\n }\n }\n }\n\n // handle hover\n for (let cgrEl of cgrEls) {\n cgrEl.onmouseover = () => { \n removeColor();\n cgrEl.classList.add(actEl);\n }\n }\n\n // loop through all items until reach the active item\n for (let cgrEl of cgrEls) {\n cgrElIdx++;\n if (cgrEl.classList.contains(actEl)) {\n break;\n }\n }\n\n // when hovering out container will reset the original active state\n cgrElsCtn.onmouseleave = () => {\n let cgrActChild = cgrElsCtn.children[cgrElIdx]; // get element of original active item\n \n removeColor();\n cgrActChild.classList.add(actEl);\n }\n}", "function highlightFeature(e) {\n\tvar layer = e.target;\n\tif (layer != current_municipal_layer) {\n\t\tlayer.setStyle({\n\t\t\tcolor: municipal_style.color_hover,\n\t\t\topacity: municipal_style.opacity_hover,\n\t\t\tweight: municipal_style.weight_hover,\n\t\t});\n\t}\n\t\n\tif (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n\t\tlayer.bringToFront();\n\t}\n\ttooltip.style(\"display\", \"inline\");\n}", "function showCategories() {\r\n let categories = [];\r\n for (let i = 0; i < data.length; i++) {\r\n categories.push(data[i].category);\r\n }\r\n categories = removeDuplicates(categories.sort());\r\n\r\n let out = \"\";\r\n out += \"Suggested categories : \";\r\n for (let i = 0; i < categories.length; i++) {\r\n out +=\r\n \"<span onclick='category.value=this.innerText' tabindex='0'>\" +\r\n categories[i] +\r\n \"</span>\";\r\n }\r\n suggestedCategory.innerHTML = out;\r\n}", "function showCategory(ev) {\n $appFullCategory.css('left', ev.clientX);\n $appFullCategory.css('top', ev.clientY);\n $appFullCategory.css('background-color', $(this).css('border-color'));\n $appFullCategory.addClass(ev.data.classToAdd);\n\n categoryTitle.empty();\n categoryTitle.append($(this).attr('name'));\n\n currentCategory = $(this).attr('id');\n\n $titlesList.empty();\n $slideshow.empty();\n\n renderTitles();\n renderSlides();\n\n setTimeout(function() {\n $modalHeader.fadeIn(300);\n $modalContainer.fadeIn(300);\n $modalFooter.fadeIn(300);\n }, 300);\n }", "function highlightFeature(e) {\n\tvar chorolayer = e.target;\n\t\n\t// style to use on mouse over\n\tchorolayer.setStyle({\n weight: 2,\n\t\tcolor: '#3b3b3b',\n\t\tfillOpacity: 0.6\n\t});\n\n\tif (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n\t\tchorolayer.bringToFront();\n\t}\n\n\t//make dashboard\n createDashboard(chorolayer.feature.properties);\n\n}", "function overSkill0() {\r\n\tget(\"tooltip-display\").style.display = \"block\";\r\n\tget(\"tooltip-text\").innerHTML = skillsDescArray[0]\r\n}", "function onDropCategoryClicked(){\n\t\tcurrCategory = $(this).text();\n\t\tsetupGallery(oData.catalogue, currCategory, currSection);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes a MySQL query to get all posts from the database. Check the new id whether in the database. If the new post id in the database, return error message. If not, return a Promise that resolves to the ID of the newlycreated user entry.
async function checkPostId(newId){ const [ posts ] = await mysqlPool.query( 'SELECT * FROM posts ORDER BY id' ); if(posts){ for(var i = 0; i < posts.length; i++){ if(posts[i].postId === newId){ return false; } } } return true; }
[ "createPost(post) {\n if (!post.subredditId) {\n return Promise.reject(new Error(\"There is no subreddit id\"));\n }\n\n return this.conn.query(\n `\n INSERT INTO posts (userId, title, url, createdAt, updatedAt, subredditId)\n VALUES (?, ?, ?, NOW(), NOW(), ?)`,\n [post.userId, post.title, post.url, post.subredditId]\n )\n .then(result => {\n return result.insertId; //insertId = post id as id is NOT NULL AUTO INCREMENT KEY\n });\n }", "async function insertNewPost(post) {\n post = extractValidFields(post, PostSchema);\n const [ result ] = await mysqlPool.query(\n 'INSERT INTO posts SET ?',\n post\n );\n \n return result.insertId;\n }", "createPost(post) {\n if (!post.subredditId) {\n return Promise.reject(new Error(\"There is no subreddit id\"));\n }\n\n return this.conn.query(\n `\n INSERT INTO posts (userId, title, url, createdAt, updatedAt, subredditId)\n VALUES (?, ?, ?, NOW(), NOW(), ?)`,\n [post.userId, post.title, post.url, post.subredditId]\n )\n .then(result => {\n return result.insertId;\n });\n }", "createPost(post) {\n return this.conn.query(\n `INSERT INTO posts (userId, title, url, createdAt, updatedAt, subredditId) VALUES (?, ?, ?, NOW(), NOW(), ?)`,\n [post.userId, post.title, post.url, post.subredditId])\n .then(result => {\n //console.log(result.subredditId);\n return result.subredditId;\n });\n // .catch(error => {\n // // Special error handling for no subreddit ID\n // if (error.code === 'ER_NO_SRID') {\n // throw new Error('This Subreddit does not exist');\n // }\n // else {\n // throw error;\n // }\n // });\n }", "async post() {\n const db = await dbPromise;\n return db.transaction('posts','readwrite').objectStore('posts').openCursor().then(\n function logItems(cursor) {\n if (!cursor) {\n return;\n }\n //if there is no mongoID --> therefore not synced\n if (cursor.value.mongodbID == null){\n console.log(cursor.value.mongodbID)\n $.ajax({\n url: '/posts/create',\n type: \"POST\",\n data: JSON.stringify({\n id: cursor.value[\"id\"],\n eventid: cursor.value[\"eventid\"],\n title: cursor.value[\"title\"],\n lat: cursor.value[\"lat\"],\n lon: cursor.value[\"lon\"],\n image: cursor.value[\"image\"],\n created: cursor.value.created\n }),\n contentType: 'application/json',\n success: function (mid) {\n //emit to all users that a new post has been uploaded\n socket.emit('Sync Post', { id: mid });\n },\n error: function (err) {\n // alert('Error: ' + err.status + ':' + err.statusText);\n }\n });\n //delete local post\n console.log(\"sfsdfsdf\"+cursor.value[\"id\"])\n cursor.delete(cursor.value[\"id\"]);\n }\n\n return cursor.continue().then(logItems);\n })\n }", "function deleteUserPosts() {\n return new Promise(async function (resolve, reject) {\n const structure = 'DELETE FROM post '\n + 'WHERE post.user_id = ? ';\n const inserts = [event.headers[\"delete_user_id\"]];\n const sql = MySQL.format(structure, inserts);\n\n await con.query(sql, function (error) {\n if (error) {\n reject(createErrorMessage(\"404\", \"Server-side Error\", \"Failed to query requested data due to server-side error\", error));\n } else {\n resolve();\n }\n });\n });\n }", "function create_post(req, callback) {\n const { author_id, title, content_body, hashtags, private } = req;\n \n const created_at = new Date();\n \n var union_sql = '';\n var UNION = 'UNION ';\n for (let i = 0; i < hashtags.length; i++) {\n union_sql += `SELECT '${hashtags[i]}' as name ${UNION}`;\n };\n union_sql = union_sql.substring(0, union_sql.length - UNION.length-1);\n var insert_post_sql = `INSERT INTO Posts SET ?`;\n var insert_hashtag_sql = hashtags.length === 0 ? '' : `INSERT INTO Hashtag (name) SELECT name from (${union_sql}) as User_Hashtags where not exists (select name from Hashtag WHERE User_Hashtags.name = Hashtag.name);`\n var pair_post_and_hashtag = hashtags.length === 0 ? '' :`INSERT INTO PostHashtag (post_id, hashtag_id) SELECT post_id, hashtag_id from (${union_sql}) as t1 inner join Hashtag using(name) CROSS JOIN (SELECT MAX(post_id) as post_id from Posts) as t2;`;\n var sql = `${insert_hashtag_sql} ${pair_post_and_hashtag}`;\n //insert the post first, then insert the hashtag (because we need the inserted post id)\n pool.query(\n insert_post_sql,\n { author_id, title, content_body, created_at, private },\n function(err, result, fields) {\n if (err) throw new Error(err);\n const returnVal = {newPostId: result.insertId};\n \n //Send the hashtag if exist\n if(sql.trim().length>0){\n pool.query(\n sql,\n function(err, result, fields) {\n if (err) throw new Error(err);\n callback(null, returnVal);\n }\n );\n }else{\n callback(null, returnVal);\n }\n }\n );\n}", "function queryPostMessage(db, channelID, body, date, userID) {\n return new Promise((resolve, reject) => {\n db.query(Constant.SQL_POST_MESSAGE, [channelID, body, date, userID, date], (err, results) => {\n if (err) {\n reject(err);\n }\n if (results.affectedRows === 0) {\n return resolve(false);\n }\n resolve(results.insertId);\n });\n });\n}", "async function getPostInfoById(id) {\n let placeholders = [id, id, id];\n let sql = \"SELECT * FROM posts WHERE pid = ?;\";\n\n sql += \"SELECT links FROM links WHERE pid = ?;\";\n sql += \"SELECT tags FROM tags WHERE pid = ?;\";\n\n return new Promise(async function (resolve, reject) {\n const result = await db.query(sql, placeholders).catch((error) => {\n fs.writeFileSync(__dirname + '/errors/' + Date.now() + 'error.log', error + '');\n });\n if (result == undefined) {\n console.log(\"There was an error getting the post info.\");\n }\n resolve(result[0]);\n });\n}", "async function getPostById(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM posts WHERE postId = ?',\n [ id ]\n );\n return results[0];\n }", "static getPost(start, num) {\n return new Promise((res, rej) => {\n let db = new DB()\n \n let newestSql = \n `select p.id, p.create_at, p.message, p.likes, p.comments,\n u.unique_name_tag, u.display_name\n from post p, user u\n where p.user_id = u.id\n order by p.id desc, p.create_at desc\n limit ${num}`\n\n let startFromSql = \n `select p.id, p.create_at, p.message, p.likes, p.comments,\n u.unique_name_tag, u.display_name\n from post p, user u\n where p.user_id = u.id and p.id <= ${start}\n order by p.id desc, p.create_at desc\n limit ${num}`\n\n db.query(start == 0 ? newestSql : startFromSql)\n .then(posts => {\n db.close()\n res(posts)\n })\n .catch(err => {\n db.close()\n rej(err)\n })\n })\n }", "function insert(newPost) {\n return db(\"posts\")\n .insert(newPost)\n .returning([\"id\", \"title\", \"description\", \"photo_url\"]);\n}", "function addPost(req, threadId){\n return new Promise(function(resolve, reject){\n let postId;\n\n Posts\n .create({\n user: req.body.user,\n content: req.body.content,\n })\n .then((post) => {\n postId = post._id;\n \n Threads\n .findByIdAndUpdate(threadId, {$push: {posts: postId}}, {new: true})\n .then((response) => {\n resolve(response);\n })\n })\n .catch(err => {\n reject(err);\n })\n });\n}", "async post() {\n const db = await dbPromise;\n return db.transaction('posts').objectStore('posts').getAll().then(function (posts) {\n // loop through all the records and create a list that contains all the mongoids\n var _id = []\n for (var i = 0; i < posts.length; i++) {\n if (posts[i].mongodbID != null) {\n _id.push(posts[i].mongodbID);\n }\n }\n console.log(_id);\n //this sends all the mongoids to the posts controller\n $.ajax({\n url: '/posts/downsync',\n type: \"POST\",\n data: JSON.stringify({\n _id\n }),\n contentType: 'application/json',\n success: function (res) {\n //the result is a list of JSON objects to be added to the event store\n for (var i = 0; i < res.length; i++ ) {\n\n const item = {\n mongodbID: res[i]._id,\n eventid: res[i].eventid,\n title: res[i].title,\n lat: res[i].lat,\n lon: res[i].lon,\n image: res[i].file,\n created: res[i].created\n };\n //render to the page\n db.transaction('posts', \"readwrite\").objectStore('posts').add(item).then(function (id) {\n db.transaction('posts').objectStore('posts').get(id).then(function (data) {\n renderPost(data.eventid, data.id, \"post\")\n mapDb.add_post(data.id, data)\n })\n })\n }\n },\n });\n });\n\n }", "async function getNumberOfApprovedPosts() {\n let sql = \"SELECT COUNT(*) as \\\"total\\\" FROM posts WHERE status = 1;\";\n return new Promise(async function (resolve, reject) {\n const result = await db.query(sql).catch((error) => {\n fs.writeFileSync(__dirname + '/errors/' + Date.now() + 'error.log', error + '');\n });\n if (result == undefined) {\n console.log(\"There was an error getting the number of posts\");\n }\n resolve(result[0]);\n });\n}", "function lastPost(threadId, threadTitle, counter, total) {\n var getLastPost = new Promise(\n function(resolve, reject) {\n Post.find({ threadId : threadId}).sort({ 'created' : -1}).limit(1).exec(function(err, post) {\n if (err) throw err;\n if (post) {\n resolve(post);\n }\n });\n }\n );\n getLastPost.then(\n function(val) {\n\n findUser(threadId, threadTitle, counter, total, val[0].user, val[0].content, val[0].created);\n }\n )\n .catch(\n function(reason){\n console.log('last post not found due to ' + reason);\n }\n );\n }", "async readPostByID(postId){\n // Checks if postId is undefined\n if(!postId){\n throw(\"Error posts.readPostByID: postId was not defined\")\n }\n\n if(typeof postId !== 'string' && typeof postId !== 'object'){\n throw(\"Error posts.readPostByID: Invalid id type passed in\")\n }\n\n // Gets the collection from the database\n const postsCollection = await posts()\n\n // If the postId passed is not already a mongo id object, we attempt to make it one, otherwise throw\n let newId\n if(typeof(postId) !== 'object'){\n \n try{\n newId = new mongo.ObjectID(postId)\n }\n catch(e){\n throw(\"Error posts.readPostByID: Invalid ID\")\n }\n }\n else{\n newId = postId\n }\n\n // Try to find the post in the data base with the postId throw error if not in db\n let post\n try{\n post = await postsCollection.findOne({_id: newId})\n }\n catch(e){\n throw(\"Error posts.readPostByID: No post with that ID\")\n }\n\n // If no post is returned, then throw\n if(!post){\n throw(\"Error posts.readPostByID: No post with that ID\")\n }\n\n return(post)\n }", "async get_last_user_id() {\n return new Promise((resolve, reject) => {\n this.db().get(\"SELECT DISTINCT id FROM users ORDER BY id DESC;\", [], (error, user) => {\n if(!error) {\n resolve(user.id);\n } else {\n // Provide feedback for the error\n console.log(error);\n resolve(false);\n }\n });\n });\n }", "function createPost(post) {\n\n // Return a promise. 'resolve' & 'reject' are callbacks provided by js.\n // The function passed to the promise will execute after 2 seconds.\n\n return new Promise(function(resolve, reject) {\n\n // Set timeout again - mimicing post to server\n\n setTimeout(function() {\n posts.push(post);\n\n // Artificially setting the error code to 'true' or 'false'\n\n const error = true;\n\n if (!error) {\n // If not an error:\n // This will run the .then function below (i.e. 'getPosts')\n \n resolve();\n }\n else {\n \n // If error:\n // This will run the .catch function below to display the error message in the console\n \n reject('Error: Something went wrong!');\n }\n\n }, 2000);\n\n });\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the line chart in the linechart svg for the country argument (e.g., `Algeria').
function drawLineChart(country) { if(!country) return; var node = document.getElementById('linechart'); node.innerHTML = ""; let year = document.getElementById("year-input").value; // Create country data object let countryData = []; timeData.forEach(d => { if(country in d){ countryData.push({ Year : String(d.Year), GDP : d[String(country)], }); } }); // Creating the box for linechart lineSvg.append("svg") .attr("width", lineWidth) .attr("height", lineHeight) .append("g"); var x = d3.scaleLinear() .domain(d3.extent(countryData, function(d) { return +d.Year;})) .range([ 0, lineInnerWidth ]); lineSvg.append("g") .attr("id", "line") .attr("transform", "translate(" + (lineWidth - lineInnerWidth)/2 +"," + ((lineHeight - lineInnerHeight)/2 + lineInnerHeight) + ")") .call(d3.axisBottom(x) .tickFormat(d3.format("d")) ); var ticks = d3.selectAll("#line .tick text"); ticks.each(function(_,i){ if(i%2 != 0) d3.select(this).remove(); }); var y = d3.scaleLinear() .domain([0, d3.max(countryData, function(d) { return +d.GDP; })]) .range([ lineInnerHeight, 0 ]); lineSvg.append("g") .attr("transform", "translate("+ (lineWidth - lineInnerWidth)/2 + "," + (lineHeight - lineInnerHeight)/2 +")") .call(d3.axisLeft(y).tickSize(-lineInnerWidth)) .call(g => g.select(".domain").remove()) .call(g => g.selectAll(".tick:not(:first-of-type) line") .attr("stroke-opacity", 0.5) .attr("stroke-dasharray", "5,10") ); lineSvg.selectAll(".tick text") .attr('fill', 'gray'); lineSvg.selectAll(".tick line") .attr('stroke', 'gray'); lineSvg.selectAll(".domain") .attr('stroke', 'gray'); lineSvg.append("path") .datum(countryData) .attr("fill", "none") .attr("stroke", "black") .attr("stroke-width", 2) .attr("transform", "translate("+ (lineWidth - lineInnerWidth)/2 + "," + (lineHeight - lineInnerHeight)/2 +")") .attr("d", d3.line() .x(function(d) { return x(+d.Year) }) .y(function(d) { return y(+d.GDP) }) ); lineSvg.append("text") .attr("text-anchor", "middle") .attr("transform", "rotate(-90)") .attr("y", 40) .attr("x", -lineHeight/2) .attr("font-family", "sans-serif") .attr("font-size", "18px") .style('fill', 'gray') .text(`GDP of ${country} (based on current USD)`) lineSvg.append("text") .attr("text-anchor", "middle") .attr("x", lineWidth/2) .attr("y", lineHeight -5) .attr("font-family", "sans-serif") .attr("font-size", "17px") .style('fill', 'gray') .text("Year"); lineSvg.select("#line") .on('mouseover', function(d,i) { div.transition() .duration(50) .style("opacity", 1); div.html(`Country: <br />GDP: `) .style("left", (d3.event.pageX) + 10 + "px") .style("top", (d3.event.pageY) + 10 + "px"); }) .on('mouseout', function(d,i) { // console.log('mouseout on ' + d.properties.name); div.transition() .duration(50) .style("opacity", 0); }); // for the hover on line chart var focus = lineSvg .append('g') .attr("transform", "translate("+ (lineWidth-lineInnerWidth)/2 + "," + (lineHeight-lineInnerHeight)/2 +")") .append('circle') .style("fill", "none") .attr("stroke", "black") .attr('r', 10) .style("opacity", 0); lineSvg .append('rect') .style("fill", "none") .style("pointer-events", "all") .attr('width', lineInnerWidth) .attr('height', lineInnerHeight) .attr("transform", "translate("+ (lineWidth-lineInnerWidth)/2 + "," + (lineHeight-lineInnerHeight)/2 +")") .on('mouseover', mouseover) .on('mousemove', mousemove) .on('mouseout', mouseout); function mouseover() { focus.style("opacity", 1) } function mousemove() { // recover coordinate we need var x0 = x.invert(d3.mouse(this)[0]); // let y0 = y.invert(d3.mouse(this)[0]); let y0 = 0; // let y0 = 0 let i = bisect(countryData, x0, 1); // bisecty(countryData, y0, 1); selectedData = countryData[i] y0 = countryData[i].GDP; focus .attr("cx", x(selectedData.Year)) .attr("cy", y(selectedData.GDP)); div.transition() .duration(50) .style("opacity", 1); div.html(`Year: ${parseInt(selectedData.Year)} <br/>GDP: ${selectedData.GDP}`) .style("left", (d3.event.pageX) + 10 + "px") .style("top", (d3.event.pageY) + 10 + "px"); } function mouseout() { focus.style("opacity", 0) div.transition() .duration(50) .style("opacity", 0); } var bisect = d3.bisector(function(d) { return d.Year; }).left; }
[ "function drawLineChart(country) {\n console.log('enter into drawLineChart: ' + country);\n\n\n lineSvg.select('g').remove();\n const xScale = d3.scaleLinear();\n var lineData;\n\n // get the GDP values for countries\n timeData.forEach(d => {\n for (var key in d) {\n if (key == \"Year\")\n d.Year = +d.Year;\n else\n d[key] = +d[key];\n }\n lineData = timeData;\n\n xScale.domain(d3.extent(timeData, function (d) { return d.Year; }))\n .range([0, lineInnerWidth]);\n\n });\n\n\n\n\n const g = lineSvg.append('g')\n .attr('transform', `translate(${lineMargin.left},${lineMargin.top})`);\n\n const yScale = d3.scaleLinear()\n .domain([0, d3.max(lineData, d => d[country])])\n .range([lineInnerHeight, 0]);\n\n\n\n g.append('g')\n .style('fill', 'gray')\n .call(d3.axisLeft(yScale));\n\n g.append('g')\n .style('fill','gray')\n .attr('transform', `translate(0,${lineInnerHeight})`)\n .call(d3.axisBottom(xScale));\n\n const singleLine = d3.line()\n .x(d => xScale(d.Year))\n .y(d => yScale(d[country]));\n\n\n\n\n g.append('path')\n .datum(lineData)\n .attr('class', 'singleLine')\n .style('fill', 'none')\n .style('stroke', 'black')\n .style('stroke-size', '2')\n .attr(\"d\", singleLine)\n .on('mouseover', mouseover)\n .on('mousemove', mousemove)\n .on('mouseout', mouseout);\n\n //add chart label\n g.append(\"text\")\n .attr(\"class\",\"xLabel\")\n .attr(\"text-anchor\",\"end\")\n .attr(\"x\",lineInnerWidth/2)\n .attr(\"y\",lineInnerHeight+35)\n .text(\"Year\")\n .style(\"fill\",\"grey\");\n\n g.append(\"text\")\n .attr(\"class\",\"yLabel\")\n .attr(\"text-anchor\",\"end\")\n .attr(\"x\",-lineMargin.left)\n .attr(\"y\",-lineMargin.left+30)\n .attr(\"dy\",\".75em\")\n .attr(\"transform\",\"rotate(-90)\")\n .style(\"fill\",\"grey\")\n .text(\"GDP for \" + country +\" (based on crrent USD\");\n\n\n\n // Create a rect on top of the svg area: this rectangle recovers mouse position\n\n g\n .append('rect')\n .style(\"fill\", \"none\")\n .style(\"pointer-events\", \"all\")\n .attr('width', width)\n .attr('height', height)\n .on('mouseover', mouseover)\n .on('mousemove', mousemove)\n .on('mouseout', mouseout);\n\n\n // This allows to find the closest X index of the mouse:\n var bisect = d3.bisector(function (d) { return d.Year; }).left;\n // Create the circle that travels along the curve of chart\n var focus = g\n .append('g')\n .append('circle')\n .style(\"fill\", \"none\")\n .attr(\"stroke\", \"black\")\n .attr('r', 8.5)\n .style(\"opacity\", 0);\n\n\n // Create the text that travels along the curve of chart\n var focusText = g\n .append('g')\n .append('text')\n .style(\"opacity\", 0)\n .attr(\"text-anchor\", \"left\")\n .attr(\"alignment-baseline\", \"middle\")\n\n // What happens when the mouse move -> show the annotations at the right positions.\n function mouseover() {\n focus.style(\"opacity\", 1)\n focusText.style(\"opacity\", 1)\n }\n\n function mousemove() {\n // recover coordinate we need\n var x0 = xScale.invert(d3.mouse(this)[0]);\n var i = bisect(lineData, x0, 1);\n selectedData = lineData[i]\n focus\n .attr(\"cx\", xScale(selectedData.Year))\n .attr(\"cy\", yScale(selectedData[country]))\n focusText\n .html(\"Year:\" + selectedData.Year + \"</br> \" + \"GDP: \" + selectedData[country])\n .attr(\"x\", xScale(selectedData.Year) + 15)\n .attr(\"y\", yScale(selectedData[country]))\n }\n function mouseout() {\n focus.style(\"opacity\", 0)\n focusText.style(\"opacity\", 0)\n }\n\n\n if (!country)\n return;\n\n}", "function drawLineChart(data, country) {\n // only draw new line chart if country is not Netherlands\n if (country != \"NLD\") {\n\n // if chart title does not exist yet, draw it\n if (!d3.select(\"#lineChart-title\").select(\"div\")[0][0]) {\n d3.select(\"#lineChart-title\")\n .append(\"div\")\n .append(\"text\")\n .text(\"Export data of Netherlands to countries\");\n };\n\n // remove all children of html map div\n d3.select(\"#lineChart\").selectAll(\"*\").remove();\n\n // margins around graph in pixels\n var margin = {top: 70, right: 80, bottom: 120, left: 60};\n\n // get chart size\n var chartSize = d3.select(\"#lineChart\").node().getBoundingClientRect();\n\n // width and height of graph in pixels\n var width = chartSize.width - 100 - margin.left - margin.right;\n var height = 450 - margin.top - margin.bottom;\n\n // g element for line chart\n var lineChart = d3.select(\"#lineChart\")\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" +\n margin.top + \")\");\n\n // open export data file\n d3.json(\"https://raw.githubusercontent.com/jellewe/programmeerproject/master/doc/export_data.json\", function(error, exportData) {\n if (error) {\n window.alert(\"an error has occured: \" + error);\n };\n\n // arrays for export and year information\n var exportArray = [];\n var yearArray = [];\n for (key in exportData[country]) {\n yearArray.push(parseInt(key));\n exportArray.push(parseInt(exportData[country][key]));\n };\n\n // check if all data available, else show 'no data' message to user\n var noData = false;\n exportArray.forEach(function(item) {\n if ((!item)) {\n noData = true;\n };\n });\n if (noData) {\n noDataMessage(data[country][\"name\"]);\n };\n\n // if line not yet drawn, draw it\n if (!(lineData[country]) && noData == false) {\n lineData[country] = exportArray;\n }\n\n // if line already drawn or no data, remove it\n else {\n delete lineData[country];\n };\n\n // get max value for y axis\n var maxYDomain = 0;\n for (key in lineData) {\n var tempMax = d3.max(lineData[key], function(d) { return d });\n if (tempMax > maxYDomain) {\n maxYDomain = tempMax;\n };\n };\n\n // scales for x and y dimensions\n var xScale = d3.scale.linear()\n .domain([d3.min(yearArray, function(d) { return d }),\n d3.max(yearArray, function(d) { return d })])\n .range([0, width]);\n var yScale = d3.scale.linear()\n .domain([0, maxYDomain])\n .range([height, 0]);\n\n // variables for x and y axes\n var xAxis = d3.svg.axis()\n .scale(xScale)\n .orient(\"bottom\")\n .ticks(21)\n .tickFormat(d3.format(\"d\"));\n var yAxis = d3.svg.axis()\n .scale(yScale)\n .orient(\"left\");\n\n // g element for x axis\n lineChart.append(\"g\")\n .attr(\"class\", \"x axis\")\n .style(\"font-size\", \"10px\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis)\n .selectAll(\"text\")\n .style(\"font-size\", axisFontSize);\n\n\n // g element for y axis\n lineChart.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis)\n .selectAll(\"text\")\n .style(\"font-size\", axisFontSize);\n\n // label for y axis\n lineChart.select(\".y\")\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"yScale\", 6)\n .attr(\"dy\", \"1.5em\")\n .style(\"text-anchor\", \"end\")\n .attr(\"font-size\", \"10px\")\n .text(\"Export in US$ thousand\");\n\n // function to draw lines\n var lineFunction = d3.svg.line()\n .defined(function(d) { return d; })\n .x(function(d, i) { return xScale(yearArray[i]); })\n .y(function(d) { return yScale(d); });\n\n // colors for lines\n var lineColors = [\"#e41a1c\", \"#377eb8\", \"#4daf4a\", \"#984ea3\", \"#ff7f00\"];\n\n // draw lines one for one\n var dataIndex = 0;\n for (key in lineData) {\n lineChart.append(\"path\")\n .attr(\"id\", \"line\")\n .data(lineColors)\n .attr(\"stroke\", lineColors[dataIndex % lineColors.length])\n .attr(\"stroke-width\", \"3px\")\n .attr(\"fill\", \"none\")\n .attr(\"d\", lineFunction(lineData[key]));\n\n // draw country text next to line\n var lastDatum = [yearArray.slice(-1)[0], lineData[key].slice(-1)[0]];\n lineChart.append(\"text\")\n .attr(\"id\", \"line-name\")\n .data(lineData[key])\n .attr(\"transform\", function(d, i) {\n return \"translate (\" + xScale(lastDatum[0]) + \",\" +\n yScale(lastDatum[1]) + \")\"; })\n .text(data[key][\"name\"]);\n\n dataIndex += 1;\n };\n });\n }\n}", "function makeLineGraph() {\n\n // Clear out the current html in the line graph svg\n svgLineGraph.html(\"\");\n\n // Filter data based on selected country\n let countryData = allYearsData.filter((row) => row[\"location\"] == selectedCountry);\n\n // Get all the years for the given country\n let timeData = countryData.map((row) => +row[\"time\"]);\n\n // Get the population data for the given country\n let populationData = countryData.map((row) => +row[\"pop_mlns\"]);\n\n let minMax = findMinMax(timeData, populationData)\n\n let funcs = drawAxes(minMax, \"time\", \"pop_mlns\", svgLineGraph, {min: 100, max: 950}, {min: 100, max: 750});\n plotLineGraph(funcs, countryData, selectedCountry)\n }", "function SVGLineChart() {\r\n }", "function createLinegraph(countryId,countryName){\n d3.select(\".svgmap\").remove()\n d3.select(\".p2\").html(\"life expectancy of\" + ' ' + countryName +' ' + \"from 1960-2013\");\n allYear = []\n values = []\n // get the data for the given country\n for( var z = 0; z < dataDict.length; z++){\n if (dataDict[z].countryCode == countryId){\n values.push(dataDict[z].lifeExpectancy)\n allYear.push({\n year: dataDict[z].year,\n lifeExpectancy: dataDict[z].lifeExpectancy\n }\n\n )\n }\n }\n\n var margin = {top: 40, right: 80, bottom: 60, left: 50},\n width = 700 - margin.left - margin.right,\n height = 300 - margin.top - margin.bottom;\n\n var x = d3.scale.linear()\n .range([0, width])\n .domain([1960,2013]);\n\n var y = d3.scale.linear()\n .range([height, 0])\n .domain([d3.min(values),d3.max(values)]);\n\n var xAxis = d3.svg.axis()\n .scale(x)\n .orient(\"bottom\")\n .tickFormat(d3.format(\"d\"));\n var yAxis = d3.svg.axis()\n .scale(y)\n .orient(\"left\");\n\n var line = d3.svg.line()\n .x(function(d) { return x(d.year); }) // >>>????\n .y(function(d) { return y(d.lifeExpectancy); });\n\n var svg = d3.select(\"body\").append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .style(\"position\", \"absolute\")\n .style(\"top\", \"40px\")\n .style(\"right\", \"10px\")\n .style(\"left\", \"800px\")\n .attr(\"class\", \"svgmap\")\n .on(\"mousemove\", mousemove)\n .on(\"mouseover\",function() { focus.style(\"display\", null) ; focus2.style(\"display\",null);lineX.style(\"display\",null);})\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\")\n\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis);\n\n svg.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis)\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 6)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(\"average life expectancy\");\n\n svg.append(\"path\")\n .attr(\"class\", \"line\")\n .attr(\"d\", line(allYear));\n\n var focus = svg.append(\"g\")\n .attr(\"class\", \"focus\")\n .style(\"display\", \"none\");\n\n focus.append(\"text\")\n .attr(\"x\", 9)\n .attr(\"dy\", \".35em\")\n .attr(\"y\",-20)\n var focus2 = svg.append(\"g\")\n .attr(\"class\",\"focus2\")\n .style(\"display\",\"none\")\n\n focus2.append(\"text\")\n .attr(\"x\", 30)\n .attr(\"dy\", \".35em\")\n .attr(\"y\", 20)\n\n var lineX = svg.append(\"line\")\n .attr(\"x1\", 0)\n .attr(\"x2\", width)\n .attr(\"stroke-width\", 2)\n .attr(\"stroke\", \"black\")\n .style(\"display\",\"none\");\n\n var lineY = svg.append(\"line\") // x-as durp\n .attr(\"y1\", 0)\n .attr(\"y2\", height)\n .attr(\"stroke-width\", 2)\n .attr(\"stroke\", \"black\");\n\n function mousemove() {\n\n hardx = d3.mouse(this)[0] - margin.left\n var x0 = Math.round(x.invert(d3.mouse(this)[0] - margin.left))\n for( var v = 0; v < allYear.length; v++){\n if (allYear[v].year == x0){\n y0 = allYear[v].lifeExpectancy\n }\n }\n\n focus.attr(\"transform\", \"translate(\" + hardx + \",\" + y(y0) + \")\");\n focus2.attr(\"transform\", \"translate(\" + hardx + \",\" + y(y0) + \")\");\n\n lineX.attr(\"y1\",y(y0));\n lineX.attr(\"y2\",y(y0));\n\n lineY.attr(\"x1\",hardx);\n lineY.attr(\"x2\",hardx);\n focus.select(\"text\").text(\"\");\n focus2.select(\"text\").text(\"\");\n timeOut = setTimeout(function() {\n focus.select(\"text\").text(y0);\n focus2.select(\"text\").text(x0);\n },delay)\n\n }\n\n}", "function updateLineChart(country)\n{\n valueLine = d3.line()\n .x(function(d,i){ return x(d.Year)})\n .y(function(d,i) {\n //console.log(d[country])\n return y(d[country])});\n var transition = d3.select(\"#linechart\").transition();\n transition.select(\".line\").duration(500)\n .attr(\"class\", \"line\")\n .attr(\"d\", valueLine(refugees));\n}", "function makeLineGraph(defaultCountry) {\n\n // Update chart based on screen width/height\n lineWidth = w * 0.425;\n lineHeight = h * 0.685;\n\n // Update range for X and Y\n lineX.range([0, lineWidth]);\n lineY.range([lineHeight, 0]);\n\n // Update zoom min/max dimensions\n zoom\n .translateExtent([[0, 0], [lineWidth, lineHeight]])\n .extent([[0, 0], [lineWidth, lineHeight]]);\n\n // Initialize X and Y axii\n xAxisLine = d3.axisBottom(lineX);\n yAxisLine = d3.axisLeft(lineY).ticks(7);\n\n // Save country we're interested in\n currentGEO = defaultCountry;\n\n d3.json(lineSelectedSector, function(error, data) {\n\n // Log any errors, and save results for usage outside of this function\n if (error) throw error;\n\n // Correctly parse the imported data and use it\n formatLineData(data, currentGEO);\n processLineData(data, currentGEO);\n\n // Update Y domain\n lineY.domain([0, d3.max(maxProductions)]).nice();\n\n // Add SVG\n svg = d3.select(\"#lineDiv\").append(\"svg\")\n .attr(\"width\", lineWidth + margin.right)\n .attr(\"height\", lineHeight + margin.bottom)\n .call(zoom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n // Call tooltip\n svg.call(circleTip);\n\n // Add scalable X and Y axii\n appendgXY();\n\n // Add description text for Y axis\n addYDescription();\n\n // Add line into SVG and use year/production for X/Y\n var line = d3.line()\n .x(d => lineX(d.year))\n .y(d => lineY(d.production));\n\n // Initialize lines\n var lines = svg.append(\"g\")\n .attr(\"class\", \"lines\");\n\n // Enter data and append a line for each country\n lines.selectAll(\".line-group\")\n .data(data).enter()\n .append(\"g\")\n .attr(\"class\", \"line-group\")\n .append(\"path\")\n .attr(\"class\", \"line\")\n .attr(\"d\", d => line(d.values))\n\n // Style line color, width and opacity based on the country we want\n .style(\"stroke\", function(d, i) {\n if (d.GEO == currentGEO) { currentGEOColor = lineColor(i) }\n return lineColor(i) })\n .style(\"stroke-width\", function(d) {\n if (d.GEO != currentGEO) { return lineStrokeOthers/zoomLevel } })\n .style(\"opacity\", function(d) {\n if (d.GEO != currentGEO) { return lineOpacity } })\n\n // Add mouseover and mouseout functions\n .on(\"mouseover\", function(d, i) {\n\n // Reset all style\n d3.selectAll(\".title-text\").remove();\n d3.selectAll(\".title-extra-text\").remove();\n d3.selectAll(\".line\").transition().duration(300)\n .style(\"stroke-width\", lineStrokeOthers/zoomLevel)\n d3.selectAll(\"circle\").transition().duration(300)\n .style(\"opacity\", circleOpacity)\n .attr(\"r\", circleRadiusOthers/zoomLevel);\n\n // Highlight line when it is hovered over\n d3.select(this).transition().duration(300)\n .style(\"opacity\", lineOpacityHover)\n .style(\"stroke-width\", lineStrokeHover/zoomLevel)\n .style(\"cursor\", \"pointer\");\n\n // Append text about country that is selected\n svg.append(\"text\")\n .attr(\"class\", \"title-text\")\n .style(\"fill\", lineColor(i))\n .text(d.GEO_TIME)\n .attr(\"text-anchor\", \"left\")\n .attr(\"x\", 45)\n .attr(\"y\", 55);\n\n // Append text about renewable resource that is used\n svg.append(\"text\")\n .attr(\"class\", \"title-extra-text\")\n .style(\"fill\", lineColor(i))\n .text(\"> \" + energySelection)\n .attr(\"text-anchor\", \"left\")\n .attr(\"x\", 60)\n .attr(\"y\", 87); })\n\n .on(\"mouseout\", function(d) {\n d3.selectAll(\".line\").transition().duration(300)\n .style(\"stroke-width\", lineStroke/zoomLevel)\n d3.selectAll(\"circle\").transition().duration(300)\n .attr(\"r\", circleRadius/zoomLevel);\n d3.select(this)\n .style(\"opacity\", lineOpacity)\n .style(\"stroke-width\", lineStroke/zoomLevel)\n .style(\"cursor\", \"none\");\n d3.selectAll(\".title-text\").remove();\n d3.selectAll(\".title-extra-text\").remove(); });\n\n // Add circles in the line\n lines.selectAll(\".circle-group\")\n .data(data).enter()\n .append(\"g\")\n .attr(\"class\", \"circle-group\")\n .style(\"fill\", (d, i) => lineColor(i))\n .selectAll(\"circle\")\n .data(d => d.values).enter()\n .append(\"g\")\n .attr(\"class\", \"circle\")\n .append(\"circle\")\n .attr(\"cx\", d => lineX(d.year))\n .attr(\"cy\", d => lineY(d.production))\n\n // Style circle width and opacity based on the country we want\n .attr(\"r\", function(d) {\n if (d.GEO != currentGEO) { return circleRadiusOthers/zoomLevel } })\n .style(\"opacity\", circleOpacity)\n\n // Change opacity and radius when the circle is being hovered over\n .on(\"mouseover\", function(d) {\n d3.select(this)\n .transition().duration(300)\n .attr(\"r\", circleRadiusHover/zoomLevel)\n .style(\"opacity\", circleOpacityOnLineHover);\n circleTip.show(d); })\n .on(\"mouseout\", function(d) {\n d3.select(this)\n .transition()\n .duration(300)\n .attr(\"r\", circleRadius/zoomLevel)\n .style(\"opacity\", circleOpacity);\n circleTip.hide(d); });\n\n // Add title\n addCountryTitle(300);\n\n });\n}", "function drawChart(country) {\n if (country['properties']['name'] === \"Germany (until 1990 former territory of the FRG)\") {\n var name = \"Germany\";\n } else {\n var name = country['properties']['name'];\n }\n\n /* Drawing graph in the 'per year' selection, plots a country vs average of europe */\n function updateData1(countrydata) {\n var graph = d3.select(\".aGraph\").transition();\n\n xgraph.domain([2000,2015]);\n\n /* Compare max values */\n var countryMax = d3.max(countrydata, function(d) {\n return d.value; });\n if(countryMax > maxEU) {\n ygraph.domain([0, countryMax]).nice();\n } else {\n ygraph.domain([0, maxEU]).nice();\n }\n\n /* Update the graph */\n graph.select(\".EUline\") /* Change the line */\n .duration(750)\n .attr(\"d\", line(euUnion));\n graph.select(\".line\") /* Change the line */\n .duration(750)\n .attr(\"d\", line(countrydata));\n graph.select(\".xgraph.axis\") /* Change the x axis */\n .duration(750)\n .call(xAxisLine);\n graph.select(\".ygraph.axis\") /* Change the y axis */\n .duration(750)\n .call(yAxisLine);\n\n graphTitle.select(\".europe\").text(\"Europe\");\n graphTitle.select(\".vs\").text(\" vs. \");\n graphTitle.select(\".country\").text(name);\n }\n\n /* Drawing graph in the 'trend' selection, plots a country vs another country.\n * Country1 is the previous selected country */\n function updateData2(country1, country2, name1, name2) {\n var graph = d3.select(\".aGraph\").transition();\n\n xgraph.domain([2000,2015]);\n\n var countryMax1 = d3.max(country1, function(d) {\n return d.value; });\n var countryMax2 = d3.max(country2, function(d) {\n return d.value; });\n\n /* Compare max values */\n if(countryMax1 > countryMax2) {\n ygraph.domain([0, countryMax1]).nice();\n } else {\n ygraph.domain([0, countryMax2]).nice();\n }\n\n /* Update the graph */\n graph.select(\".EUline\") /* Change the line */\n .duration(750)\n .attr(\"d\", line(country1));\n graph.select(\".line\") /* Change the line */\n .duration(750)\n .attr(\"d\", line(country2));\n graph.select(\".xgraph.axis\") /* Change the x axis */\n .duration(750)\n .call(xAxisLine);\n graph.select(\".ygraph.axis\") /* Change the y axis */\n .duration(750)\n .call(yAxisLine);\n\n graphTitle.select(\".europe\").text(name1);\n graphTitle.select(\".vs\").text(\" vs. \");\n graphTitle.select(\".country\").text(name2);\n }\n\n var countrydata = [];\n /* Make an array with data of the country per year */\n for(var row in country['unemploymentData']) {\n if(!isNaN(country['unemploymentData'][row][0]['Value'])) {\n countrydata.push({year: parseInt(row), value: parseFloat(country['unemploymentData'][row][0]['Value'])});\n }\n }\n\n if ($(\"#typeSelect\").val() === \"peryear\") {\n updateData1(countrydata);\n } else {\n updateData2(previousCountry, countrydata, previousname, name);\n }\n\n /* Initialise the previous country for 'updatedata2' */\n previousCountry = countrydata;\n previousname = name;\n }", "drawChart(activeCountry) {\n this.activeCountry = activeCountry;\n let that = this;\n if (activeCountry === null || activeCountry === undefined) {\n return;\n }\n\n // Removes the previous line chart\n d3.select(\"#line-chart-svg\").remove();\n\n // Converts the abbreviated country name to the actual country name\n let goodName = that.data[\"population\"].filter(d => d.geo === that.activeCountry.toLowerCase());\n\n // Selects the current country\n let selectedCountry = that.data[\"countries\"].filter(d => d.Country === goodName[0][\"country\"]);\n\n // Scale for the y-axis\n let aScale = d3\n .scaleBand()\n .domain([\"Winners\", \"Runners-Up\", \"Third Place\", \"Semifinalists\", \"Quarterfinalists\", \"Round of 16\", \"Group Stage\", \"Did Not Qualify\"])//that.data[\"countries\"].map(d => d.placement))\n .rangeRound([0, 400]);\n\n // Scale for the x-axis\n let iScale_line = d3\n .scaleLinear()\n .domain([1930, 2014])\n .rangeRound([10, 600]);\n\n let aLineGenerator = d3\n .line()\n .x(function(d) {\n // Takes off the \"finish\" at the end of the data so that it is just the year\n let noFinish = d.Year.substring(0, 4);\n return iScale_line(noFinish);\n })\n .y(function(d) { \n return aScale(d.Placement) \n });\n\n // Adds the line chart to the bottom left of the css grid layout\n d3.select(\"#line-chart\").classed(\"bottomright-grid\", true).append(\"svg\").attr(\"id\", \"line-chart-svg\").attr(\"width\", \"100%\").attr(\"height\", \"800\");\n \n // Adds the y-axis to the svg\n d3.select(\"#line-chart-svg\").append(\"g\").attr(\"id\", \"left-axis\");\n\n // Creates the y-axis\n let aAxis_line = d3.axisLeft(aScale).ticks(9);\n\n // Populates the y-axis\n d3.select(\"#left-axis\").attr(\"transform\", \"translate(80,50)\").call(aAxis_line);\n\n // Adds titles to the axes\n d3.select(\"#line-chart-svg\").append(\"text\").text(\"Placement\").attr(\"transform\", \"translate(-1, 30)\");\n d3.select(\"#line-chart-svg\").append(\"text\").text(\"Year\").attr(\"transform\", \"translate(400, 500)\");\n\n // Adds the x-axis to the svg\n d3.select(\"#line-chart-svg\").append(\"g\").attr(\"id\", \"bottom-axis\");\n\n // Creates the x-axis\n let bottomAxis = d3.axisBottom(iScale_line)\n .tickValues(d3.range(1930, 2014 + 4, 4))\n .tickFormat(d3.format(\"d\"));\n\n // Populates the x-axis\n d3.select(\"#bottom-axis\").attr(\"transform\", \"translate(70, 450)\").call(bottomAxis);\n\n if (selectedCountry.length === 0) {\n return;\n }\n \n // Finds the indices of all the world cups in the given data to be used in creating the line\n let beginFinish = 1930 + \"Finish\";\n let endFinish = 2014 + \"Finish\";\n let arr = Object.entries(selectedCountry[0]);\n let beginIndex = arr.findIndex(d => d[0] === beginFinish);\n let endIndex = arr.findIndex(d => d[0] === endFinish);\n\n let ranger = arr.slice(beginIndex, endIndex + 1);\n\n // Needed to ensure the .enter and .update only iterate through once\n // doesn't work otherwise\n let holder = [];\n holder.push(1);\n \n // Adds the line to the line chart\n let aLine = d3.select(\"#line-chart-svg\").append(\"g\").attr(\"class\", \"line-chart-x\").attr(\"id\", \"line-chart-path\")\n .attr(\"transform\", \"translate(72,73)\").selectAll(\"path\").data(holder);\n\n // Holds the newly formatted data to be passed into the line generator\n let newArr = [];\n \n // Handle entering, updating, and exiting new information\n aLine.join(\n enter =>\n enter\n .append(\"path\")\n .attr(\"class\", \"line-chart-x\")\n .attr(\"d\", function(d) {\n for (let i = 0; i < ranger.length; i++) {\n let newer = {\"Year\": ranger[i][0], \"Placement\": ranger[i][1]};\n newArr.push(newer);\n }\n return aLineGenerator(newArr);\n \n }),\n update =>\n update\n .attr(\"class\", \"line-chart-x\")\n .style(\"stroke-width\", 2)\n .style(\"fill\", \"none\")\n .attr(\"d\", function() {\n return aLineGenerator(data);\n }),\n exit => exit.remove()\n );\n }", "function mapToLineChartClick(countryCode){\r\n // set country code\r\n $(\"#curr-country-code\").val(countryCode);\r\n\r\n // draw line chart\r\n drawLineChart();\r\n}", "function drawLines (linegraph, employments, data, country, color, x, y) {\n\n employments.forEach(function(employment) {\n var employmentData = data[employment];\n\n var line = d3.line()\n .x(function(d) { return x(d.Year); })\n .y(function(d) { return y(d.Country[country]); });\n\n linegraph.append(\"path\")\n .datum(employmentData)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", color(employment))\n .attr(\"stroke-width\", 2)\n .attr(\"d\", line);\n });\n}", "function make_line_graph(country){\n\t\td3.selectAll(\".linegraph\").remove()\n\n\t\t//aggregating the data\n\t\tmedals_data = [{medal : \"gold\", counts : []},{medal : \"silver\", counts : []}, {medal : \"bronze\", counts : []}]\n\t\tyears.forEach(function(y){\n\t\t\tgold = 0;\n\t\t\tsilver = 0;\n\t\t\tbronze = 0;\n\t\t\tdata.forEach(function (d){\n\n\t\t\t\tif (d['Year'] == y && d['Country'] == country){\n\t\t\t\t\tgold += +d['Gold Medals'];\n\t\t\t\t\tsilver += +d['Silver Medals'];\n\t\t\t\t\tbronze += +d['Bronze Medals'];\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t\tmedals_data.forEach(function (m){\n\t\t\t\tconsole.log(m);\n\t\t\t\tif (m.medal == 'gold'){\n\t\t\t\t\tm['counts'].push({year : y, medals : gold});\n\t\t\t\t}\n\t\t\t\tif (m.medal == 'silver'){\n\t\t\t\t\tm['counts'].push({year : y, medals : silver});\n\t\t\t\t}\n\t\t\t\tif (m.medal == 'bronze'){\n\t\t\t\t\tm['counts'].push({year : y, medals : bronze});\n\t\t\t\t}\n\t\t\t})\n\t\t});\n\n\n\t\tvar format = d3.time.format('%Y');\n\n\n\t\tvar x = d3.time.scale().range([margin.left,width]).domain([format.parse('2000'),format.parse('2012')]);\n\n\n\t\tvar y = d3.scale.linear().range([0,height]).domain([150,0]);\n\n\t\tvar xAxis = d3.svg.axis()\n\t\t .scale(x)\n\t\t .orient(\"bottom\");\n\t\tvar yAxis = d3.svg.axis()\n \t\t.scale(y)\n \t\t.orient(\"left\");\n\n \tvar line = d3.svg.line()\n \t\t.interpolate(\"linear\")\n\n \t\t.x(function(d) {return x(format.parse(d.year)); })\n \t\t.y(function(d) {return y(d.medals); });\n\n \tvar color = d3.scale.ordinal()\n\t\t .range([\"#8c7853\",\"#C0C0C0\",\"#FFD700\"])\n\t\t .domain([\"bronze\",\"silver\",\"gold\"]);\n\n\t\tvar medals = color.domain().map(function(name) {\n \t\treturn {\n \t\t\tname: name,\n \t\t\tvalues: medals_data.map(function(d) {\n \t\treturn {year: d.year, medals: +d[medals]};\n \t\t\t})\n \t\t};\n \t\t});\n\n \t\tsvg3.append(\"g\")\n \t\t.attr(\"class\", \"x axis\")\n \t\t.attr(\"transform\", \"translate(0,\" + height + \")\")\n \t\t.call(xAxis);\n\n \t\tsvg3.append(\"g\")\n \t\t.attr(\"class\", \"y axis\")\n \t\t.attr(\"transform\",\"translate(\" + margin.left + \",0)\")\n \t\t.call(yAxis)\n \t\t.append(\"text\")\n \t\t.attr(\"transform\", \"rotate(-90)\")\n \t\t.attr(\"y\", 6)\n \t\t.attr(\"dy\", \".71em\")\n \t\t.style(\"text-anchor\", \"end\")\n \t\t.text(\"Medals\");\n\n \t\tvar medal = svg3.selectAll(\".medal\")\n \t\t.data(medals_data)\n \t\t.enter().append(\"g\")\n \t\t.attr(\"class\", \"linegraph\");\n\n \t\tmedal.append(\"path\")\n \t\t.attr(\"class\", \"line\")\n \t\t.attr(\"class\",\"linegraph\")\n \t\t.attr(\"d\", function(d) { return line(d.counts); })\n \t\t.style(\"fill\",\"none\")\n \t\t.style(\"stroke\", function(d) { return color(d.medal); });\n\n\n\n\n\n\t}", "function drawLine() {\n\n var data = new google.visualization.DataTable();\n data.addColumn('number', 'X');\n data.addColumn('number', 'Clients');\n data.addRows(self.charts.line.rows);\n\n var options = self.charts.line.options;\n\n var chart = new google.visualization.LineChart(document.getElementById('chart_div'));\n\n chart.draw(data, options);\n }", "function vertLine (data){\n // console.log(data)\n\n // setup a mouse over element, added id so that it can be redrawn\n // when another country is added. \n var mouseOver = svg.append(\"g\").attr(\"id\", \"vert\")\n\n // add a path (the vertical line) grey, 1px width\n mouseOver.append(\"path\")\n .attr(\"class\", \"mouse-line\")\n .style(\"stroke\", \"#3D4849\") //charcoal grey\n .style(\"stroke-width\", \"1px\")\n\n // Retrieves all elements with class name 'line'\n // I added this class name to each of the paths earlier\n var lines2 = document.getElementsByClassName('line');\n\n //Adds a mouse-per-line class to each of the data elements\n var mousePerLine = mouseOver.selectAll('.mouse-per-line')\n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"mouse-per-line\"); //adds class to each datapoint, \n // so we can reference it later\n\n // Adds a rectangle to each of the elements of mousePerLine\n // This also means that there will always be 6 rect, regardless of whether \n // the checkboxes are checked or not...\n mousePerLine.append(\"rect\")\n .attr(\"width\", \"5\")\n .attr(\"height\", \"5\")\n .attr(\"x\", \"-2.5\") //center the rect\n .attr(\"y\", \"-2.5\")\n .style(\"stroke\", function (d) {\n return color(d.country); //still using category10 \n })\n .style(\"fill\", \"transparent\")\n .style(\"stroke-width\", \"1px\")\n .attr(\"opacity\", \"0\") //Such that it doesn't appear on page load.\n\n //Adds the text values that appear 5,-7 pixels away from each mousePerLine element\n // This way, when the line reaches the end, it isn't as cluttered\n // I added some font specifications to make it more unique\n // China and Brazil will inevitably overlap :( but after 2003, it looks nice\n mousePerLine.append(\"text\")\n .attr(\"transform\", \"translate(5,-5)\")\n .attr(\"font-size\", \"12px\")\n .style('fill', '#3D4849')\n .attr(\"font-family\", \"courier\")\n\n //Adds a rectangle to catch the mouse's position on the canvas, spanning the entire canvas\n mouseOver.append('svg:rect')\n .attr('width', width)\n .attr('height', height)\n .attr('fill', 'none') //colorless\n .attr('pointer-events', 'all') //In CSS, this means that this SVG\n // element will be the target of the following pointer events\n\n .on('mouseout', function () {// on mouse out hide line, rectangles and text\n d3.select(\".mouse-line\") //The vertical line\n .style(\"opacity\", \"0\");\n d3.selectAll(\".mouse-per-line rect\") // The rectangles\n .style(\"opacity\", \"0\");\n d3.selectAll(\".mouse-per-line text\") // The text (numbers)\n .style(\"opacity\", \"0\");\n })\n .on('mouseover', function () {// on mouse in show line, rectangles and text\n d3.select(\".mouse-line\")\n .style(\"opacity\", \"1\");\n d3.selectAll(\".mouse-per-line rect\")\n .style(\"opacity\", \"1\");\n d3.selectAll(\".mouse-per-line text\")\n .style(\"opacity\", \"1\");\n })\n .on('mousemove', function () {// mouse moving over canvas\n \n //'this' references the current calling element\n var mouse = d3.mouse(this); //get mouse (with x,y coords)\n\n //Specifies the path, which is calculated based on the mouse position\n d3.select(\".mouse-line\") //selects the vertical line\n .attr(\"d\", function () { // create the path for the vert. line\n //M stands for moveto\n var d = \"M\" + mouse[0] + \",\" + height; //The line is from mouseX, height \n d += \" \" + mouse[0] + \",\" + 0; // to mouseX, 0, such that it is vertical\n return d;\n });\n\n //Selects all mouse-per-line classes, which was defined previously\n //for each of the 6 data points.\n d3.selectAll(\".mouse-per-line\")\n //applies the transform: translate property to each of the rectangles/text/line\n .attr(\"transform\", function (d, i) {\n var beginning = 0\n end = lines2[i].getTotalLength()\n //This reads the entire path length for each of the lines based on index i. \n target = -1; //some initial target value\n\n // infinite loop until the position, pos, is \"found\"\n // on the canvas. This is done by rounding a target\n // to be half of beginning + end, based on the current\n // values of end and beginning that will be dynamically\n // updated based on the conditional statements and the current mouseX position\n // I've removed some unnecessary conditions that was in the original \n // source code because I noticed that they will always/never occur. \n while (true) {\n target = Math.floor((beginning + end) / 2);\n pos = lines2[i].getPointAtLength(target); //get point at target\n //This is the condition that breaks out of the loop,\n // where the target is found, strictly equal to end or begining\n // console.log(pos, mouse[0], target, end, beginning)\n if ((target === end || target === beginning)) {\n break;\n }\n else if (pos.x > mouse[0]) end = target;\n else beginning = target;\n }\n // Appends the text values based on the y-scale value\n // rounded to 2 decimal places, using the discovered 'pos'\n // from the previous while (true) loop.\n // Invert does the opposite of scale, so given\n // a range value, returns the corresponding domain. \n d3.select(this).select('text')\n .text(yScale.invert(pos.y).toFixed(2));\n //Finally, return the translate coordinates for each path\n return \"translate(\" + mouse[0] + \",\" + pos.y + \")\";\n });\n })\n}", "drawLineChart(){\n\t\tlet crimeRatesPerYearAndPerCrimeType = this.createCrimeRateData();\n\t\tthis.createLineChart(crimeRatesPerYearAndPerCrimeType);\n\t}", "function make_line(variable) {\n line.y(function (d) {\n return y(+d[variable]);\n });\n\n linegroup.append(\"path\")\n .attr(\"class\", \"info line\")\n .attr(\"id\", variable)\n .style(\"stroke\", function (d) {\n return d.color = color(variable);\n })\n .attr(\"d\", function (d) {\n return line(data_country);\n });\n }", "function drawLineChart(jsonData) {\n\n var options = {\n title: 'Level of Nitrogen Dioxoide (micrograms) Per Cubic Meter Over a 24 Hour Period',\n hAxis: {title: 'Time of Day'},\n vAxis: {title: 'Amount of No2 Per Cubic Meter of Air (µg/m3)'},\n };\n // Create our data table out of JSON data loaded from server.\n var data = new google.visualization.DataTable(jsonData);\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.LineChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n}", "function drawPopulationLineOnChart() {\r\n // define line generator for main data lines plotted on chart.\r\n aleph.mainline = d3\r\n .line()\r\n .x(function (d) {\r\n return (\r\n aleph.margin.line[aleph.windowSize].left +\r\n aleph.xMain(aleph.parseDate(d.year))\r\n );\r\n })\r\n .y(function (d) {\r\n return (\r\n aleph.margin.line[aleph.windowSize].top +\r\n aleph.yMain(d[aleph.lineChartyAxisType] /* .counts */ /* value */)\r\n );\r\n });\r\n\r\n // Append a 'g' element to contain the plotted data line and all related DOM content\r\n d3.selectAll(\".aleph-lineChart-group\")\r\n .append(\"g\")\r\n .attr(\r\n \"class\",\r\n \"aleph-line-group aleph-line-group-\" +\r\n aleph.currentlySelectedScenario.scenarioSubmissionNumber +\r\n \" scenarioNumber-\" +\r\n aleph.currentlySelectedScenario.scenarioSubmissionNumber +\r\n \" scenarioUID-\" +\r\n aleph.currentlySelectedScenario.scenarioUIDCode\r\n );\r\n\r\n // Append path for plotted data line\r\n d3.selectAll(\r\n \".aleph-line-group.aleph-line-group-\" +\r\n aleph.currentlySelectedScenario.scenarioSubmissionNumber\r\n )\r\n .append(\"path\")\r\n .datum(aleph.currentlySelectedScenario.lineChartData)\r\n .attr(\r\n \"class\",\r\n \"line mainline changeMainlineStyle-\" +\r\n aleph.currentlySelectedScenario.scenarioSubmissionNumber\r\n )\r\n .style(\"stroke\", function () {\r\n return aleph.currentlySelectedScenario.lineColour;\r\n })\r\n .attr(\"d\", aleph.mainline);\r\n\r\n // call function to append and draw sparkline in righthand margin.\r\n drawSparkLine(aleph.currentlySelectedScenario);\r\n\r\n // appedn all vertex marker circles to plotted lines ...\r\n d3.selectAll(\r\n \".aleph-line-group-\" +\r\n aleph.currentlySelectedScenario.scenarioSubmissionNumber\r\n )\r\n .selectAll(\"aleph-Line-Vertex-Marker-Circles\")\r\n .data(aleph.currentlySelectedScenario.lineChartData)\r\n .enter()\r\n .append(\"circle\")\r\n .attr(\"class\", function (d) {\r\n return (\r\n \"aleph-Line-Vertex-Marker-Circles scenario-\" +\r\n aleph.currentlySelectedScenario.scenarioSubmissionNumber\r\n );\r\n })\r\n .attr(\"cx\", function (d, i) {\r\n return (\r\n aleph.margin.line[aleph.windowSize].left +\r\n aleph.xMain(aleph.parseDate(d.year))\r\n );\r\n })\r\n .attr(\"cy\", function (d, i) {\r\n return (\r\n aleph.margin.line[aleph.windowSize].top +\r\n aleph.yMain(d[aleph.lineChartyAxisType] /* .counts */ /* value */)\r\n );\r\n })\r\n .attr(\"r\", 5)\r\n .style(\"stroke\", aleph.currentlySelectedScenario.lineColour);\r\n\r\n // move chart mouseover interaction content to front of vis ...\r\n d3.selectAll(\".mouse-over-effects\").moveToFront();\r\n\r\n // append DOM items to allow user mouseover ability ..\r\n aleph.mousePerLine = mouseG\r\n .selectAll(\".mouse-per-line\")\r\n .data(aleph.scenariosData)\r\n .enter()\r\n .append(\"g\")\r\n .attr(\"class\", \"mouse-per-line\");\r\n\r\n // append DOM circle items to highlight user mouseover ability ..\r\n aleph.mousePerLine\r\n .append(\"circle\")\r\n .attr(\"class\", \"aleph-marker-circle\")\r\n .attr(\"r\", 5)\r\n .style(\"stroke\", function (d) {\r\n var colour = d3\r\n .selectAll(\r\n \".line.mainline.changeMainlineStyle-\" +\r\n aleph.currentNumberOfSavedScenarios /* NEED TO FIX THIS COLOUR STYLING TO GET NEW COLOUR */\r\n )\r\n .style(\"stroke\");\r\n return colour;\r\n });\r\n\r\n // append DOM text item to highlight user mouseover ability ..\r\n aleph.mousePerLine\r\n .append(\"text\")\r\n .attr(\"class\", \"aleph-mouseover-textlabel\")\r\n .style(\"stroke\", aleph.currentlySelectedScenario.lineColour);\r\n /* .attr(\"transform\", \"translate(10,3)\") */\r\n\r\n // if item has not been built yet, i.e. on drawing of first data line ...\r\n if (document.getElementById(\"aleph-mouseRectangle\") == null) {\r\n // append an SVG rect to allow mouseover interaction to occur\r\n mouseG\r\n .append(\"svg:rect\")\r\n .attr(\"class\", \"aleph-mouseRectangle\")\r\n .attr(\"id\", \"aleph-mouseRectangle\")\r\n .attr(\r\n \"width\",\r\n svgWidth -\r\n aleph.margin.line[aleph.windowSize].right -\r\n aleph.margin.line[aleph.windowSize].left\r\n )\r\n .attr(\r\n \"height\",\r\n svgHeight -\r\n aleph.margin.line[aleph.windowSize].top -\r\n aleph.margin.line[aleph.windowSize].bottom\r\n )\r\n .attr(\"x\", aleph.margin.line[aleph.windowSize].left)\r\n .attr(\"y\", aleph.margin.line[aleph.windowSize].top)\r\n .on(\"mouseover\", function () {\r\n if (Object.keys(aleph.scenarios).length > 0) {\r\n aleph.chartLines = document.getElementsByClassName(\"line mainline\");\r\n\r\n // on mouse in show line, circles and text\r\n d3.select(\".mouse-line\").style(\"opacity\", \"1\");\r\n d3.selectAll(\".mouse-per-line circle\").style(\"opacity\", \"1\");\r\n d3.selectAll(\".mouse-per-line text\").style(\"opacity\", \"1\");\r\n\r\n // bring tootlitp to fron to page/DOM structure\r\n // d3.selectAll(\".aleph-toolTip-g\")\r\n // .classed(\"aleph-hide\", false)\r\n // .moveToFront();\r\n\r\n // D3 v4\r\n // determine x and y coordinates of cursor pointer\r\n var x = d3.event.pageX;\r\n var y = d3.event.pageY;\r\n\r\n aleph.chartDragX = x;\r\n aleph.chartDragY = y;\r\n\r\n // function called to define and build tooltip structure and content\r\n cursorCoords(/* d, */ x, y);\r\n } // end if ....\r\n return;\r\n })\r\n .on(\"mousemove\", function () {\r\n // if one of more data line has been drawn already\r\n if (Object.keys(aleph.scenarios).length > 0) {\r\n aleph.chartLines = document.getElementsByClassName(\"line mainline\");\r\n\r\n // mouse moving over canvas\r\n var mouse = d3.mouse(this);\r\n aleph.mouseoverRectangle = this;\r\n\r\n d3.select(\".mouse-line\").attr(\"d\", function () {\r\n var d =\r\n \"M\" +\r\n mouse[0] +\r\n \",\" +\r\n (svgHeight -\r\n aleph.margin.line[aleph.windowSize].top -\r\n aleph.margin.line[aleph.windowSize].bottom);\r\n\r\n d += \" \" + mouse[0] + \",\" + 0;\r\n return d;\r\n });\r\n\r\n aleph.xYear;\r\n\r\n // move mouseover DOM content ...\r\n d3.selectAll(\".mouse-per-line\").attr(\"transform\", function (d, i) {\r\n if (aleph.chartLines[i]) {\r\n (aleph.xYear = aleph.xMain.invert(\r\n mouse[0] - aleph.margin.line[aleph.windowSize].left\r\n )),\r\n (bisect = d3.bisector(function (d) {\r\n return d.date;\r\n }).right);\r\n idx = bisect(d.values, aleph.xYear);\r\n\r\n var beginning = 0,\r\n end = aleph.chartLines[i].getTotalLength(),\r\n target = null;\r\n\r\n while (true) {\r\n target = Math.floor((beginning + end) / 2);\r\n pos = aleph.chartLines[i].getPointAtLength(target);\r\n if (\r\n (target === end || target === beginning) &&\r\n pos.x !== mouse[0]\r\n ) {\r\n break;\r\n }\r\n if (pos.x > mouse[0]) end = target;\r\n else if (pos.x < mouse[0]) beginning = target;\r\n else break; //position found\r\n }\r\n\r\n aleph.currentLineData;\r\n\r\n // update mouseover text content\r\n // d3.select(this)\r\n // .select(\"text\")\r\n // .attr(\"x\", 10)\r\n // .attr(\"y\", -15)\r\n // .text(function (d) {\r\n // aleph.currentLineData = d;\r\n // return numberWithCommas(\r\n // aleph.yMain\r\n // .invert(\r\n // Number(pos.y - aleph.margin.line[aleph.windowSize].top)\r\n // )\r\n // .toFixed(0)\r\n // );\r\n // });\r\n\r\n return \"translate(\" + mouse[0] + \",\" + pos.y + \")\";\r\n }\r\n });\r\n\r\n // call function to update coordinates and position of tooltip\r\n // D3 v4\r\n var x = d3.event.pageX;\r\n var y = d3.event.pageY;\r\n\r\n // function called to define and build tooltip structure and content\r\n cursorCoords(/* d, */ x, y);\r\n } // end if ....\r\n return;\r\n })\r\n .on(\"mouseout\", function () {\r\n // on mouse out hide line, circles and text\r\n d3.select(\".mouse-line\").style(\"opacity\", \"0\");\r\n d3.selectAll(\".mouse-per-line circle\").style(\"opacity\", \"0\");\r\n d3.selectAll(\".mouse-per-line text\").style(\"opacity\", \"0\");\r\n d3.selectAll(\".aleph-toolTip-Div\").classed(\"aleph-hide\", true);\r\n\r\n return;\r\n })\r\n .on(\"mousedown\", function () {\r\n d3.event.stopPropagation();\r\n d3.select(this).style(\"point-events\", \"none\");\r\n })\r\n .call(\r\n d3\r\n .drag()\r\n .on(\"start\", started)\r\n .on(\"drag\", function () {\r\n dragging();\r\n })\r\n .on(\"end\", function () {\r\n ended();\r\n return;\r\n })\r\n );\r\n } // end if ...\r\n\r\n transitionLineChart();\r\n\r\n d3.selectAll(\".aleph-mouseRectangle\").moveToFront();\r\n\r\n return;\r\n}", "function displayLineGraph_Population(populationData, countryName) {\n\n // Filter populationData to return only data for matching country name\n // i.e. Only returns data for the desired country for line graphs\n let countryPopulation = populationData.filter(country => country.Country == countryName);\n\n // Display population data to console for checking\n // Should be array of length 1\n // console.log(countryPopulation);\n\n // Extract years (keys) and populations (values) from data \n populationYears = Object.keys(countryPopulation[0]);\n populationAmounts = Object.values(countryPopulation[0]);\n // Converting 0 values to null\n if(populationAmounts.indexOf(0) !== -1) {\n for (let j=0; j < populationAmounts.length; j++) {\n populationAmounts.splice(populationAmounts.indexOf(0), 1, null);\n }\n }\n // Select the first 10 years of data for the actual population graph\n // Convert year string to number\n // Plot with both lines and markers for each data point\n let lineData_actual = {\n x: populationYears.slice(0,10).map(i => Number(i)),\n y: populationAmounts.slice(0,10),\n name: \"Actual\",\n type: \"scatter\",\n mode: \"lines+markers\"\n };\n \n // Select the last three years of data for the predicted population graph\n // Need to select the last data point of the actual population so graphs\n // are continuous\n // Make colour orange and with dotted line to visually differentiate between data sets\n // Plot with both lines and markers for each data point\n let lineData_predicted = {\n x: populationYears.slice(9,12).map(i => Number(i)),\n y: populationAmounts.slice(9,12),\n color: \"orange\",\n line: { dash: \"dot\", width: 4 },\n name: \"Predicted\",\n type: \"scatter\",\n mode: \"lines+markers\"\n };\n\n // Place both data sets together in array\n let lineData = [lineData_actual, lineData_predicted];\n\n // Set title for line graph and x and y axes\n let lineLayout = {\n title: countryName + \" - Population Actual and Predicted 1970 to 2050\",\n xaxis: { title: \"Years\" },\n yaxis: { title: \"Population (thousands(k)/ millions(M)/ billions(B))\" }\n };\n \n // Use plotly to display line graph at div ID \"line2\" with lineData and lineLayout\n Plotly.newPlot('line1', lineData, lineLayout);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new object that will be used for the chart totals
function objectCreation(chartItems) { chartItems = Array.from(chartItems).sort(); for (let item of chartItems) { chartTotals.push({ item: item, total: 0, color: getLegendColor(item) }); } }
[ "processTotals() {\n let income_statement = this.company.income_statement;\n let results = {\n totals:\n [\n {\n name: \"Revenue\", 'value': income_statement.total_revenue,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Total Revenue\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n {\n name: \"OpEx\", 'value': income_statement.total_operating_costs,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Operating Expenses\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n {\n name: \"EBIT\", 'value': income_statement.operating_income,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Operating Income\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n {\n name: \"Other\", 'value': income_statement.total_other_income_expense,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Other Income / Expense\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n {\n name: \"Pretax\", 'value': income_statement.pretax_income,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Pretax Income\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n {\n name: \"Taxes\", 'value': income_statement.total_tax_provision,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Income Tax Provision\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n ]\n };\n\n if (income_statement.net_income_attributable_noncontrolling_interest !== null) {\n\n results.totals.push(\n {\n name: \"MinInt\", 'value': income_statement.net_income_attributable_noncontrolling_interest,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Minority Interest\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }, line: \"\"\n },\n {\n name: \"NetIncome\", 'value': income_statement.net_income_post_minority_interest,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Net Income after Minority Interest\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }\n }\n )\n } else {\n results.totals.push(\n {\n name: \"NetIncome\", 'value': income_statement.net_income,\n bar: { start: 0, end: 0, range: 0 }, class: \"\", text: { x: 0, y: 0 },\n account: \"Net Income\",\n connections: { x1: 0, x2: 0, y1: 0, y2: 0 }\n }\n )\n }\n\n return results;\n\n }", "calculateTotal () {\n this.total = {};\n\n // reset the values\n Bill.TYPES.forEach(type => this.total[type] = 0);\n\n for (let type in this.total) {\n this.total[type] = this.data\n .filter(bill => bill.type === type)\n .reduce((c, n) => (c.amount ? c.amount : c) + n.amount, 0);\n }\n }", "_makeReport() {\n const report = {\n total: this.addedGoods.map(good => good.price * good.quantity).reduce((x, y) => x + y, 0),\n goods: []\n };\n report.goods = [...this.addedGoods];\n report.goods.forEach(good => { good.total = good.price * good.quantity });\n return report;\n }", "function renderTotals(arr){\n buildChart(arr);\n}", "chartDataForView() {\n const valueField = {\n [AMOUNT_TYPE.raw]: 'rawTotal',\n [AMOUNT_TYPE.cooked]: 'cookedTotal'\n }[this.activeAmountType];\n\n return this.chartData.map(record => ({\n category: record.category,\n total: Math.abs(record[valueField])\n }));\n }", "function initEarnings() {\n var earnings = {};\n\n earnings.tipTotal = 0;\n earnings.mealCount = 0;\n earnings.tipAverage = 0;\n\n return earnings;\n }", "function createTotalRow() {\n let totalRow = document.createElement('tr');\n let tdLabel = document.createElement('td');\n let tdTotal = document.createElement('td');\n\n tdLabel.textContent = \"Total\";\n tdLabel.style.textAlign=\"right\";\n totalRow.appendChild(tdLabel);\n tdTotal.textContent = 0;\n tdTotal.setAttribute(\"class\", \"currency\");\n totalRow.appendChild(tdTotal);\n totalRow.setAttribute(\"id\", \"total\");\n\n return totalRow;\n}", "function categoryTotal(name, amount) {\r\n var self = this;\r\n self.name = name;\r\n self.amount = amount;\r\n}", "function IndicadorTotal () {}", "function TotalBarChart(wrapper) {\n SimpleChart.call(this,wrapper);\n}", "function createCookieTotalsObj() {\n for (let i = 6; i < 21; i++) {\n cookieTotals[i] = 0;\n }\n}", "function createMonthlyTotals(arr){\n \n var orderedDates = orderResults(arr, \"processed_date\");\n var date1 = orderedDates[0][\"processed_date\"];\n var totalMonthlyDiff = monthDiff(orderedDates);\n\n var startDate= date1.split('/')[1] + '/' + date1.split('/')[2];\n\n // create an array of all months\n var initYear = Number(startDate.split('/')[1]);\n var initMonth = Number(startDate.split('/')[0] ) -1;\n var currMonth, currYear;\n var monthTotal = [];\n\n //create the object for every month in the range of the dataset\n for(var j=0; j<=totalMonthlyDiff; j++){ \n currMonth = ((initMonth+j) % 12 );\n if(!currYear) currYear=initYear;\n if(currMonth===0) currYear ++;\n monthTotal.push({\n \"month\" : (\"0\" + String(currMonth+1)).slice(-2) + '/' + currYear, \n \"total\" : 0,\n \"customers\" : []\n\n });\n } \n\n // fill the objects with \"total\" and individual customer purchases\n for(var k=0; k<monthTotal.length; k++){\n \n var monthTotalMonth = monthTotal[k][\"month\"]; \n \n for(var l=0; l<orderedDates.length; l++){ // for all the data\n // if date matches add value to price\n var orderedDatesMonth = monthAndYear(orderedDates[l][\"processed_date\"]);\n \n if(orderedDatesMonth === monthTotalMonth){\n // add value of order to total cost\n monthTotal[k][\"total\"] += orderedDates[l][\"total_cost\"];\n // add individual customer purchases for use with the tooltip\n monthTotal[k][\"customers\"].push({\n \"customer\": orderedDates[l]['customer'],\n \"order_cost\":orderedDates[l][\"total_cost\"]\n })\n orderedDates.splice(l,1); // delete entry so it won't be searched again (optimisation)\n l--; //decrease inc if found to counteract effect of splice removing an element\n }\n \n\n }\n \n }\n /* the final array of objects \n month, total, customers\n customer\n order_cost\n */\n\n return monthTotal;\n\n }// createMonthlyTotals()", "function getObjectWithTotalProperty(total) {}", "function createSummaryData()\n {\n summaryData = {\n \"info\" : klpData[\"report_info\"],\n \"school_count\" : klpData[\"school_count\"],\n \"teacher_count\" : klpData[\"teacher_count\"],\n \"gender\" : klpData[\"gender\"],\n \"student_total\": klpData[\"student_count\"],\n \"ptr\" : klpData[\"ptr\"],\n \"school_perc\" : klpData[\"school_perc\"]\n };\n\n summaryData['girl_perc'] = Math.round(( summaryData[\"gender\"][\"girls\"]/summaryData[\"student_total\"] )* 100);\n summaryData['boy_perc'] = 100 - summaryData['girl_perc'];\n renderSummary();\n }", "addSubTotals () { \n var depth = this.addSubtotalDepth\n\n // BUILD GROUPINGS / SORT VALUES\n var subTotals = []\n var latest_grouping = []\n for (var r = 0; r < this.data.length; r++) { \n var row = this.data[r]\n if (row.type !== 'total') {\n var grouping = []\n for (var g = 0; g < depth; g++) {\n var dim = this.dimensions[g].name\n grouping.push(row.data[dim].value)\n }\n if (grouping.join('|') !== latest_grouping.join('|')) {\n subTotals.push(grouping)\n latest_grouping = grouping\n }\n row.sort = [0, subTotals.length-1, r]\n }\n }\n\n // GENERATE DATA ROWS FOR SUBTOTALS\n for (var s = 0; s < subTotals.length; s++) {\n var subtotal = new Row('subtotal')\n\n for (var d = 0; d < this.columns.length; d++) {\n var column = this.columns[d]\n subtotal.data[column.id] = '' // set default\n\n if (this.columns[d].id === '$$$_index_$$$' || d === this.dimensions.length ) {\n var subtotal_label = subTotals[s].join(' | ')\n subtotal.data[this.columns[d]['id']] = {'value': subtotal_label, 'cell_style': ['total']}\n } \n\n if (column.type == 'measure') {\n var subtotal_value = 0\n if (column.pivoted) {\n var cellKey = [column.pivot_key, column.field_name].join('.') \n } else {\n var cellKey = column.id\n }\n for (var mr = 0; mr < this.data.length; mr++) {\n var data_row = this.data[mr]\n if (data_row.type == 'line_item' && data_row.sort[1] == s) {\n subtotal_value += data_row.data[cellKey].value\n } \n }\n var cellValue = {\n value: subtotal_value,\n rendered: formatter(subtotal_value), \n cell_style: ['total']\n }\n subtotal.data[cellKey] = cellValue\n }\n }\n subtotal.sort = [0, s, 9999]\n this.data.push(subtotal)\n }\n this.sortData()\n this.has_subtotals = true\n }", "function calcTotals() {\n var incomes = 0;\n var expenses = 0;\n var budget;\n // calculate total income\n data.allItems.inc.forEach(function(item) {\n incomes+= item.value;\n })\n //calculate total expenses\n data.allItems.exp.forEach(function(item) {\n expenses+= item.value;\n })\n //calculate total budget\n budget = incomes - expenses;\n // Put them in our data structure\n data.total.exp = expenses;\n data.total.inc = incomes;\n //Set Budget\n data.budget = budget;\n }", "function createChart() {\n\n var byStartDT = _.partial(bydate, \"DateExpected\"),\n data = tableData.sort(byStartDT),\n dates = _.map(_.pluck(data, \"DateExpected\"), parsedate),\n revenue = _.pluck(data, \"ValueRevenue\"),\n cost = _.pluck(data, \"ValueCost\"),\n balance = revenue.RollingBalance(cost, sBalance),\n chart = new Highcharts.Chart({ chart: { renderTo: \"chart\", zoomType: 'xy'},\n credits: { enabled: false },\n title: { text: \"Cashflow Management\" },\n xAxis: { type: \"datetime\" },\n yAxis: [\n { //Primary Axis\n min: 0,\n title: { text: \"Amount\" }\n },\n { //Secondary Axis\n min: 0,\n title: { text: \"Balance\" },\n opposite: true\n }\n\n ],\n series: [{\n type: \"column\",\n name: \"Revenue\",\n color: \"#A1CB68\",\n pointWidth: 10,\n data: _.zip(dates, revenue)\n }, {\n type: \"column\",\n name: \"Cost\",\n color: \"#D34C4A\",\n pointWidth: 10,\n data: _.zip(dates, cost)\n }, {\n type: \"areaspline\",\n name: \"Balance\",\n color: \"#0077C4\",\n fillOpacity: 0.2,\n dashStyle: 'shortdot',\n yAxis: 1,\n data: _.zip(dates, balance)\n }],\n }); // End of CHART variables\n }", "function Total(){\n\t\tvar totalCost = 0;\n\t\tthis.addTotal = function(total){\n\t\t\ttotalCost += parseFloat(total);\n\t\t};\n\t\tthis.getTotal = function(){\n\t\t\treturn totalCost.toFixed(2);\n\t\t};\n\t}", "function agregarTotal(){\n var total = 0;\n for(let i=0 ; i<factura.productos.length;i++){\n total = total + factura.productos[i].pstotal;\n }\n var trTotal = document.createElement(\"tr\");\n trTotal.innerHTML=`<td colspan='4'>TOTAL</td> <td>${total}</td>`;\n xtabla.appendChild(trTotal);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles request to get the target lock state for homekit
getTargetLockState(callback) { this.getLockCurrentState(callback); }
[ "function handleLock(type) {\n\t\t\t//onLockRecived make the locking action according to the status of the object\n\t\t\treturn getLockingObject(type, onLockRecieved)\n\t\t}", "function jsDAV_Locks_LockInfo() {}", "getLockCurrentState(callback) {\n callback(null, this.getDeviceCurrentStateAsHK());\n }", "updatelockStates(accessory) {\n var self = this;\n\n var lockService = accessory.getService(self.Service.LockMechanism);\n // var doorService = accessory.getService(self.Service.ContactSensor);\n\n lockService.getCharacteristic(self.Characteristic.LockTargetState)\n .updateValue(accessory.context.targetState || accessory.context.currentState);\n lockService.getCharacteristic(self.Characteristic.LockCurrentState)\n .updateValue(accessory.context.currentState);\n // doorService.getCharacteristic(self.Characteristic.ContactSensorState)\n // .updateValue(accessory.context.doorState);\n \n var batteryService = accessory.getService(self.Service.BatteryService);\n\n if(batteryService) {\n batteryService\n .setCharacteristic(self.Characteristic.BatteryLevel, accessory.context.batt);\n \n batteryService\n .setCharacteristic(self.Characteristic.StatusLowBattery, accessory.context.low);\n } \n }", "function progressLockState(lockRequest, now){\n\n // WaitUnil is used to skip ticks. This is part of back-off.\n if( lockRequest.waitUntil && now < lockRequest.waitUntil ) {\n // do nothing\n }\n // If this is a new request, or we set the outerKey without having the innerKey.\n else if(lockRequest.state === \"requested\" || lockRequest.state === \"set-outer\" ) {\n\n // Attempt to own outerKey.\n setItem(lockRequest.outerKey, lockRequest.id);\n\n // Check if we can (or already do) own the innerKey.\n let innerOwner = getItem(lockRequest.innerKey);\n if( innerOwner && innerOwner !== lockRequest.id) {\n // If someone else owns the innerKey, we will try again later.\n innerKeyAlreadyOwned(lockRequest, now, innerOwner);\n } else {\n // Set the innerKey, we will see in a moment if our outerKey holds up\n setItem(lockRequest.innerKey, lockRequest.id);\n lockRequest.state = \"set-inner\";\n\n debug(lockRequest.id, \"set innerKey. InnerKey was\", innerOwner );\n }\n }\n // If we have set the innerKey.\n else if( lockRequest.state === \"set-inner\" ) {\n\n // Check if we still own the outerKey\n let outerOwner = getItem(lockRequest.outerKey);\n if (outerOwner !== lockRequest.id) {\n // We lost ownership, try everything again in a bit.\n outerKeyAlreadyOwned(lockRequest, now, outerOwner);\n } else {\n // Grant the lock.\n const taskPromise = grantLockRequest(lockRequest, now),\n releaseFulfilledTask = makeReleaseFulfilledTask(lockRequest),\n releaseRejectedTask = makeReleaseRejectedTask(lockRequest);\n\n // When the callback task is complete, release the lock for the\n // type of task.\n taskPromise.then( releaseFulfilledTask, releaseRejectedTask );\n }\n }\n // If we have granted a lock.\n else if( lockRequest.state === \"locked\" ) {\n // keep setting the innerKey so it doesn't expire.\n setItem(lockRequest.innerKey, lockRequest.id);\n }\n // If we are in the completed state\n else if( COMPLETED_STATES[lockRequest.state] === true ) {\n // do nothing, `progressKeyLocksStates` will discard this lockRequest\n }\n // UH OH!!!\n else {\n debug(lockRequest.id, \"unexpected-state\", lockRequest.state);\n lockRequest.reject(new Error(`Unexpected state ${lockRequest.state}`));\n lockRequest.state = \"unexpected-state\";\n }\n // Return the current state of the lockRequest so `progressKeyLocksStates`\n // can use it to do the right thing.\n return lockRequest.state;\n }", "function lockCommand(sn, state) {\n $.ajax({\n method: 'POST',\n url: '/lock/' + sn,\n data: '{\"lock-command\":\"' + state + '\"}',\n headers: {\n 'Content-Type': 'application/json'\n },\n success: function() {\n\t\t\t\tgetLocks();\n },\n error: function(xhr, textStatus, errorThrown) {\n alert(errorThrown);\n }\n });\n }", "function getWalletLockStatus() {\n getJSON('GET', '/wallet', null, function(code, json) {\n if (json === null) {\n updateWalletLockStatus(false);\n } else {\n let wallet = JSON.parse(json);\n if (wallet.unlocked)\n updateWalletLockStatus(true);\n else\n updateWalletLockStatus(false);\n }\n });\n}", "function getLocks() {\n\t\tvar params = {\n\t\t\tmethod: 'GET',\n\t\t\turl: '/lock/',\n\t\t\tsuccess: function(data) {\n\t\t\t\tallLocks = data;\t\n\t\t\t\trender(allLocks);\n\t\t\t},\n\t\t\terror: function(xhr, textStatus, errorThrown) {\n\t\t\t\talert(xhr.responseText + ' (' + errorThrown + ')')\n\t\t\t\talert(xhr.responseText)\n\t\t\t}\n\t\t};\n\t\t// we're signed in.\n\t\tif (muranoToken) {\n\t\t\t// include the token as a header\n\t\t\t// note that this is not strictly necessary\n\t\t\t// since the API will have put it in the cookie, \n\t\t\t// but a native mobile app would have to do this.\n\t\t\tparams.headers = {\n\t\t\t\t'token': muranoToken\n\t\t\t};\n\t\t\t// call the user-specific lock listing.\n\t\t\tparams.url = '/user/lock/';\n\t\t}\n\t\t$.ajax(params);\n\t}", "getState() {\n return __awaiter(this, void 0, void 0, function* () {\n const dhcsr = yield this.memory.read32(3758157296 /* DHCSR */);\n if (dhcsr & 33554432 /* S_RESET_ST */) {\n const newDHCSR = yield this.memory.read32(3758157296 /* DHCSR */);\n if (newDHCSR & 33554432 /* S_RESET_ST */ && !(newDHCSR & 16777216 /* S_RETIRE_ST */)) {\n return 0 /* TARGET_RESET */;\n }\n }\n if (dhcsr & 524288 /* S_LOCKUP */) {\n return 1 /* TARGET_LOCKUP */;\n }\n else if (dhcsr & 262144 /* S_SLEEP */) {\n return 2 /* TARGET_SLEEPING */;\n }\n else if (dhcsr & 131072 /* S_HALT */) {\n return 3 /* TARGET_HALTED */;\n }\n else {\n return 4 /* TARGET_RUNNING */;\n }\n });\n }", "constructor(status){\n this.lock_state = status;\n }", "open() {\n if (this.lock_status_id === 4) {\n return Promise.resolve();\n }\n return this.send_command(2).then(() => {\n return this.await_event('status:unlocked');\n });\n }", "async handleKeyScan(e) {\n e.preventDefault();\n const request = {\n id: this.state.scannedKey\n };\n await fetchKeyStatus(request, \"POST\", res => {\n if (res.key.keyStatus === \"PENDING\") {\n this.setState(state => {\n return {\n keyPending: true,\n keyCheckedIn: true,\n keyRecord: res.key,\n disableForm: true\n };\n });\n } else if (res.key.keyStatus === \"IN\") {\n this.setState(state => {\n return {\n keyPending: false,\n keyCheckedIn: true,\n keyRecord: res.key,\n disableForm: true\n };\n });\n } else if (res.key.keyStatus === \"OUT\" && res.trans) {\n this.setState(state => {\n return {\n keyPending: false,\n keyCheckedIn: false,\n keyRecord: res.key,\n keyTransaction: res.trans,\n disableForm: true\n };\n });\n }\n });\n }", "getDaemonLockState() {\n return __awaiter(this, void 0, void 0, function* () {\n const [err] = yield await_to_js_1.default(this.rpc.lock());\n if (err !== null && err.message === error_1.EJErrorCode.DAEMON_RPC_LOCK_ATTEMPT_ON_UNENCRYPTED_WALLET) {\n return types_1.WalletLockState.UNLOCKED;\n }\n return types_1.WalletLockState.LOCKED;\n });\n }", "get LOCK_OWNED() { return 2; }", "setTargetLockState(lockState, callback) {\n this.logger(`Sending command to set lock state to: ${lockState}`);\n if (lockState !== this.getDeviceCurrentStateAsHK()) {\n const targetLockValue = lockState === 0 ? false : true;\n this.device.sendLockCommand(targetLockValue, callback);\n }\n else {\n callback();\n }\n }", "function requestLockDoor () {\n const requestData = JSON.stringify(\n {\n performative: 'achieve',\n sender: 'paranoid',\n receiver: 'porter',\n content: 'locked(door)'\n }\n )\n jrClient.send('POST', '/agents/porter/inbox', _ => {}, requestData)\n}", "lock() {\n const { actions } = this.props;\n\n actions.clearKeys()\n .then((res) => {\n const lockState = Object.assign({}, this.defaultState);\n lockState.coins = this.state.coins;\n\n this.toggleAutoRefresh(true);\n setTimeout(() => {\n this.toggleMenu();\n }, 10);\n setTimeout(() => {\n this.setState(lockState);\n }, 20);\n });\n }", "getDoorLockState()\n {\n return this._doorLockState;\n }", "function setLockedStatus() {\n var lockedObj = $(\"locked\");\n var unlockedObj = $(\"unlocked\");\n var lockedByObj = $(\"lockedBy\");\n var lockedDateObj = $(\"lockedDate\");\n // var lockedTimeObj = $(\"lockedTime\");\n\n\t// call WFR to get lock info from server & set view fields\n try {\n var parameters = {\n tableName:'afm_docs',\n fieldNames:toJSON(['afm_docs.table_name','afm_docs.field_name','afm_docs.pkey_value','afm_docs.locked','afm_docs.locked_by','afm_docs.lock_date'])\n };\n var result = Workflow.call('AbCommonResources-getDataRecords', parameters);\n\n var rows = result.data.records;\n for (var i=0,row; row = rows[i]; i++) {\n if (row['afm_docs.table_name'] == docmanager_tableName && row['afm_docs.field_name'] == docmanager_fieldName && row['afm_docs.pkey_value'] == docmanager_pkey_value) {\n lockedObj.value = (row['afm_docs.locked'] == 'No') ? '0' : '1';\n lockedByObj.value = row['afm_docs.locked_by'];\n lockedDateObj.value = row['afm_docs.lock_date'];\n// lockedTimeObj.value = row['afm_docs.lock_time'];\n docmanager_lock_status = lockedObj.value;\n break;\n }\n }\n } catch (e) {\n Workflow.handleError(e);\n }\n\n\t// set DOM displayed values that depend on lock status\n\tif (docmanager_lock_status > 0) {\n\t\tlockedObj.checked = 1;\n\t\tunlockedObj.checked = 0;\n\t\t// currently locked by\n\t\tlockOwnerObj = $(\"lockPanel_afm_docs.locked_by\");\n\t\tif (lockOwnerObj.value != '' && View.user.name != lockOwnerObj.value ) {\n\t\t Ext.get(\"existingLockMessageArea\").show();\n\t\t}\n\t} else {\n\t\tlockedObj.checked = 0;\n\t\tunlockedObj.checked = 1;\t\t\n\t}\n\n\tvar labelElem = $(\"lockedByLabel\");\n\tvar translatedLabel = getMessage(\"message_lockedby_label\");\n\tlabelElem.innerHTML = translatedLabel;\n\n\tlabelElem = $(\"lockedOnLabel\");\n\ttranslatedLabel = getMessage(\"message_lockedon_label\");\n\tlabelElem.innerHTML = translatedLabel;\n\n\tlabelElem = $(\"lockedDateLabel\");\n\ttranslatedLabel = getMessage(\"message_lockeddate_label\");\n\tlabelElem.innerHTML = translatedLabel;\n\n\tlabelElem = $(\"lockedLabel\");\n\ttranslatedLabel = getMessage(\"message_locked_label\");\n\tlabelElem.innerHTML = translatedLabel;\n\n\tlabelElem = $(\"unlockedLabel\");\n\ttranslatedLabel = getMessage(\"message_unlocked_label\");\n\tlabelElem.innerHTML = translatedLabel;\n\n\tlabelElem = $(\"breakLockLabel\");\n\ttranslatedLabel = getMessage(\"message_breaklock_label\");\n\tlabelElem.innerHTML = translatedLabel;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to create a timestamp for 9am today
function createTimeStamp8pm(){ let today = new Date(); var ms = today.getTime(); var msPerDay = 86400 * 1000; var msto8pm = 72000000; let eightPMToday = ms - (ms % msPerDay) + msto8pm; return eightPMToday; }
[ "function createTimeStamp9am(){\n let today = new Date();\n \n var ms = today.getTime();\n var msPerDay = 86400 * 1000;\n var msto9am = 32400000;\n let nineAMToday = ms - (ms % msPerDay) + msto9am;\n return nineAMToday; \n }", "function createTimestamp(){\n var min = new Date().getMinutes();\n var minutes;\n if(min < 10){\n minutes = \"0\" + min;\n }else {\n minutes = min;\n }\n return timestamp = new Date().getHours() + \":\" + minutes;\n }", "function makeTimestamp() {\n const now = new Date();\n const date = `${now.getFullYear()}-${padDate(now.getMonth() + 1)}-${padDate(now.getDate())}`;\n const time = `${padDate((now.getHours() + 1) % 12)}-${padDate(now.getMinutes() + 1)}-${padDate(now.getSeconds() + 1)}`;\n const meridiem = now.getHours() >= 12 ? 'PM' : 'AM';\n return `${date}--at--${time}--${meridiem}`;\n}", "function create_timestamp() {\n const now = new Date();\n\n const hours = now.getHours().toString().padStart(2, '0');\n const minutes = now.getMinutes().toString().padStart(2, '0');\n const seconds = now.getSeconds().toString().padStart(2, '0');\n const millis = now.getMilliseconds().toString().padStart(3, '0');\n\n return `${hours}:${minutes}:${seconds}.${millis}`;\n }", "function timestampGenerator() {\n const now = new Date()\n const timestamp =\n now.getUTCFullYear() + '-' +\n String(now.getUTCMonth() + 1).padStart(2, '0') + '-' +\n String(now.getUTCDate()).padStart(2, '0') + ' ' +\n String(now.getUTCHours()).padStart(2, '0') + ':' +\n String(now.getUTCMinutes()).padStart(2, '0') + ':' +\n String(now.getUTCSeconds()).padStart(2, '0')\n return timestamp\n}", "function generateTimestamp() {\n\tvar date = new Date();\n\tvar month = prefixZero(date.getMonth());\n\tvar dateNum = prefixZero(date.getDate());\n\tvar hours = prefixZero(date.getHours());\n\tvar minutes = prefixZero(date.getMinutes());\n\tvar seconds = prefixZero(date.getSeconds());\n\n\treturn date.getYear() + \"\" + month + \"\" + dateNum + \"\" + hours + \"\" + minutes + \"\" + seconds;\n}", "function makeTimestamp() {\n var timestamp = (new Date()).toLocaleString();\n return timestamp;\n}", "function dateForToday() {\n return new Date().toMidnight();\n}", "function dateNowMidnight() {\n return DateTime.fromObject({ hour: 0 })\n}", "static generateTimestamp() {\n return Date.now()\n }", "generateTimeStamp() {\n var m = new Date();\n var dateString =\n m.getUTCFullYear() +\n \"/\" +\n (\"0\" + (m.getUTCMonth() + 1)).slice(-2) +\n \"/\" +\n (\"0\" + m.getUTCDate()).slice(-2) +\n \" \" +\n (\"0\" + m.getUTCHours()).slice(-2) +\n \":\" +\n (\"0\" + m.getUTCMinutes()).slice(-2) +\n \":\" +\n (\"0\" + m.getUTCSeconds()).slice(-2);\n return dateString;\n }", "function setDefaultTimestamp(){\n let date = document.getElementById(\"event_date\");\n let time = document.getElementById(\"event_time\");\n let oneDay = 24 * 60 * 60 * 1000;\n let tomorrow = new Date(new Date().getTime() + oneDay);\n date.value = tomorrow.toISOString().split(\"T\")[0];\n time.value = \"10:00\";\n}", "function shiftTime(timestamp) {\n if(timestamp.length > 0 ) {\n timestamp = moment(timestamp).add(5,'hours').format('MM/DD/YYYY hh:mm:ss A');\n }\n\n return timestamp;\n}", "function startingHour(wd) { //weekday\n if (wd < 5) {\n currentDate.setHours(9);\n } else if (wd == 5) {\n currentDate.setHours(10);\n }\n return currentDate.getHours();\n}", "function current_time() {\n var hh = today.getHours()\n var mm = today.getMinutes()\n\n if (mm < 10) {\n mm = \"0\" + mm\n }\n\n if (hh >= 12) {\n hh = hh % 12\n return (hh + \":\" + mm + \"pm\")\n } else {\n return (hh + \":\" + mm + \"am\")\n }\n}", "function createTime(time) {\n var date = new Date();\n var hour = parseInt(time.slice(0, 2));\n var minute = parseInt(time.slice(2, 4));\n date.setHours(hour, minute, 0, 0);\n return date;\n}", "function CreateTimestamp()\n{\nreturn \"timestamp=\" + new Date().getTime().toString();\n}", "function getRandomTimestamp() {\n const day0 = 1546819200;\n const duration_day = 86400;\n const start_day = 28800;\n const duration_hour = 3600;\n\n const r_week = getRandomNumber(0, new Date().getWeek());\n const r_day = getRandomNumber(0, 4);\n const r_hour = getRandomNumber(0, 9);\n const r_minute = getRandomNumber(0, 3);\n\n return (\n day0\n + r_week * 7 * duration_day\n + r_day * duration_day\n + start_day\n + duration_hour * r_hour\n + r_minute * 15 * 60\n );\n}", "function genTS() {\n return Math.floor(Date.now())\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If for some reason a stream does not have the same number of chunks as the mediaBuffer expects, disable that stream.
function MediaStreamFilter$incorrectChunks(playback) { if (!config.incorrectChunkCountEnabled) { // return nothing, if filter is not enabled return; } var _log = new log.CategoryLog('IncorrectChunks Filter'), invalidStreamMap = {}; function logInvalidStream (stream) { if (!invalidStreamMap[stream.downloadableId]) { invalidStreamMap[stream.downloadableId] = stream; _log.error("Stream disabled because chunk count does not match media buffer", {'downloadableId': stream.downloadableId}); } } /** * @param {CadmiumMediaStream} stream */ function shouldDisallowStream_incorrectChunksFilter(stream) { if (!stream.header) { return false } else { if (stream.header.chunkInfos.length !== playback.mediaBuffer.videoChunks.length) { logInvalidStream(stream); return true; } else { return false; } } } return { filterId: 'ic', shouldDisallowStream: shouldDisallowStream_incorrectChunksFilter }; }
[ "startWithoutRemovingChunks() {\n // Do nothing on stop, just restart the stream\n this.mediaRecorder.onstop = null\n this.mediaRecorder.stop();\n console.log(\"Stop with a null function\")\n\n const stream = this.createNewStream(); \n\n\n // intiates the recorder\n this.mediaRecorder = new MediaRecorder(stream, {mimeType: this.mimeType});\n console.log(this.mediaRecorder)\n\n // below code is used to save the audio, taken from https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder\n this.mediaRecorder.onstop = function(e) {\n this._onStopRecorderCallBack(e);\n }.bind(this);\n \n this.mediaRecorder.ondataavailable = function(e) {\n console.log(this.chunks)\n this.chunks.push(e.data);\n }.bind(this)\n\n this.mediaRecorder.start();\n console.log(\"Starting recording...\");\n console.log(this.mediaRecorder.state);\n\n rc.event(RoomClient.EVENTS.startRecord);\n }", "function enableOutgoingStream() {\n localMediaStream.getTracks().forEach((track) => {\n track.enabled = true;\n });\n}", "checkEos() {\n let sb = this.sourceBuffer,\n mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for (let type in sb) {\n let sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n\n if (sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');\n // Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch (e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }", "unlockAudio() {\n if (!this.unlocked) {\n var buffer = this.audioContext.createBuffer(1, 1, 22050);\n var node = this.audioContext.createBufferSource();\n node.buffer = buffer;\n node.start(0);\n this.unlocked = true;\n }\n }", "checkEos () {\n let sb = this.sourceBuffer, mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for (let type in sb) {\n let sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n\n if (sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');\n // Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch (e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }", "function enableOutgoingStream() {\n\tlocalMediaStream.getTracks().forEach(track => {\n\t\ttrack.enabled = true;\n\t})\n}", "function createEmptyStream() {\n if (typeof MediaStream !== 'undefined') {\n return new MediaStream();\n }\n\n throw new Error('cannot create a clean mediaStream');\n}", "unmute() {\n if (!this.mediaStream) return;\n this.mediaStream\n .getAudioTracks()\n .forEach((track) => { track.enabled = true; });\n }", "function onStreamBufferingCompleted(e) {\n //var nextStream = getNextStream();\n var isLast = e.streamInfo.isLast;\n\n if (mediaSource && isLast) {\n mediaSourceController.signalEndOfStream(mediaSource);\n }\n //if (!nextStream) return;\n //nextStream.activate(mediaSource);\n }", "function _dropMedia(chunk, reason) {\n var media = chunk.media;\n chunk.media = null;\n chunk.mediaRequest = undefined;\n chunk.setDownloading(MediaBuffer$CHUNK_WAITING);\n media && DEBUG && _log.debug('Dropped chunk', chunk, { 'Reason': reason }, _getLogFields());\n return media ? media.length : 0;\n }", "function _dropBuffer() {\n playback.mediaBuffer.discardVideoMediaBasedOnFilter();\n }", "function MdxCameraChunk(stream, size) {\r\n\tlog(\"CameraChunk...\");\r\n\t\r\n\tstream.skip(size);\r\n\t\r\n\tlog(\"Oops, not impelemented yet\");\r\n}", "function check_skip_buffer(){\n\t\t\tif(options.skip_buffer === true){\n\t\t\t\tlog.trace('skip_buffer true')\n\t\t\t\tif(typeof msg !== 'string' && Array.isArray(msg)) {\n\t\t\t\t\tvar str = msg.join(options.join + '\\u000f');\n\t\t\t\t} else {\n\t\t\t\t\tvar str = msg === null || msg === undefined ? '' : msg;\n\t\t\t\t}\n\n\t\t\t\tstr = options.skip_verify === true ? str : x.verify_string(str, options.url);\n\t\t\t\tsay_str(str);\n\t\t\t} else {\n\t\t\t\tlog.trace('skip_buffer false')\n\t\t\t\tadd_to_buffer(msg, function(data, opt){\n\t\t\t\t\tsay_str(data);\n\t\t\t\t});\n\t\t\t}\n\t\t}", "disableStream(stream) {\n const funcName = 'Config.disableStream()';\n checkArgumentLength(1, 1, arguments.length, funcName);\n const s = checkArgumentType(arguments, constants.stream, 0, funcName);\n this.cxxConfig.disableStream(s);\n }", "function onChunkProcess() {\n numChunksProcessed++\n\n // Play when init segment and first audio segment has been added.\n // This should of course have a smarter behaviour.\n if (numChunksProcessed === 2) {\n audio.play()\n }\n\n // Tell the MediaSource we have appended all buffers we wanted.\n if (numChunksProcessed === audioUrls.length) {\n mediaSource.endOfStream()\n }\n}", "prepareRecorder() {\r\n if (!this.$_stream) {\r\n return\r\n }\r\n\r\n this.$_mediaRecorder = new MediaRecorder(this.$_stream, {\r\n mimeType: this.mimeType\r\n })\r\n\r\n this.$_mediaRecorder.ignoreMutedMedia = true\r\n\r\n this.$_mediaRecorder.addEventListener('start', () => {\r\n this.isRecording = true\r\n this.isPaused = false\r\n this.$emit('start')\r\n })\r\n\r\n this.$_mediaRecorder.addEventListener('resume', () => {\r\n this.isRecording = true\r\n this.isPaused = false\r\n this.$emit('resume')\r\n })\r\n\r\n this.$_mediaRecorder.addEventListener('pause', () => {\r\n this.isPaused = true\r\n this.$emit('pause')\r\n })\r\n\r\n // Collect the available data into chunks\r\n this.$_mediaRecorder.addEventListener('dataavailable', (e) => {\r\n if (e.data && e.data.size > 0) {\r\n this.chunks.push(e.data)\r\n }\r\n }, true)\r\n\r\n // On recording stop get the data and emit the result\r\n // than clear all the recording chunks\r\n this.$_mediaRecorder.addEventListener('stop', () => {\r\n this.$emit('stop')\r\n // type: \"video/x-matroska;codecs=avc1,opus\"\r\n const blobData = new Blob(this.chunks, {type: \"video/mp4\"})\r\n if (blobData.size > 0) {\r\n this.$emit('result', blobData)\r\n }\r\n this.chunks = []\r\n this.isPaused = false\r\n this.isRecording = false\r\n }, true)\r\n }", "function _getNextIdleChunkThatNeedsMedia(chunks) {\n for (var chunk = chunks.getForTime(playback.mediaTime.value); chunk && (chunk.media || chunk.downloading !== MediaBuffer$CHUNK_WAITING); chunk = chunk.next) { };\n return chunk;\n }", "disableStreams() {\n\n Utils.logDebug(`Disabling all streams.`);\n\n for (let bridgeid in this.hue.instances) {\n\n if (this._isStreaming[bridgeid] === undefined ||\n this._isStreaming[bridgeid][\"state\"] === StreamState.STOPPED) {\n\n continue;\n }\n\n this._isStreaming[bridgeid][\"state\"] = StreamState.STOPPING;\n\n if (this._isStreaming[bridgeid][\"entertainment\"] !== undefined) {\n\n this._isStreaming[bridgeid][\"entertainment\"].closeBridge();\n if (this._isStreaming[bridgeid][\"groupid\"] !== undefined) {\n this.hue.instances[bridgeid].disableStream(\n this._isStreaming[bridgeid][\"groupid\"]\n );\n }\n\n delete(this._isStreaming[bridgeid][\"entertainment\"]);\n }\n\n this._isStreaming[bridgeid][\"state\"] = StreamState.STOPPED;\n }\n }", "deactivateStreaming() {\n\t\tif (this.socket !== null) {\n\t\t\tthis.socket.disconnect();\n\t\t\tthis.socket = null;\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the list of cells at the given column index
function getCellByCellIndex( opts: Options, // The table table: Block, cellIndex: number ): List<Block> { return table.nodes.map(row => row.nodes.get(cellIndex)); }
[ "function getCellsAtColumn(opts,\n// The table\ntable, columnIndex) {\n return table.nodes.map(function (row) {\n return row.nodes.get(columnIndex);\n });\n}", "function getCellsAtColumn(opts,\n// The table\ntable, columnIndex) {\n return table.nodes.map(function (row) {\n return row.nodes.get(columnIndex);\n });\n}", "getCell(index) {\n return this.cells[index];\n }", "getCellAt(index) {\n return this._cells[index];\n }", "function getCol(matrix, index) {\r\n\tlet col = []\r\n\tfor (let row of matrix) {\r\n\t\tcol.push(row[index])\r\n\t}\r\n\treturn col\r\n}", "function column(j) {\n let res = [];\n for(let i = 0; i < 9; i++) {\n res.push(grid[i][j]);\n }\n return res;\n}", "function getColumnList(colIndex) {\n return $(\"button\").filter(i => i % COLS === colIndex);\n}", "function getCol(matrix, index) {\r\n let col = []\r\n for (let row of matrix) {\r\n col.push(row[index])\r\n }\r\n return col\r\n}", "getColumn(colXPos) {\n const resultCols = []\n this.gameMovingObjects.forEach(cell => {\n if (cell.position.x === colXPos) {\n resultCols.push(cell)\n }\n })\n return resultCols\n }", "function getRelatedColCells(sudokuGrid, selectedCellRow, selectedCellCol) {\n let colCells = [];\n for (let i = 0; i < 9; i++) {\n colCells.push(sudokuGrid[i][selectedCellCol]);\n }\n return colCells;\n}", "function get_col(index) {\n return index % COLS;\n}", "getColumnIndexes(index, gridSize) {\n const columnData = [index]\n // Generating after Data\n for (let i=index+gridSize; i < gridSize*gridSize; i+=gridSize) {\n columnData.push(i)\n }\n // Generating before Data\n for (let i=index-gridSize; i > -1; i-=gridSize) {\n columnData.push(i)\n }\n return columnData\n }", "getCellByIndex(index) {\n return this.data[index];\n }", "function cells(row) /* (row : row) -> list<cell> */ {\n return row.cells;\n}", "function returnColumn(cell){\n return cell%9;\n}", "col_view(col_idx) {\n const that = this;\n return new Proxy(this, {\n get: function(target, prop) {\n const idx = parseInt(prop);\n if (!isNaN(idx)) {\n // The column idx is fixed by col_idx. Prop becomes the row_idx. Now need to\n // return the item list.\n return that._grid[prop][col_idx];\n }\n return undefined;\n }\n });\n }", "getCol(n) {\n let c = [];\n for (let i = 0; i < this.rows; i++) {\n c.push(this.data[i][n]);\n }\n return c;\n }", "function getCellIndexes(address) {\n return [parseInt(address.match(/\\d+/)[0], 10) - 1, getColIndex(address.match(/[A-Z]+/i)[0])];\n}", "boardCell (index) {\n return $$('td')[index];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parseResponseToField This function takes all the data in data and tries to find an HTML container in fieldContainer to write this data to the screen.
function parseResponseToFields(data, fieldContainer, wrapAround) { wrapAround = wrapAround || {}; if (data == null) return; fieldContainer = $(fieldContainer); $.each(data, function(fieldName, fieldValue) { var cell = fieldContainer.find("." + fieldName).empty(); if (!fieldValue) return; if (fieldValue.constructor != Array) fieldValue = [fieldValue]; $.each(fieldValue, function(index, value) { if (wrapAround[fieldName]) //a WrapAround was provided! We expect HTML { cell.append($(wrapAround[fieldName]).text(value)); } else //Simple text only { cell.text(value); } }) }) }
[ "function handleResponse(data) {\n var parsedResponse = JSON.parse(data.currentTarget.response);\n var parsedItems = Object.values(parsedResponse.items);\n var itemTimeslotArray = buildTimeslotArray(parsedItems);\n // pageConstructor(parsedItems, itemTimeslotArray);\n htmlConstructor(parsedItems, itemTimeslotArray);\n}", "function collectDataFromFields() {\n\n //2a.SUBMTI\n $(document).on(\"click\", \".cq-dialog-submit\", function(event) {\n\n var $form = $(\".coral-structuredMultifield\").parents(\".cq-dialog\");\n var $multiFieldNode = $form.find(\"[\" + COMPOSITE_REQUIRED + \"]\");\n\n $multiFieldNode.each(function(counter, fieldSet){\n\n var $node = $(this);\n\n var $parentName = $node.attr(MULTIFIELD_NAME);\n\n if(~$parentName.indexOf(\"./\")){$parentName = $parentName.substring(1);}\n\n\n //DELETE old nodes to POST new ones\n deleteRootNode($parentName);\n\n\n var $structuredField = $node.find(\"[class='coral-Form-fieldset']\");\n\n\n //NEW LIST OF ITEMS (ROOT NODE)\n $structuredField.each(function(j, field){\n var $structuredFields = $(field).find(\"[class='coral-Form-fieldwrapper']\");\n $structuredFields.each(function(i,fields){\n\t\t\t\t\t\tfillValueHelper($form, $parentName +\"/\"+ $structuredField.data(\"name\"), $(fields).find(\"[name]\"), j);\n });\n //fillValueHelper($form, $parentName + $structuredField.data(\"name\"), $(field).find(\"[name]\"), j);\n });\n });\n deleteExtraFieldsTag($form);\n\n });\n\n function fillValueHelper($form, fieldSetName, $field, $counter) {\n\n var name = $field.attr(\"name\");\n var $form = $(\".cq-dialog\");\n var $multiFieldNode = $form.find(\"[\" + COMPOSITE_REQUIRED + \"]\");\n if (!name) { return; }\n $('<input />')\n .attr('type', 'hidden')\n .attr('name', \".\" + fieldSetName + \"-\" + ++$counter + \"/\" + name)\n .attr('value', $field.val())\n .appendTo($form);\n\n }\n }", "function extractContent(response){\r\n\t\r\n\t//error_message\r\n\tupdateMessageBox(\"\");\r\n\t\r\n\tvar evalArr = response.match(/<eval_script[\\s\\S]*?<\\/eval_script>/g);\r\n\tresponse\t= response.replace(evalArr, '')\r\n\tvar errorArr = response.match(/<error_communication[\\s\\S]*?<\\/error_communication>/g);\r\n\t\r\n\tfor (errorArr_i in errorArr){\r\n\t\t\r\n\t\tappendMessageBox(errorArr[errorArr_i]);\r\n\t\t\r\n\t}\r\n\t\r\n\t//modify_tag_content\r\n\tvar contentArr = response.match(/<contentStart__[\\s\\S]*?<\\/contentEnd>/g);\r\n\t\r\n\tfor (content_i in contentArr){\r\n\t\t\r\n\t\tvar opening_tag = contentArr[content_i].match(/<contentStart__[\\s\\S]*?>/g)[0];\r\n\t\tvar type \t= opening_tag.split(\"__\")[1];\r\n\t\tvar id \t\t= opening_tag.split(type+\"__\")[1].split(\">\")[0]\r\n\t\tvar new_value\t= contentArr[content_i].replace(opening_tag,\"\").replace(\"</contentEnd>\",\"\")\r\n\t\t\r\n\t\tvar element \t= document.getElementById(id)\r\n\t\t\r\n\t\tvar attach = true\r\n\t\t\r\n\t\tif (element != undefined){\r\n\t\t\t\r\n\t\t\tif (type == \"update\"){\r\n\t\t\t\t\r\n\t\t\t\tupdateInnerHTML(id, new_value)\r\n\t\t\t\t\r\n\t\t\t\tif (id == \"student_page_view_container\"){\r\n\t\t\t\t\t\r\n\t\t\t\t\tattach = false\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tid_arr = id.split(\"field_id\")\r\n\t\t\t\t\r\n\t\t\t\tif (id.indexOf(\"field_id\") != -1 && id.indexOf(\"field_id____\") == -1 && id_arr[1].length != 0){\r\n\t\t\t\t\t\r\n\t\t\t\t\tsend(id)\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}else if (type == \"append\"){\r\n\t\t\t\t\r\n\t\t\t\tprependInnerHTML(id, new_value)\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}else{\r\n\t\t\t\r\n\t\t\tappendMessageBox('WARNING:' + id + ' undefined')\r\n\t\t\t\r\n\t\t}\r\n\t\tif (attach == true){\r\n\t\t\t\r\n\t\t\tattachJQuery();\r\n\t\t\t\r\n\t\t\t//Centers dialogs after ajax content load && sets max width screen size\r\n\t\t\tif ($(\"#\"+id).hasClass('ui-dialog-content')) {\r\n\t\t\t\t\r\n\t\t\t\tif ($(\"#\"+id).parent().width()>1200){\r\n\t\t\t\t\t\r\n\t\t\t\t\t$(\"#\"+id).dialog(\"option\", \"width\", 1200);\r\n\t\t\t\t\t\r\n\t\t\t\t}else{\r\n\t\t\t\t\t\r\n\t\t\t\t\t$(\"#\"+id).dialog(\"option\", \"width\", \"auto\");\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t$(\"#\"+id).dialog(\"option\", \"position\", [\"center\",dialog_Ypos()]);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor (evalArr_i in evalArr){\r\n\t\t\r\n\t\tfeval = evalArr[evalArr_i].split(\"<eval_script>\")[1].split(\"</eval_script>\")[0]\r\n\t\teval(feval);\r\n\t\t\r\n\t}\r\n\t\r\n}", "_parse() {\n const match = this._nextMatch();\n if (!match) { throw Error(`Cannot parse tag ${this.id}: ${this.data}`) }\n this.fields = this._extractFields(match);\n }", "_parse() {\n const match = this._nextMatch();\n if (!match) { throw Error(`Cannot parse tag ${this.id}: ${this.data}`); }\n this.fields = this._extractFields(match);\n }", "function parseInitialData ( responseText, callback )\n{\n const re = /{.*}/\n const $ = _cheerio.load( responseText )\n\n let initialData = $( 'div#initial-data' ).html() || ''\n initialData = re.exec( initialData ) || ''\n\n if ( !initialData ) {\n const scripts = $( 'script' )\n\n for ( let i = 0; i < scripts.length; i++ ) {\n const script = $( scripts[ i ] ).html()\n\n const lines = script.split( '\\n' )\n lines.forEach( function ( line ) {\n let i\n while ( ( i = line.indexOf( 'ytInitialData' ) ) >= 0 ) {\n line = line.slice( i + 'ytInitialData'.length )\n const match = re.exec( line )\n if ( match && match.length > initialData.length ) {\n initialData = match\n }\n }\n } )\n }\n }\n\n if ( !initialData ) {\n return callback( 'could not find inital data in the html document' )\n }\n\n const errors = []\n const results = []\n\n const json = JSON.parse( initialData[ 0 ] )\n\n const items = _jp.query( json, '$..itemSectionRenderer..contents.*' )\n\n debug( 'items.length: ' + items.length )\n\n for ( let i = 0; i < items.length; i++ ) {\n const item = items[ i ]\n\n let result = undefined\n let type = 'unknown'\n\n const hasList = ( item.compactPlaylistRenderer || item.playlistRenderer )\n const hasChannel = ( item.compactChannelRenderer || item.channelRenderer )\n const hasVideo = ( item.compactVideoRenderer || item.videoRenderer )\n\n const listId = hasList && ( _jp.value( item, '$..playlistId' ) )\n const channelId = hasChannel && ( _jp.value( item, '$..channelId' ) )\n const videoId = hasVideo && ( _jp.value( item, '$..videoId' ) )\n\n if ( videoId ) {\n type = 'video'\n }\n\n if ( channelId ) {\n type = 'channel'\n }\n\n if ( listId ) {\n type = 'list'\n }\n\n try {\n switch ( type ) {\n case 'video':\n {\n const thumbnail = _jp.value( item, '$..thumbnail..url' )\n const title = (\n _jp.value( item, '$..title..text' ) ||\n _jp.value( item, '$..title..simpleText' )\n )\n\n const author_name = (\n _jp.value( item, '$..shortBylineText..text' ) ||\n _jp.value( item, '$..longBylineText..text' )\n )\n\n const author_url = (\n _jp.value( item, '$..shortBylineText..url' ) ||\n _jp.value( item, '$..longBylineText..url' )\n )\n\n // publish/upload date\n const agoText = (\n _jp.value( item, '$..publishedTimeText..text' ) ||\n _jp.value( item, '$..publishedTimeText..simpleText' )\n )\n\n const viewCountText = (\n _jp.value( item, '$..viewCountText..text' ) ||\n _jp.value( item, '$..viewCountText..simpleText' )\n )\n\n const viewsCount = Number( viewCountText.split( /\\s+/ )[ 0 ].split( /[,.]/ ).join( '' ).trim() )\n\n const lengthText = (\n _jp.value( item, '$..lengthText..text' ) ||\n _jp.value( item, '$..lengthText..simpleText' )\n )\n const duration = parseDuration( lengthText || '0:00' )\n\n const description = (\n _jp.value( item, '$..description..text' ) ||\n _jp.value( item, '$..descriptionSnippet..text' )\n )\n\n // url ( playlist )\n // const url = _jp.value( item, '$..navigationEndpoint..url' )\n const url = TEMPLATES.YT + '/watch?v=' + videoId\n\n result = {\n type: 'video',\n\n videoId: videoId,\n url: url,\n\n title: title.trim(),\n description: description,\n\n thumbnail: _normalizeThumbnail( thumbnail ),\n\n seconds: Number( duration.seconds ),\n timestamp: duration.timestamp,\n duration: duration,\n\n ago: agoText,\n views: Number( viewsCount ),\n\n author: {\n name: author_name,\n url: TEMPLATES.YT + author_url,\n }\n }\n }\n break\n\n case 'list':\n {\n const thumbnail = _jp.value( item, '$..thumbnail..url' )\n const title = (\n _jp.value( item, '$..title..text' ) ||\n _jp.value( item, '$..title..simpleText' )\n )\n\n const author_name = (\n _jp.value( item, '$..shortBylineText..text' ) ||\n _jp.value( item, '$..longBylineText..text' ) ||\n _jp.value( item, '$..shortBylineText..simpleText' ) ||\n _jp.value( item, '$..longBylineText..simpleTextn' )\n ) || 'YouTube'\n\n const author_url = (\n _jp.value( item, '$..shortBylineText..url' ) ||\n _jp.value( item, '$..longBylineText..url' )\n ) || ''\n\n const video_count = (\n _jp.value( item, '$..videoCountShortText..text' ) ||\n _jp.value( item, '$..videoCountText..text' ) ||\n _jp.value( item, '$..videoCountShortText..simpleText' ) ||\n _jp.value( item, '$..videoCountText..simpleText' ) ||\n _jp.value( item, '$..thumbnailText..text' ) ||\n _jp.value( item, '$..thumbnailText..simpleText' )\n )\n\n // url ( playlist )\n // const url = _jp.value( item, '$..navigationEndpoint..url' )\n const url = TEMPLATES.YT + '/playlist?list=' + listId\n\n result = {\n type: 'list',\n\n listId: listId,\n url: url,\n\n title: title.trim(),\n thumbnail: _normalizeThumbnail( thumbnail ),\n\n videoCount: video_count,\n\n author: {\n name: author_name,\n url: TEMPLATES.YT + author_url,\n }\n }\n }\n break\n\n case 'channel':\n {\n const thumbnail = _jp.value( item, '$..thumbnail..url' )\n const title = (\n _jp.value( item, '$..title..text' ) ||\n _jp.value( item, '$..title..simpleText' ) ||\n _jp.value( item, '$..displayName..text' )\n )\n\n const author_name = (\n _jp.value( item, '$..shortBylineText..text' ) ||\n _jp.value( item, '$..longBylineText..text' ) ||\n _jp.value( item, '$..displayName..text' ) ||\n _jp.value( item, '$..displayName..simpleText' )\n )\n\n const video_count_label = (\n _jp.value( item, '$..videoCountText..text' ) ||\n _jp.value( item, '$..videoCountText..simpleText' )\n )\n\n let sub_count_label = (\n _jp.value( item, '$..subscriberCountText..text' ) ||\n _jp.value( item, '$..subscriberCountText..simpleText' )\n )\n\n // first space separated word that has digits\n if ( typeof sub_count_label === 'string' ) {\n sub_count_label = (\n sub_count_label.split( /\\s+/ )\n .filter( function ( w ) { return w.match( /\\d/ ) } )\n )[ 0 ]\n }\n\n // url ( playlist )\n // const url = _jp.value( item, '$..navigationEndpoint..url' )\n const url = (\n _jp.value( item, '$..navigationEndpoint..url' ) ||\n '/user/' + title\n )\n\n result = {\n type: 'channel',\n\n name: author_name,\n url: TEMPLATES.YT + url,\n\n title: title.trim(),\n thumbnail: _normalizeThumbnail( thumbnail ),\n\n videoCount: Number( video_count_label.replace( /\\D+/g, '' ) ),\n videoCountLabel: video_count_label,\n\n subCount: _parseSubCountLabel( sub_count_label ),\n subCountLabel: sub_count_label\n }\n }\n break\n\n default:\n // ignore other stuff\n }\n\n if ( result ) {\n results.push( result )\n }\n } catch ( err ) {\n debug( err )\n errors.push( err )\n }\n }\n\n const ctoken = _jp.value( json, '$..continuation' )\n results._ctoken = ctoken\n\n if ( errors.length ) {\n return callback( errors.pop(), results )\n }\n\n return callback( null, results )\n}", "renderResponse() {\n let containerId = this.getResponseContainer();\n\n let container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = this.getResponseHtml();\n } else {\n console.error('Cannot locate container: ' + containerId);\n }\n }", "function collectDataFromFields(){\n function fillValue($form, fieldSetName, $field, counter){\n var name = $field.attr(\"name\");\n\n if (name) {\n //strip ./\n if (name.indexOf(\"./\") == 0) {\n name = name.substring(2);\n }\n\n //remove the field, so that individual values are not POSTed\n $field.remove();\n\n $('<input />').attr('type', 'hidden')\n .attr('name', fieldSetName + \"/\" + counter + \"/\" + name)\n .attr('value', $field.val())\n .appendTo($form);\n }\n\n }\n\n $(document).on(\"click\", \".cq-dialog-submit\", function () {\n var $multifield = $(\"[\" + DATA_EAEM_NESTED + \"]\").first();\n\n if( _.isNotEmpty($multifield)){\n var childPrefix = $multifield.attr('data-element-prefix');\n var $form = $(this).closest(\"form.foundation-form\");\n var $fieldSets;\n var $fields;\n\n $fieldSets = $multifield.find(\"[class='coral-Form-fieldset']\");\n\n $fieldSets.each(function (counter, fieldSet) {\n $fields = $(fieldSet).children().children(CFFW);\n\n $fields.each(function (j, field) {\n fillValue($form, $(fieldSet).data(\"name\"), $(field).find(\"[name]\"), childPrefix + (counter + 1));\n });\n });\n }\n });\n }", "function collectDataFromFields(){\n function fillValue($form, fieldSetName, $field, counter, valToVal){\n var name = $field.attr(\"name\");\n\n if (!name) {\n return;\n }\n\n //strip ./\n if (name.indexOf(\"./\") == 0) {\n name = name.substring(2);\n }\n\n var value = $field.val();\n\n if( $field.prop(\"type\") == \"checkbox\" ){\n value = $field.prop(\"checked\") ? $field.val() : \"\";\n }\n\n $('<input />').attr('type', 'hidden')\n .attr('name', fieldSetName + \"/\" + counter + \"/\" + name)\n .attr('value', value )\n .appendTo($form);\n\n\n //remove the field, so that individual values are not POSTed\n $field.remove();\n }\n\n $(document).on(\"click\", \".cq-dialog-submit\", function () {\n var $multifields = $(\"[\" + DATA_EAEM_NESTED + \"]\");\n\n if(_.isEmpty($multifields)){\n return;\n }\n\n var $form = $(this).closest(\"form.foundation-form\"),\n $fieldSets, $fields;\n\n $multifields.each(function(i, multifield){\n $fieldSets = $(multifield).find(\"[class='coral-Form-fieldset']\");\n\n $fieldSets.each(function (counter, fieldSet) {\n $fields = $(fieldSet).children().children(CFFW);\n //TO Store as Child Notes\n var valToVal = '';\n $fields.each(function (j, field) {\n\n if(valToVal == ''){\n valToVal = $(field).find(\"[name]\").val();\n\n } else {\n var str = $(field).find(\"[name]\").val();\n valToVal = valToVal + \":\" + str;\n }\n\n fillValue($form, $(fieldSet).data(\"name\"), $(field).find(\"[name]\"), (counter + 1));\n });\n\n //add the record JSON in a hidden field as string - support classic UI\n $('<input />').attr('type', 'hidden')\n .attr('name', SOLR_FACET_FIELDS)\n .attr('value', valToVal)\n .appendTo($form);\n\n\n });\n });\n });\n }", "function parseFldDataRecord(node, cf_type)\n{\n var flds = [];\n var sub_flds = [];\n node.children().each(function(){\n var chld_node = $(this);\n var cn_tag = chld_node.children(\":first\").get(0).tagName;\n var cn_chld = chld_node.children(\":first\");\n //alert('DR children: ' + cn_tag);\n if(cn_tag == 'swe:Time'){\n var fldObj = parseFldTime(cn_chld, chld_node.attr(\"name\"));\n flds.push(fldObj);\n }\n if(cn_tag == 'swe:DataArray'){\n var da_tag = cn_chld.children(\":first\").get(0).tagName;\n var da_chld = cn_chld.children(\":first\");\n sub_flds = [];\n v_flds = parseFldDataRecord(da_chld, cf_type);\n for(var j = 0; j < v_flds.length; j++){\n flds.push(v_flds[j]);\n }\n //alert('Internal v_flds length: ' + v_flds.length);\n }\n if(cn_tag == 'swe:Vector'){\n //alert('Vector name: ' + chld_node.attr(\"name\"));\n sub_flds = [];\n v_flds = parseFldVector(cn_chld, chld_node.attr(\"name\"));\n for(var j = 0; j < v_flds.length; j++){\n flds.push(v_flds[j]);\n }\n }\n if(cn_tag == 'swe:Category'){\n var fldObj = parseFldCategory(cn_chld, chld_node.attr(\"name\")); \n flds.push(fldObj);\n }\n if(cn_tag == 'swe:Quantity'){\n //alert('field/Quanity name: ' + chld_node.attr(\"name\")); \n var fldObj = parseFldQuantity(cn_chld, chld_node.attr(\"name\")); \n flds.push(fldObj);\n }\n });\n\n return flds;\n}", "_parseContent(item) {\n const textFieldClass = this.getCSS(this._data.mode, \"textField\");\n return item.querySelector(`.${textFieldClass}`).innerHTML;\n }", "function Events_HandlesResponseFromForm(objDocument)\r\n{\r\n var strResponse = null;\r\n \r\n // Get the pipeline field\r\n var objPipeline = objDocument.getElementById(\"vwg_pipeline\");\r\n if(objPipeline!=null)\r\n {\r\n // Get the pipeline response\r\n strResponse = objPipeline.value;\r\n \r\n // Clean the pipeline field\t\t\t\t\t\t\t\t\r\n objPipeline.value = \"\";\r\n }\r\n \r\n // Handle the response\r\n Events_HandlesResponseFromPipeline(strResponse);\r\n}", "function renderResponse(targetElem, containerElem, response) {\n\n\t\tvar html = '';\n\t\tif (response.body) {\n\t\t\tif (/text\\/html/.test(response.headers['content-type'])) {\n\t\t\t\thtml = response.body.toString();\n\t\t\t} else {\n\t\t\t\t// escape non-html so that it can render correctly\n\t\t\t\tif (typeof response.body == 'string')\n\t\t\t\t\thtml = response.body.replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\t\t\t\telse\n\t\t\t\t\thtml = JSON.stringify(response.body);\n\t\t\t}\n\t\t}\n\n\t\ttargetElem.innerHTML = html;\n\t\tbindAttrEvents(targetElem, containerElem);\n\t\tsubscribeOutputElements(targetElem, containerElem);\n\t}", "function reformatDataForDisplay(dataPro, resp) {\n var searchedIds = SearchService.searchFields.split(',');\n var reformatResult = [];\n if (resp['FieldData'] !== null) {\n //Loop each searched ids\n _.each(searchedIds, function (fieldId, index) {\n var foundData = _.find(resp['FieldData'], function (fieldItem) {\n if (fieldItem[\"FieldId\"].toUpperCase() === fieldId.toUpperCase()) {\n return fieldItem;\n }\n });\n\n //When the field id appears in advance coding, but not in section 4 of the rule add/edit screen\n if (typeof foundData === 'undefined' || foundData === null) {\n foundData = {};\n foundData[\"FieldId\"] = fieldId;\n foundData[dataPro] = null;\n }\n reformatResult.push(foundData);\n });\n\n var newResponse = {};\n newResponse['SearchResultTypeData'] = resp['SearchResultTypeData'];\n newResponse['FieldData'] = reformatResult;\n return newResponse;\n } else return resp;\n }", "function collectDataFromFields(){\n $(document).on(\"click\", \".cq-dialog-submit\", submitHandler);\n\n function submitHandler(){\n var $multifields = $(\"[\" + DATA_EAEM_NESTED + \"]\");\n\n if(_.isEmpty($multifields)){\n return;\n }\n\n var $form = $(this).closest(\"form.foundation-form\"),\n $fieldSets, $fields;\n\n if(!validateSubmittables()){\n return;\n }\n\n $multifields.each(function(i, multifield){\n $fieldSets = $(multifield).find(\"[class='coral-Form-fieldset']\");\n\n $fieldSets.each(function (counter, fieldSet) {\n $fields = $(fieldSet).children().children(CFFW);\n\n $fields.each(function (j, field) {\n fillValue($form, $(fieldSet).data(\"name\"), $(field).find(\"[name]\"), (counter + 1));\n });\n });\n });\n }\n }", "function fillScreenFieldWithTextDiv(obj,xmlFieldName,xmlTextFieldName,screenFieldName) {\n var lf_node = obj.data.getElementsByTagName(xmlFieldName)[0].childNodes[0];\n var lf_typeof = typeof(lf_node);\n var lf_screenElement;\n if (xmlTextFieldName!='') {\n var lf_node_text = obj.data.getElementsByTagName(xmlTextFieldName)[0].childNodes[0];\n var lf_typeof_text = typeof(lf_node);\n var lf_value = '';\n var lf_text = '';\n if (lf_node==null || lf_typeof=='undefined') {\n lf_value = '';\n } else {\n lf_value = lf_node.nodeValue;\n }\n if (lf_node_text==null || lf_typeof_text=='undefined') {\n lf_text = '';\n } else {\n lf_text = lf_node_text.nodeValue;\n }\n lf_screenElement = document.getElementById(screenFieldName);\n if (lf_screenElement==null || typeof(lf_screenElement)=='undefined' ) {\n // we are not doing anything here :-)\n } else {\n lf_screenElement.innerHTML = lf_value + ' ' + lf_text;\n }\n2 } else {\n if (lf_node==null || lf_typeof=='undefined') {\n lf_screenElement = document.getElementById(screenFieldName);\n if (lf_screenElement==null || typeof(lf_screenElement)=='undefined' ) {\n // we are not doing anything here :-)\n } else {\n lf_screenElement.innerHTML = '';\n }\n } else {\n lf_screenElement = document.getElementById(screenFieldName);\n if (lf_screenElement==null || typeof(lf_screenElement)=='undefined' ) {\n // we are not doing anything here :-)\n } else {\n lf_screenElement.innerHTML = lf_node.nodeValue;\n }\n }\n }\n}", "function updateResponseContainer(response) {\n responseContainer.querySelector('pre').innerText = JSON.stringify(response, null, 2);\n responseContainer.classList.add('response-container--visible');\n}", "function renderResponse(targetElem, containerElem, response) {\n\n\tresponse.body = response.body || '';\n\tvar type = response.headers['content-type'];\n\tif (/application\\/html\\-deltas\\+json/.test(type)) {\n\t\tif (typeof response.body != 'object' || !Array.isArray(response.body))\n\t\t\tconsole.log('Improperly-formed application/html-deltas+json object', response);\n\t\telse {\n\t\t\tif (Array.isArray(response.body[0])) {\n\t\t\t\tresponse.body.forEach(function(delta) {\n\t\t\t\t\trenderHtmlDelta(delta, targetElem, containerElem);\n\t\t\t\t});\n\t\t\t} else\n\t\t\t\trenderHtmlDelta(response.body, targetElem, containerElem);\n\t\t}\n\t} else {\n\t\t// format the output by type\n\t\tvar html = '';\n\t\tif (/text\\/html/.test(type))\n\t\t\thtml = response.body.toString();\n\t\telse {\n\t\t\t// escape non-html so that it can render correctly\n\t\t\tif (typeof response.body != 'string')\n\t\t\t\thtml = JSON.stringify(response.body);\n\t\t\thtml = response.body.replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\t\t}\n\n\t\tlocal.client.unlisten(targetElem); // make sure to unregister listeners before replaceing\n\t\ttargetElem.innerHTML = html;\n\t\tlocal.env.postProcessRegion(targetElem, containerElem);\n\t}\n\n\tbindAttrEvents(targetElem, containerElem);\n\tsubscribeElements(targetElem, containerElem);\n}", "viewSurveyFields() {\n\t\tconst { registrant, formFields } = this.props;\n\t\tif(registrant && registrant.SurveyData && formFields){\n\t\t\tlet fullSurveyInfo = [];\n\t\t\tlet xmlDoc = parseXml(registrant.SurveyData);\n\t\t\tlet rootNode = xmlDoc.firstChild;\n\t\t\tlet responsesNode = rootNode.firstChild;\n\t\t\tformFields.forEach((fieldObj) => {\n\t\t\t\tif(fieldObj.type === 'T' || fieldObj.type === 'TO') {\n\t\t\t\t\tlet val = getTextFromXml(responsesNode, fieldObj.tag);\n\t\t\t\t\tfullSurveyInfo.push(<div className=\"col-xs-12 col-sm-6 more-field\"><span className=\"more-field-title\">{fieldObj.label}: </span>{val}</div>);\n\t\t\t\t} else if ((fieldObj.type === 'O' || fieldObj.type === 'M') && fieldObj.responses) {\n\t\t\t\t\tlet vals = [];\n\t\t\t\t\tfieldObj.responses.forEach((response) => {\n\t\t\t\t\t\tif(getPickFromXml(responsesNode, response.rTag)){\n\t\t\t\t\t\t\tvals.push(response.rLabel);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tfullSurveyInfo.push(<div className=\"col-xs-12 col-sm-6 more-field\"><span className=\"more-field-title\">{fieldObj.label}: </span>{vals.join(', ')}</div>);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn fullSurveyInfo;\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the coordinates for the robot based on the direction of Robot Parameters : robot Instance created initially
function updateCoordinates(robotInstance) { let direction = robotInstance.getDirection(); let currentXCoordinate = robotInstance.getXCoordinate(); let currentYCoordinate = robotInstance.getYCoordinate(); switch (direction) { case validDirections.NORTH: robotInstance.setYCoordinate(currentYCoordinate + 1); break; case validDirections.EAST: robotInstance.setXCoordinate(currentXCoordinate + 1); break; case validDirections.SOUTH: robotInstance.setYCoordinate(currentYCoordinate - 1); break; case validDirections.WEST: robotInstance.setXCoordinate(currentXCoordinate - 1); break; default: break; } }
[ "function Robot(width, height, x, y) {\n\tthis.width = width;\n\tthis.height = height;\n\tthis.x = x;\n\tthis.y = y; \n\t\t\t\t\n\tthis.newPos = function() {\n this.x = this.x;\n this.y = this.y; \n\t}; \n}", "function Robot() {\n this.coordinates = [0, 0];\n this.directions = [{ name: 'North', value: [0, 1] },\n { name: 'East', value: [1, 0] },\n { name: 'South', value: [0, -1] },\n { name: 'West', value: [-1, 0] }];\n this.directionIndex = 0;\n\n this.right = function() {\n this.directionIndex = (this.directionIndex + 1) % 4;\n };\n\n this.left = function() {\n this.directionIndex = (this.directionIndex + 3) % 4;\n };\n\n this.report = function() {\n console.log('Direction: ' + this.direction()['name']);\n console.log('Coordinates:' + this.coordinates);\n };\n\n this.direction = function() {\n return this.directions[this.directionIndex];\n };\n\n this.move = function() {\n for (var i = 0; i < this.coordinates.length; i++) {\n this.coordinates[i] += this.direction()['value'][i];\n if (this.coordinates[i] < 0) {\n this.coordinates[i] = 0;\n }\n }\n };\n}", "constructor(robot,limitX,limitY){\n this.robot = new Robot(robot.x,robot.y,robot.orientation);\n this.limitX=limitX;\n this.limitY=limitY;\n\n }", "function setPos(params) {\n\tvar params = params || {};\n\tCamera.duration = 0;\n\tCamera.easing = platino.ANIMATION_CURVE_LINEAR;\n\tCamera.lookAt_eyeX = params.eyeX || params.centerX;\n\tCamera.lookAt_centerX = params.centerX;\n\tCamera.lookAt_eyeY = params.eyeY || params.centerY;\n\tCamera.lookAt_centerY = params.centerY;\n\tCamera.lookAt_eyeZ = params.eyeZ;\n\tCamera.skipOnComplete = params.skipOnCompleteListener || false;\n\tgame.moveCamera(Camera);\n}", "constructor(robotLoc, parcels) {\n this.robotLoc = robotLoc;\n this.parcels = parcels;\n }", "function placeRobot() {\n\tvar newPosition = {\n\t\tx: document.getElementById(\"x-pos\").value,\n\t\ty: document.getElementById(\"y-pos\").value\n\t}\n\tvar newOrientation = document.getElementById(\"orientation\");\n\tvar positionValid = true; // flag\n\tvar orientationValid; // flag\n\n\t// validate x and y\n\tObject.keys(newPosition).forEach(function (key) { // gets property key names (x or y)\n\t\tvar tempKeyName;\n\t\tif(positionValid) {\n\t\t\tswitch(key) { // check if x or y\n\t\t\t\tcase \"x\": // validate x position\n\t\t\t\t\ttempKeyName = \"X Position\";\n\t\t\t\t\tpositionValid = validatePositionInput(tempKeyName, newPosition.x);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"y\": // validate y position\n\t\t\t\t\ttempKeyName = \"Y Position\";\n\t\t\t\t\tpositionValid = validatePositionInput(tempKeyName, newPosition.y);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\ttempKeyName = \"\"; // avoids undefined error\n\t\t\t}\n\t\t}\n\t});\n\n\t// if positions valid, validate orientation\n\tif (positionValid) orientationValid = validateOrientation(newOrientation.value);\n\t \n\t// if position & orientation valid, place robot image & update robot object\n\tif (positionValid && orientationValid) {\n\t\tsetRobotLocation(newPosition.x, newPosition.y, newOrientation.value);\n\t\tif (robot.placed == false) {\n\t\t\tshowRobot(); // display the robot\n\t\t\tdisplayCommands(); // initialise game commands\n\t\t}\n\t}\n\n\treturn false; // stop page refresh\n}", "function setPosition() {\n logger.info(`Setting servoCam position to H ${currentHPos}, V ${currentVPos}`);\n hCamServo.servoWrite(currentHPos);\n vCamServo.servoWrite(currentVPos);\n _onStatusChange(getStatus());\n }", "function Robot(){\n this.x = null;\n this.y = null;\n this.face = null\n}", "function CarRobot() {\n\tvar that = this;\n\t/*=======\n\tRobot State\n\t========*/\n\tthat.Measurements = new Object();\n\t// PWM duty cycles\n\tthat.Measurements.PWM = new Array();\n\tthat.Measurements.PWM[0] = 0.3;\n\tthat.Measurements.PWM[1] = 0.6;\n\t// RevPWM duty cycles\n\tthat.Measurements.RevPWM = new Array();\n\tthat.Measurements.RevPWM[0] = 0.3;\n\tthat.Measurements.RevPWM[1] = 0.6;\n\t// PWM frequencies\n\tthat.Measurements.F = new Array();\n\tthat.Measurements.F[0] = 100;\n\tthat.Measurements.F[1] = 100;\n\t// Wheel RPMs\n\tthat.Measurements.RPM = new Array();\n\tthat.Measurements.RPM[0] = 250;\n\tthat.Measurements.RPM[1] = 180;\n\t// General Robot Kinematics\n\tthat.Measurements.CurveRadius = 500;\n\tthat.Measurements.Speed = 0.6;\n\t// Color\n\tthat.Measurements.Sensor = 0;\n\tthat.Measurements.Color = 0;\n\tthat.Measurements.RGBColor = 0;\n\t\n\t\n\t/*=======\n\tRobot Setpoints\n\t========*/\n\tthat.SetPoints = new Object();\n\t// Wheel RPMs\n\tthat.SetPoints.RPM = new Array();\n\tthat.SetPoints.RPM[0] = 270;\n\tthat.SetPoints.RPM[1] = 150;\n\t// General Robot Kinematics\n\tthat.SetPoints.CurveRadius = 400;\n\tthat.SetPoints.Speed = 0.4;\n\t\n\t/*======\n\tRobot Targets\n\t=======*/\n\tthat.Targets = new Object();\n\tthat.Targets.CommandColor = 0;\n\tthat.Targets.PathChosen = 0;\n\t\n\t/*=======\n\tRobot Settings\n\t========*/\n\tthat.Settings = new Object();\n\tthat.Settings.DesiredSpeed = 0;\n\tthat.Settings.Cruise = new Object();\n\tthat.Settings.Cruise.Sharpness = 100;\n\tthat.Settings.Cruise.Kp = 0;\n\tthat.Settings.Cruise.Kd = 0;\n\tthat.Settings.Cruise.Ki = 0;\n\tthat.Settings.Cruise.DBrake = 0;\n\tthat.Settings.Cruise.PBrake = 0;\n\tthat.Settings.Cruise.DecayRate = 0;\n\tthat.Settings.Motor = new Object();\n\tthat.Settings.Motor.Kp = 0;\n\tthat.Settings.Motor.Kd = 0;\n\t\n\t/*=======\n\tRobot Parameters\n\t========*/\n\tthat.Parameters = new Object();\n\tthat.Parameters.MaxRPM = 300;\t\t// 300 rpm\n\tthat.Parameters.WheelRadius = 3.5;\t// 3.5cm\n\tthat.Parameters.WheelBase = 18;\t\t// 18cm\n\t\n\t/*=======\n\tMethods\n\t========*/\n\tthat.SaveSettings = function() {\n\t\tlocalStorage.setItem(\"DesiredSpeed\", that.Settings.DesiredSpeed);\n\t\tlocalStorage.setItem(\"CruiseSharpness\", that.Settings.Cruise.Sharpness);\n\t\tlocalStorage.setItem(\"CruiseKp\", that.Settings.Cruise.Kp);\n\t\tlocalStorage.setItem(\"CruiseKd\", that.Settings.Cruise.Kd);\n\t\tlocalStorage.setItem(\"CruiseKi\", that.Settings.Cruise.Ki);\n\t\tlocalStorage.setItem(\"DBrake\", that.Settings.Cruise.DBrake);\n\t\tlocalStorage.setItem(\"PBrake\", that.Settings.Cruise.PBrake);\n\t\tlocalStorage.setItem(\"DecayRate\", that.Settings.Cruise.DecayRate);\n\t\tlocalStorage.setItem(\"MotorKp\", that.Settings.Motor.Kp);\n\t\tlocalStorage.setItem(\"MotorKd\", that.Settings.Motor.Kd);\n\t}\n\t\n\tthat.RetrieveSettings = function() {\n\t\tthat.Settings.DesiredSpeed = localStorage.getItem(\"DesiredSpeed\") || that.Settings.DesiredSpeed;\n\t\tthat.Settings.Cruise.Sharpness = localStorage.getItem(\"CruiseSharpness\") || that.Settings.Cruise.Sharpness;\n\t\tthat.Settings.Cruise.Kp = localStorage.getItem(\"CruiseKp\") || that.Settings.Cruise.Kp;\n\t\tthat.Settings.Cruise.Kd = localStorage.getItem(\"CruiseKd\") || that.Settings.Cruise.Kd;\n\t\tthat.Settings.Cruise.Ki = localStorage.getItem(\"CruiseKi\") || that.Settings.Cruise.Ki;\n\t\tthat.Settings.Cruise.DBrake = localStorage.getItem(\"DBrake\") || that.Settings.Cruise.DBrake;\n\t\tthat.Settings.Cruise.PBrake = localStorage.getItem(\"PBrake\") || that.Settings.Cruise.PBrake;\n\t\tthat.Settings.Cruise.DecayRate = localStorage.getItem(\"DecayRate\") || that.Settings.Cruise.DecayRate;\n\t\tthat.Settings.Motor.Kp = localStorage.getItem(\"MotorKp\") || that.Settings.Motor.Kp;\n\t\tthat.Settings.Motor.Kd = localStorage.getItem(\"MotorKd\") || that.Settings.Motor.Kd;\n\t}\n\t\n\tthat.UpdateMeasurements = function(RPMLS, RPML, RPMRS, RPMR, TA0CCR0_REG, TA0CCR1_REG, TA0CCR2_REG, TA2CCR0_REG, TA2CCR1_REG, TA2CCR2_REG, lastSensorPosition, Color) {\n\t\t// First update the RPMs, as they require least calculations.\n\t\tthat.SetPoints.RPM[0] = RPMLS;\n\t\tthat.Measurements.RPM[0] = RPML;\n\t\tthat.SetPoints.RPM[1] = RPMRS;\n\t\tthat.Measurements.RPM[1] = RPMR;\n\t\t\n\t\t// Then, update the sensor measurements\n\t\tthat.Measurements.Sensor = lastSensorPosition;\n\t\tthat.Measurements.Color = Color;\n\t\t\n\t\t// Then, calculate the duty cycles...\n\t\tthat.Measurements.PWM[0] = TA0CCR1_REG/TA0CCR0_REG;\n\t\tthat.Measurements.RevPWM[0] = TA0CCR2_REG/TA0CCR0_REG;\n\t\tthat.Measurements.PWM[1] = TA2CCR1_REG/TA2CCR0_REG;\n\t\tthat.Measurements.RevPWM[1] = TA2CCR2_REG/TA2CCR0_REG;\n\t\t\n\t\t// Then, calculate Frequencies...\n\t\t// Assume that Input Clock is 4MHz\n\t\t// f = 4MHz/TAxCCR0\n\t\tthat.Measurements.F[0] = 4000000/TA0CCR0_REG;\n\t\tthat.Measurements.F[1] = 4000000/TA2CCR0_REG;\n\t\t\n\t\t// Now the hardest part...\n\t\t// Calculate Actual Linear speed and actual curve radius based on RPMs\n\t\t// It takes diffDriver\n\t\tthat.Measurements.CurveRadius = getCurveRadius(that.Measurements.RPM[0], that.Measurements.RPM[1]);\n\t\tthat.Measurements.Speed = getSpeed(that.Measurements.RPM[0], that.Measurements.RPM[1]);\n\t\t// Calculate Setpoint Linear speed and setpoint curve radius based on RPM setpoints\n\t\tthat.SetPoints.CurveRadius = getCurveRadius(that.SetPoints.RPM[0], that.SetPoints.RPM[1]);\n\t\tthat.SetPoints.Speed = getSpeed(that.SetPoints.RPM[0], that.SetPoints.RPM[1]);\t\t\n\t}\n\t\n\t/*=======\n\tInternal DiffDriver functions\n\t========*/\n\tvar getWheelLinearSpeed = function(RPM) {\n\t\t// 2*pi/60 ==> 0.105. This is conversion factor from RPM to rad/s\n\t\treturn RPM*(0.105)*that.Parameters.WheelRadius;\n\t}\n\t\n\tvar getSpeed = function(RPML, RPMR) {\n\t\tvar speed1 = getWheelLinearSpeed(RPML);\n\t\tvar speed2 = getWheelLinearSpeed(RPMR);\n\t\t// The actual speed is the arithmetic mean of the linear speed of both wheels\n\t\treturn (speed1 + speed2)/2;\n\t}\n\t\n\tvar getCurveRadius = function(RPML, RPMR) {\n\t\tvar speed1 = getWheelLinearSpeed(RPML);\n\t\tvar speed2 = getWheelLinearSpeed(RPMR);\n\t\t// Derived somewhere.\n\t\treturn (that.Parameters.WheelBase*(speed1+speed2))/(2*(speed1-speed2));\n\t}\n}", "function updateRobotPosition(timeDiff) {\n // Store away current position\n actualState.lastCenterX = actualState.centerX;\n actualState.lastCenterY = actualState.centerY;\n \n // Update x, y, and theta due to current velocities.\n actualState.centerX = actualState.centerX + (timeDiff / 1000.0) *\n (actualState.velX * Math.cos(actualState.theta) + actualState.velY * Math.sin(actualState.theta));\n actualState.centerY = actualState.centerY + (timeDiff / 1000.0) *\n (actualState.velX * Math.sin(-actualState.theta) + actualState.velY * Math.cos(actualState.theta));\n actualState.theta = fixupAngle(actualState.theta - actualState.velRot * (timeDiff / 1000.0));\n\n // Move robot back to center if it's about to go within 3 feet of border.\n if (actualState.centerX <= page.centerX - (page.realGridWidth / 2 - 3) ||\n actualState.centerX >= page.centerX + (page.realGridWidth / 2 - 3)) {\n // Recenter the page and clear the path\n page.centerX = actualState.centerX;\n page.centerY = actualState.centerY;\n clearDrawnPath();\n }\n if (actualState.centerY <= page.centerY - (page.realGridHeight / 2 - 3) ||\n actualState.centerY >= page.centerY + (page.realGridHeight / 2 - 3)) {\n page.centerX = actualState.centerX;\n page.centerY = actualState.centerY;\n clearDrawnPath();\n }\n}", "setCoords(testingMode){\n if (this.direction == \"right\" || this.direction == \"left\" ){\n if (testingMode !== \"start\"){\n var yCor = window.innerHeight/2;\n }else{\n var yCor = Math.floor(Math.random() * window.innerHeight);\n }\n super.setY(yCor); \n if(this.direction == \"right\"){\n super.setX(-this.radius);\n }\n super.setX(window.innerWidth + this.radius);\n }\n else if (this.direction == \"up\" || this.direction == \"down\" ){\n if (testingMode !== \"start\"){\n var xCor = window.innerWidth/2;}\n else{\n \n var xCor = Math.floor(Math.random() * window.innerWidth);\n }\n super.setX(xCor); \n if(this.direction == \"up\"){\n super.setY(window.innerHeight + this.radius);\n }\n super.setY(-this.radius);\n }\n }", "function Robot() {\n this.motors = 2;\n }", "constructor() {\n this.coordinates = [0, 0];\n this.directionArray = [\"north\", \"east\", \"south\", \"west\"];\n this.bearing = \"north\";\n\n }", "_moveRobot(grid, robots, robotColor, direction) {\n let initialRow = robots[robotColor].row;\n let initialColumn = robots[robotColor].column;\n this._setValue(grid, initialRow, initialColumn, gridCell.EMPTY_CELL);\n while (this._movesForRobot(grid, robots, robotColor).includes(direction)) {\n if (direction === MOVE_UP) {\n // update the row of the robot.\n robots[robotColor].row--;\n } else if (direction === MOVE_DOWN) {\n robots[robotColor].row++;\n } else if (direction === MOVE_LEFT) {\n robots[robotColor].column--;\n } else if (direction === MOVE_RIGHT) {\n robots[robotColor].column++;\n }\n }\n this._setValue(\n grid,\n robots[robotColor].row,\n robots[robotColor].column,\n gridCell.ROBOT_CELL\n );\n }", "function moveRobot() {\n\tvar squarePos;\n\tvar axis;\n\t\n\t// determine movement direction and axis (x or y) & update robot\n\tswitch(robot.orientation) {\n\t\tcase \"north\":\n\t\t\tsquarePos = robot.position.y + 1, axis = \"y\";\n\t\t\tbreak;\n\t\tcase \"east\":\n\t\t\tsquarePos = robot.position.x + 1, axis = \"x\";\n\t\t\tbreak;\n\t\tcase \"south\":\n\t\t\tsquarePos = robot.position.y - 1, axis = \"y\";\n\t\t\tbreak;\n\t\tcase \"west\":\n\t\t\tsquarePos = robot.position.x - 1, axis = \"x\";\n\t\t\tbreak;\n\t}\n\n\t// if valid square on table, update robot object and move\n\tif (validateMoveRobot(squarePos)) {\n\t\tif (axis == \"x\") { setRobotLocation(squarePos, \"\", \"\"); }\n\t\telse if (axis == \"y\") { setRobotLocation(\"\", squarePos, \"\"); }\n\t\tupdateEyeOrientation(robot.orientation);\n\t\tclearInputs();\n\t}\n}", "function changePosition(robot, move) {\n if (robot.orientation === 'north') {\n robot.position[1] -= moveValue[move];\n } else if (robot.orientation === 'south') {\n robot.position[1] += moveValue[move];\n } else if (robot.orientation === 'east') {\n robot.position[0] += moveValue[move];\n } else {\n robot.position[0] -= moveValue[move];\n }\n}", "function Robot() {\n\tthis.motors = 2;\n}", "teleport()\n {\n if (this.xPos === 0 && this.yPos === 12 && this.direction === Directions.West)\n {\n this.xPos = 14;\n }\n else if (this.xPos === 14 && this.yPos === 12 && this.direction === Directions.East)\n {\n this.xPos = 0;\n }\n }", "initializedRobotPositions() {\n for (let key in this.robots) {\n let row = this.generateRandomNumber(this.rows);\n let column = this.generateRandomNumber(this.columns);\n while (this.getValue(row, column) !== gridCell.EMPTY_CELL) {\n row = this.generateRandomNumber(this.rows);\n column = this.generateRandomNumber(this.columns);\n }\n this.robots[key].row = row;\n this.robots[key].column = column;\n this.setValue(row, column, gridCell.ROBOT_CELL);\n }\n\n this.initialRobots = utils.deepCopy(this.robots);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws the snapped polyline (after processing snaptoroad response).
function drawSnappedPolyline() { var lineSymbol = { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW }; snappedPolyline = new google.maps.Polyline({ path: snappedCoordinates, strokeColor: 'blue', strokeWeight: 3, icons: [{ icon: lineSymbol, offset: '100%' }], }); //snappedPolyline.setMap(null); //polylines.push(snappedPolyline); var track = new google.maps.DirectionsService(),snappedPolyline,snap_path1=[]; snappedPolyline.setMap(map); for(j=0;j<snappedCoordinates.length-1;j++){ track.route({origin: snappedCoordinates[j],destination: snappedCoordinates[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) { if(status == google.maps.DirectionsStatus.OK) { snap_path1 = snap_path1.concat(result.routes[0].overview_path); snappedPolyline.setPath(snap_path1); } else { console.log("Directions request failed: "+status); } }); } //animateArrow(); }
[ "function drawSnappedPolyline() {\n routePath.setPath(snappedCoordinates);\n}", "function drawSnappedPolyline() {\n let snappedPolyline = new google.maps.Polyline({\n path: snappedCoordinates,\n strokeColor: \"#7094cf\",\n strokeWeight: 6,\n strokeOpacity: 0.9,\n });\n\n snappedPolyline.setMap(map);\n polylines.push(snappedPolyline);\n }", "function drawSnappedPolyline() {\n var snappedPolyline = new google.maps.Polyline({\n path: snappedCoordinates,\n strokeColor: 'black',\n strokeWeight: 3\n });\n\n snappedPolyline.setMap(map);\n polylines.push(snappedPolyline);\n }", "function drawSnappedPolyline() {\n var snappedPolyline = new google.maps.Polyline({\n path: snappedCoordinates,\n strokeColor: 'white',\n strokeWeight: 3\n });\n\n snappedPolyline.setMap(map);\n polylines.push(snappedPolyline);\n}", "function drawSnappedPolyline() {\n var snappedPolyline = new google.maps.Polyline({\n path: snappedCoordinates,\n strokeColor: 'black',\n strokeWeight: 3\n });\n\n snappedPolyline.setMap(map);\n polylines.push(snappedPolyline);\n}", "function drawSnappedPolyline(caseNo) {\n\t\tvar colorValue;\n\t\tvar title;\n\t\tif (caseNo == 1) {\n\t\t\ttitle = 'BUS tr4';\n\t\t colorValue = '#000000';\n\t }\n\t else if(caseNo == 2){\n\t\t\ttitle = 'BUS 303';\n\t \tcolorValue = '#0D47A1';\n\t }\n\t else{\n\t\t\ttitle = 'BUS 306';\n\t \tcolorValue = '#C51162';\n\t }\n\t var lineSymbol = {\n\t path: google.maps.SymbolPath.CIRCLE,\n\t scale: 7,\n \t title:title,\n\t strokeColor: colorValue\n\t };\n\n var flightPath = new google.maps.Polyline({\n path: snappedCoordinates,\n geodesic: true,\n icons: [{\n icon: lineSymbol,\n offset: '100%'\n }],\n strokeColor: colorValue,\n strokeOpacity: 1.0,\n strokeWeight: 4\n });\n\n var reversePath = new google.maps.Polyline({\n path: reverseCoordinates,\n geodesic: true,\n icons: [{\n icon: lineSymbol,\n offset: '100%'\n }],\n title:title,\n strokeColor: colorValue,\n strokeOpacity: 1.0,\n strokeWeight: 4\n });\n\n // busStop(nearestLat, nearestLong, msg);\n animateCircle(flightPath);\n animateCircle(reversePath);\n flightPath.setMap(map);\n reversePath.setMap(map);\n snappedCoordinates = [];\n reverseCoordinates = [];\n\t}", "function drawPolyline() {\r\n\r\n var markersPositionArray = [];\r\n //Obtaining latLng of all markers on map\r\n markersArray.forEach(function(event) {\r\n markersPositionArray.push(event.getPosition());\r\n });\r\n //Used for route planned elevation chart\r\n posArray = markersPositionArray;\r\n \r\n //Checks if there is already a polyline drawn on map\r\n //Removing the polyline from map before we draw new one\r\n if (polyline !== null) {\r\n polyline.setMap(null);\r\n }\r\n \r\n //Draw a new polyline at markers' position\r\n polyline = new google.maps.Polyline({\r\n map: map,\r\n path: markersPositionArray,\r\n strokeColor: '#FF0000',\r\n strokeOpacity: 0.4\r\n });\r\n }", "function drawPolyline() {\n if (polyline) {\n polyline.setMap(null);\n polyline = null;\n }\n\n polyline = new google.maps.Polyline({\n strokeColor: '#FFB000',\n strokeOpacity: 1.0,\n strokeWeight: 5\n });\n polyline.setMap(map);\n\n var path = [];\n\n for (var i = 0; i < scope.markers.length; i++) {\n path.push(scope.markers[i].position);\n }\n polyline.setPath(path);\n }", "function drawLine() {\n drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE);\n drawingManager.setOptions({\n drawingControl: true,\n drawingControlOptions: {\n position: google.maps.ControlPosition.TOP_CENTER,\n drawingModes: [google.maps.drawing.OverlayType.POLYLINE]\n },\n polylineOptions: {\n editable: true,\n id: count,\n }\n });\n}", "function drawLine(gpResponse) {\r\n var driftPoly = gpResponse.results[0].value.features;\r\n\r\n var driftGraphics = driftPoly.map(function(line) {\r\n line.symbol = driftLine;\r\n return line;\r\n });\r\n\r\n driftLayer.addMany(driftGraphics);\r\n\r\n // Zoom to drift line\r\n view.goTo({\r\n target: driftGraphics\r\n });\r\n\r\n // Hide Standby Spinner\r\n standby.hide();\r\n }", "function DrawRS(trips) {\n\tdisplayed_data = trips; // modification to allow reductions across visualizations.\n\tfor (var j = 0; j < trips.length; j++) { // Check Number of Segments and go through all segments\n\t\tvar TPT = new Array();\n\t\tTPT = TArr[trips[j].tripid].split(','); // Find each segment in TArr Dictionary. \n\t\tvar polyline = new L.Polyline([]).addTo(drawnItems);\n\t\tpolyline.setStyle({\n\t\t\tcolor: 'red', // polyline color\n\t\t\tweight: 1, // polyline weight\n\t\t\topacity: 0.5, // polyline opacity\n\t\t\tsmoothFactor: 1.0\n\t\t});\n\t\tfor (var y = 0; y < TPT.length - 1; y = y + 2) { // Parse latlng for each segment\n\t\t\tpolyline.addLatLng([parseFloat(TPT[y + 1]), parseFloat(TPT[y])]);\n\t\t}\n\t}\n}", "function drawPolyline(maps,options,element){return appendShape(maps.renderer.drawPolyline(options),element);}", "function updatePolyline() {\r\n //Grab the line\r\n var line = viewer.entities.getById('line');\r\n \r\n //Destroy it\r\n if(line != undefined) {\r\n viewer.entities.remove(line);\r\n }\r\n\r\n //Get list of waypoint data sorted by number\r\n var waypoints = getSortedPoints();\r\n\r\n //fill coordinate array\r\n var coordinates = [];\r\n waypoints.forEach(function f(point, i){\r\n coordinates.push(point.longitude);\r\n coordinates.push(point.latitude);\r\n coordinates.push(point.height);\r\n });\r\n\r\n //Add new line with new coordinates\r\n line = viewer.entities.add({\r\n name:\"Waypoint Line\",\r\n id:\"line\",\r\n polyline : {\r\n positions : Cesium.Cartesian3.fromDegreesArrayHeights(coordinates),\r\n width : 2,\r\n material : Cesium.Color.RED\r\n }\r\n }); \r\n }", "function cvjs_drawSpaceObject_RedlinePolyline() {\n\t\tcvjs_addHandleFunc_RedlinePolyline();\n}", "function LI_drawPoint(event) {\r\n if (LI_state == \"drawing\") { //Checks if in desired LI_state\r\n // if (!cancel) { //Checks if user clicked on LI_cancel button\r\n if (!LI_drawing) { //Checks what phase of line create user is in\r\n LI_graphics.clear(); //Clears current LI_graphics on screen\r\n //Changes LI_drawing value\r\n LI_drawing = true;\r\n //Updates starting point\r\n // points = [event.data.global.x, event.data.global.y];\r\n //Creates the starting point for the line\r\n LI_currentStart = new Point(event.data.global.x, event.data.global.y, windowContainer);\r\n LI_currentStart.image.name = LI_pointContainer.length;\r\n\r\n LI_pointContainer.push(LI_currentStart);\r\n //Updates text and LI_cancel button\r\n\r\n setMainText(LI_mainText, 2, LI_lineContainer);\r\n }//end LI_drawing if\r\n else {\r\n //Creates the end point of the line\r\n var endPoint = new Point(event.data.global.x, event.data.global.y, windowContainer);\r\n endPoint.image.name = LI_pointContainer.length;\r\n LI_pointContainer.push(endPoint);\r\n //Contructs the line graphic to be place inside the line object\r\n var lineImage = new PIXI.Graphics();\r\n lineImage.lineStyle(1, 0x000070)\r\n .moveTo(LI_currentStart.x, LI_currentStart.y)\r\n .lineTo(endPoint.x, endPoint.y);\r\n lineImage.name = LI_lineContainer.length;\r\n lineImage.interactive = true;\r\n lineImage.buttonMode = true;\r\n lineImage\r\n .on(\"pointerdown\", LI_lineSelect)\r\n .on(\"pointerup\", LI_onDragLineEnd)\r\n .on(\"pointerupoutside\", LI_onDragLineEnd)\r\n .on(\"pointermove\", LI_onDragLineMove);\r\n //Creates the hit area of said line graphic\r\n var polyPts;\r\n if (LI_currentStart.x > endPoint.x) {\r\n polyPts = [LI_currentStart.x - 5, LI_currentStart.y - 5, LI_currentStart.x + 5, LI_currentStart.y + 5, endPoint.x + 5, endPoint.y + 5, endPoint.x - 5, endPoint.y - 5];\r\n }\r\n else if (LI_currentStart.x < endPoint.x) {\r\n polyPts = [LI_currentStart.x - 5, LI_currentStart.y + 5, LI_currentStart.x + 5, LI_currentStart.y - 5, endPoint.x + 5, endPoint.y - 5, endPoint.x - 5, endPoint.y + 5];\r\n }\r\n else if (LI_currentStart.x == endPoint.x) {\r\n polyPts = [LI_currentStart.x - 5, LI_currentStart.y, LI_currentStart.x + 5, LI_currentStart.y, endPoint.x + 5, endPoint.y, endPoint.x - 5, endPoint.y];\r\n }\r\n //Used to show hitarea for testing purposes\r\n // var pGraphic = new PIXI.LI_graphics();\r\n // pGraphic.beginFill(0x1C2833);\r\n // pGraphic.drawPolygon(polyPts);\r\n // app.stage.addChild(pGraphic);\r\n lineImage.hitArea = new PIXI.Polygon(polyPts);\r\n windowContainer.addChild(lineImage);\r\n //contructs line object\r\n LI_currentStart.image\r\n .on(\"pointerdown\", LI_onDragPointStart)\r\n .on(\"pointerup\", LI_onDragPointEnd)\r\n .on(\"pointerupoutside\", LI_onDragPointEnd)\r\n .on(\"pointermove\", LI_onDragPointMove);\r\n endPoint.image\r\n .on(\"pointerdown\", LI_onDragPointStart)\r\n .on(\"pointerup\", LI_onDragPointEnd)\r\n .on(\"pointerupoutside\", LI_onDragPointEnd)\r\n .on(\"pointermove\", LI_onDragPointMove);\r\n LI_currentLine = new Line(LI_currentStart, endPoint, LI_backgroundImage, LI_lineContainer.length, lineImage);\r\n //Calls data functions to show user the results on the line they drew\r\n LI_currentLine.displayDetails(windowContainer); //Displays the details of the line by fetching its information\r\n\r\n createGraph(LI_graphs, LI_currentLine, LI_boundary_tlx, LI_boundary_tly); //Creates a graph from said line\r\n windowContainer.addChild(LI_graphs);\r\n LI_lineContainer.push(LI_currentLine); //Adds this line to the area of lines\r\n LI_drawing = false; //Ends the LI_drawing LI_state\r\n LI_endDraw();\r\n\r\n }//end else\r\n // }//end LI_cancel if\r\n }// end active if\r\n\r\n}", "drawPolygone(){\n\t\tfor(let i = 0; i < this.lines.length; i++ ){\n\n\t\t\tlet x1 = this.lines[i].x;\n\t\t\tlet\ty1 = this.lines[i].y;\n\n\t\t\tif(this.lines[i+1]){\n\t\t\t\tlet\tx2 = this.lines[i+1].x;\n\t\t\t\tlet\ty2 = this.lines[i+1].y;\n\t\t\t\tthis.moveTo(x1, y1);\n\t\t\t\tthis.lineTo(x2, y2);\n\t\t\t}else{\n\t\t\t\tthis.lineTo(this.lines[0].x, this.lines[0].y);\n\t\t\t}\n\t\n\t\t}\n\t}", "function plot_preprogrammed_route()\r\n{\r\n var route = google.maps.geometry.encoding.decodePath(route_line)\r\n var start = route[0];\r\n var end = route[route.length - 1];\r\n var start = new google.maps.Marker({\r\n position: start,\r\n map: map,\r\n title: \"Route Start\"\r\n });\r\n var end = new google.maps.Marker({\r\n position: end,\r\n map: map,\r\n title: \"Route End\"\r\n });\r\n var poly = new google.maps.Polyline({\r\n map: map,\r\n path: route,\r\n strokeColor: '#0000FF',\r\n strokeOpacity: 0.8,\r\n strokeWeight: 3\r\n });\r\n}", "function maybeSetupPolyline(step) {\n setupTextSlidePreserveMap();\n showSite();\n if (!polyline) {\n polyline = new GPolyline([]); \n map.addOverlay(polyline);\n polyline.enableDrawing();\n if (step > 0) {\n GEvent.bind(polyline, \"mouseover\", polyline, \n\t\t polyline.enableEditing);\n GEvent.bind(polyline, \"mouseout\", polyline, \n\t\t polyline.disableEditing);\n }\n if (step > 1) {\n GEvent.addListener(polyline, \"click\", \n\t\t\t function (latlng, index) {\n if (index === 0) {\n\t polyline.enableDrawing({\"fromStart\": true});\n\t} else if (index == polyline.getVertexCount() - 1) {\n\t polyline.enableDrawing({\"fromStart\": false});\n\t}\n });\n }\n }\n map.addOverlay(polyline);\n}", "function drawSnake() {\n // loop through the snake parts drawing each part on the canvas\n snake.forEach(drawSnakePart)\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows the clear filter button for the given tag.
function showClearFilterBtn(tag) { forEach(".clear-filter-text", function (node) { node.innerHTML = "filter on " + tag; }); SetNodesVisibility(".clear-filter", true); }
[ "function clearFiltering() {\n document.getElementById(\"filter-container\").innerHTML = \"\";\n }", "function clearFilter() {\n for (var i = 0; i < allProducts.length; i++) {\n allProducts[i].style.display = \"block\";\n }\n\n // display filder button\n filterButton.style.display = \"none\";\n }", "function clearFilterClick() {\n filterBar.value = '';\n clearFilter();\n}", "function filterClear(){\r\n\t\tg_searchText = \"\";\r\n\t\tjQuery('.uc-catdialog-button-clearfilter').val('');\r\n\t\tloadCats();\r\n\t}", "function hideClearFilterBtn() {\n SetNodesVisibility(\".clear-filter\", false);\n}", "clearFiltersAndShow() {\n this.clearFilters(true);\n this.show();\n }", "function clearFilters() {\n genderFilter();\n $('#day-filter-btn').html(\"Any Location\")\n $('#city-filter-btn').html(\"Any Day\")\n $('#childcare-filter-btn').html(\"Childcare\")\n }", "function displayResetFilter(){\n \n resetSearchButton.css({\"visibility\":\"visible\"});\n \n if( regionInput.val() === \"*\" && periodInput.val() === \"*\" && $(topicsElement).val() === null ) {\n \n resetSearchButton.css({\"visibility\":\"hidden\"});\n \n }\n \n }", "hideClearButtonOfProductsSearchForm() {\n this.getProductsSearchBar().clearButton.style.display = \"none\";\n }", "function clearFilterText() {\n vm.filterText = \"\";\n }", "function onClearSearch() {\n $('#search').val('');\n $('#types .btn-primary').removeClass('btn-primary').addClass('btn-light');\n $('#clear-filter').fadeOut();\n $('#items').children().fadeIn();\n $('#items').unmark();\n }", "clearFilter() {\n this.scope['filterName'] = null;\n this.setFilterFunction(null);\n // this.updateSize_(false);\n }", "renderClearButton() {\n if (this.state.showClearButton) {\n return (\n <button onClick={this.clearSearchValue} >\n <IconComponent iconName=\"times\" iconColor=\"gray\" className=\"clear-icon\"></IconComponent>\n </button>\n );\n }\n }", "registerClearFilterButton() {\n\t\tconst sidebar = this.getSidebarView(),\n\t\t\tclearBtn = this.calendarView.find('.js-calendar__clear-filters');\n\t\tapp.showPopoverElementView(clearBtn);\n\t\tclearBtn.on('click', () => {\n\t\t\t$('.js-calendar__extended-filter-tab a').removeClass('active');\n\t\t\tapp.moduleCacheSet('CurrentCvId', null);\n\t\t\tapp.setMainParams('showType', 'current');\n\t\t\tapp.moduleCacheSet('defaultShowType', 'current');\n\t\t\tsidebar.find('input:checkbox').prop('checked', false);\n\t\t\tsidebar.find('option:selected').prop('selected', false).trigger('change.select2');\n\t\t\tsidebar.find('.js-sidebar-filter-container').each((_, e) => {\n\t\t\t\tlet element = $(e);\n\t\t\t\tlet cacheName = element.data('cache');\n\t\t\t\tif (element.data('name') && cacheName) {\n\t\t\t\t\tapp.moduleCacheSet(cacheName, '');\n\t\t\t\t}\n\t\t\t});\n\t\t\tlet calendarSwitch = sidebar.find('.js-switch--showType [class*=\"js-switch--label\"]'),\n\t\t\t\tactualUserCheckbox = sidebar.find('.js-input-user-owner-id[value=' + app.getMainParams('userId') + ']');\n\t\t\tcalendarSwitch.last().removeClass('active');\n\t\t\tcalendarSwitch.first().addClass('active');\n\t\t\t$('input[data-val=\"current\"]', calendarSwitch).prop('checked', true);\n\t\t\tif (actualUserCheckbox.length) {\n\t\t\t\tactualUserCheckbox.prop('checked', true);\n\t\t\t} else {\n\t\t\t\tapp.setMainParams('usersId', undefined);\n\t\t\t}\n\t\t\tthis.reloadCalendarData();\n\t\t});\n\t}", "function clearFilterTags() {\n\t\t$('.location-filter-wrap').find(':checked').prop(\"checked\", false);\n\t\tclearBtnState();\n\t}", "renderClearButton() {\n const { formId, onClear } = this.props;\n return (\n <Button\n aria-controls={formId}\n onClick={onClear}\n className=\"search-box__clear\"\n title={i18n._t('Admin.CLEAR', 'Clear')}\n >{i18n._t('Admin.CLEAR', 'Clear')}</Button>\n );\n }", "function clearTag(){\n document.getElementById(\"tagDiv\").innerHTML = \"\";\n }", "function CreateClearButton(sID) {\n var sClearButtonElement = document.getElementById(sID + '-clear-button'); // get the clear button elements\t\n if (sClearButtonElement) // is already there?\n {\n sClearButtonElement.style.cssText = 'display:block'; // ensure to show\n return;\n }\n //\n // Create the clear button\n //\n var sFilterHeaderElement = document.getElementById(sID);\n if (sFilterHeaderElement) {\n var sClearButton = '<a href=\\'javascript:ClearFilterOptions(\\\"' + sID + '\\\");\\' id=\"' + sID + '-clear-button\" class=\"clear-button\">Clear</a>';\n sFilterHeaderElement.innerHTML = sFilterHeaderElement.innerHTML + sClearButton;\n }\n}", "function clearFilter() {\n filterBar.disabled = false;\n filterType.disabled = false;\n markers.filtered = null;\n setFilterParam('none', '');\n\n updateVisibleMarkers();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if mouse is clicked and if the mouse pointer is inside the playbutton.
function checkIfButtonClicked() { // if the mouse pointer is inside the play button then switch the state to level. if (mouseIsPressed && collidePointCircle(mouseX, mouseY, width / 2, height / 2, width / 6)) { state = "level"; clickSound.play(); } // check if store is clicked if it is then change state to store. if (mouseIsPressed && collidePointCircle(mouseX, mouseY, width / 1.059, height / 1.1, width / 15)) { storeSound++; if (storeSound === 1) { clickSound.play(); } state = 'store'; } }
[ "function mouseClicked() {\n if (mouseX > width / 3 &&\n mouseX < 2 * width / 3 &&\n mouseY > height / 1.3 &&\n mouseY < height / 1.1) {\n sliderDotX = mouseX;\n mySongLength = mySong.duration();\n var timeStamp = map(sliderDotX, width / 3, 2 * width / 3, 0, mySongLength);\n mySong.jump(timeStamp);\n } else if (mouseX > width / 3.15 - 20 &&\n mouseX < width / 3.15 + 5 &&\n mouseY > height / 1.3 &&\n mouseY < height / 1.1) {\n //If the play button is clicked, the song start and stop\n if (mySong.isPlaying()) {\n mySong.pause();\n } else {\n mySong.loop();\n }\n }\n}", "function mousePressed() {\n playing = true;\n }", "function mouseClicked() {\n // If it has been clicked return true\n return true;\n }", "checkMouseClick(){\n\n // checking if mouse is inside tile\n if(this.mouseInside()){\n\n // checking if mouse is both down and also has not been accounted for\n if(Util.mouse().down && !this.clicking){\n // setting trap\n this.clicking = true;\n return this.clicking;\n }\n\n // checking for mouse release actual \"click\" event\n if(!Util.mouse().down && this.clicking){\n // resetting trap\n this.clicking = false;\n return this.clicking;\n }\n\n }\n\n return false;\n\n }", "function mouseClicked(){\n if(!start && !gameOver && isRectClicked('start') ) {\n\t\tstart = true;\n\t\tgameOver = false;\n\t\tmySoundSFX.play();\n }\n\tif( gameOver && isRectClicked('gameOver') ){ \n\t\tinitialiseGame();\n\t\tgameOver = false;\n\t\tstart = false;\n\t}\n\n if(isRectClicked('sound')){\n if(basicVolume > 0 ){\n basicVolume = 0;\n }else{\n basicVolume = 0.1;\n }\n }\n}", "function containsMouse(mouse,that) \n\t{\n\t\t//was originally having object access issues, this can be cleaned up later\n\t\tvar mx = mouse.x;\n\t\tvar my = mouse.y;\n\t\t\n\t\t//if the mouse coords are within the button return true\n\t\tif(mx > that.position.x - that.size.x/2 && mx < that.position.x + that.size.x/2\n\t\t\t&& my > that.position.y - that.size.y/2 && my < that.position.y + that.size.y/2)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t\t\t\n\t}", "function mousePressed() {\n videoPlayback.mousePressed();\n}", "static isMousePressed() {\n return Input.mousePressed && !Input.mouseDisabled;\n }", "function mouseOverGUI() {\n\tfor (var i = 0; i < buttons.objectList.length; i++) {\n\t\t//use mouseDownOnButton rather than releasedThisFrame because button activates on mouse release, whereas task selection here activates on mouse press\n\t\tif (buttons.objectList[i].visible && collisionPoint(GameManager.mousePos.x,GameManager.mousePos.y,\n\t\t\t\tbuttons.objectList[i],buttons.objectList[i].affectedByCamera)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function mousePressed() {\n // Check if the mouse is in the x range of the target\n if (mouseX > targetX - targetSizeX/2 && mouseX < targetX + targetSizeX/2) {\n // Check if the mouse is also in the y range of the target\n if (mouseY > targetY - targetSizeY/2 && mouseY < targetY + targetSizeY/2) {\n gameOver = true;\n }\n }\n}", "function isOverButton() {\n\t\tif (!Number.isInteger(mouseX) || !Number.isInteger(mouseY)) return false;\n\t\t\n\t\treturn (\n\t\t\tmouseX >= x &&\n\t\t\tmouseX <= x + width &&\n\t\t\tmouseY >= y &&\n\t\t\tmouseY <= y + height\n\t\t);\n\t}", "function mousePressed() {\n if (showGameOver) { //if its game over reset the game\n resetGame();\n }\n if (showGameWin) {\n resetGame();\n } else if (gameStart === false) {\n gameStart = true;\n //intro sound (small one before the music)\n clickButton.play();\n //loops music\n mainMusic.loop();\n }\n}", "function mousePressed() {\n if (showGameOver) { //if its game over reset the game\n resetGame();\n }\n if (showGameWin) {\n resetGame();\n } else if (gameStart === false) {\n gameStart = true;\n //intro sound (small one before the music)\n clickButton.play();\n //loops music\n // mainMusic.loop();\n }\n}", "function mousePressed(){\n if(((mouseX >= 320 && mouseY >= 402) && (mouseX <= 371 && mouseY <= 425)) || ((mouseX <= 294 && mouseY >= 402) && (mouseX >= 237 && mouseY <= 425))){\n difEyebrow = !difEyebrow;\n }\n}", "function mousePressed() {\n\tgood = checkDur();\n\tcanBreak = !overLink;\n}", "function mousePressed() {\n //Allows for the buttons to be used, alongside the state they change to when\n //pressed on.\n\n //The play button to start the game\n if (\n mouseX > play.x &&\n mouseX < play.x + play.w &&\n mouseY > play.y &&\n mouseY < play.y + play.h &&\n state === `title`\n ) {\n state = `inGame`;\n }\n\n //The button to look at the instructions\n if (\n mouseX > howToPlay.x &&\n mouseX < howToPlay.x + howToPlay.w &&\n mouseY > howToPlay.y &&\n mouseY < howToPlay.y + howToPlay.h &&\n state === `title`\n ) {\n state = `howToPlay`;\n }\n\n //A \"back\" button, so you can move back to the menu and play\n if (\n mouseX > backToMenu.x &&\n mouseX < backToMenu.x + backToMenu.w &&\n mouseY > backToMenu.y &&\n mouseY < backToMenu.y + backToMenu.h &&\n state === `howToPlay`\n ) {\n state = `title`;\n } else if (state === `inGame`) {\n //Allows the player to shoot when it is the \"inGame\" state\n player.weaponAim();\n }\n}", "isClicked(_clickPosition) {\n let difference = new EIA2_Endaufgabe_HannahDuerr.Vector(_clickPosition.x - this.position.x, _clickPosition.y - this.position.y);\n //return true when the click overlapped with the player\n return (difference.length < this.radius);\n }", "function checkClick(Sprite) {\n if (mouseX > Sprite.x - Sprite.width / 2 &&\n mouseX < Sprite.x + Sprite.width / 2 &&\n mouseY > Sprite.y - Sprite.height / 2 &&\n mouseY < Sprite.y + Sprite.height / 2) {\n return true;\n }\n}", "function mousePressed()\n{\n \n //if (dsp == false) {\n //parent.stop();}\n //print('new click');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new JSA CAS Frame from the given binary avatar definition view.
static fromBin(avdv) { var frame; //------- frame = new CASFrame(); frame.setFromBin(avdv); return frame; }
[ "function makeIssueScanningFrame() {\n miro.board.widgets.create([\n {\n type: \"SHAPE\",\n style: {\n shapeType: 3,\n backgroundColor: \"#ffffff\",\n backgroundOpacity: 1,\n borderColor: \"transparent\",\n borderWidth: 24,\n borderOpacity: 1,\n borderStyle: 2,\n fontFamily: 10,\n textColor: \"#ffffff\",\n textAlign: \"l\",\n textAlignVertical: \"t\",\n fontSize: 50,\n bold: 0,\n italic: 0,\n underline: 0,\n strike: 0,\n highlighting: \"\",\n },\n x: -4781.387461938883,\n y: 1068.9953430335418,\n width: 3728.72123191848,\n height: 2081.64518335326\n },\n\n {\n type: \"TEXT\",\n x: \"-4797\",\n y: \"-120\",\n width: 710,\n scale: 5.213,\n text: \"<p><strong>The Business Model Canvas</strong></p>\",\n plainText: \"The Business Model Canvas\",\n },\n\n {\n type: \"frame\",\n x: -4781.387461938883,\n y: 1072.929022366622,\n width: bmcWidth,\n height: bmcHeight,\n // title: \"Business Model Canvas\",\n capabilities: {\n editable: false,\n },\n style: {\n backgroundColor: \"#ffffff\",\n },\n },\n ]);\n}", "function createFrame(user) {\n const row = $(\"#user-frame-row\");\n const div = $(\"#user-frame-box-\" + user.login);\n const buttonImg = document.createElement(\"img\");\n buttonImg.setAttribute(\"class\", \"add-user-button\");\n buttonImg.src = ADD_USER_BUTTON;\n const a = document.createElement(\"a\");\n a.setAttribute(\"class\", \"user-frame-image\");\n a.id = user.login.split(' ').join('-') + \"-frame\";\n const avatar = document.createElement(\"img\");\n avatar.setAttribute(\"class\", \"rounded-circle img-fluid d-block mx-auto frame-avatar\");\n avatar.src = user.avatar_url;\n a.appendChild(avatar);\n deleteLoading(user.login);\n\n //append new elements\n div.append(buttonImg);\n div.prepend(a);\n\n //attach user to the frame\n $(\"#\" + a.id).data(a.id, user);\n }", "static fromXML(frmel) {\nvar frame;\n//-------\nframe = new CASFrame();\nframe.setFromXML(frmel);\nreturn frame;\n}", "createAvatar() {\n this.avatar = new Avatar(this.camera, this);\n }", "function createFrame(service) {\n var frame = document.createElement('iframe');\n frame.setAttribute('src', 'https://bitlabs.nl/mopify/auth/' + service + '/frame/#' + window.location.host);\n frame.style.width = 1 + 'px';\n frame.style.height = 1 + 'px';\n // Add to body and register in frames object\n body.append(frame);\n return frame;\n }", "static create(time, dur, bones, morphs) {\nvar frame;\n//------\nframe = new CASFrame();\nframe.set(time, dur, bones, morphs);\nreturn frame;\n}", "function _createAvatar(k){\n \tvar w=k.parent;\n \tvar d = document.createElement('div'),\n s = d.style,\n dn = w.parent.parent.domNode;\n d.className = \"mstrmojo-qb-avatar\";\n dn.appendChild(d);\n w.avatar = d;\n return d;\n }", "createAvatar(obj) {\n return new VideoAvatar(this.scene, null, this.customOptions);\n }", "function makeIssueScanningFrame() {\n miro.board.widgets.create([\n {\n type: \"frame\",\n x: -4684,\n y: 979,\n width: bmcWidth,\n height: bmcHeight,\n style: {\n backgroundColor: \"#ffffff\",\n },\n },\n ]);\n}", "function createOuiseoFrame() {\n var frame = document.createElement('div');\n frame.id = 'ouiseo_frame';\n return frame;\n }", "create(options) {\n if (!this.instance) {\n this.instance = new RB.DraftReviewBannerView(options);\n this.instance.render();\n }\n\n return this.instance;\n }", "function FrameImpl(params) {\n var command = params.command, headers = params.headers, body = params.body, binaryBody = params.binaryBody, escapeHeaderValues = params.escapeHeaderValues, skipContentLengthHeader = params.skipContentLengthHeader;\n this.command = command;\n this.headers = Object.assign({}, headers || {});\n if (binaryBody) {\n this._binaryBody = binaryBody;\n this.isBinaryBody = true;\n }\n else {\n this._body = body || '';\n this.isBinaryBody = false;\n }\n this.escapeHeaderValues = escapeHeaderValues || false;\n this.skipContentLengthHeader = skipContentLengthHeader || false;\n }", "function zoto_photo_frame(options){\n\tthis.options = options||{};\n\tthis.box_height = this.options.height || 100;\n\tthis.box_width = this.options.width || 100;\n\tthis.spacer_src = this.options.spacer_src || '/image/clear.gif';\n\t\n\tthis.el = SPAN({'class':'photo_frame'});\n\t\n\tthis.__init = false;\n\tthis.__name = 'zoto_photo_frame';\n}", "function creatingView(bgColor, widthValue, heightValue, topValue, leftValue, rightValue, bottomValue){\n \n var universalView = Ti.UI.createView({\n backgroundColor: \"#fff\",\n width: widthValue,\n height: heightValue,\n top: topValue,\n left: leftValue,\n right: rightValue,\n bottom: bottomValue\n });\n \n return universalView;\n}", "function creatingView(bgColor, widthValue, heightValue, topValue, leftValue, rightValue, bottomValue){\n \n var universalView = Ti.UI.createView({\n backgroundColor: \"#fff\",\n width: widthValue,\n height: heightValue,\n top: topValue,\n left: leftValue,\n right: rightValue,\n bottom: bottomValue\n });\n \n return universalView;\n}", "function getViewObject(tabsFrame){\n var fileToConvert = tabsFrame.fileToConvert;\n var originalView = tabsFrame.fileContents;\n var fileExt = fileToConvert.substring((fileToConvert.length - 5), (fileToConvert.length));\n \n // if *.axvw file...\n if (fileExt.toUpperCase() == \".AXVW\") {\n // remove any non-essential titles (PDF, XLS, etc)\n originalView = removeNonEssentialTitles(originalView);\n \n // convert the string to a DOM object \n var domObject = getViewAsDOM(originalView);\n \n // un-nest afmTableGroups\n originalView = preprocessView(domObject);\n \n // get the titles\n var titles = getTitles(domObject);\n }\n \n // process the view, converting it a view object\n var myView = new Ab.ViewDef.View();\n if ((originalView != undefined) && (originalView != null) && (originalView != \"\")) {\n var myConverter = new Ab.ViewDef.Convert(originalView, \"myView\");\n myConverter.convertDo();\n var convertedContents = myConverter.getConvertedContentsAsJavascript();\n if (myConverter.hasUnconvertableSections()) \n alert(myConverter.getDescriptionOfUnconvertableSections());\n eval(convertedContents);\n }\n \n return {\n viewObj: myView,\n viewTitles: titles\n };\n}", "static fromJSON(jsnframe) {\nvar frame;\n//--------\nframe = new CASFrame();\nframe.setFromJSON(jsnframe);\nreturn frame;\n}", "function makePictureFrame() {\n // Calculate rotation necessary to face picture towards user at spawn time.\n var rotation = Quat.multiply(Quat.fromPitchYawRollDegrees(0, 180, 0), Camera.getOrientation());\n rotation.x = 0;\n rotation.z = 0;\n var data = getDataFromNASA();\n var pictureFrameProperties = {\n name: 'Tutorial Picture Frame',\n description: data.explanation,\n type: 'Model',\n dimensions: {\n x: 1.2,\n y: 0.9,\n z: 0.075\n },\n position: center,\n rotation: rotation,\n textures: JSON.stringify({\n Picture: data.url\n }),\n modelURL: MODEL_URL,\n lifetime: 3600,\n dynamic: true,\n }\n var pictureFrame = Entities.addEntity(pictureFrameProperties);\n\n var OUTER_FRAME_MODEL_URL = \"http://hifi-production.s3.amazonaws.com/tutorials/pictureFrame/outer_frame.fbx\";\n var outerFrameProps = {\n name: \"Tutorial Outer Frame\",\n type: \"Model\",\n position: center,\n rotation: rotation,\n modelURL: OUTER_FRAME_MODEL_URL,\n lifetime: 3600,\n dynamic: true,\n dimensions: {\n x: 1.4329,\n y: 1.1308,\n z: 0.0464\n },\n parentID: pictureFrame // A parentd object will move, rotate, and scale with its parent.\n }\n var outerFrame = Entities.addEntity(outerFrameProps);\n Script.stop();\n}", "function buildAvatar() {\n\t\tlet canvas = document.getElementById(\"canvas\");\n\t\tlet ctx = canvas.getContext(\"2d\");\n\n\n\t\t// DRAW\n\t\t// Here we need to think about the ORDER in which we're going to put the parts of the images : HEAD first then EYES because they come in front : HEAD >>> EYES\n\n\t\t//DRAW BACKHAIR\n\t\tctx.drawImage(avatarBackhair, (800 - avatarBackhair.width) / 2, 130);\n\n\t\t// DRAW HEAD\n\t\tctx.drawImage(avatarHead, (800 - avatarHead.width) / 2, 125); // center elements horizontally - x axis, then y axis\n\n\t\t// DRAW HAIR\n\t\tctx.drawImage(avatarHair, (800 - avatarHair.width) / 2, 25);\n\n\t\t// DRAW EYES\n\t\tctx.drawImage(avatarEyes, (800 - avatarEyes.width) / 2, 300);\n\n\t\t// DRAW MOUTH\n\t\tctx.drawImage(avatarMouth, (800 - avatarMouth.width) / 2, 520);\n\n\t\t//DRAW NOSE\n\t\tctx.drawImage(avatarNose, (800 - avatarNose.width) / 2, 350);\n\n\t\t//DRAW MASK\n\t\tctx.drawImage(avatarMask, (800 - avatarMask.width) / 2, 480);\n\n\t\t// DRAW CLOTHING\n\t\tctx.drawImage(avatarClothing, (800 - avatarClothing.width) / 2, 700);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: generateDynamicDataRef DESCRIPTION: Returns a dynamic binding string. ARGUMENTS: sourceName string the name of the dynamic source returned from the findDynamicSources function bindingName string the name of a dynamic source binding returned from generateDynamicSourceBindings RETURNS: string the code to insert on the page
function generateDynamicDataRef(sourceName, bindingName, dropObject) { var paramObj = new Object(); paramObj.bindingName = bindingName; var retStr = extPart.getInsertString("", "URL_DataRef", paramObj); if (dwscripts.canStripScriptDelimiters(dropObject, true)) { retStr = dwscripts.stripScriptDelimiters(retStr, true); } return retStr; }
[ "function generateDynamicDataRef(sourceName, bindingName, dropObject)\n{\n var retVal = \"\";\n var sbObj = null;\n \n // First check if this recordset datasource is returned from a stored procedure. If so,\n // get the stored procedure SB object which returns the recordset. Otherwise,\n // just grab the associated recordset SB. \n sbObj = getStoredProcedureFromDSTitle(sourceName);\n if (!sbObj)\n {\n var sbObjs = dwscripts.getServerBehaviorsByTitle(sourceName);\n if (sbObjs.length > 0) \n {\n sbObj = sbObjs[0];\n }\n }\n\n if (sbObj)\n {\n var paramObj = new Object();\n paramObj.sourceName = sbObj.getRecordsetName();\n paramObj.bindingName = bindingName;\n\n retVal = extPart.getInsertString(\"\", \"Recordset_DataRef\", paramObj);\n }\n \n // We need to strip the cfoutput tags if we are inserting into a CFOUTPUT tag\n // or binding to the attributes of a ColdFusion tag.\n if (dwscripts.canStripCfOutputTags(dropObject, true))\n {\n retVal = dwscripts.stripCFOutputTags(retVal, true);\n } \n\n return retVal;\n}", "function generateDynamicDataRef(elementName,bindingName,dropObject)\n{\n var retStr=\"\";\n\n var ssRec = findSSrecByTitle(elementName,\"command\")\n if (!ssRec) return retStr;\n\n var tokenindex = bindingName.indexOf(\".\");\n if (tokenindex != -1) \n {\n elementName = bindingName.substring(0,tokenindex);\n bindingName = bindingName.substring(tokenindex+1);\n }\n \n if (ssRec.recordset)\n {\n if ((bindingName == MM.LABEL_FirstRecordIndex) || (bindingName == MM.LABEL_LastRecordIndex) || (bindingName == MM.LABEL_TotalRecordIndex)) \n {\n // Recordset statistics. These are useful when the page \n // is being used for navigation through a large set of records.\n // Typically you add some text to the page that says something\n // like:\n // Records 10 to 15 of 63\n // where 10 corresponds to [first record index]\n // 15 corresponds [last record index]\n // 63 corresponds [total records]\n\n if (bindingName == MM.LABEL_FirstRecordIndex) \n {\n retStr = \"<%= (\" + elementName + \"_first\" + \") %>\";\n }\n else if (bindingName == MM.LABEL_LastRecordIndex) \n {\n retStr = \"<%= (\" + elementName + \"_last\" + \") %>\";\n }\n else if (bindingName == MM.LABEL_TotalRecordIndex) \n {\n retStr = \"<%= (\" + elementName + \"_total\" + \") %>\";\n }\n }\n else \n {\n retStr = \"<%= \" + elementName + \".Fields.Item(\\\"\" + bindingName + \"\\\").Value\" + \" %>\";\n }\n }\n else\n {\n retStr = \"<%= \" + elementName + \".Parameters.Item(\\\"\" + bindingName + \"\\\").Value\" + \" %>\";\n }\n\n // If the string is being inserted inside a script block, strip the\n // script delimiters.\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n\n return retStr;\n}", "function generateDynamicSourceBindings(sourceName)\r\n{\r\n var retVal = new Array();\r\n\r\n var siteURL = dw.getSiteRoot();\r\n\r\n //For localized object name\r\n if (sourceName != \"URL\")\r\n {\r\n sourceName = \"URL\";\r\n }\r\n\r\n if (siteURL.length)\r\n {\r\n var bindingsArray = dwscripts.getListValuesFromNote(siteURL, sourceName);\r\n retVal = getDataSourceBindingList(bindingsArray, \r\n DATASOURCELEAF_FILENAME,\r\n true,\r\n \"URL.htm\");\r\n }\r\n\r\n return retVal;\r\n}", "function generateDynamicDataRef(elementName,bindingName,dropObject)\n{\n retStr = \"<%= Session(\\\"\" + bindingName + \"\\\") %>\";\n\n // If the string is being inserted inside a script block, strip the\n // script delimiters.\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n\n return retStr;\n}", "function generateDynamicDataRef(elementName,bindingName,dropObject)\n{\n var retStr = \"\";\n\n var re = /^Form\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n retStr = \"<%= Request.Form(\\\"\" + RegExp.$1 + \"\\\") %>\";\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n return retStr;\n }\n \n var re = /^Cookies\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n retStr = \"<%= Request.Cookies(\\\"\" + RegExp.$1 + \"\\\") %>\";\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n return retStr;\n }\n\n var re = /^QueryString\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n retStr = \"<%= Request.QueryString(\\\"\" + RegExp.$1 + \"\\\") %>\";\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n return retStr;\n }\n\n\n var re = /^ServerVariables\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n retStr = \"<%= Request.ServerVariables(\\\"\" + RegExp.$1 + \"\\\") %>\";\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n return retStr;\n }\n\n var re = /^ClientCertificate\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n retStr = \"<%= Request.ClientCertificate(\\\"\" + RegExp.$1 + \"\\\") %>\";\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n return retStr;\n }\n\n retStr = \"<%= Request(\\\"\" + bindingName + \"\\\") %>\";\n if (dwscripts.canStripScriptDelimiters(dropObject))\n retStr = dwscripts.stripScriptDelimiters(retStr);\n return retStr;\n}", "function generateDynamicSourceBindings(elementName)\n{\n var BindingsArray = new Array();\n var outArray;\n\n var dom = dw.getDocumentDOM();\n if (dom) {\n var fileURL = dom.URL;\n if (!fileURL.length)\n fileURL = dwscripts.getTempURLForDesignNotes();\n if (fileURL.length){\n\n getValuesFromNote(fileURL,BindingsArray,\"Request\",\"requestCount\");\n\n var FormVarArray = new Array();\n getValuesFromNote(fileURL,FormVarArray,\"RequestQString\",\"requestQStringCount\");\n for (var fvar=0;fvar < FormVarArray.length ;fvar++) {\n BindingsArray.push(\"QueryString.\" + FormVarArray[fvar]);\n }\n\n\n var FormVarArray = new Array();\n getValuesFromNote(fileURL,FormVarArray,\"RequestForm\",\"requestFormCount\");\n for (var fvar=0;fvar < FormVarArray.length ;fvar++) {\n BindingsArray.push(\"Form.\" + FormVarArray[fvar]);\n }\n\n var CookieVarArray = new Array();\n getValuesFromNote(fileURL,CookieVarArray,\"RequestCookie\",\"requestCookieCount\");\n for (var cvar=0;cvar < CookieVarArray.length ;cvar++) {\n BindingsArray.push(\"Cookies.\" + CookieVarArray[cvar]);\n }\n\n var ServerVarArray = new Array();\n getValuesFromNote(fileURL,ServerVarArray,\"RequestServerVar\",\"requestServerVarCount\");\n for (var svar=0;svar < ServerVarArray.length ;svar++) {\n BindingsArray.push(\"ServerVariables.\" + ServerVarArray[svar]);\n }\n\n var CertArray = new Array();\n getValuesFromNote(fileURL,CertArray,\"RequestCert\",\"requestCertCount\");\n for (var ctvar=0;ctvar < CertArray.length ;ctvar++) {\n BindingsArray.push(\"ClientCertificate.\" + CertArray[ctvar]);\n }\n\n outArray = GenerateObjectInfoForSourceBindings(BindingsArray, datasourceleaf_filename, \"Request.htm\",\"\");\n }\n }\n \n return outArray;\n\n}", "function generateDynamicSourceBindings(sourceName)\n{\n var retList = new Array();\n var sbObj = null;\n \n // First check if this recordset datasource is returned from a stored procedure. If so,\n // get the stored procedure SB object which returns the recordset. Otherwise,\n // just grab the associated recordset SB. \n sbObj = getStoredProcedureFromDSTitle(sourceName);\n if (!sbObj)\n {\n var sbObjs = dwscripts.getServerBehaviorsByTitle(sourceName);\n if (sbObjs.length > 0) \n {\n sbObj = sbObjs[0];\n }\n }\n \n if (sbObj) \n {\n var bindingsArray = new Array();\n\n //Try to retrieve the information from database\n var bindingsAndTypeArray = sbObj.getRecordsetBindings();\n\n //pull out only the binding information\n for (var i=0; i < bindingsAndTypeArray.length; i+=2) \n {\n bindingsArray.push(bindingsAndTypeArray[i]);\n }\n \n retList = getDataSourceBindingList(bindingsArray, DATASOURCELEAF_FILENAME, false, \"Recordset.htm\");\n }\n\n return retList;\n}", "function inspectDynamicDataRef(expression)\r\n{\r\n var retArray = new Array();\r\n\r\n if(expression.length)\r\n {\r\n var params = extPart.findInString(\"URL_DataRef\", expression);\r\n if (params)\r\n {\r\n retArray[0] = \"URL\";\r\n retArray[1] = params.bindingName;\r\n }\r\n }\r\n \r\n return retArray;\r\n}", "function inspectDynamicDataRef(expression)\n{\n var retVal = new Array();\n\n if (expression.length)\n { \n var params = extPart.findInString(\"Recordset_DataRef\", expression);\n if (params)\n {\n // Find the original sbObject. Note that we look through recordsets and\n // stored procs since stored procs can return a recordset too.\n var sbObjs = dwscripts.getServerBehaviorsByFileName(\"Recordset.htm\");\n sbObjs = sbObjs.concat(dwscripts.getServerBehaviorsByFileName(\"CFStoredProc.htm\"));\n for (var i=0; i < sbObjs.length; i++)\n {\n if (sbObjs[i].getRecordsetName() == params.sourceName)\n {\n // Use different title if recordset vs. storedproc recordset.\n retVal[0] = (!sbObjs[i].isCallObject()) ? sbObjs[i].getTitle()\n : dwscripts.sprintf(MM.LABEL_StoredProcRecordset, params.sourceName);\n retVal[1] = params.bindingName;\n break;\n }\n }\n } \n }\n \n return retVal;\n}", "function generateDynamicSourceBindings(elementName)\n{\n var ssRec = findSSrecByTitle(elementName,\"command\")\n\n if (!ssRec)\n {\n\t var node = findSourceNode(elementName);\n\t if( !node ) return;\n\t \n\t ssRec = findSSrec(node,\"command\");\n\t if( !ssRec && node.previousSibling ) {\n\t\tssRec = findSSrec(node.previousSibling,\"command\");\n\t }\n } \n \n if (!ssRec) return;\n \n var BindingsArray = new Array();\n var outArray;\n \n var cdName = ssRec.cdName;\n \n var comDom = dreamweaver.getDocumentDOM(dreamweaver.getConfigurationPath() + \"/ServerBehaviors/ASP_VBS/Command2.htm\")\n \n //always get the return value first\n {\n CachedParametersArray = getCachedParametersArray(cdName);\n if (CachedParametersArray.length)\n {\n //we use +3 since our Parameter has name,type,direction\n for (var j=0; j < CachedParametersArray .length ; j+=3)\n {\n var dir = CachedParametersArray[j+1];\n if (dir == 4 || dir == 2 || dir == 3)\n {\n BindingsArray.push(CachedParametersArray[j]);\n }\n }\n }\n else\n {\n BindingsArray = comDom.parentWindow.getDynamicBindings(ssRec.selectedNode, true)\n\t\n\t var CachedParameterString = MMDB.getSPParamsAsString(ssRec.cname,ssRec.sql);\n SaveParametersForCache(cdName,CachedParameterString);\n }\n }\n \n //If this returns a recordset, get those values too\n if (ssRec.recordset)\n {\n CachedCTArray = getCachedColumnAndTypeArray(ssRec.recordset);\n if (CachedCTArray.length)\n {\n for (var j=0; j < CachedCTArray.length ; j+=2)\n {\n BindingsArray.push(ssRec.recordset + \".\" + CachedCTArray[j]);\n }\n }\n else\n {\n var colArray = new Array();\n colArray = comDom.parentWindow.getDynamicBindings(ssRec.selectedNode);\n SaveColumnAndTypeArrayForCache(ssRec.recordset,colArray);\n for (var cvar=0;cvar < colArray.length ;cvar+=2) \n {\n BindingsArray.push(ssRec.recordset + \".\" + colArray[cvar]);\n }\n }\n BindingsArray.push(ssRec.recordset + \".\"+ MM.LABEL_FirstRecordIndex);\n BindingsArray.push(ssRec.recordset + \".\"+ MM.LABEL_LastRecordIndex);\n BindingsArray.push(ssRec.recordset + \".\"+ MM.LABEL_TotalRecordIndex);\n }\n\n outArray = GenerateObjectInfoForSourceBindings(BindingsArray, datasourceleaf_filename, \"Command2\");\n \n return outArray;\n}", "function createDynamicData(rs, col)\n{\n var retVal = \"\";\n\n var retVal = \"\";\n if (rs){\n var colArray = dwscripts.getFieldNames(rs);\n if (dwscripts.findInArray(colArray, col) != -1){\n var paramObj = new Object();\n paramObj.sourceName = rs;\n paramObj.bindingName = col;\n\n retVal = extPart.getInsertString(\"\", \"Recordset_DataRef\", paramObj);\n }\n }\n return retVal;\n}", "function inspectDynamicDataRef(expression)\n{\n var retArray = new Array();\n if(expression.length) \n {\n // Quickly reject if the expression doesn't contain \"<%=\"\n var exprIndex = expression.indexOf(\"<%=\");\n if (exprIndex != -1)\n {\n // No need to search the string prior to the \"<%=\"\n expression = expression.substr(exprIndex);\n\n var TranslatorDOM = dreamweaver.getDocumentDOM(dreamweaver.getConfigurationPath() + \"/Translators/ASP.htm\");\n if (TranslatorDOM) \n {\n TranslatedStr = TranslatorDOM.parentWindow.miniTranslateMarkup(\"\", \"\", expression, false);\n if (TranslatedStr.length)\n {\n var found = TranslatedStr.search(/mm_dynamic_content\\s+source=(\\w+)\\s+binding=\"([^\"]*)\"/i)\n if (found != -1)\n {\n //map the name to node \n elementNode = findSourceNode(RegExp.$1);\n if (elementNode)\n {\n if (elementNode.tagName == \"MM_CMDRECSET\") \n {\n ///map the node to SSRec to get the title.\n parentNode = elementNode.parentNode;\n ssRec = findSSrec(parentNode,\"command\");\n } \n else \n {\n ssRec = findSSrec(elementNode,\"command\");\n }\n \n if (ssRec)\n { \n retArray[0] = ssRec.title;\n\n if (elementNode.tagName == \"MM_CMDRECSET\") \n {\n retArray[1] = RegExp.$1 + \".\" + RegExp.$2;\n } \n else \n {\n retArray[1] = RegExp.$2;\n }\n }\n }\n }\n //alert(\"source=\" + retArray[0] + \" binding=\" + retArray[1])\n }\n }\n }\n }\n return retArray;\n}", "function generateDynamicSourceBindings(elementName, singleArray)\n{\n var BindingsArray = new Array();\n var outArray;\n\n var siteURL = dw.getSiteRoot()\n\n if (siteURL.length){\n //For localized object name\n if (elementName != \"Session\") \n elementName = \"Session\"\n\n getValuesFromNote(siteURL,BindingsArray,elementName,\"sessionCount\");\n outArray = GenerateObjectInfoForSourceBindings(BindingsArray, datasourceleaf_filename, \"Session.htm\",\"\");\n }\n \n return outArray;\n\n}", "function inspectDynamicDataRef(expression)\n{\n var retArray = new Array();\n if(expression.length) {\n\n // Quickly reject if the expression doesn't contain \"<%=\"\n var exprIndex = expression.indexOf(\"<%=\");\n if (exprIndex != -1)\n {\n // No need to search the string prior to the \"<%=\"\n expression = expression.substr(exprIndex);\n\n var TranslatorDOM = dreamweaver.getDocumentDOM(dreamweaver.getConfigurationPath() + \"/Translators/ASP.htm\");\n if (TranslatorDOM) {\n TranslatedStr = TranslatorDOM.parentWindow.miniTranslateMarkup(\"\", \"\", expression, false);\n if (TranslatedStr.length)\n {\n var found = TranslatedStr.search(/mm_dynamic_content\\s+source=(\\w+)\\s+binding=\"([^\"]*)\"/i)\n if (found != -1)\n {\n retArray[0] = RegExp.$1\n retArray[1] = RegExp.$2\n //alert(\"source=\" + retArray[0] + \" binding=\" + retArray[1])\n }\n }\n }\n }\n }\n \n return retArray;\n}", "function deleteDynamicSource(sourceName, bindingName)\r\n{\r\n var siteURL = dw.getSiteRoot();\r\n \r\n if (siteURL.length)\r\n {\r\n //For localized object name\r\n if (sourceName != \"URL\")\r\n {\r\n sourceName = \"URL\";\r\n }\r\n\r\n dwscripts.deleteListValueFromNote(siteURL, sourceName, bindingName);\r\n }\r\n}", "function deleteDynamicSource(sourceName,bindingName)\n{\n var dom = dw.getDocumentDOM();\n if (dom) {\n var fileURL = dom.URL;\n if (!fileURL.length)\n fileURL = dwscripts.getTempURLForDesignNotes();\n if (fileURL.length){\n\n var re = /^Form\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n deleteValueFromNote(fileURL,\"requestFormCount\",\"RequestForm\",RegExp.$1);\n return;\n } \n\n var re = /^Cookies\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n deleteValueFromNote(fileURL,\"requestCookieCount\",\"RequestCookie\",RegExp.$1);\n return;\n } \n\n var re = /^QueryString\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n deleteValueFromNote(fileURL,\"requestQStringCount\",\"RequestQString\",RegExp.$1);\n return;\n }\n\n\n var re = /^ServerVariables\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n deleteValueFromNote(fileURL,\"requestServerVarCount\",\"RequestServerVar\",RegExp.$1);\n return;\n }\n\n var re = /^ClientCertificate\\.(\\w+)/i;\n index = bindingName.search(re);\n if (index != -1) {\n deleteValueFromNote(fileURL,\"requestCertCount\",\"RequestCert\",RegExp.$1);\n return;\n }\n\n\n deleteValueFromNote(fileURL,\"requestCount\",\"Request\",bindingName);\n } \n }\n}", "function editDynamicSource(sourceName, bindingName)\n{\n var bHandled = false;\n var sbObj = getStoredProcedureFromDSTitle(sourceName);\n if (!sbObj)\n {\n var sbObjs = dwscripts.getServerBehaviorsByTitle(sourceName);\n \n if (sbObjs.length > 0) \n {\n sbObj = sbObjs[0];\n }\n }\n\n if (sbObj)\n {\n\tdreamweaver.popupServerBehavior(sbObj); \n\tbHandled = true;\n }\n return bHandled;\n}", "static cfnDynamicReference(ref) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_CfnDynamicReference(ref);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.cfnDynamicReference);\n }\n throw error;\n }\n return new SecretValue(ref);\n }", "function addDynamicSource()\r\n{\r\n MM.retVal = \"\";\r\n MM.URLContents = \"\";\r\n dw.popupCommand(\"URL Variable\");\r\n\r\n if (MM.retVal == \"OK\")\r\n {\r\n var theResponse = MM.URLContents;\r\n\r\n if (theResponse.length)\r\n {\r\n var siteURL = dw.getSiteRoot();\r\n if (siteURL.length)\r\n {\r\n dwscripts.addListValueToNote(siteURL, \"URL\", theResponse); \r\n }\r\n else\r\n {\r\n alert(MM.MSG_DefineSite);\r\n }\r\n }\r\n else \r\n {\r\n alert(MM.MSG_DefineURL);\r\n }\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This class helps to play a collection of DIV child elements under a HTML element with id value refered by 'slideContainer'. To get the best effect, it is recommended to keep the child DIV elements hidden initially. For example: ....content comes here.... ... ... other slides come here ... ...
function Slideshow(slideContainer, options) { // private: input fields this.slideContainer = slideContainer; this.blurringPeriod = options.blurringPeriod; this.displayPeriod = options.displayPeriod; // private: internal variables this.slideIndex = 0; this.selectorExpression = "#"+slideContainer+" > div"; this.slideCount = $(this.selectorExpression).length; // private: internal methods this.fadeIn = ___Slideshow_fadeIn; this.fadeOut = ___Slideshow_fadeOut; // public: exposed operations this.play = ___Slideshow_play; }
[ "function generateSlides() {\n const parentEle = document.querySelector('#container');\n currentQContent = [dataVizPage[state.q_id], ...sharedContent]\n\n currentQContent.forEach((slide, i) => {\n const slideElement = document.createElement('div');\n //element position absolute\n slideElement.style.zIndex = `-${i}`;\n slideElement.style.position = 'absolute';\n slideElement.classList.add('slide');\n slideElement.setAttribute('id', `slide${state.q_id}-${i}`)\n if (i == 0) {\n slideElement.classList.add('center');\n } else {\n slideElement.classList.add('right');\n }\n slideElement.innerHTML = `${currentQContent[i].slide_text}`;\n parentEle.appendChild(slideElement);\n });\n\n}", "function initialize(){\r\n\t\t\t//set the appropriate zIndex to each slide\r\n\t\t\tslides.each(function(){\r\n\t\t\t\tzindex--;\r\n\t\t\t\t$(this).css({\r\n\t\t\t\t\t\"zIndex\": zindex\r\n\t\t\t\t});\r\n\t\t\t\t//hide the ones we don't need to display\r\n\t\t\t\tif(zindex<9996){\r\n\t\t\t\t\t$(this).hide();\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\t//display first 4 in the exact positions they should be displayed\r\n\t\t\t$(slides[0]).css({\r\n\t\t\t\tleft:'0px',\r\n\t\t\t\ttop:'0px',\r\n\t\t\t\twidth:slideWidth\r\n\t\t\t});\r\n\t\t\t$(slides[1]).css({\r\n\t\t\t\tleft:left1,\r\n\t\t\t\ttop:top1,\r\n\t\t\t\twidth:width1\r\n\t\t\t});\r\n\t\t\t$(slides[2]).css({\r\n\t\t\t\tleft:left2,\r\n\t\t\t\ttop:top2,\r\n\t\t\t\twidth:width2\r\n\t\t\t});\r\n\t\t\t$(slides[3]).css({\r\n\t\t\t\tleft:left3,\r\n\t\t\t\ttop:top3,\r\n\t\t\t\twidth:width3\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\t//create 3 divs to hover the slides, onclick would initiate the moving to particular slide and stopping the animation\r\n\t\t\t$(element).append('<div class=\"control\" id=\"firstControl\">&nbsp;</div>');\r\n\t\t\t$(\"#firstControl\").css({\r\n\t\t\t\tleft:slideWidth,\r\n\t\t\t\ttop:top1,\r\n\t\t\t\twidth: slideWidth*0.2,\r\n\t\t\t\theight: slideHeight*0.6\r\n\t\t\t});\r\n\t\t\t$(element).append('<div class=\"control\" id=\"secondControl\">&nbsp;</div>');\r\n\t\t\t$(\"#secondControl\").css({\r\n\t\t\t\tleft:slideWidth*1.2,\r\n\t\t\t\ttop:top2,\r\n\t\t\t\twidth: slideWidth*0.16,\r\n\t\t\t\theight:slideHeight*0.4\r\n\t\t\t});\r\n\t\t\t$(element).append('<div class=\"control\" id=\"thirdControl\"></div>');\r\n\t\t\t$(\"#thirdControl\").css({\r\n\t\t\t\tleft:slideWidth*1.36,\r\n\t\t\t\ttop:top3,\r\n\t\t\t\twidth: slideWidth*0.09,\r\n\t\t\t\theight:slideHeight*0.2\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\t$(\".control\").bind(\"click\",function(){\r\n\t\t\t\tif(autoplay){\r\n\t\t\t\t\tclearTimeout(t);\r\n\t\t\t\t\tclearTimeout(tempTimer);\r\n\t\t\t\t\tautoplay=false;\r\n\t\t\t\t\t$(\".pp\").attr(\"id\",\"play\");\r\n\t\t\t\t\t$(\".pp\").html(playLbl);\r\n\t\t\t\t}\r\n\t\t\t\tswitch($(this).attr('id')){\r\n\t\t\t\t\tcase 'firstControl':\r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'secondControl': \r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'thirdControl':\r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tanimateSlides();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\t//creating the play/pause button and it's functionality\r\n\t\t\tif(autoplay){\r\n\t\t\t\t$(element).append('<div id=\"pause\" class=\"pp\">Pause</div>');\r\n\t\t\t}else{\r\n\t\t\t\t$(element).append('<div id=\"play\" class=\"pp\">Play</div>');\r\n\t\t\t}\r\n\t\t\t$(\".pp\").bind(\"click\",function(){\r\n\t\t\t\tif($(this).attr('id')=='pause'){\r\n\t\t\t\t\tautoplay = false;\r\n\t\t\t\t\t$(this).attr(\"id\",\"play\");\r\n\t\t\t\t\t$(\".pp\").html(playLbl);\r\n\t\t\t\t\tclearTimeout(t);\r\n\t\t\t\t\tclearTimeout(tempTimer);\r\n\t\t\t\t}else{\r\n\t\t\t\t\tautoplay = true;\r\n\t\t\t\t\t$(this).attr(\"id\",\"pause\");\r\n\t\t\t\t\t$(\".pp\").html(pauseLbl);\r\n\t\t\t\t\tanimateSlides();\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\t//playing the slides\r\n\t\t\tif(autoplay){ animateSlides(); }\r\n\t\t\t\r\n\t\t}", "function divfader(container) \n{\n\t// Public playback variables\n\tthis.autoplay = true;\n\tthis.fadeTimer = 400;\n\tthis.delay = 2000;\n\n\tvar containers = {\n\t\t// Container classes\n\t\tcontent: '.divfader-content',\n\t\tcontroller: '.divfader-controller',\n\t\tnext: '.divfader-next',\n\t\tprevious: '.divfader-previous',\n\t\tcontrol: '.divfader-control'\n\t}\n\tvar controlClasses = {\n\t\t// CSS Clases used to differentiate active and inactive controls\n\t\tactive: 'divfader-control-active',\n\t\tinactive: 'divfader-control'\n\t}\n\n\tvar that = this; // <--- I don't like the web.\n\n\tvar container = $(container);\n\tvar content = container.children(containers.content).children().hide();\n\tvar controller = container.children(containers.controller);\n\tvar controls;\n\tvar controlNext = container.children(containers.next);\n\tvar controlPrevious = container.children(containers.previous);\n\n\tvar\tcurrent = content.length-1;\n\tvar timeout;\n\n\n\t// ------------------------\n\t// Initialization\n\t// ------------------------\n\t// Onload\n\t$(document).ready(function() {\n\t\tinitializeControls();\n\n\t\tif (that.autoplay) cycle();\n\t\telse showSlide(0);\n\t});\n\n\n\t// Initialize controls (dots)\n\tfunction initializeControls() {\n\t\t// Remove prefix (.) from container class\n\t\tvar className = containers.control;\n\t\tclassName.replace('.', '');\n\n\t\t// Add controls to DOM\n\t\tfor (n = 0; n < content.length; n++) {\n\t\t\tcontroller.append('<div class=\"' + className +'\"></div>');\n\t\t}\n\n\t\t// Save controls\n\t\tcontrols = controller.children();\n\t}\n\n\n\t// ------------------------\n\t// Actions\n\t// ------------------------\n\t// Controller clicked (dot)\n\tcontroller.on('click', '*', function(event){\n\t\tabortCycle();\n\t showSlide($(event.target).index(), true);\n\t});\n\n\t// Next clicked\n\tcontrolNext.on('click',function(event){\n\t\tabortCycle();\n\t nextSlide(true);\n\t});\n\n\t// Previous clicked\n\tcontrolPrevious.on('click',function(event){\n\t\tabortCycle();\n\t previousSlide(true);\n\t});\n\n\t// Cycle through slides\n\tfunction cycle() {\n\t\t// Fade in next slide, recursively\n\t nextSlide();\n\t if (that.autoplay) {\n\t \ttimeout = setTimeout(cycle, that.delay+that.fadeTimer);\n\t }\n\t}\n\n\n\t// ------------------------\n\t// Playback functions\n\t// ------------------------\n\t// Show specific slide\n\t// Responsive will ensure that controls are updated instantly\n\tfunction showSlide(slideId, responsive) {\n\t\t// Stop all other animations\n\t\tcontent.stop();\n\n\t\t// Responsive controls (update control instantly)\n\t\tif (responsive) setActiveControl(slideId);\n\n\t\t// Only fade out for new slides\n\t\tif (slideId != current) {\n\t\t\t// Fade out previous slide\n\t\t\tslide = content.eq(current);\n\t\t\tslide.fadeOut(that.fadeTimer, fadeIn);\n\t\t}\n\t\telse fadeIn();\n\n\t\tfunction fadeIn() {\n\t\t\tcurrent = slideId;\n\n\t\t\t// Update controls normally\n\t\t\tif (!responsive) setActiveControl(slideId);\n\n\t\t\t// Fade in\n\t\t\tslide = content.eq(slideId);\n\t\t slide.fadeIn(that.fadeTimer);\n\t\t};\n\t}\n\n\t// Show next slide\n\t// Responsive will ensure that controls are updated instantly\n\tfunction nextSlide(responsive) {\n\t\tshowSlide((current+1) % content.length, responsive);\n\t}\n\n\t// Show previous slide\n\t// Responsive will ensure that controls are updated instantly\n\tfunction previousSlide(responsive) {\n\t\tshowSlide((current-1) % content.length, responsive);\n\t}\n\n\t// Set active control (dot)\n\tfunction setActiveControl(id) {\n\t\tcontrols.removeClass(controlClasses.active).addClass(controlClasses.inactive);\n\t\tcontrols.eq(id).removeClass(controlClasses.inactive).addClass(controlClasses.active);\n\t}\n\n\t// Abort that.autoplay cycle\n\tfunction abortCycle() {\n\t\tthat.autoplay = false;\n\t\tclearTimeout(timeout);\n\t}\n}", "function hideSliders(){\r\n\tif($Class('slides').length == 0)\r\n\t\treturn;\r\n\t$Class('slides')[0].style.display = 'none';\r\n\t$('slide1c').parentNode.style.display = 'none';\r\n\t$Class('slides2')[0].style.marginTop = '-10px';\r\n}", "generateSlides(){\n let children = [];\n for (let x = 0; x < this.state.images.length; x++){\n children.push(<div className={'hidden image' + this.state.indexes[x]} key={x} onClick={() => this.changeSlide(x)}> <Slide image={this.state.images[x]} /> </div>)\n }\n return children;\n }", "function set_slider_elements() {\n\t$( ':regex(class,^slider#)' ).each(\n\t\tfunction( intIndex ){\n\t\t\tvar classes = $(this).attr('class').split(' ');\n\t\t\tfor (var i=0; i<classes.length; i++) {\n\t\t\t\tlogger(classes[i].match(\"^slider#.*$\"));\n\t\t\t\tif ( classes[i].match(\"^slider#.*$\") ) {\n\t\t\t\t\tlogger(\"got a match\");\n\t\t\t\t\tvar class_to_hide = classes[i].split('#');\n\t\t\t\t\tclass_to_hide = class_to_hide[class_to_hide.length-1];\n\t\t\t\t\tlogger(class_to_hide);\n\t\t\t\t\t// Attach the effect control\n\t\t\t\t\tattachEffect($(this), class_to_hide, \"slider\");\n\t\t\t\t\t\n\t\t\t\t\t// Hide the element\n\t\t\t\t\t$(\".\"+class_to_hide).hide();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t);\n}", "function SlideShow(ID) {\n // CHECKS\n if(ID == null){\n console.error(\"Slides Module: Missing ID.\"); \n return 0;\n }\n\n // Check if a string was passed\n if(typeof(ID) == \"string\"){\n this.ID = ID;\n this.mainDiv=document.getElementById(this.ID); \n if(this.mainDiv == null){\n console.error(\"Slides Module: Could not find: \" + this.ID); \n return 0;\n }\n }\n else{\n // Check if an object was passed \n this.mainDiv=ID;\n if(document.body.contains(ID)){\n console.error(\"Slides Module: Could not find Slide module in document.\"); \n return 0;\n }\n }\n\n // Variables\n this.urlLength=0; // Number of slide image URLs\n this.position = 0; // Current slide position \n this.previousSlide = 0; // Previous slide position \n this.slideShowStarted=false; // Track if slideshow was started\n this.url = new Array(); // Store slide image URLs here \n this.imageW = new Array(); // Store slide image width here \n this.imageH = new Array(); // Store slide image height here \n this.slideDesc = new Array(); // Store slide description here \n this.magnifyObjs = new Array(); // Store slide image Magnification Objects here\n\n // Selectors\n this.slideDivs = this.mainDiv.getElementsByClassName('slide');\n this.slideDescDivs = this.mainDiv.getElementsByClassName('slideDesc'); \n this.images = this.mainDiv.getElementsByTagName(\"img\");\n\n this.left = this.mainDiv.getElementsByClassName('prev')[0];\n this.right = this.mainDiv.getElementsByClassName('next')[0];\n\n // STRUCTURE of Divs in document\n // __SlideShow__\n // | --slide |\n // | --slideDesc | \n\n // Check if STRUCTURE is present in document\n //if(this.slideDivs.length==0 || this.slideDescDivs.length==0 || this.images.length==0){\n // console.error(\"Slides Module: Detected missing structures in document. Refer to module for structure definition.\"); \n // return 0;\n // }\n\n // Set Defaults\n this.scrollLeft=0; \n this.scrollTop=0; \n\n // Trigger the dynamicResize() method whenever slides need to be re-sized\n // CSS for slideDiv is set in changeImage() \n // Execute these once the prototype is created:\n\n var self=this; // 'this' is not preserved in callbacks, so send a copy to the callback functions\n\n this.moveSlides = setInterval(function(){ self.moveRight() }, 5000);\n\n this.left.onclick = function() {self.moveLeft();self.addKeyControls(self); clearInterval(self.moveSlides);};\n this.right.onclick = function() {self.moveRight();self.addKeyControls(self); clearInterval(self.moveSlides);};\n this.setupSlides();\n\n // All is well!\n console.log('Slides Module instantiated with ID:'+ID);\n}", "function slider(){\n\t// Jesli dojdzie do ostatnie elementu zacznij od nowa \n\tif(slides < 0){\n\t\tslides = images.length - 1\n\t}\n\t// Wstaw animacje dla wszystkich divow\n\tarray.forEach(function(a){\n\t\ta.style.animation = 'move 2s'\n\t})\t\n\n\t// Wytnij element === slides z tablicy === array \n\t// W pierwszej iteracji array[slides] === array[33] === div pierwszy na stronie dzieki array.reverse()\n\tcontainer.removeChild(array[slides])\n\t// Wstawia wyciety element na koncu listy divow. Null powoduje ze wstawia defaultowo na koniec\n\tcontainer.insertBefore(array[slides], null)\t\n\t// W nastepenj funkcji nie wezmie ostatniego tylko przedostani\n\tslides--\n\t// Wywolaj funkcje slider() po 4sekundach\n\tsetTimeout(slider, 4000)\n}", "function Carousel(element, main_container)\n {\n var self = this;\n element = $(element);\n main_container = $(main_container);\n\n var container = $(\">ul\", element);\n var panes = $(\">ul>li\", element);\n\n var pane_width = 0;\n var pane_count = panes.length;\n console.debug(\"pane_count\", pane_count);\n\n var current_pane = 0;\n\n\n\n /**\n * initial\n */\n this.init = function() {\n setPaneDimensions();\n\n $(window).on(\"load resize orientationchange\", function() {\n setPaneDimensions();\n //updateOffset();\n })\n };\n\n\n /**\n * set the pane dimensions and scale the container\n */\n function setPaneDimensions() {\n pane_width = element.width();\n panes.each(function() {\n $(this).width(pane_width);\n });\n container.width(pane_width*pane_count);\n };\n\n\n /**\n * show pane by index\n * @param {Number} index\n */\n this.showPane = function( index ) {\n // between the bounds\n index = Math.max(0, Math.min(index, pane_count-1));\n current_pane = index;\n\n var offset = -((100/pane_count)*current_pane);\n setContainerOffset(offset, true);\n };\n\n this.showLast = function(){\n this.showPane(this.pane_count-1)\n }\n\n function setContainerOffset(percent, animate) {\n container.removeClass(\"animate\");\n\n if(animate) {\n container.addClass(\"animate\");\n }\n\n if(Modernizr.csstransforms3d) {\n container.css(\"transform\", \"translate3d(\"+ percent +\"%,0,0) scale3d(1,1,1)\");\n }\n else if(Modernizr.csstransforms) {\n container.css(\"transform\", \"translate(\"+ percent +\"%,0)\");\n }\n else {\n var px = ((pane_width*pane_count) / 100) * percent;\n container.css(\"left\", px+\"px\");\n }\n }\n\n this.next = function() { return this.showPane(current_pane+1, true); };\n this.prev = function() { return this.showPane(current_pane-1, true); };\n\n\n\n function handleHammer(ev) {\n console.log(ev);\n // disable browser scrolling\n ev.gesture.preventDefault();\n\n switch(ev.type) {\n case 'dragright':\n case 'dragleft':\n // stick to the finger\n var pane_offset = -(100/pane_count)*current_pane;\n var drag_offset = ((100/pane_width)*ev.gesture.deltaX) / pane_count;\n\n // slow down at the first and last pane\n if((current_pane == 0 && ev.gesture.direction == Hammer.DIRECTION_RIGHT) ||\n (current_pane == pane_count-1 && ev.gesture.direction == Hammer.DIRECTION_LEFT)) {\n drag_offset *= .4;\n }\n\n setContainerOffset(drag_offset + pane_offset);\n break;\n\n case 'swipeleft':\n self.next();\n ev.gesture.stopDetect();\n break;\n\n case 'swiperight':\n self.prev();\n ev.gesture.stopDetect();\n break;\n\n case 'release':\n // more then 50% moved, navigate\n if(Math.abs(ev.gesture.deltaX) > pane_width/2) {\n if(ev.gesture.direction == 'right') {\n self.prev();\n } else {\n self.next();\n }\n }\n else {\n self.showPane(current_pane, true);\n }\n break;\n }\n }\n\n element.hammer({ drag_lock_to_axis: true })\n .on(\"release dragleft dragright swipeleft swiperight\", handleHammer);\n\n\n \n var next_button = main_container.children(\".carousel-right\");\n var prev_button = main_container.children(\".carousel-left\");\n \n console.debug(\"next_button\", next_button); \n console.debug(\"prev_button\", prev_button); \n next_button.click(function(evt){\n console.debug(\"next click\");\n self.next();\n });\n prev_button.click(function(evt){\n console.debug(\"prev click\");\n self.prev();\n });\n\t\t\t$(document).on('keydown', function(evt) {\n\t\t\t\tif (main_container.is(\":visible\")) {\n\t\t\t\t\tif (evt.keyCode == 37) { self.prev(); }\n\t\t\t\t\tif (evt.keyCode == 39) { self.next(); }\n\t\t\t\t\tif (evt.keyCode == 27) {\n\t\t\t\t\t\t// escape to close\n\t\t\t\t\t\t$scope.$apply(function() {\n\t\t\t\t\t\t\t$location.path($location.path().split('/').slice(0,-2).join('/'));\n\t\t\t\t\t\t});\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\n }", "function showDivs(slideNo) {\n let slides = $(\".boardSlides\");\n //if you go too far right or left, this will keep you in the loop of slides\n if (slideNo > slides.length) {\n slideIndex = 1\n }\n if (slideNo < 1) {\n slideIndex = slides.length;\n }\n for (i = 0; i < slides.length; i++) {\n slides[i].style.display = \"none\";\n }\n slides[slideIndex-1].style.display = \"block\";\n }", "function tiSlideshow(container, options, id) {\n this.container = container;\n this.options = options;\n this.maskId = \"\";\n this.isOpen = false;\n this.imageList = [];\n this.currentImageIndex = 0;\n $.tiSlideshow.interfaces[id] = this;\n if (this.options.auto)\n this.open();\n }", "function BannerSlide(domElem) {\n var self = this;\n\n self.domElem = $(domElem);\n \n self.subSlides = [];\n\n self.domElem.children(\"li.subslide\").each(function(i){\n var subslide = new BannerSubSlide(this, self);\n self.subSlides.push(subslide);\n });\n}", "function SlideCarousel(){\n\n\t\t//carousel private variables\n\t\tvar slides = [],\n\t\t coordinates = TouchCoords(),\n\t\t events = EventManager(),\n\t\t currentSlide,\n\t\t currentSlideGroup = [],\n\t\t slideIndex,\n\t\t intransition = false,\n\t\t iscycling = false,\n\t\t isfrozen = false,\n\t\t isOutslideHidden = false;\n\n\n\t\t//private functions\n\t\t//cycles the carousel slide stack in specified direction\n\t\t//requires a slide instance to transition to\n\t\tfunction cycle( direction, inSlide, callback ){\n\n\t\t\t//default result\n\t\t\tvar result = { success: false };\n\n\t\t\t//only cycle if direction is provided.\n\t\t\tif( direction &&\n\t\t\t inSlide &&\n\t\t\t !iscycling &&\n\t\t\t !isfrozen ){\n\n\t\t\t\t//set incycle flag - stop multiple calls to cycle while dragging mouse\n\t\t\t\tiscycling = true;\n\n\t\t\t\t//conditional variables set based on left/right direction\n\t\t\t\tvar findSlide = findSlideInCarousel( inSlide );\n\n\t\t\t\t//slide found, transition to it\n\t\t\t\tif( findSlide.success ){\n\n\t\t\t\t\ttransition( direction, inSlide, callback );\n\t\t\t\t\tslideIndex = findSlide.index;\n\t\t\t\t\tresult = {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\taction: 'cycle',\n\t\t\t\t\t\tdirection: direction,\n\t\t\t\t\t\tindex: slideIndex\n\t\t\t\t\t};\n\n\t\t\t\t//slide doesnt exist in in this carousel, cancel cycle flag\n\t\t\t\t} else {\n\n\t\t\t\t\tiscycling = false;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t}\n\n\n\t\t//find adjacent slides as defined by any JSON properties that might\n\t\t//differentiate from normal index sorting from slides array\n\t\tfunction findAdjacentSlides(){\n\n\t\t\t//vars\n\t\t\tvar result = { success: false },\n\t\t\t adjacentkeys = [ 'previous', 'next' ];\n\n\t\t\t//set result for prev/next\n\t\t\tadjacentkeys.forEach( function( key, index ){\n\n\t\t\t\tif( currentSlide &&\n\t\t\t\t currentSlide.properties[ key ] &&\n\t\t\t\t currentSlide.properties[ key ].slide ){\n\n\t\t\t\t\tresult[ key ] = slides[ currentSlide.properties[ key ].slide ] || null;\n\t\t\t\t\tresult.success = true;\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t\t//set default values for result being the normal adjacent slides as defined by the slides array order\n\t\t\tresult.previous = result.previous || slides[ slideIndex - 1 ] || null;\n\t\t\tresult.next = result.next || slides[ slideIndex + 1 ] || null;\n\n\t\t\t//return the result\n\t\t\treturn result;\n\n\t\t}\n\n\n\t\t//find a slide within the carousel object\n\t\t//findSlide can be either an object instance, ID name (string), or an index\n\t\t//search results evaluate explicity, must match type\n\t\t//returns result object with status, slide reference and the index within the array\n\t\tfunction findSlideInCarousel( querySlide ){\n\n\t\t\t//create result object\n\t\t\tvar result = { success: false };\n\n\t\t\t//iterate through carousel slides array to compare slides\n\t\t\tslides.some( function( searchSlide, slideIndex ){\n\n\t\t\t\t//slide is found\n\t\t\t\tif( searchSlide === querySlide ||\n\t\t\t\t searchSlide.properties.id === querySlide ||\n\t\t\t\t searchSlide.index === querySlide ){\n\n\t\t\t\t\t//create matching result object\n\t\t\t\t\tresult = {\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tslide: searchSlide,\n\t\t\t\t\t\tindex: slideIndex\n\t\t\t\t\t};\n\n\t\t\t\t\treturn result;\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t\treturn result;\n\n\t\t}\n\n\n\t\t//reorders next/prev status around an indicated slide\n\t\tfunction reorderSlides( searchSlide ){\n\n\t\t\t//found flag\n\t\t\tvar foundit = false,\n\t\t\t baseStatus = isOutslideHidden ? \"hidden \" : \"\";\n\n\t\t\t//carousel slide array iteration\n\t\t\tslides.forEach( function( compareSlide ){\n\n\t\t\t\t//remove slide transform attribute if left over\n\t\t\t\tcompareSlide.wrapper.removeAttribute( 'style' );\n\n\t\t\t\t//test to see if we've found our slide\n\t\t\t\tif( compareSlide == searchSlide ){\n\n\t\t\t\t\tfoundit = true;\n\n\t\t\t\t//if not, set slide status dependent on foundit value\n\t\t\t\t} else {\n\n\t\t\t\t\tif( !foundit ){\n\n\t\t\t\t\t\tcompareSlide.setStatus( baseStatus + \"previous notransition\" );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tcompareSlide.setStatus( baseStatus + \"next notransition\" );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} );\n\n\t\t}\n\n\n\t\t//handles actual class management to facilitate css transition animation between slides.\n\t\t//requires a slide reference to set to current and a direction that is being transitioned.\n\t\t//helper method to 'cycle'\n\t\tfunction transition( direction, inSlide, callback ){\n\n\n\t\t\t//set bool transition state to true\n\t\t\tintransition = true;\n\n\t\t\t//set default state of direction\n\t\t\tdirection = direction || 'next';\n\n\t\t\t//determine type of currenslide, whether its a slide object or a veeva jumpto object - create temp slide to transition 'to' if so\n\t\t\tvar outSlide = currentSlide,\n\t\t\t outStatus = ( direction == 'next' ) ? 'previous' : 'next',\n\t\t\t inTransComplete = false,\n\t\t\t outTransComplete = false;\n\t\t\t isOutslideHidden = inSlide.hasStatus( 'hidden' );\n\n\t\t\t//error check to make sure our current slide is the right type of object now\n\t\t\tif( inSlide ){\n\n\t\t\t\t//trigger custom slide transition events if defined\n\t\t\t\tinSlide.events.dispatchEvent( { type:'transitionto', details:inSlide } );\n\t\t\t\toutSlide.events.dispatchEvent( { type:'transitionfrom', details:outSlide } );\n\n\t\t\t\t//remove hidden state so the frame can transition\n\t\t\t\tinSlide.setStatus( 'hidden', 'remove' );\n\n\t\t\t\t//set delay so the slide to display can transition (currently is display:none, must make it display before transitioning else there is no transition)\n\t\t\t\tsetTimeout( startSlideTransition, 10 );\n\n\t\t\t}\n\n\n\t\t\t//Transition Functions\n\t\t\t//begin slide transition - set state of current slide. fire custom start transition event methods\n\t\t\tfunction startSlideTransition( ){\n\n\t\t\t\tinSlide.setStatus( \"current\" );\n\t\t\t\tinSlide.wrapper.removeAttribute( \"style\" );\n\t\t\t\tinSlide.wrapper.addEventListener( 'transitionend', inSlideTransitionEnd, false );\n\n\t\t\t\toutSlide.setStatus( outStatus );\n\t\t\t\toutSlide.wrapper.removeAttribute( \"style\" );\n\t\t\t\toutSlide.wrapper.addEventListener( 'transitionend', outSlideTransitionEnd, false );\n\n\t\t\t}\n\n\t\t\t//what happens when inSlide is finished transitioning onto screen\n\t\t\tfunction inSlideTransitionEnd( ){\n\n\t\t\t\tinSlide.wrapper.removeEventListener( 'transitionend', inSlideTransitionEnd );\n\t\t\t\tdelete inSlide.offsets;\n\n\t\t\t\tinTransComplete = true;\n\t\t\t\tcheckIfTransitionComplete();\n\n\t\t\t}\n\n\n\t\t\t//what happens when outSlide is finished transitioning off screen\n\t\t\tfunction outSlideTransitionEnd( ){\n\n\t\t\t\toutSlide.wrapper.removeEventListener( 'transitionend', outSlideTransitionEnd );\n\t\t\t\tdelete outSlide.offsets;\n\n\t\t\t\toutTransComplete = true;\n\t\t\t\tcheckIfTransitionComplete();\n\n\t\t\t}\n\n\n\t\t\t//checks to see if both slides have finished transitioning - wraps up transition if true\n\t\t\tfunction checkIfTransitionComplete(){\n\n\t\t\t\tif( inTransComplete && outTransComplete ){\n\n\t\t\t\t\t//wrap up transition settings\n\t\t\t\t\treorderSlides( inSlide );\n\t\t\t\t\tcurrentSlide = inSlide;\n\t\t\t\t\tslideIndex = inSlide.index;\n\t\t\t\t\tintransition = false;\n\t\t\t\t\tiscycling = false;\n\n\t\t\t\t\t//fire custom slide events\n\t\t\t\t\tinSlide.events.dispatchEvent( { type:'focus', details: inSlide } );\n\t\t\t\t\toutSlide.events.dispatchEvent( { type:'blur', details: outSlide } );\n\n\t\t\t\t\t//update adjacent slidegroup\n\t\t\t\t\tupdateSlideGroup();\n\n\t\t\t\t\t//hide adjacent slide if flag is true\n\t\t\t\t\tif( isOutslideHidden ){\n\n\t\t\t\t\t\toutSlide.setStatus( 'hidden', 'add' );\n\n\t\t\t\t\t}\n\n\t\t\t\t\t//fire callback\n\t\t\t\t\tif( callback && typeof callback == 'function' ){\n\n\t\t\t\t\t\tcallback.call( this );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\n\t\t//update slide group that contains current inSlide and its adjacents\n\t\tfunction updateSlideGroup(){\n\n\t\t\tif( currentSlide ){\n\n\t\t\t\tvar prevSlide = findAdjacentSlides().previous || null,\n\t\t\t\t nextSlide = findAdjacentSlides().next || null,\n\t\t\t\t pushArray = [ prevSlide, currentSlide, nextSlide ];\n\n\t\t\t\tpushArray.forEach( function( pushSlide ){\n\n\t\t\t\t\tif( pushSlide ){\n\n\t\t\t\t\t\tcurrentSlideGroup.push( pushSlide );\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t}\n\n\n\t\t// return accessor object\n\t\treturn Object.create(\n\n\t\t\t{\n\n\t\t\t\t//coordinate tracking object instance\n\t\t\t\tget coordinates() { return coordinates; },\n\n\n\t\t\t\t//currentSlide getter / setter\n\t\t\t\tget currentSlide() { return currentSlide; },\n\t\t\t\tset currentSlide( value ) {\n\t\t\t\t\tcurrentSlide = value;\n\t\t\t\t\tupdateSlideGroup();\n\t\t\t\t},\n\t\t\t\tget currentSlideGroup() { return currentSlideGroup; },\n\t\t\t\tget currentIndex() { return slideIndex; },\n\n\n\t\t\t\t//touch coord event reference\n\t\t\t\tget events() { return events; },\n\n\n\t\t\t\t//flags indicating state of carousel cycling and transitions\n\t\t\t\tflags: {\n\t\t\t\t\tget cycling() { return iscycling; },\n\t\t\t\t\tget freeze() { return isfrozen; },\n\t\t\t\t\tset freeze( value ) { isfrozen = value; },\n\t\t\t\t\tget transitioning() { return intransition; }\n\t\t\t\t},\n\n\t\t\t\t//slides array getter\n\t\t\t\tget slides() { return slides; },\n\t\t\t\tset slides( value ) { slides = value; },\n\n\n\t\t\t\t//slideIndex getter/setter\n\t\t\t\tget slideIndex() { return slideIndex; },\n\t\t\t\tset slideIndex( value ) { slideIndex = value; },\n\n\n\t\t\t\t//Object type\n\t\t\t\ttype: 'CAROUSEL',\n\n\t\t\t},\n\t\t\t{\n\n\t\t\t\tcycle: {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t\tvalue: cycle\n\t\t\t\t},\n\n\t\t\t\tfindAdjacentSlides: {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t\tvalue: findAdjacentSlides\n\t\t\t\t},\n\n\t\t\t\tfindSlide: {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t\tvalue: findSlideInCarousel\n\t\t\t\t},\n\n\t\t\t\ttransition: {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t\tvalue: transition\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t);\n\n\t}", "function play() {\n /* Stops a cycle before start a new one */\n if($cycle)\n clearInterval($cycle);\n\n // SetInterval - Just for code reuse\n var setInt = function (callback) {\n $cycle = setInterval(callback, slideInterval());\n };\n\n if(directionToRight())\n setInt(slideRight);\n else\n setInt(slideLeft);\n }", "function slideShow() {\n $('.slide-viewer').each(function() {\n // set up variables specific to each slider\n var $this = $(this); // jQuery selection for the slide-viewer\n var $container = $this.find('.slide-container');\n var $slides = $this.find('.slide');\n var buttons = []; // Array for the buttons that allow you to select a slide\n var currentIndex = 0; // Index of slide currently on\n var timer; // timer to change slide every 5 s\n var $slideButtons = $this.next(); // Could be > 1 slideshow on page; get right one\n\n // Create button for each slide\n $slides.each(function(index) {\n var $button = $('<button type=\"button\" class=\"slide-button\"></button>');\n if (index === currentIndex) {\n $button.addClass('selected');\n }\n $button.on('click', function() {\n move(index);\n });\n $slideButtons.append($button);\n buttons.push($button);\n });\n\n // Start timer; at this point the script is done, rest of code is just functions\n autoAdvance();\n\n // Function to move new slide into view and hides old one\n function move(newIndex) {\n var newSlidePosition, animationDirection;\n\n autoAdvance(); // Reset timer\n\n // slide @ newIndex already selected or previous selection still animating,\n // so don't change slide \n if ((newIndex === currentIndex) || ($container.is(':animated'))) {\n return;\n }\n\n // Update which button is selected\n buttons[currentIndex].removeClass('selected');\n buttons[newIndex].addClass('selected');\n\n // Determine which direction the slides should animate\n if (newIndex > currentIndex) {\n newSlidePosition = '100%'; // New slide should be placed on right of current\n animationDirection = '-100%'; // Slides should animate from right to left\n } else {\n newSlidePosition = '-100%'; // New slide should be placed on left of current\n animationDirection = '100%'; // Slides should animate from left to right\n }\n\n // Position new slide\n $slides.eq(newIndex).css({left: newSlidePosition, display: 'block'});\n // Animate new slide into view\n $container.animate({left: animationDirection}, function() {\n $slides.eq(currentIndex).css({display: 'none'}); // Hide old slide\n $slides.eq(newIndex).css({left: '0'});\n $container.css({left: '0'}); // Make sure container back where it should be\n currentIndex = newIndex; // All done, update currentIndex\n });\n }\n\n // Creates timer to auto-advance slide\n function autoAdvance() {\n clearTimeout(timer); // Clear old timer\n timer = setTimeout(function() {\n if (currentIndex === ($slides.length - 1)) {\n move(0);\n } else {\n move(currentIndex+1);\n }\n }, 5000);\n }\n });\n}", "function slideshow( slideshowname ) {\r\n // ss = new slideshow(\"ss\");\r\n\r\n // Name of this object\r\n // (required if you want your slideshow to auto-play)\r\n // For example, \"SLIDES1\"\r\n this.name = slideshowname;\r\n\r\n // When we reach the last slide, should we loop around to start the\r\n // slideshow again?\r\n this.repeat = true;\r\n\r\n // Number of images to pre-fetch.\r\n // -1 = preload all images.\r\n // 0 = load each image is it is used.\r\n // n = pre-fetch n images ahead of the current image.\r\n // I recommend preloading all images unless you have large\r\n // images, or a large amount of images.\r\n this.prefetch = -1;\r\n\r\n // IMAGE element on your HTML page.\r\n // For example, document.images.SLIDES1IMG\r\n this.image;\r\n\r\n // ID of a DIV element on your HTML page that will contain the text.\r\n // For example, \"slides2text\"\r\n // Note: after you set this variable, you should call\r\n // the update() method to update the slideshow display.\r\n this.textid;\r\n\r\n // Milliseconds to pause between slides.\r\n // Individual slides can override this.\r\n this.timeout = 3000;\r\n\r\n // Hook functions to be called before and after updating the slide\r\n // this.pre_update_hook = function() { }\r\n // this.post_update_hook = function() { }\r\n\r\n // These are private variables\r\n this.slides = new Array();\r\n this.current = 0;\r\n this.timeoutid = 0;\r\n\r\n //--------------------------------------------------\r\n // Public methods\r\n //--------------------------------------------------\r\n this.add_slide = function(slide) {\r\n // Add a slide to the slideshow.\r\n // For example:\r\n // SLIDES1.add_slide(new slide(\"s1.jpg\", \"link.html\"))\r\n\r\n var i = this.slides.length;\r\n\r\n // Prefetch the slide image if necessary\r\n if (this.prefetch == -1) {\r\n slide.load();\r\n }\r\n\r\n this.slides[i] = slide;\r\n }\r\n\r\n //--------------------------------------------------\r\n this.play = function(timeout) {\r\n // This method implements the automatically running slideshow.\r\n // If you specify the \"timeout\" argument, then a new default\r\n // timeout will be set for the slideshow.\r\n\r\n // Make sure we're not already playing\r\n this.pause();\r\n\r\n // If the timeout argument was specified (optional)\r\n // then make it the new default\r\n if (timeout) {\r\n this.timeout = timeout;\r\n }\r\n\r\n // If the current slide has a custom timeout, use it;\r\n // otherwise use the default timeout\r\n if (typeof this.slides[ this.current ].timeout != 'undefined') {\r\n timeout = this.slides[ this.current ].timeout;\r\n } else {\r\n timeout = this.timeout;\r\n }\r\n\r\n // After the timeout, call this.loop()\r\n this.timeoutid = setTimeout( this.name + \".loop()\", timeout);\r\n }\r\n \r\n//--------------------------------------------------\r\n this.playPause = function(id) {\r\n // This method implements the automatically running slideshow.\r\n // If you specify the \"timeout\" argument, then a new default\r\n // timeout will be set for the slideshow.\r\n\r\n\tif (document.getElementById(id).value == \"Pause\") {\r\n\t\tdocument.getElementById(id).value = \"Play \";\r\n\t\tclearTimeout(this.timeoutid);\r\n\t\tthis.timeoutid = 0;\r\n\t} else {\r\n\t\tthis.next();\r\n\t\t\r\n\t\tdocument.getElementById(id).value = \"Pause\";\r\n\r\n\t\tclearTimeout(this.timeoutid);\r\n\t\tthis.timeoutid = 0;\r\n\r\n\t\t// If the current slide has a custom timeout, use it;\r\n\t\t// otherwise use the default timeout\r\n\t\tif (typeof this.slides[ this.current ].timeout != 'undefined') {\r\n\t\t\ttimeout = this.slides[ this.current ].timeout;\r\n\t\t} else {\r\n\t\t\ttimeout = this.timeout;\r\n\t\t}\r\n\r\n\t\t// After the timeout, call this.loop()\r\n\t\tthis.timeoutid = setTimeout( this.name + \".loop()\", timeout);\r\n\t}\r\n }\r\n\r\n //--------------------------------------------------\r\n this.pause = function() {\r\n // This method stops the slideshow if it is automatically running.\r\n\r\n if (this.timeoutid != 0) {\r\n\r\n clearTimeout(this.timeoutid);\r\n this.timeoutid = 0;\r\n\r\n }\r\n }\r\n\r\n //--------------------------------------------------\r\n this.update = function() {\r\n // This method updates the slideshow image on the page\r\n\r\n // Make sure the slideshow has been initialized correctly\r\n if (! this.valid_image()) { return; }\r\n\r\n\r\n // Convenience variable for the current slide\r\n var slide = this.slides[ this.current ];\r\n\r\n // Load the slide image if necessary\r\n slide.load();\r\n\r\n // Update the image.\r\n this.image.src = slide.image.src;\r\n\tthis.image.alt = slide.text;\r\n\tthis.image.title = slide.text;\r\n\r\n // Call the post-update hook function if one was specified\r\n if (typeof this.post_update_hook == 'function') {\r\n this.post_update_hook();\r\n }\r\n\r\n // Do we need to pre-fetch images?\r\n if (this.prefetch > 0) {\r\n\r\n var next, prev, count;\r\n\r\n // Pre-fetch the next slide image(s)\r\n next = this.current;\r\n prev = this.current;\r\n count = 0;\r\n do {\r\n\r\n // Get the next and previous slide number\r\n // Loop past the ends of the slideshow if necessary\r\n if (++next >= this.slides.length) next = 0;\r\n if (--prev < 0) prev = this.slides.length - 1;\r\n\r\n // Preload the slide image\r\n this.slides[next].load();\r\n this.slides[prev].load();\r\n\r\n // Keep going until we have fetched\r\n // the designated number of slides\r\n\r\n } while (++count < this.prefetch);\r\n }\r\n }\r\n\r\n //--------------------------------------------------\r\n this.goto_slide = function(n) {\r\n // This method jumpts to the slide number you specify.\r\n // If you use slide number -1, then it jumps to the last slide.\r\n // You can use this to make links that go to a specific slide,\r\n // or to go to the beginning or end of the slideshow.\r\n // Examples:\r\n // onClick=\"myslides.goto_slide(0)\"\r\n // onClick=\"myslides.goto_slide(-1)\"\r\n // onClick=\"myslides.goto_slide(5)\"\r\n\r\n if (n == -1) {\r\n n = this.slides.length - 1;\r\n }\r\n\r\n if (n < this.slides.length && n >= 0) {\r\n this.current = n;\r\n }\r\n\r\n this.update();\r\n }\r\n\r\n //--------------------------------------------------\r\n this.next = function() {\r\n // This method advances to the next slide.\r\n\r\n // Increment the image number\r\n if (this.current < this.slides.length - 1) {\r\n this.current++;\r\n } else if (this.repeat) {\r\n this.current = 0;\r\n }\r\n\r\n this.update();\r\n }\r\n\r\n\r\n //--------------------------------------------------\r\n this.previous = function() {\r\n // This method goes to the previous slide.\r\n\r\n // Decrement the image number\r\n if (this.current > 0) {\r\n this.current--;\r\n } else if (this.repeat) {\r\n this.current = this.slides.length - 1;\r\n }\r\n\r\n this.update();\r\n }\r\n\r\n //--------------------------------------------------\r\n this.zoomUp = function() {\r\n // This method increments the image height by 50\r\n var oldHeight = this.image.height;\r\n this.image.height = oldHeight + 50;\t\t\r\n this.update();\r\n }\r\n\r\n //--------------------------------------------------\r\n this.zoomDown = function() {\r\n // This method increments the image height by 50\r\n var oldHeight = this.image.height;\r\n this.image.height = oldHeight - 50;\t\t\r\n this.update();\r\n }\r\n\r\n //--------------------------------------------------\r\n this.get_text = function() {\r\n // This method returns the text of the current slide\r\n\r\n return(this.slides[ this.current ].text);\r\n }\r\n\r\n //--------------------------------------------------\r\n this.hotlink = function() {\r\n // This method calls the hotlink() method for the current slide.\r\n\r\n this.slides[ this.current ].hotlink();\r\n }\r\n\r\n//--------------------------------------------------\r\n this.loop = function() {\r\n // This method is for internal use only.\r\n // This method gets called automatically by a JavaScript timeout.\r\n // It advances to the next slide, then sets the next timeout.\r\n // If the next slide image has not completed loading yet,\r\n // then do not advance to the next slide yet.\r\n\r\n // Make sure the next slide image has finished loading\r\n if (this.current < this.slides.length - 1) {\r\n next_slide = this.slides[this.current + 1];\r\n if (next_slide.image.complete == null || next_slide.image.complete) {\r\n this.next();\r\n }\r\n } else { // we're at the last slide\r\n this.next();\r\n }\r\n\r\n // Keep playing the slideshow\r\n this.play( );\r\n }\r\n\r\n\r\n //--------------------------------------------------\r\n this.valid_image = function() {\r\n // Returns 1 if a valid image has been set for the slideshow\r\n\r\n if (!this.image)\r\n {\r\n return false;\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n\r\n //--------------------------------------------------\r\n this.getElementById = function(element_id) {\r\n // This method returns the element corresponding to the id\r\n\r\n if (document.getElementById) {\r\n return document.getElementById(element_id);\r\n }\r\n else if (document.all) {\r\n return document.all[element_id];\r\n }\r\n else if (document.layers) {\r\n return document.layers[element_id];\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n }", "init (container){\n this.container = container ? $(container) : $(this.container);\n this.slideIndex = this.container.find(this.slide).length;\n this.slides = this.container.find(this.slide);\n this.slideText = this.container.find(this.slideText);\n this.pagerContainer = this.container.find(this.pagerContainer);\n this.pagerLeft = this.container.find(this.pagerLeft);\n this.pagerRight = this.container.find(this.pagerRight);\n this.loop = false;\n\n this.pagerEvents();\n this.autoTransition();\n }", "function slideLoop($id){\n\t\t\t//swap\n\t\t\t$prevId = ($id==0)?$slidesc-1:$id-1;\n\t\t\t$slides.eq($prevId).after($slides.eq($id));\n\t\t\t$slides.not($slides.eq($prevId)).hide();\n\t\t\t//effect\n\t\t\t$slides.eq($id).delay($options.delay).fadeIn($options.speed,function(){\n\t\t\t\t$next = ($id==$slidesc-1)?0:$id+1;\n\t\t\t\tslideLoop($next);\n\t\t\t});\n\t\t}", "function cycleItems(){\n var item = $('.slider-container div').eq(currentIndex);\n items.hide();\n item.css('display', 'inline-block');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a new TitleBar
function TitleBar(target) { _super.call(this, target); this._buttons = 0 /* NoButton */; this.addClass(TitleBar.Class); var icon = this._icon = new porcelain.Component(); icon.addClass(TitleBar.IconClass); var label = this._label = new porcelain.Label(); label.addClass(TitleBar.LabelClass); label.addClass(porcelain.CommonClass.LargeText); var clsBtn = this._closeButton = new porcelain.Button(); clsBtn.addClass(TitleBar.CloseButtonClass); var maxBtn = this._maximizeButton = new porcelain.Button(); maxBtn.addClass(TitleBar.MaximizeButtonClass); var minBtn = this._minimizeButton = new porcelain.Button(); minBtn.addClass(TitleBar.MinimizeButtonClass); var rstBtn = this._restoreButton = new porcelain.Button(); rstBtn.addClass(TitleBar.RestoreButtonClass); var btnBox = this._buttonBox = new porcelain.Component(); btnBox.addClass(TitleBar.ButtonBoxClass); btnBox.append(minBtn, rstBtn, maxBtn, clsBtn); // the order is important for CSS float layout this.append(icon, btnBox, label); this.setButtons(15 /* Mask */ & ~8 /* Restore */); }
[ "function Titlebar(u, t, m, g, b, o, r, a){\n this.Username = u;\n this.Title = t;\n this.Message = m;\n this.Group = g;\n this.Background = b;\n this.Border = o;\n this.More = r;\n this.RemoveBars = a;\n}", "static InspectorTitlebar() {}", "function createTitle()\n\t{\n\t\tvar self = this, elems = this.elements;\n\n\t\t// Destroy previous title element, if present\n\t\tif(elems.title !== null) elems.title.remove();\n\n\t\t// Create elements\n\t\telems.tooltip.prepend(\n\t\t\t'<div class=\"ui-tooltip-titlebar ui-widget-header\">' +\n\t\t\t\t'<a class=\"ui-tooltip-close ui-state-default\" role=\"button\"><span class=\"ui-icon ui-icon-close\"></span></a>' +\n\t\t\t\t'<div id=\"ui-tooltip-title-'+self.id+'\" class=\"ui-tooltip-title\"></div>' +\n\t\t\t'</div>'\n\t\t);\n\t\telems.titlebar = elems.tooltip.find('.ui-tooltip-titlebar').eq(0);\n\t\telems.title = elems.tooltip.find('.ui-tooltip-title').eq(0);\n\t\telems.button = elems.tooltip.find('.ui-tooltip-close').eq(0);\n\n\t\t// Update title with contents\n\t\tself.updateTitle.call(self, self.options.content.title.text);\n\n\t\t// Create title close buttons if enabled\n\t\tif(self.options.content.title.button)\n\t\t{\n\t\t\telems.button.hover(\n\t\t\t\tfunction(){ $(this).addClass('ui-state-hover'); },\n\t\t\t\tfunction(){ $(this).removeClass('ui-state-hover'); }\n\t\t\t)\n\t\t\t.click(function()\n\t\t\t{\n\t\t\t\tif(elems.tooltip.hasClass('ui-state-disabled')){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tself.hide();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.bind('mousedown keydown', function(){ $(this).addClass('ui-state-active ui-state-focus'); })\n\t\t\t.bind('mouseup keyup click mouseout', function(){ $(this).removeClass('ui-state-active ui-state-focus'); });\n\t\t}\n\t\telse elems.button.remove();\n\t}", "function createTitle()\n {\n var self = this;\n \n // Destroy previous title element, if present\n if(self.elements.title !== null) self.elements.title.remove();\n \n // Create title element\n self.elements.title = $(document.createElement('div'))\n .addClass(self.options.style.classes.title)\n .css( jQueryStyle(self.options.style.title, true) )\n .html(self.options.content.title.text)\n .prependTo(self.elements.contentWrapper);\n \n // Create title close buttons if enabled\n if(self.options.content.title.button !== false\n && typeof self.options.content.title.button == 'string')\n {\n var button = $(document.createElement('a'))\n .attr('href', '#')\n .css({ 'float': 'right', position: 'relative' })\n .addClass(self.options.style.classes.button)\n .html(self.options.content.title.button)\n .prependTo(self.elements.title)\n .click(self.hide);\n }\n }", "function initTitleBar (appName) {\r\n /* Retrieve necessary elements */\r\n let TitleBar = document.getElementById(\"window-titlebar\");\r\n let TitleBarTitle = document.getElementById(\"window-titlebar-title\");\r\n\r\n let MinBtn = document.getElementById(\"window-min-btn\");\r\n let MaxBtn = document.getElementById(\"window-max-btn\");\r\n let ExitBtn = document.getElementById(\"window-close-btn\");\r\n\r\n TitleBarTitle.innerHTML = appName;\r\n\r\n let sysPlatform;\r\n if (process.platform === \"win32\") {\r\n sysPlatform = \"windows\";\r\n\r\n MinBtn.innerHTML = \"&#8722;\";\r\n MaxBtn.innerHTML = \"&#10064;\";\r\n ExitBtn.innerHTML = \"&#10005;\";\r\n } else if (process.platform === \"darwin\") {\r\n sysPlatform = \"mac\";\r\n } else {\r\n sysPlatform = \"linux\";\r\n MinBtn.innerHTML = \"&#8722;\";\r\n MaxBtn.innerHTML = \"&#9744;\";\r\n ExitBtn.innerHTML = \"&#10005;\";\r\n }\r\n\r\n TitleBar.setAttribute(\"class\", sysPlatform);\r\n\r\n /* Adding functionality on: Minimize Window Button */\r\n MinBtn.addEventListener(\"click\", (e) => {\r\n let window = BrowserWindow.getFocusedWindow();\r\n\r\n window.minimize();\r\n });\r\n\r\n /* Adding functionality on: Maximize Window Button */\r\n MaxBtn.addEventListener(\"click\", (e) => {\r\n let window = BrowserWindow.getFocusedWindow();\r\n\r\n if (window.isMaximized())\r\n window.unmaximize();\r\n else\r\n window.maximize();\r\n });\r\n\r\n /* Adding functionality on: Exit Window Button */\r\n ExitBtn.addEventListener(\"click\", (e) => {\r\n let window = BrowserWindow.getFocusedWindow();\r\n\r\n window.close();\r\n });\r\n}", "function createTitle() {\n return new Title(_angular_core.inject(DOCUMENT$1));\n}", "_createTitlebar() {\n const { Titlebar, Color } = require('custom-electron-titlebar');\n const { Menu, MenuItem } = require('electron').remote;\n\n const self = this;\n\n self._titlebar = new Titlebar({\n backgroundColor: Color.fromHex('#002a4d'),\n icon: './img/icons/icon.png'\n });\n\n const menu = new Menu();\n\n const checked =\n localStorage.getItem('fancy-titlebar-enabled') === 'true' ? true : false;\n const config = {\n label: 'Color changing title bar',\n type: 'checkbox',\n checked: checked,\n click: function() {\n config.checked = !config.checked;\n localStorage.setItem('fancy-titlebar-enabled', config.checked);\n self._UI.updateTitlebarColor(self, self._UI.albumCoverImage);\n\n /**\n * To update the little tick icon, the whole menu must be updated :/\n */\n const newMenu = new Menu();\n const newSecondaryItem = new MenuItem({\n label: 'Configuration',\n submenu: [config]\n });\n\n if (process.platform === 'darwin') {\n newMenu.append(mainItem);\n }\n newMenu.append(newSecondaryItem);\n self._titlebar.updateMenu(newMenu);\n }\n };\n\n let mainItem = new MenuItem({\n label: 'Configuration',\n submenu: [config]\n });\n\n let secondaryItem = undefined;\n\n if (process.platform === 'darwin') {\n mainItem = new MenuItem({\n label: require('electron').remote.app.getName(),\n submenu: [\n {\n role: 'quit',\n accelerator: 'Cmd+Q'\n }\n ]\n });\n\n secondaryItem = new MenuItem({\n label: 'Configuration',\n submenu: [config]\n });\n }\n\n menu.append(mainItem);\n if (secondaryItem) {\n menu.append(secondaryItem);\n }\n\n self._titlebar.updateMenu(menu);\n }", "function InitTitleTextControl(strObj, text)\n{\n\ttry {\n\t\tInitTextControl(strObj, text);\n\n\t\tbtn = MFBar.GetObjectUnknown(strObj);\n btn.Text = text;\n\t\tbtn.FontSize = L_TitleFontSize_NUMBER;\n\t\tbtn.BackColor = g_clrFrameTitleBar;\n\t\tbtn.ColorStatic = 0x0f0f0f;\n\t\tbtn.ColorHover = 0x0f0f0f;\n\t\tbtn.ColorDisable = 0x0f0f0f;\n\t\tMFBar.EnableObjectInput(strObj, false); // enable dragging by the text\n\n\t\tbtn = MFBar.GetObjectUnknown(strObj + \"Full\");\n btn.Text = text;\n\t\tbtn.FontSize = L_TitleFontSize_NUMBER;\n\t\tbtn.BackColor = DVD.ColorKey;\n\t\tbtn.ColorStatic = 0xf0f0f0;\n\t\tbtn.ColorHover = 0xf0f0f0;\n\t\tbtn.ColorDisable = 0xf0f0f0;\n\t\tMFBar.EnableObjectInput(strObj + \"Full\", false); // enable dragging by the text\n\t}\n\n\tcatch (e)\n\t{\n\t}\n}", "function TitleWidget(screen, widgetId) {\n Widget.call(this, screen, widgetId, \"title\");\n}", "function Scene_OmoriTitleScreen() { this.initialize.apply(this, arguments); }", "function setTitleBar(frm, titleName)\n{\n\tif(kony.os.deviceInfo().name != \"thinclient\")\n\t\tfrm.title = titleName;\n}", "_createHeader() {\n var layout = new qx.ui.layout.HBox();\n var header = new qx.ui.container.Composite(layout);\n header.setAppearance(\"app-header\");\n\n var title = new qx.ui.basic.Label(\"Demo Browser\");\n var version = new qxl.versionlabel.VersionLabel();\n version.setFont(\"default\");\n\n header.add(title);\n header.add(new qx.ui.core.Spacer(), { flex: 1 });\n header.add(version);\n\n return header;\n }", "function setTitleBar(frm, titleName) {\n if (kony.os.deviceInfo().name != \"thinclient\") frm.title = titleName;\n}", "function _createTitle() {\n\tthis.titleSurface = new Surface({\n\t\tcontent: '',\n\t\tsize: [undefined, this.options.titleSize]\n\t});\n\n\tthis.bufferAmount += this.options.bufferSize;\n\tvar titleSurfaceModifier = new StateModifier({\n\t\ttransform: Transform.translate(0, this.bufferAmount, 2)\n\t});\n\n\tthis.add(titleSurfaceModifier).add(this.titleSurface);\n}", "setTitle(title) {\n\t\tthis.title = title;\n\t}", "function WINDOW_HEADER$static_(){ToolbarSkin.WINDOW_HEADER=( new ToolbarSkin(\"window-header\"));}", "async _refreshBarTitle() {\n this._top.attr(\"width\", this._dimView.width).attr(\"height\", this._barTitleHeight);\n }", "function Window_TitleCommand() {\n this.initialize.apply(this, arguments);\n}", "function createTitle() {\n return new Title(Object(_angular_core__WEBPACK_IMPORTED_MODULE_2__[\"inject\"])(DOCUMENT$1));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A method decorator that ensures the actor is in the expected state before proceeding. If the actor is not in the expected state, the decorated method returns a rejected promise.
function expectState(expectedState, method) { return function(...args) { if (this.state !== expectedState) { const msg = "Wrong State: Expected '" + expectedState + "', but current " + "state is '" + this.state + "'"; return Promise.reject(new Error(msg)); } return method.apply(this, args); }; }
[ "function expectState(expectedState, method) {\n return function(...args) {\n if (this.state !== expectedState) {\n let msg = \"Wrong State: Expected '\" + expectedState + \"', but current \"\n + \"state is '\" + this.state + \"'\";\n return Promise.reject(new Error(msg));\n }\n\n return method.apply(this, args);\n };\n}", "abstractStepMoveAllowedToPromise(movingBack) {\n return Promise.resolve(this.stepMoveAllowed(movingBack));\n }", "validate() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (this.hasAsync) {\n\t\t\t\tthis.passes(() => resolve(true));\n\t\t\t\tthis.fails(() => resolve(false));\n\t\t\t} else {\n\t\t\t\tthis.passes() ? resolve(true) : resolve(false);\n\t\t\t}\n\t\t});\n\t}", "async verify(...expectations) {\n await this._arc.idle;\n let received = await this._handle.toList();\n let misses = [];\n for (let item of received.map(r => r.rawData[this._field])) {\n let i = expectations.indexOf(item);\n if (i >= 0) {\n expectations.splice(i, 1);\n } else {\n misses.push(item);\n }\n }\n this._handle.clearItemsForTesting();\n\n let errors = [];\n if (expectations.length) {\n errors.push(`Expected, not received: ${expectations.join(' ')}`);\n }\n if (misses.length) {\n errors.push(`Received, not expected: ${misses.join(' ')}`);\n }\n\n return new Promise((resolve, reject) => {\n if (errors.length === 0) {\n resolve();\n } else {\n reject(new Error(errors.join(' | ')));\n }\n });\n }", "challengeCanBeResolved(propID) {\n return __awaiter(this, void 0, void 0, function* () {\n const deployed = this.requireDeployed();\n return yield deployed.methods.challengeCanBeResolved(propID).call();\n });\n }", "async function assertState(state) {}", "onClick() {\n const { mutate, getMutationInput, validateData, onSuccess, onFail } = this.props;\n this.setInProgress(() => {\n mutate(getMutationInput())\n .then(({ data }) => {\n const errors = validateData(data);\n if (errors) {\n this.setFail(() => {\n if (onFail) onFail(errors);\n this.setDefault();\n });\n } else {\n this.setSuccess(() => {\n if (onSuccess) onSuccess(data);\n this.setDefault();\n });\n }\n })\n .catch((errors) => {\n this.setFail(onFail ? () => onFail(errors) : this.setDefault);\n });\n });\n }", "assertTransitionLegal(allowedState, transitionTo) {\n if (!(this.state === allowedState)) {\n throw new Error(`Assertion failure: cannot transition from ${TraitState[this.state]} to ${TraitState[transitionTo]}.`);\n }\n }", "thenWithState(onResolve = function(r) { return r }, onReject = function(e) { throw e }) { return new StatefulPromise(this.then(onResolve, onReject)); }", "handleState() {\n return this.checkHealth();\n }", "function requireState(obj)\n{\n if (!isState(obj))\n throw AssertionException(\"Is not a valid state: \" + obj);\n}", "handle(event, context) {\n return __awaiter(this, void 0, void 0, function* () {\n const failedGoal = event.data.SdmGoal[0];\n if (failedGoal.state !== \"failure\") { // atomisthq/automation-api#395\n automation_client_1.logger.debug(`Nevermind: failure reported when the state was=[${failedGoal.state}]`);\n return Promise.resolve(automation_client_1.Success);\n }\n const id = repoRef_1.repoRefFromSdmGoal(failedGoal, yield RequestDownstreamGoalsOnGoalSuccess_1.fetchScmProvider(context, failedGoal.repo.providerId));\n const goals = RequestDownstreamGoalsOnGoalSuccess_1.sumSdmGoalEventsByOverride(yield fetchGoalsOnCommit_1.fetchGoalsForCommit(context, id, failedGoal.repo.providerId), [failedGoal]);\n const goalsToSkip = goals.filter(g => isDependentOn(failedGoal, g, mapKeyToGoal(goals)))\n .filter(g => g.state === \"planned\");\n yield Promise.all(goalsToSkip.map(g => storeGoals_1.updateGoal(context, g, {\n state: \"skipped\",\n description: `Skipped ${g.name} because ${failedGoal.name} failed`,\n })));\n return automation_client_1.Success;\n });\n }", "beRejected() {\n return this._actual.then(\n function() {\n this._assert(false, null, '${actual} resolved incorrectly.');\n }.bind(this),\n function(error) {\n this._assert(\n true, '${actual} rejected correctly with ' + error + '.', null);\n }.bind(this));\n }", "notifyGameOver(gameResult) {\n // Nothing to do here for now.\n return Promise.resolve();\n }", "validate({ getState, action }, allow, reject) {\n const state = getState();\n if (timerSel.status(state) === 'started') {\n // already started just silently reject\n return reject();\n }\n if (timerSel.value(state) > 0) {\n allow(action);\n } else {\n reject(timerStartError(new Error('Can\\'t start, already zero. Reset first')));\n }\n }", "async function expectReversion(instance, revertReason, from, method, ...args) {\n if (revertReason === \"\") {\n revertReason = \"invalid opcode\";\n }\n try {\n await instance[method](...args, { from });\n }\n catch (error) {\n if (!error.message.includes(revertReason)) {\n assert.equal(error.message, revertReason);\n }\n else {\n assert.isOk(true);\n return;\n }\n }\n assert.isNotOk(true, `${method}(...[${args.length}]) did not revert`);\n }", "get failed () {\n if (this.hasOwnProperty('thrown')) return true;\n if (!this.promise) return false;\n if (!this.promise.settled) return undefined;\n return this.promise.hasOwnProperty('rejected');\n }", "isNotSelected() {\n return this.then(() => this._assertSelected(false));\n }", "function checkActsConsistency(){\n checkConsistency(Action.ACTS);\n //set expections\n verifyCondition = true;\n expectations = Expect.AFTER_ACTS;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Event handler for test pass
onTestPass(test) { this._passes++; this._out.push(test.title + ': pass'); let status_id = this.qaTouch.statusConfig('Passed'); let caseIds = this.qaTouch.TitleToCaseIds(test.title); if (caseIds.length > 0) { let results = caseIds.map(caseId => { return { case_id: caseId, status_id: status_id, }; }); this._results.push(...results); } }
[ "runTests() {\n this.testCorrect()\n this.testComplete()\n }", "function newTestEventHandler() {\n\t$('#test_status').delegate('.newbtn', 'click', function() { \n\t\ttest_review_mode=false;\n\t\ttimed_test_mode=false;\n\t\t//Need to first check to see if there are generated tests that the user\n\t\t//has not taken and only if there aren't any, generate a new test -- Maya Jan '13\n\t\tgenerateNewTest(sess_data['user_id'],cur_test_type)\n\t});\n}", "onTestEnd(test) {\n if (this._results.length === 0) {\n console.warn(\"No test cases were matched. Ensure that your tests are declared correctly and matches TRxxx\");\n return;\n }\n this.qaTouch.publish(this._results);\n }", "function RUN_TEST_AFTER_EVENT(evt, callback)\n{\n\to.addListener(evt,function(){o.test(function(){callback(arguments);});});\n}", "pass(description) {\n this.results.get(this.currentContext).passes++;\n this.results.get(this.currentContext).tests++;\n console.log(`[PASSED] ${description}`);\n }", "function newTimedTestEventHandler() {\n\t$('#test_status').delegate('.newtimebtn', 'click', function() { \n\t\ttest_review_mode=false;\n\t\ttimed_test_mode=true;\n\t\t//Need to first check to see if there are generated tests that the user\n\t\t//has not taken and only if there aren't any, generate a new test -- Maya Jan '13\n\t\tgenerateNewTest(sess_data['user_id'],cur_test_type)\n\t});\n}", "function subscribeToTestRunner(){\n\n page.evaluate(function(){\n\n if(window.Y && Y.Test && Y.Test.Runner) {\n\n function handleTestResult(data){\n switch(data.type) {\n case Y.Test.Runner.TEST_PASS_EVENT:\n // onsole.log(\"Test named '\" + data.testName + \"' passed.\");\n window.TestRunProgress += '.'\n break;\n case Y.Test.Runner.TEST_FAIL_EVENT:\n // onsole.log(\"Test named '\" + data.testName + \"' failed with message: '\" + data.error.message + \"'.\");\n window.TestRunProgress += 'F'\n break;\n case Y.Test.Runner.TEST_IGNORE_EVENT:\n // onsole.log(\"Test named '\" + data.testName + \"' was ignored.\");\n window.TestRunProgress += 'I'\n break;\n }\n }\n Y.Test.Runner.subscribe(Y.Test.Runner.TEST_FAIL_EVENT, handleTestResult);\n Y.Test.Runner.subscribe(Y.Test.Runner.TEST_IGNORE_EVENT, handleTestResult);\n Y.Test.Runner.subscribe(Y.Test.Runner.TEST_PASS_EVENT, handleTestResult);\n }\n return true;\n });\n\n}", "function doExecAndDisplayTests(event) {\n event.stopPropagation();\n var numAttempts = setNumAttempts(id);\n outputLog = new FeedbackLog(world, id, numAttempts);\n outputLog.numAttempts += 1;\n runAGTest(world, id, outputLog);\n\n // TODO: extract and document this...\n var tip_tests = document.getElementsByClassName(\"data\"),\n offsetWidth = $(\".inner-titles\");\n if (offsetWidth.length) {\n offsetWidth = offsetWidth[0].offsetWidth - 50 + \"px\";\n for(var i = 0; i < tip_tests.length; i++) {\n tip_tests[i].style.maxWidth = offsetWidth;\n }\n }\n sessionStorage.setItem(id + \"_popupFeedback\", '');\n}", "_passed(test) {\n const sessionId = this._getSessionId();\n this._updateJob(sessionId, { 'test[success]': true, 'test[name]': test.title });\n }", "function testRun()\r\n{\r\n}", "function hptClickHandler(evt){\n evt.stopPropagation();\n showHidePassedTests();\n }", "function testEvent(){ testEvent.fired = true; }", "runTest() {\n this.result.recordResultWhileTesting();\n }", "function handleEvent(event){\r\n \r\n var message = \"\",\r\n results = event.results,\r\n i, len;\r\n \r\n switch(event.type){\r\n case testRunner.BEGIN_EVENT:\r\n message = \"YUITest@\" + YUITest.version + \"\\n\";\r\n \r\n if (testRunner._groups){\r\n message += \"Filtering on groups '\" + testRunner._groups.slice(1,-1) + \"'\\n\";\r\n }\r\n break;\r\n \r\n case testRunner.COMPLETE_EVENT:\r\n message = \"\\nTotal tests: \" + results.total + \", Failures: \" + \r\n results.failed + \", Skipped: \" + results.ignored +\r\n \", Time: \" + (results.duration/1000) + \" seconds\\n\";\r\n \r\n if (failures.length){\r\n message += \"\\nTests failed:\\n\";\r\n \r\n for (i=0,len=failures.length; i < len; i++){\r\n message += \"\\n\" + (i+1) + \") \" + failures[i].name + \" : \" + failures[i].error.getMessage() + \"\\n\";\r\n if (failures[i].error.stack) {\r\n message += \"Stack trace:\\n\" + filterStackTrace(failures[i].error.stack) + \"\\n\";\r\n }\r\n }\r\n \r\n message += \"\\n\";\r\n }\r\n \r\n if (errors.length){\r\n message += \"\\nErrors:\\n\";\r\n \r\n for (i=0,len=errors.length; i < len; i++){\r\n message += \"\\n\" + (i+1) + \") \" + errors[i].name + \" : \" + errors[i].error.message + \"\\n\";\r\n if (errors[i].error.stack) {\r\n message += \"Stack trace:\\n\" + filterStackTrace(errors[i].error.stack) + \"\\n\";\r\n }\r\n }\r\n \r\n message += \"\\n\";\r\n }\r\n \r\n message += \"\\n\\n\";\r\n break;\r\n \r\n case testRunner.TEST_FAIL_EVENT:\r\n message = \"F\";\r\n failures.push({\r\n name: stack.concat([event.testName]).join(\" > \"),\r\n error: event.error\r\n });\r\n\r\n break;\r\n \r\n case testRunner.ERROR_EVENT:\r\n errors.push({\r\n name: stack.concat([event.methodName]).join(\" > \"),\r\n error: event.error\r\n });\r\n\r\n break;\r\n \r\n case testRunner.TEST_IGNORE_EVENT:\r\n message = \"S\";\r\n break;\r\n \r\n case testRunner.TEST_PASS_EVENT:\r\n message = \".\";\r\n break;\r\n \r\n case testRunner.TEST_SUITE_BEGIN_EVENT:\r\n stack.push(event.testSuite.name);\r\n break;\r\n \r\n case testRunner.TEST_CASE_COMPLETE_EVENT:\r\n case testRunner.TEST_SUITE_COMPLETE_EVENT:\r\n stack.pop();\r\n break;\r\n \r\n case testRunner.TEST_CASE_BEGIN_EVENT:\r\n stack.push(event.testCase.name);\r\n break;\r\n \r\n //no default\r\n } \r\n \r\n cli.print(message);\r\n }", "function accept() {\n // Show the passed message.\n console.log(color.greenBright(` [✓] Passed`));\n\n // Process the next specs.\n next();\n }", "function runTest() {\n\n // check they've selected a test to run\n if (view.testIndex === null) {\n displayToast('Please pick a test');\n return;\n }\n\n // change to the current tests tab\n view.selectedTab = 0;\n\n // send the request to the server to run the test\n view.testingCancelled = false;\n //logger.debug('Asking server to run a test: ' + view.test, logfile);\n ipcRenderer.send('run-test', view.testIndex);\n\n // show the status dialog\n $mdDialog.show({\n controller: 'StatusController',\n controllerAs: 'app',\n templateUrl: './modules/status/status.html',\n parent: angular.element(document.body),\n clickOutsideToClose: false,\n fullscreen: true\n });\n\n }", "function didPass(grade , testTypes ){\n // Using a switch & case to iterate over each test with the grade provided\n switch(testTypes){\n case \"standard\" : \n grade = Math.floor(Math.random() * (+100 - +0));\n if(grade >= 89 && grade <= 100){\n return true\n }\n break;\n case \"pop-quiz\" : \n grade = Math.floor(Math.random() * (+100 - +0));\n if(grade >= 60 && grade <= 100){\n return true\n }\n break;\n case \"final\" : \n grade = Math.floor(Math.random() * (+100 - +0));\n if(grade >= 90 && grade <= 100){\n return true\n }\n break;\n case \"pre-test\" : \n grade = Math.floor(Math.random() * (+100 - +0));\n if(grade >= 50 && grade <= 100){\n return true\n }\n break;\n case \"post-test\" : \n grade = Math.floor(Math.random() * (+100 - +0));\n console.log(\"your score is : \" + grade );\n if(grade >= 75 && grade <= 100){\n return true\n }\n break;\n default : \n return false;\n \n }\n}", "function onDone(event){\n\tconsole.log('done button clicked');\n\tif (validateContents() === true){ \n finishTest();\n }\n\telse {\n\t\trepeatTest();\n\t\treset();\n\t}\n}", "function onRunTestClicked(e) {\n e.preventDefault();\n executableModuleMessageChannel.send('ui_backend', {'command': 'run_test'});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Vote for a local address
function SeenLocal(addr) { // LOCK(cs_mapLocalHost); if (!mapLocalHost[addr]) return false; mapLocalHost[addr].nScore++; AdvertizeLocal(); return true; }
[ "function find_own_vote_address() {\n for(var i=0 ; i < eth.keys.length ; i++) {\n var addr = eth.secretToAddress(eth.keys[i]);\n //Got it.\n if( registeredState(addr) != \"0x\") { return addr; }\n }\n return null;\n}", "function AdvertizeLocal() {\n // LOCK(cs_vNodes)\n vNodes.forEach(function(pnode) {\n if (pnode.fSuccessfullyConnected) {\n let addrLocal = GetLocalAddress(pnode.addr);\n if (addrLocal.IsRoutable() && addrLocal != pnode.addrLocal) {\n pnode.PushAddress(addrLocal);\n pnode.addrLocal = addrLocal;\n }\n }\n })\n}", "function delegate(address to) public{\n\t\tVoter storage sender = voters[msg.sender] ; //asssigns reference\n\t\tif(sender.voted) return ;\n\t\twhile(voters[to].delegate != address(0) && voters[to].delegate != msg.sender)\n\t\tto = voters[to].delegate ;\n\t\tif(to == msg.sender) return ;\n\t\tsender.voted = true ;\n\t\tsender.delegate = to ;\n\t\t Voter storage delegateTo = voters[to];\n if (delegateTo.voted)\n proposals[delegateTo.vote].voteCount += sender.weight;\n else\n delegateTo.weight += sender.weight;\n }", "function IsReachable(addr) { }", "function checkVote() {\n\t\n db.find({account: addr}, function(err, docs) {\n \tif(err) {\n \t\talert(\"Error : \" + e);\n \t}\n \tif (!docs.length) {\n \t\talert(\"Error : no account with this address \" + addr + \" found in the database!\");\n \t\treturn;\n \t} else if (docs.length>1) {\n \t\talert(\"Error : two or more accounts with this address \" + addr + \" found in the database!\");\n \t\treturn;\n \t} else {\n \t\tvar x;\n \t\ttry {\n \t\t\tx = new BigNumber(docs[0].privateVotingKey);\n \t\t} catch (e) {\n \t\t\tconsole.log(e);\n \t\t\tvar personalPrivateKey = docs[0].personalPrivateKey;\n \t\t\tx = createPrivateVotingKey(addr, personalPrivateKey);\n \t\t}\n \t\t\n var voter = WaveVoteAddr.getVoterBis(web3.eth.accounts[accounts_index]);\n var yG = [voter[5][0], voter[5][1]];\n var vote = [voter[6][0], voter[6]][1];\n \n var totalVotant = WaveVoteAddr.totalregistered();\n var totalCandidat = WaveVoteAddr.getTotalAnswers();\n \n \tvar res = cryptoAddr.checkVote(x,yG,vote, totalVotant, totalCandidat);\n \t\n \tif (res[0]) {\n \t\talert(\"Your vote is : \" + web3.toUtf8(WaveVoteAddr.answerList(res[2])));\n \t} else {\n \t\talert(res[1]);\n \t}\n \t}\n });\n\t\n}", "function updateNewVote(_myVoterAddress){\r\n $(\"#\" + _myVoterAddress+\"_cell\").html(\"<span class='label label-primary'>Voted</span>\"); \r\n loadTotalVotes(Ballot);\r\n }", "async function approveLpCoreAddress() {\n\t\t\tawait mockDaiContractInstance.methods\n\t .approve(\n\t lpCoreAddress,\n\t appMockDaiBalanceinWei\n\t )\n\t .send({from: irrigateAddress})\n\t .catch((e) => {\n\t console.log(`Error approving DAI allowance: ${e.message}`)\n console.log('Trying again')\n approveLpCoreAddress()\n\t })\n\t }", "function voteForCandidate() {\n candidateName = $(\"#candidate\").val();\n contractInstance.IncrementVote(candidateName, {from: web3.eth.accounts[0]}, function() {\n let div_id = candidates[candidateName];\n $(\"#\" + div_id).html(contractInstance.NumVotes.call(candidateName).toString());\n });\n}", "function gotoAddr() {\r\n var inp = prompt(\"Enter address or label\", \"\");\r\n var addr = 0;\r\n if (labels.find(inp)) {\r\n addr = labels.getPC(inp);\r\n } else {\r\n if (inp.match(/^0x[0-9a-f]{1,4}$/i)) {\r\n inp = inp.replace(/^0x/, \"\");\r\n addr = parseInt(inp, 16);\r\n } else if (inp.match(/^\\$[0-9a-f]{1,4}$/i)) {\r\n inp = inp.replace(/^\\$/, \"\");\r\n addr = parseInt(inp, 16);\r\n }\r\n }\r\n if (addr === 0) {\r\n message(\"Unable to find/parse given address/label\");\r\n } else {\r\n regPC = addr;\r\n }\r\n updateDebugInfo();\r\n }", "function vote(votedUsername, votedFor, voterIPv4Address, voterUserAgent, response) {\r\n if (voterUserAgent.indexOf(\"HighFidelityInterface\") === -1) {\r\n var responseObject = {\r\n status: \"error\",\r\n text: \"Error while voting!\"\r\n };\r\n\r\n response.statusCode = 500;\r\n response.setHeader('Content-Type', 'application/json');\r\n return response.end(JSON.stringify(responseObject));\r\n }\r\n\r\n var query = `REPLACE INTO \\`multiConAvatarContestVotes\\` (voterUsername, votedFor, voterIPv4Address)\r\n VALUES ('${votedUsername}', '${votedFor}', '${voterIPv4Address}')`;\r\n\r\n connection.query(query, function(error, results, fields) {\r\n if (error) {\r\n var responseObject = {\r\n status: \"error\",\r\n text: \"Error while voting! \" + JSON.stringify(error)\r\n };\r\n\r\n response.statusCode = 500;\r\n response.setHeader('Content-Type', 'application/json');\r\n return response.end(JSON.stringify(responseObject));\r\n }\r\n \r\n var responseObject = {\r\n status: \"success\",\r\n text: \"Successfully voted.\"\r\n };\r\n\r\n response.statusCode = 200;\r\n response.setHeader('Content-Type', 'application/json');\r\n return response.end(JSON.stringify(responseObject));\r\n });\r\n}", "function voteClicked($this, $fromMap) {\n // don't let user click again\n $('.vote_button').hide();\n \n //do not increase the counters html value, if not allowed to vote\n if($.cookie('demand') != 'true') {\n // increase counter at users view\n var sel = '#counter_' + $this;\n var countString = \"\" + (parseInt($(sel).html()) + 1);\n $(sel).html(countString);\n $('.top_vote_info').html('Danke für Deine Stimme!');\n }\n\n // if vote was sent from map, call AJAX vote\n // otherwise vote was already executed by rails remote form\n if($fromMap) {vote($this);};\n}", "function geolocateByIP() {\n\tif (google.loader.ClientLocation) {\n\t\tvar location = google.loader.ClientLocation;\n\t\tcurrentAddress = location.address.city + ', ' + location.address.region;\n\t\tstoreMyLocation(location.latitude, location.longitude);\n\t} else {\n\t\tcurrentAddress = 'San Fransisco, CA';\n\t\tstoreMyLocation(37.75, -122.45);\n\t}\n}", "updateAddressValue(address, value) {\n this.universe[parseInt(address)] = value;\n\n this.update();\n }", "async checkNodeAddress(address) {\n const result = await this.requestServer(address, 'ping', {\n method: 'GET',\n timeout: this.options.request.pingTimeout\n });\n\n if(result.address != this.address) {\n throw new Error(`Host ${this.address} is wrong`);\n }\n }", "async function castVote(web3, address, choice_, options) {\n const contract = new web3.eth.Contract(pollInfo.abi, address);\n const methods = contract.methods;\n const choice = toHex(web3, choice_);\n const method = await methods.vote(choice);\n const result = await method.send(options);\n const receipt = await web3.eth.getTransactionReceipt(result.transactionHash);\n const ev = UTILS.decodeLog(web3, contract,\n receipt.logs, [\"Vote\"]);\n \n return ev.shift().outcome;\n}", "function gotoAddr() {\n\tvar inp = prompt( \"Enter address or label\", \"\" );\n\tvar addr = 0;\n\tif( findLabel( inp ) ) {\n\t\taddr = getLabelPC( inp );\n\t} else {\n\t\tif( inp.match( new RegExp( /^0x[0-9a-f]{1,4}$/i ) ) ) {\n\t\t\tinp = inp.replace( /^0x/, \"\" );\n\t\t\taddr = parseInt( inp, 16 );\n\t\t} else if( inp.match( new RegExp( /^\\$[0-9a-f]{1,4}$/i))) {\n\t\t\tinp = inp.replace( /^\\$/, \"\" );\n\t\t\taddr = parseInt( inp, 16 );\n\t\t}\n\t}\n\tif( addr == 0 ) {\n\t\talert( \"Unable to find/parse given address/label\" );\n\t} else {\n\t\tregPC = addr;\n\t}\n\tupdateDebugInfo();\n}", "function submitAddress( addr ) {\r\n\tgeocode( addr, function( places ) {\r\n\t\tvar n = places && places.length;\r\n\t\tlog( 'Number of matches: ' + n );\r\n\t\tif( ! n ) {\r\n\t\t\tspin( false );\r\n\t\t\tdetailsOnly( S(\r\n\t\t\t\tlog.print(),\r\n\t\t\t\tT('didNotFind')\r\n\t\t\t) );\r\n\t\t}\r\n\t\telse if( n == 1 ) {\r\n\t\t\tfindPrecinct( places[0], addr );\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif( places ) {\r\n\t\t\t\tdetailsOnly( T('selectAddressHeader') );\r\n\t\t\t\tvar $radios = $('#radios');\r\n\t\t\t\t$radios.append( formatPlaces(places) );\r\n\t\t\t\t$detailsbox.show();\r\n\t\t\t\t$details.find('input:radio').click( function() {\r\n\t\t\t\t\tvar radio = this;\r\n\t\t\t\t\tspin( true );\r\n\t\t\t\t\tsetTimeout( function() {\r\n\t\t\t\t\t\tfunction ready() {\r\n\t\t\t\t\t\t\tfindPrecinct( places[ radio.id.split('-')[1] ] );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif( $.browser.msie ) {\r\n\t\t\t\t\t\t\t$radios.hide();\r\n\t\t\t\t\t\t\tready();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t$radios.slideUp( 350, ready );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}, 250 );\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tsorry();\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}", "selectedAddress(value, event) {\n if (value === this.current) {\n this.savedAddress = this.unverifiedAddress;\n } else if (value === this.verified) {\n this.savedAddress = this.verifiedAddress;\n if (this.isBussinessUnit) {\n this.savedAddress = { ...this.savedAddress,\n unit: {\n uid: this.unverifiedAddress.unit.uid\n }\n }\n }\n if (this.unverifiedAddress.userId) {\n this.savedAddress = { ...this.savedAddress,\n userId: this.unverifiedAddress.userId,\n }\n }\n }\n this.$emit('selectedAddress', {\n label: this.formAddressValues(this.savedAddress),\n value: this.savedAddress,\n });\n }", "function verifiedAddressListener() {\n var address2 = $form.find('#addressLine2').val();\n\n var addressObj = {\n 'addressLine': $form.find('#addressLine1').val(),\n 'locality': $form.find('#city').val(),\n 'state': $form.find('#state').val(),\n 'postalCode': $form.find('#zip').val()\n };\n\n $.each(addressObj, function(key, value) {\n if (validator.isEmptyField(value)) {\n addressObj = false;\n }\n });\n\n $('[data-address=\"verifiable\"]').each(function() {\n if ($(this).hasClass('error')) {\n addressObj = false;\n }\n });\n\n if (addressObj) {\n verifiedAddress.getVerifiedAddress(addressObj, address2);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function CheckUpdate takes an array of the user's starred files and their respective last udated dates and checks to see if the dates have changed. If the dates have changed, the script will log that to the Logger
function CheckUpdate(){ //logging start of method Logger.log("starting CheckUpdate()"); //declaring variables var user = Session.getEffectiveUser(); //returns email address var log = setUp(-1); //returns the Spreadsheet Object of the log var files, curDate, name, file, prevDate; var numFiles = log.getActiveSheet().getLastRow(); //looping through starred files recorded on the log to check if they were updated for(i = 2; i <= numFiles; i++){ //getting information from spreadsheet name = log.getActiveSheet().getRange(i, 1).getValue(); prevDate = log.getActiveSheet().getRange(i, 2).getValue(); //getting current date files = DriveApp.getFilesByName(name); if(files.hasNext() == false){ Logger.log("File missing from spreadsheet log"); IDfiles(); return; } file = files.next(); curDate = file.getLastUpdated(); curDate = curDate.toString(); //send an email to the user if the file has been updated //then overwrites the old date in the log to record the changes //email will be received in the user's gmail from themselves if(prevDate != curDate){ Logger.log("Update Found for " + name + " ...Sending Email"); MailApp.sendEmail(user, name + " has been modified", "A collaborator has modified " + name + " please check your Drive for changes."); log.getActiveSheet().getRange(i, 2).setValue(curDate); } else { Logger.log(name + " Not Updated"); } } //logging and returning the method Logger.log("returning CheckUpdates()"); return; }
[ "function checkUpdate() {\n\tif(file_date(serviceIniFile) > serviceIniFileDate)\n\t\texit(0);\n}", "function checkFileTrackerUpToDate() {\n let currentDate = getDate();\n let keys = Object.keys(roomsFileTracker);\n \n keys.forEach(function(key) {\n console.log(\"Key: \" + key);\n let sample = roomsFileTracker[key].date;\n if((typeof(date) !== 'undefined') && (currentDate !== sample)) {\n populateRoomsFileTracker();\n return false;\n }\n });\n return true;\n}", "function isUpToDate(outputFile, inputFiles, opts)\n{\n\tif (opts && opts.force)\n\t{\n\t\tif (opts && opts.debug)\n\t\t\tconsole.log(`Forcing update of target file ${outputFile}...`);\n\t\treturn false;\n\t}\n\t\n\t// Get the target file time\n\tvar targetTime = filetime(outputFile);\n\tif (targetTime == 0)\n\t{\n\t\tif (opts && opts.debug)\n\t\t\tconsole.log(`Target file ${outputFile} doesn't exist, needs update...`);\n\n\t\treturn false;\n\t}\n\n\t// Any input files?\n\tif (!inputFiles || inputFiles.length == 0)\n\t\treturn false;\n\n\t// Check each\n\tfor (var f of inputFiles)\n\t{\n\t\tif (filetime(f) > targetTime)\n\t\t{\n\t\t\tif (opts && opts.debug)\n\t\t\t\tconsole.log(`Target file '${outputFile}' is stale compared to '${f}', needs update...`)\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (opts && opts.debug)\n\t{\n\t\tconsole.log(`Target file '${outputFile}' is update to date with respect to:`);\n\t\tfor (var f of inputFiles)\n\t\t{\n\t\t\tconsole.log(` ${f}`);\n\t\t}\n\t}\n\n\n\treturn true;\n}", "function checkForUpdate()\r\n\t\t\t{\r\n\t\t\t\tappUpdater.checkNow();\r\n\t\t\t}", "function checkUpdates() {\n\tGitCUpdate.files([ 'package.json' ], (err, results)=> {\n\t\tif (err) return;\n\t\tresults.forEach(file=> {\n\t\t\tlet c = file.contents.toString();\n\t\t\tif (c[0] === \"{\") {\n\t\t\t\tlet data = JSON.parse(c);\n\t\t\t\t\n\t\t\t\tlet msg = (data.version > pJson.version)? \"Доступно обновление! -> github.com/xTCry/VCoin \\t[\"+(data.version +\"/\"+ pJson.version)+\"]\":\n\t\t\t\t\t\t\t// (data.version != pJson.version)? \"Версии различаются! Проверить -> github.com/xTCry/VCoin \\t[\"+(data.version +\"/\"+ pJson.version)+\"]\":\n\t\t\t\t\t\t\tfalse;\n\t\t\t\tif(msg) {\n\t\t\t\t\tif(onUpdatesCB) onUpdatesCB(msg);\n\t\t\t\t\telse con(msg, \"white\", \"Red\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}", "function date_checker() {\n // If date is new, added to date_tracker array\n date_only = DateTime.substr(0, 10);\n if (!date_tracker.includes(date_only)) {\n date_tracker.push(date_only);\n\n // Completes auto_transfers before CSV input transactions if date_only is new\n amendment_check(false);\n }\n }", "function checkForUpdatesToTodos() {\n return new Promise(function(resolve) {\n listFiles(\".\").then(function(filenames) {\n\n filenames.forEach(function(filename) {\n\n fs.stat(filename, function(err, stats){\n if (err) throw err;\n if (stats.mtime <= mtimes[filename]) {\n return;\n }\n\n mtimes[filename] = stats.mtime;\n\n findTodosInFile(filename).then(function(fileinfo){\n // TODO: Optimize this so that spurious updates aren't sent down.\n // For example, if there's a change but it doesn't affect anything\n // shown in the frontend (eg, line numbers don't change and the edit\n // isn't in a TODO line), then don't push an update.\n if (fileinfo.todos.length || fileinfo.hadTodos) {\n resolve(true);\n }\n });\n });\n });\n });\n });\n}", "function checkforupdate(){\n\t\t\tif (update_needed){\n\t\t\t\treturn ; \t\t\t\t\n\t\t\t}\n\n\t\t\tconsole.log(\"checking for update\");\n\t\t\tvar images_in_file = 0;\n\n\t\t\t$.get(\"check.php\", function(data){\n\t\t\t\t\timages_in_file = data; \n\t\t\t\t\tconsole.log(\"image number previous: \"+on_server);\n\t\t\t\t\tconsole.log(\"image number current: \"+images_in_file);\n\t\t\t\t\tif(images_in_file > on_server){\n\t\t\t\t\t\tupdate_needed = true; \n\t\t\t\t\t};\n\t\t\t});\n\t\t}", "function checkForChangedFiles() {\n\n// edit this line below with the ID \"XXXXXXXxxXXXwwerr0RSQ2ZlZms\" of the folder you want to monitor for changes\n var folderID = '\"' + \"1AO_tQMMz2c6_l69s9vo9PW0PTy4nrYqi\" + '\"';\n\n// Email Configuration\n var emailFromName =\"Kamerový zapezpečovací systém (Neodpovídejte)\";\n var emailSubject = \"Registrován pohyb\";\n var emailBody = \"<br>Detekován pohyb<br>\";\n var emailFooter = \"Administrátor mv.marekvitula@gmail.com\";\n\n var folderSearch = folderID + \" \" + \"in parents\";\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName('Obrazky');\n //var email = sheet.getRange(\"E1\").getValue();\n var email = \"mv.marekvitula@gmail.com\";\n var timezone = ss.getSpreadsheetTimeZone();\n var today = new Date();\n\n // Run script next day, and set below to 24 hours\n // 60 * 1000 = 60 second\n // 60* (60 * 1000) = 60 mins which is 1 hour\n // 24* (60* (60 * 1000)) = 1 day which 24 hours\n //var oneDayAgo = new Date(today.getTime() - 1 * 24 * 60 * 60 * 1000);\n var oneDayAgo = new Date(today.getTime() - 1 * 60 * 1000);\n\n var startTime = oneDayAgo.toISOString();\n\n var search = '(trashed = true or trashed = false) and '+ folderSearch +' and (modifiedDate > \"' + startTime + '\")';\n\n var files = DriveApp.searchFiles(search);\n\n var row = \"\", count=0;\n\n while( files.hasNext() ) {\n\n var file = files.next();\n var fileName = file.getName();\n var fileURL = file.getUrl();\n var lastUpdated = Utilities.formatDate(file.getLastUpdated(), timezone, \"yyyy-MM-dd HH:mm\");\n var dateCreated = Utilities.formatDate(file.getDateCreated(), timezone, \"yyyy-MM-dd HH:mm\")\n\n var type=file.getMimeType();\n\n if(type==MimeType.JPEG)\n {\n sheet.appendRow([file.getDateCreated(),file.getName(),type,file.getUrl(),'=IMAGE(\"https://drive.google.com/uc?export=view&id=' + file.getId() + '\",1)']);\n sheet.setRowHeight(sheet.getLastRow(), 200);\n row += \"<li>\" + lastUpdated + \" <a href='\" + fileURL + \"'>\" + fileName + \"</a></li>\";\n }\n\n count++;\n }\n\n if (row !== \"\") {\n row = \"<p>\" + count + \" fotografií bylo nasnímáno. Tady je seznam:</p><ol>\" + row + \"</ol>\";\n row += emailBody+\"<br>\" + \"<br><small> \"+emailFooter+\" </a>.</small>\";\n MailApp.sendEmail(email, emailSubject, \"\", {name: emailFromName, htmlBody: row});\n }\n}", "async function checkLatestEntry (userId) {\n\n let currentCodedDate = (currentDate.month + 1) + '/' + currentDate.date + '/' + currentDate.year;\n const user = await User.findById(userId);\n\n //if user hasnothing in log OR latestEntryDateFormatted does not match with currentEntryDateFormatted... addEntry\n if(user.codingLogEntries.length === 0) {\n addEntry(userId);\n } else { // if logEntries aren't empty, check for latestDate vs currentDate: same -> update, different -> add\n let lastCodedEntryDate = user.codingLogEntries[user.codingLogEntries.length - 1].dateCodedFormatted;\n let lastCodedEntry = user.codingLogEntries[user.codingLogEntries.length - 1];\n\n if(lastCodedEntryDate == currentCodedDate) { //if you've already entered in something today, update\n updateEntry(userId, lastCodedEntry._id);\n } else { // if you haven't entered in something today but there are things from the past (I do this because lastCodedEntry would be undefined outside of this else)\n addEntry(userId);\n }\n\n }\n\n // req.flash('success_msg', 'Time coded updated!!');\n // res.redirect('/');\n }", "async function checkFileDate() {\n\tcurrentFileDate = moment(new Date).format(\"YYYY-MM-DD\");\n\tif (oldFileDate != currentFileDate) {\n\t\tcanLog = false;\n\t\twhile (logging) {\n\t\t\tawait delay(100);\n\t\t}\n\t\tcloseFile();\n\t\tlet oldFilename = basepath + filenameArg + oldFileDate + '.log';\n\t\tfs.renameSync(filename, oldFilename);\n\t\toldFileDate = currentFileDate;\n\t\topenFile();\n\t}\n}", "function scriptUpdateCheck() {\r\n\tif (Date.now() - scriptLastCheck >= 86400000) { // 86400000 == 1 day\r\n\t\t// At least a day has passed since the last check. Sends a request to check for a new script version\r\n\t\tGM_setValue(\"scriptLastCheck\", Date.now().toString());\r\n\t\tscriptCheckVersion();\r\n\t}\r\n\telse {\r\n\t\t// If a new version was previously detected the notice will be shown to the user\r\n\t\t// This is to prevent that the notice will only be shown once a day (when an update check is scheduled)\r\n\t\tif (scriptLastRemoteVersion > scriptVersion) {\r\n\t\t\tscriptShowUpdateMessage(true, scriptLastRemoteVersion);\r\n\t\t}\r\n\t}\r\n}", "function checkModifiedByNotNull()\n{ \n var strModifiedBy = \"\";\n var strLastDate;\n var fromTotalDate;\n var toTotalDate;\n var fileDate;\n var retStr;\n var noteHandle;\n var theKeys; \n var theValue;\n var REPORT_STR = new Array();\n var siteRootLen = 0;\n var fileRelPath = \"\"; \n var theFile = fileName.substr(fileName.lastIndexOf(dwscripts.FILE_SEP)+1);\n var strFileDate = DWfile.getModificationDateObj(fileName);\n\n strLastDate = addDays(new Date(),intNoofDays-1);\n strLastDate = new Date(strLastDate.getFullYear(),strLastDate.getMonth(),strLastDate.getDate(),0,0,0,0);\n retStr=\"\";\n theValue=\"\";\n noteHandle = MMNotes.open(fileName);\n if (noteHandle > 0)\n {\n theKeys = MMNotes.getKeys(noteHandle); \n \n for(var j=0; j< theKeys.length; j++)\n {\n if (theKeys[j] == 'ccLastSubmitter')\n { \n theValue = MMNotes.get(noteHandle, theKeys[j]);\n strModifiedBy = theValue;\n }\n } // end for loop\n }//end if \n\n if (indexDaysModified == 0) \n { \n if ((strLastDate <= strFileDate) && (modifiedBy.toLowerCase() == strModifiedBy.toLowerCase().match(modifiedBy, \"i\"))) \n { \n\t var intLastMonth = strLastDate.getMonth();\n\t\tvar intLastDate = strLastDate.getDate();\n\t\tvar intLastYear = strLastDate.getFullYear();\n\t\t\n\t\tstrLastDate = localizeDateStr(intLastMonth,intLastDate,intLastYear); \n\n var intFileMonth = strFileDate.getMonth();\n var intFileDate = strFileDate.getDate();\n var intFileYear = strFileDate.getFullYear();\n\t \n\t var fileTime = (strFileDate - new Date(intFileYear,intFileMonth,intFileDate,0,0,0,0)); //in milliseconds\n\t var fileHrs = parseInt((fileTime)/(1000*60*60));\n\t var fileMins = parseInt(((fileTime)-(fileHrs*60*60*1000))/(1000*60));\n\n strFileDate = localizeDateStr(intFileMonth,intFileDate,intFileYear); \n \n\t\t\n\t\tdateRange = strLastDate + \" \" + MM.MSG_To + \" \" + localizeDateStr(htmlMonth,htmlDay,htmlYear);\n\t if (fileMins <= 9)\n\t fileMins = \"0\" + fileMins;\n\t \n\t if (parseInt(fileHrs) > 12)\n {\n fileHrs = parseInt(fileHrs) - 12;\n\n var strTime = localizeTimeStr(fileHrs,fileMins,\"PM\");\n }\n\t else if(parseInt(fileHrs) == 12)\n\t\t{\n\t\t var strTime = localizeTimeStr(fileHrs,fileMins,\"PM\");\n\t\t}\n\t\telse\t \n {\n var strTime = localizeTimeStr(fileHrs,fileMins,\"AM\");\n } \n fileDate = strFileDate + \" \" + strTime;\n\n\t\tfilePath = \"\";\t\t\n\t\tfilePath = fileName.substr(0,(fileName.lastIndexOf(dwscripts.FILE_SEP)+1));\n\t\tsiteRootLen = dreamweaver.getSiteRoot().length;\n\t\tfileRelPath = filePath.substr(siteRootLen); \t \t\t \n if(indexViewPath == 0)\n\t {\n\t filePath = filePath.replace(\"|\",\":\"); \n\t }// end if\n else if(indexViewPath == 1) \n\t {\n\t filePath = testServer + fileRelPath;\n\t\t} \n\t \n REPORT_STR.push( MM.MSG_ModifiedBy + \"= \" + strModifiedBy + \" \"); \n retStr += REPORT_STR.join(\", \");\n\t fileCount++;\n var viewPath = \"\\\"\" + filePath + theFile +\"\\\"\" ;\n\t bodytext += \"\\r\\n\";\n\t bodytext += \" <tr>\" + \"\\r\\n\";\n bodytext += \" <td nowrap>\" + theFile + \"</td>\" + \"\\r\\n\";\n bodytext += \" <td nowrap>\" + fileDate + \"</td>\" + \"\\r\\n\" ;\n bodytext += \" <td nowrap>\" + theValue + \"</td>\" + \"\\r\\n\";\n bodytext += \" <td nowrap>\" + \"<a href=\" + viewPath+ \">\" + MM.Column_View + \"</a>\" + \"</td>\" + \"\\r\\n\";\n bodytext += \" </tr>\" + \"\\r\\n\";\n\t if (theValue == MM.Column_NotKnown) \n\t {\n\t notKnown = MM.MSG_Notknown + \" \" + MM.MSG_NotContribute + \"\\r\\n\";\n\t } \n retStr += MM.MSG_ModifiedDt + \"= \" + strFileDate + \" \" ;\n FileExist += retStr;\n reportItem(REP_ITEM_CUSTOM, fileName, retStr,0,REP_ICON_NOTE);\n } \n } \n else\n { \n if (strToTotalDate <= strFromTotalDate) \n {\n fromTotalDate = strToTotalDate;\n toTotalDate = strFromTotalDate;\n }\n else\n {\n fromTotalDate = strFromTotalDate;\n toTotalDate = strToTotalDate;\n } \n\t// add 1 day to include the toTotalDate date\n\ttoTotalDate = new Date(toTotalDate + (24*60*60*1000-1)); \n\tif ((fromTotalDate <= strFileDate) && (strFileDate <= toTotalDate) && (modifiedBy.toLowerCase() == strModifiedBy.toLowerCase().match(modifiedBy, \"i\"))) \n { \n\t fromTotalDate = new Date(fromTotalDate);\n var fromTotalMonth = fromTotalDate.getMonth(); \n\t var fromTotalDay = fromTotalDate.getDate();\n\t var fromTotalYear = fromTotalDate.getFullYear();\n\t var toTotalMonth = toTotalDate.getMonth(); \n\t var toTotalDay = toTotalDate.getDate();\n\t var toTotalYear = toTotalDate.getFullYear();\n\n var intFileMonth = strFileDate.getMonth();\n var intFileDate = strFileDate.getDate();\n var intFileYear = strFileDate.getFullYear();\n\t var fileTime = (strFileDate - new Date(intFileYear,intFileMonth,intFileDate,0,0,0,0)); //in milliseconds\n\t var fileHrs = parseInt((fileTime)/(1000*60*60));\n\t var fileMins = parseInt(((fileTime)-(fileHrs*60*60*1000))/(1000*60));\n\n\t toTotalDate = localizeDateStr(toTotalMonth,toTotalDay,toTotalYear); \n\t fromTotalDate = localizeDateStr(fromTotalMonth,fromTotalDay,fromTotalYear);\n\t strFileDate = localizeDateStr(intFileMonth,intFileDate,intFileYear); \n\t dateRange = fromTotalDate + \" \" + MM.MSG_To + \" \" + toTotalDate;\n\n\n\t if (fileMins <= 9)\n\t fileMins = \"0\" + fileMins;\n\t \t \t\t \t\t \n\t if (parseInt(fileHrs) > 12)\n {\n fileHrs = parseInt(fileHrs) - 12;\n var strTime = localizeTimeStr(fileHrs,fileMins,\"PM\");\n }\n\t\t else if(parseInt(fileHrs) == 12)\n\t\t {\n\t\t var strTime = localizeTimeStr(fileHrs,fileMins,\"PM\");\n\t\t }\n else\t \n {\n var strTime = localizeTimeStr(fileHrs,fileMins,\"AM\");\n } \n\n fileDate = strFileDate + \" \" + strTime;\n \n \t\t filePath = \"\";\t\t\n\t\t filePath = fileName.substr(0,(fileName.lastIndexOf(dwscripts.FILE_SEP)+1));\n\t\t siteRootLen = dreamweaver.getSiteRoot().length;\n\t\t fileRelPath = filePath.substr(siteRootLen); \t \t\t \n if(indexViewPath == 0)\n\t {\n\t filePath = filePath.replace(\"|\",\":\"); \n\t }// end if\n else if(indexViewPath == 1) \n\t {\n\t filePath = testServer + fileRelPath;\n\t\t }\n\t\t\n REPORT_STR.push( MM.MSG_ModifiedBy + \"= \" + strModifiedBy + \" \"); \n retStr += REPORT_STR.join(\", \");\n\t\t fileCount++;\n var viewPath = \"\\\"\" + filePath + theFile + \"\\\"\";\n\t bodytext += \"\\r\\n\";\n\t\t bodytext += \" <tr>\" + \"\\r\\n\";\n bodytext += \" <td nowrap>\" + theFile + \"</td>\" + \"\\r\\n\";\n bodytext += \" <td nowrap>\" + fileDate + \"</td>\" + \"\\r\\n\" ;\n bodytext += \" <td nowrap>\" + theValue + \"</td>\" + \"\\r\\n\";\n bodytext += \" <td nowrap>\" + \"<a href=\" + viewPath+ \">\" + MM.Column_View + \"</a>\" + \"</td>\" + \"\\r\\n\";\n bodytext += \" </tr>\" + \"\\r\\n\";\n\n\t if (theValue == MM.Column_NotKnown) \n\t {\n\t notKnown = MM.MSG_Notknown + \" \" + MM.MSG_NotContribute + \"\\r\\n\";\n\t }\n retStr += MM.MSG_ModifiedDt + \"= \" + strFileDate + \" \" ;\n FileExist += retStr;\n reportItem(REP_ITEM_CUSTOM, fileName, retStr,0,REP_ICON_NOTE);\n } \n } \n }", "function checkforUpdate() {\n\t//Checks if there is a valid update. If yes returns result object. \n\tApplication.checkUpdate(function(err, result) {\n\t\tif (err) {\n\t\t\t//Checking for update is failed\n\t\t\t//TODO log error\n\t\t\t// smfOracle.logAnalytics(\"Error [checkUpdate] \" + err)\n\t\t}\n\t\telse {\n\t\t\t//Update is successful. We can show the meta info to inform our app user.\n\t\t\tif (result.meta) {\n\t\t\t\tvar isMandatory = (result.meta.isMandatory && result.meta.isMandatory === true) ? true : false;\n\n\t\t\t\tvar updateTitle = (result.meta.title) ? result.meta.title : 'A new update is ready!';\n\n\t\t\t\tvar updateMessage = \"Version \" + result.newVersion + \" is ready to install.\\n\\n\" +\n\t\t\t\t\t\"What's new?:\\n\" + JSON.stringify(result.meta.update) +\n\t\t\t\t\t\"\\n\\n\"\n\n\t\t\t\t//adding mandatory status message.\n\t\t\t\tupdateMessage += (isMandatory) ? \"This update is mandatory!\" : \"Do you want to update?\";\n\n\t\t\t\t//Function will run on users' approve\n\t\t\t\tfunction onFirstButtonPressed() {\n\t\t\t\t\tif (result.meta.redirectURL && result.meta.redirectURL.length != 0) {\n\t\t\t\t\t\t//RaU wants us to open a URL, most probably core/player updated and binary changed. \n\t\t\t\t\t\tSMF.Net.browseOut(result.meta.redirectURL);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tDialog.showWait();\n\t\t\t\t\t\t//There is an update waiting to be downloaded. Let's download it.\n\t\t\t\t\t\tresult.download(function(err, result) {\n\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t//Download failed\n\t\t\t\t\t\t\t\tDialog.removeWait();\n\t\t\t\t\t\t\t\talert(\"Autoupdate download failed: \" + err);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t//All files are received, we'll trigger an update.\n\t\t\t\t\t\t\t\tresult.updateAll(function(err) {\n\t\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\t\t//Updating the app with downloaded files failed\n\t\t\t\t\t\t\t\t\t\tDialog.removeWait();\n\t\t\t\t\t\t\t\t\t\talert(\"Autoupdate update failed: \" + err);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t//After that the app will be restarted automatically to apply the new updates\n\t\t\t\t\t\t\t\t\t\tApplication.restart();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//We will do nothing on cancel for the timebeing.\n\t\t\t\tfunction onSecondButtonPressed() {\n\t\t\t\t\t//do nothing\n\t\t\t\t}\n\n\t\t\t\t//if Update is mandatory we will show only Update now button.\n\t\t\t\tif (isMandatory) {\n\t\t\t\t\talert({\n\t\t\t\t\t\ttitle: updateTitle,\n\t\t\t\t\t\tmessage: updateMessage,\n\t\t\t\t\t\tfirstButtonText: \"Update now\",\n\t\t\t\t\t\tonFirstButtonPressed: onFirstButtonPressed\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\talert({\n\t\t\t\t\t\ttitle: updateTitle,\n\t\t\t\t\t\tmessage: updateMessage,\n\t\t\t\t\t\tfirstButtonText: \"Update now\",\n\t\t\t\t\t\tsecondButtonText: \"Later\",\n\t\t\t\t\t\tonFirstButtonPressed: onFirstButtonPressed,\n\t\t\t\t\t\tonSecondButtonPressed: onSecondButtonPressed\n\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t});\n}", "function checkForUpdate() {\n executeRequest(\"https://brodaleegitlabplugin.herokuapp.com/?version=last\")\n .then(res => {\n if (res.last_version) {\n if (manifest.version < res.last_version) {\n navigator.getFromStore('lastupdatedate', function (res) {\n if (!res.lastupdatedate) {\n navigator.sendNotification(MESSAGES.notifications.update.title, MESSAGES.notifications.update.message)\n navigator.store({lastupdatedate: Date.now()})\n } else {\n let date = new Date(res.lastupdatedate)\n let now = new Date(Date.now())\n if ((now.getHours() - date.getHours()) > 1) {\n navigator.sendNotification(MESSAGES.notifications.update.title, MESSAGES.notifications.update.message)\n navigator.store({lastupdatedate: Date.now()})\n }\n }\n })\n }\n }\n })\n}", "function getLastDateInFolder(parentFolder, priorLastDate) {\n try {\n\n //Logger.log(\"getLastDateInFolder' started for %s\", drive.name);\n //var lastMod = drive.getLastUpdated();\n //Logger.log(\"drive last date gotten\");\n //var lastModF = Utilities.formatDate(lastMod, 'UTF', 'yyyy_MMM_dd_HH_mm')\n //Logger.log(\"drive last date: $s\",lastModF);\n // var ret = lastModF;\n var ret = priorLastDate;\n //console.info(\"getLastDateInFolder parentFolder: %s\", parentFolder.name);\n //var parentFolder2 = DriveApp.getFolderById(parentFolder.id);\n var folders = parentFolder.getFolders();\n //Logger.log (\"loop through folders\");\n while (folders.hasNext()) {\n var folder = folders.next();\n //console.info(\"*** got folder %s - %s modified at: %s \", folder.getId(), folder.getName(), folder.getLastUpdated());\n //ret = folder.getLastUpdated();\n var newDate = getLastDateInFolder(folder, ret)\n if (+newDate > +ret) {\n //ret = folder.getLastUpdated();\n ret = newDate;\n //console.info(\"Update modified date to %s from folder %s\", ret, folder.getName());\n }\n }\n\n var fileMatches = parentFolder.getFiles();\n while (fileMatches.hasNext()) {\n var file = fileMatches.next();\n //console.info(\"getLastDateInFolder got file: %s / %s with last mod date: %s\", parentFolder.getName(), file.getName(), file.getLastUpdated());\n if (+file.getLastUpdated() > +ret) {\n ret = file.getLastUpdated();\n //console.info(\"Update modified date to %s from file %s\", ret, file.getName());\n } else {\n //console.info(\"not updated for date: %s\", file.getLastUpdated());\n }\n }\n\n } catch (err) {\n console.info(\"getLastDateInFolder error \"+err);\n ret = new Date(888, 1, 1);\n }\n\n return ret;\n}", "function checkExamUpdates() {\n if (new Date() - module.exports.getExamLastUpdated() > examDataUpdate) {\n module.exports.fetchData();\n if (new Date() - module.exports.getExamLastUpdated() < 10000) {\n // updated within 10 seconds - new data, process it\n module.exports.processData();\n }\n }\n}", "function checkForUpdates() {\n logger.success('Ionic Deploy: Checking for updates');\n $ionicDeploy.check().then(function(hasUpdate) {\n logger.success('Ionic Deploy: Update available: ' + hasUpdate);\n vm.hasUpdate = hasUpdate;\n }, function(err) {\n logger.error('Ionic Deploy: Unable to check for updates', err);\n });\n }", "function checkForUpdates () {\n console.log('checkForUpdates');\n vm.checkingForUpdate = true;\n deploy.check().then(function(hasUpdate) {\n console.log('hasUpdate',hasUpdate);\n $timeout(function () {\n vm.hasUpdate = hasUpdate;\n vm.checkingForUpdate = false; \n });\n }, function(err) {\n console.error('Ionic Deploy: Unable to check for updates', err);\n vm.checkingForUpdate = false;\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the addition of v1 and v2. Target is the object receiving the values (v1 by default)
static add(v1, v2, target) { if (!target) target = v1.copy(); else target.set(v1); target.add(v2); return target; }
[ "function vAdd(a, b) {\n return vec(a.x + b.x, a.y + b.y);\n}", "plus(other) {\n return new Vector(this.x + other.x, this.y + other.y);\n }", "plusXY(x, y) {\n return v2(this.x + x, this.y + y);\n }", "static add(a,b) {\n if (a.values.length != b.values.length) return null;\n var newValues = [];\n for (var i = 0; i < a.values.length; i++) {\n newValues.push(a.values[i] + b.values[i])\n }\n return new VectorN(newValues);\n }", "static add(v1, v2) {\n return new Vertex(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);\n }", "function addtest(v1, v2, expected) {\n results.total++;\n var r = calculator.addition(v1, v2);\n if (r !== expected) {\n results.bad++;\n console.log(\"Expected \" + expected +\n \", but was \" + r);\n }\n }", "function addm( m1, m2 ) {\n\treturn m( m1.value + m2.value, \"(\" + m1.source + \"+\" + m2.source + \")\");\n}", "function add(a, b) {\n return {\n x: a.x + b.x,\n y: a.y + b.y\n };\n}", "function addVec(vector1, vector2){\n\t\tlet result = Vec2();\n\n\t\tresult.x = vector1.x + vector2.x;\n\t\tresult.y = vector1.y + vector2.y;\n\n\t\treturn result;\n\t}", "function soma2Valores(valor1,valor2){\nreturn valor1 + valor2\n}", "plus(other)\n {\n return new Vector3(\n this.x + other.x,\n this.y + other.y,\n this.z + other.z\n );\n }", "function add(a, b) {\n return (a + b);\n }", "function add(a, b) {\n var total = (a + b);\n return total;\n }", "__add__(op) {\n if( this.type() === \"str\" || op.type() === \"str\" ) {\n return new Value(this.toString() + op.toString());\n }\n\n if( this.type() === \"float\" || op.type() === \"float\" ) {\n return new Value(this.toFloat() + op.toFloat());\n }\n\n return new Value(this.toInt() + op.toInt());\n }", "function add2car(d1, d2) {\n var total = d1 + \" \" + d2;\n return total;\n}", "add(value1, value2 = this.memory) {\n if (value2 !== undefined) {\n console.log(`${value1} + ${value2} = ${this.memory}`);\n this.memory = value1 + value2;\n return this.memory;\n } else {\n console.log(new Error('Must input two values to add'));\n return this.memory;\n }\n }", "function vec_plus(u, v) {\n return point(u.x + v.x, u.y + v.y)\n}", "addWeight(value1, value2){\n return value1 + value2\n }", "function addVectors (vectorA, vectorB)\r\n{\r\n //Return total Vector\r\n return [vectorA[0] + vectorB[0], vectorA[1] + vectorB[1]];\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the task service
async prepareTask() { this.options.task && (this.task = await this.addService('task', new this.TaskTransport(this.options.task))); if(!this.task) { return; } if(this.options.task.workerChangeInterval) { await this.task.add('workerChange', this.options.task.workerChangeInterval, () => this.changeWorker()); } }
[ "async prepareTask() {\n this.options.task && (this.task = await this.addService('task', new this.TaskTransport(this.options.task)));\n \n if(!this.task) {\n return;\n }\n\n if(this.options.task.calculateCpuUsageInterval) {\n await this.task.add('calculateCpuUsage', this.options.task.calculateCpuUsageInterval, () => this.calculateCpuUsage());\n }\n }", "prepareTasks() {\n // if no tasks specified do them all\n if (this.tasks.length === this.getMandatoryTasks().length) {\n for (const t in this.default_tasks) this.new(t);\n }\n this.tasks.forEach(t => {\n this.data[t] = {};\n });\n }", "function init_task(task, resource, cb) {\n common.get_ssh_connection(resource, function(err, conn) {\n if(err) return cb(err);\n var service = task.service;\n if(service == null) return cb(new Error(\"service not set..\"));\n\n db.Service.findOne({name: service}, function(err, service_detail) {\n if(err) return cb(err);\n if(!service_detail) return cb(\"Couldn't find such service:\"+service);\n if(!service_detail.pkg || !service_detail.pkg.scripts) return cb(\"package.scripts not defined\");\n \n var workdir = common.getworkdir(task.instance_id, resource);\n var taskdir = common.gettaskdir(task.instance_id, task._id, resource);\n var envs = {\n SCA_WORKFLOW_ID: task.instance_id.toString(),\n SCA_WORKFLOW_DIR: workdir,\n SCA_TASK_ID: task._id.toString(),\n SCA_TASK_DIR: taskdir,\n SCA_SERVICE: service,\n SCA_SERVICE_DIR: \"$HOME/.sca/services/\"+service,\n SCA_PROGRESS_URL: config.progress.api+\"/status/\"+task.progress_key/*+\".service\"*/,\n };\n task._envs = envs;\n\n async.series([\n function(next) {\n common.progress(task.progress_key+\".prep\", {name: \"Task Prep\", status: 'running', progress: 0.05, msg: 'Installing sca install script', weight: 0});\n conn.exec(\"mkdir -p ~/.sca && cat > ~/.sca/install.sh && chmod +x ~/.sca/install.sh\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write ~/.sca/install.sh\");\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n fs.createReadStream(__dirname+\"/install.sh\").pipe(stream);\n });\n },\n function(next) {\n common.progress(task.progress_key+\".prep\", {progress: 0.3, msg: 'Running sca install script (might take a while for the first time)'});\n conn.exec(\"cd ~/.sca && ./install.sh\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to run ~/.sca/install.sh\");\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n function(next) {\n common.progress(task.progress_key+\".prep\", {progress: 0.5, msg: 'Installing/updating '+service+' service'});\n /*\n var url = service_detail.repository.url;\n //trim \"git+\" from git+https\n if(url.indexOf(\"git+https://\") == 0) {\n url = url.substring(4);\n }\n */\n var repo_owner = service.split(\"/\")[0];\n //logger.debug(\"ls .sca/services/\"+service+ \" >/dev/null 2>&1 || mkdir -p .sca/services/\"+repo_owner+\" && LD_LIBRARY_PATH=\\\"\\\" git clone \"+service_detail.git.clone_url+\" .sca/services/\"+service);\n conn.exec(\"ls .sca/services/\"+service+ \" >/dev/null 2>&1 || (mkdir -p .sca/services/\"+repo_owner+\" && LD_LIBRARY_PATH=\\\"\\\" git clone \"+service_detail.git.clone_url+\" .sca/services/\"+service+\")\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to git clone. code:\"+code);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n\n function(next) {\n logger.debug(\"making sure requested service is up-to-date\");\n conn.exec(\"cd .sca/services/\"+service+\" && LD_LIBRARY_PATH=\\\"\\\" git pull\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to git pull in ~/.sca/services/\"+service);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n \n /* can't get this thing to work..\n //run service install.sh (if used)\n //TODO - once installed file gets created, install.sh will never run..\n //to reduce the confusion, I am 60% leaning toward not having install.sh and let service owner do any install step during start.sh or run.sh\n function(next) {\n if(!service_detail.pkg.scripts.install) return next(); \n conn.exec(\"ls .sca/services/\"+service+ \"/installed >/dev/null 2>&1 || cd .sca/services/\"+service+\"; ./install.sh && echo $! > installed\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to run install.sh:\"+code);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n */\n\n function(next) {\n common.progress(task.progress_key+\".prep\", {progress: 0.7, msg: 'Preparing taskdir'});\n logger.debug(\"making sure taskdir(\"+taskdir+\") exists\");\n conn.exec(\"mkdir -p \"+taskdir, function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed create taskdir:\"+taskdir);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n\n //install resource keys\n function(next) { \n if(!task.resource_deps) return next();\n async.forEach(task.resource_deps, function(resource, next_dep) {\n if(resource.user_id != task.user_id) return next_dep(\"resource dep aren't owned by the same user\");\n logger.info(\"storing resource key for \"+resource._id+\" as requested\");\n common.decrypt_resource(resource);\n\n //now handle things according to the resource type\n switch(resource.type) {\n case \"hpss\": \n //envs.HPSS_PRINCIPAL = resource.config.username;\n //envs.HPSS_AUTH_METHOD = resource.config.auth_method;\n //envs.HPSS_KEYTAB_PATH = \"$HOME/.sca/keys/\"+resource._id+\".keytab\";\n\n //now install the hpss key\n var key_filename = \".sca/keys/\"+resource._id+\".keytab\";\n conn.exec(\"cat > \"+key_filename+\" && chmod 600 \"+key_filename, function(err, stream) {\n if(err) return next_dep(err);\n stream.on('close', function(code, signal) {\n if(code) return next_dep(\"Failed to write keytab\");\n logger.info(\"successfully stored keytab for resource:\"+resource._id);\n next_dep();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n var keytab = new Buffer(resource.config.enc_keytab, 'base64');\n stream.write(keytab);\n stream.end();\n });\n break;\n default: \n next_dep(\"don't know how to handle resource_deps with type:\"+resource.type);\n }\n }, next);\n },\n\n //make sure dep task dirs are synced \n function(next) {\n if(!task.deps) return next(); //skip\n async.forEach(task.deps, function(dep, next_dep) {\n //if resource is the same, don't need to sync\n if(task.resource_id.toString() == dep.resource_id.toString()) return next_dep();\n db.Resource.findById(dep.resource_id, function(err, source_resource) {\n if(err) return next_dep(err);\n if(!source_resource) return next_dep(\"couldn't find dep resource:\"+dep.resource_id);\n if(source_resource.user_id != task.user_id) return next_dep(\"dep resource aren't owned by the same user\");\n var source_path = common.gettaskdir(task.instance_id, dep._id, source_resource);\n var dest_path = common.gettaskdir(task.instance_id, dep._id, resource);\n logger.debug(\"syncing from source:\"+source_path);\n logger.debug(\"syncing from dest:\"+dest_path);\n //TODO - how can I prevent 2 different tasks from trying to rsync at the same time?\n common.progress(task.progress_key+\".sync\", {status: 'running', progress: 0, weight: 0, name: 'Transferring source task directory'});\n transfer.rsync_resource(source_resource, resource, source_path, dest_path, function(err) {\n if(err) common.progress(task.progress_key+\".sync\", {status: 'failed', msg: err.toString()});\n else common.progress(task.progress_key+\".sync\", {status: 'finished', msg: \"Successfully synced\", progress: 1});\n next_dep(err);\n }, function(progress) {\n common.progress(task.progress_key+\".sync\", progress);\n });\n });\n }, next);\n },\n \n //install config.json in the taskdir\n function(next) { \n if(!task.config) { \n logger.info(\"no config object stored in task.. skipping writing config.json\");\n return next();\n }\n //common.progress(task.progress_key+\".prep\", {status: 'running', progress: 0.6, msg: 'Installing config.json'});\n logger.debug(\"installing config.json\");\n logger.debug(task.config);\n conn.exec(\"cat > \"+taskdir+\"/config.json\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write config.json\");\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(JSON.stringify(task.config, null, 4));\n stream.end();\n });\n },\n \n //write _status.sh\n function(next) { \n //not all service has status\n if(!service_detail.pkg.scripts.status) return next(); \n\n logger.debug(\"installing _status.sh\");\n conn.exec(\"cd \"+taskdir+\" && cat > _status.sh && chmod +x _status.sh\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write _status.sh -- code:\"+code);\n next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(\"#!/bin/bash\\n\");\n for(var k in envs) {\n var v = envs[k];\n var vs = v.replace(/\\\"/g,'\\\\\"')\n stream.write(\"export \"+k+\"=\\\"\"+vs+\"\\\"\\n\");\n }\n stream.write(\"~/.sca/services/\"+service+\"/\"+service_detail.pkg.scripts.status);\n stream.end();\n });\n },\n \n //write _stop.sh\n function(next) { \n //not all service has stop\n if(!service_detail.pkg.scripts.stop) return next(); \n\n logger.debug(\"installing _stop.sh\");\n conn.exec(\"cd \"+taskdir+\" && cat > _stop.sh && chmod +x _stop.sh\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write _stop.sh -- code:\"+code);\n next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(\"#!/bin/bash\\n\");\n for(var k in envs) {\n var v = envs[k];\n var vs = v.replace(/\\\"/g,'\\\\\"')\n stream.write(\"export \"+k+\"=\\\"\"+vs+\"\\\"\\n\");\n }\n stream.write(\"~/.sca/services/\"+service+\"/\"+service_detail.pkg.scripts.stop);\n stream.end();\n });\n },\n \n //write _boot.sh\n function(next) { \n if(!service_detail.pkg.scripts.run && !service_detail.pkg.scripts.start) {\n console.dir(service_detail.pkg.scripts);\n return next(\"pkg.scripts.run nor pkg.scripts.start defined in package.json\"); \n }\n \n //common.progress(task.progress_key+\".prep\", {status: 'running', progress: 0.6, msg: 'Installing config.json'});\n logger.debug(\"installing _boot.sh\");\n conn.exec(\"cd \"+taskdir+\" && cat > _boot.sh && chmod +x _boot.sh\", function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write _boot.sh -- code:\"+code);\n next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(\"#!/bin/bash\\n\");\n for(var k in envs) {\n var v = envs[k];\n if(v.replace) {\n var vs = v.replace(/\\\"/g,'\\\\\"')\n } else {\n //probably number\n var vs = v;\n }\n stream.write(\"export \"+k+\"=\\\"\"+vs+\"\\\"\\n\");\n }\n if(service_detail.pkg.scripts.run) stream.write(\"~/.sca/services/\"+service+\"/\"+service_detail.pkg.scripts.run+\"\\n\");\n if(service_detail.pkg.scripts.start) stream.write(\"~/.sca/services/\"+service+\"/\"+service_detail.pkg.scripts.start+\"\\n\");\n stream.end();\n });\n },\n\n //end of prep\n function(next) {\n common.progress(task.progress_key+\".prep\", {status: 'finished', progress: 1, msg: 'Finished preparing for task'}, next);\n },\n \n //finally, start the service\n function(next) {\n if(!service_detail.pkg.scripts.start) return next(); //not all service uses start\n\n logger.debug(\"starting service: ~/.sca/services/\"+service+\"/\"+service_detail.pkg.scripts.start);\n common.progress(task.progress_key/*+\".service\"*/, {/*name: service_detail.label,*/ status: 'running', msg: 'Starting Service'});\n\n conn.exec(\"cd \"+taskdir+\" && ./_boot.sh > start.log 2>&1\", {\n /* BigRed2 seems to have AcceptEnv disabled in sshd_config - so I can't use env: { SCA_SOMETHING: 'whatever', }*/\n }, function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) {\n return next(\"Service startup failed with return code:\"+code+\" signal:\"+signal);\n } else {\n task.status = \"running\";\n task.status_msg = \"Started service\";\n task.start_date = new Date();\n task.save(next);\n }\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n }, \n \n //or run it synchronously (via run.sh)\n function(next) {\n if(!service_detail.pkg.scripts.run) return next(); //not all service uses run (they may use start/status)\n\n logger.debug(\"running_sync service: ~/.sca/services/\"+service+\"/\"+service_detail.pkg.scripts.run);\n common.progress(task.progress_key/*+\".service\"*/, {/*name: service_detail.label,*/ status: 'running', /*progress: 0,*/ msg: 'Running Service'});\n\n task.status = \"running_sync\"; //mainly so that client knows what this task is doing (unnecessary?)\n task.status_msg = \"Running service\";\n task.start_date = new Date();\n task.save(function() {\n conn.exec(\"cd \"+taskdir+\" && ./_boot.sh > run.log 2>&1\", {\n /* BigRed2 seems to have AcceptEnv disabled in sshd_config - so I can't use env: { SCA_SOMETHING: 'whatever', }*/\n }, function(err, stream) {\n if(err) next(err);\n stream.on('close', function(code, signal) {\n if(code) {\n return next(\"Service failed with return code:\"+code+\" signal:\"+signal);\n } else {\n load_products(task, taskdir, conn, function(err) {\n if(err) return next(err);\n common.progress(task.progress_key, {status: 'finished', /*progress: 1,*/ msg: 'Service Completed'});\n task.status = \"finished\"; \n task.status_msg = \"Service ran successfully\";\n task.finish_date = new Date();\n task.save(next);\n });\n }\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n });\n },\n ], function(err) {\n cb(err); \n }); \n });\n\n });\n}", "function start_task(task, resource, cb) {\n common.get_ssh_connection(resource, function(err, conn) {\n if(err) return cb(err);\n var service = task.service;\n if(service == null) return cb(new Error(\"service not set..\"));\n\n //get_service(service, function(err, service_detail) {\n _service.loaddetail(service, function(err, service_detail) {\n if(err) return cb(err);\n if(!service_detail) return cb(\"Couldn't find such service:\"+service);\n //logger.debug(service_detail);\n if(!service_detail.pkg || !service_detail.pkg.scripts) return cb(\"package.scripts not defined\");\n\n logger.debug(\"service_detail.pkg\");\n logger.debug(service_detail.pkg);\n\n var workdir = common.getworkdir(task.instance_id, resource);\n var taskdir = common.gettaskdir(task.instance_id, task._id, resource);\n\n //service dir includes branch name (optiona)\n var servicedir = \"$HOME/.sca/services/\"+service;\n if(task.service_branch) servicedir += \":\"+task.service_branch;\n\n var envs = {\n //deprecated\n SCA_WORKFLOW_ID: task.instance_id.toString(),\n SCA_WORKFLOW_DIR: workdir,\n SCA_TASK_ID: task._id.toString(),\n SCA_TASK_DIR: taskdir,\n SCA_SERVICE: service,\n SCA_SERVICE_DIR: servicedir,\n SCA_PROGRESS_URL: config.progress.api+\"/status/\"+task.progress_key,\n\n //WORKFLOW_ID: task.instance_id.toString(),\n INST_DIR: workdir,\n //TASK_ID: task._id.toString(),\n //TASK_DIR: taskdir,\n //SERVICE: service,\n SERVICE_DIR: servicedir, //where the application is installed\n //WORK_DIR: workdir,\n //PROGRESS_URL: config.progress.api+\"/status/\"+task.progress_key,\n };\n\n //optional envs\n if(service.service_branch) {\n //deprecated\n envs.SCA_SERVICE_BRANCH = service.service_branch;\n\n envs.SERVICE_BRANCH = service.service_branch;\n }\n\n task._envs = envs;\n\n //insert any task envs\n if(task.envs) for(var key in task.envs) {\n envs[key] = task.envs[key];\n }\n //insert any resource envs\n if(resource.envs) for(var key in resource.envs) {\n envs[key] = resource.envs[key];\n }\n if(task.resource_deps) task.resource_deps.forEach(function(resource_dep) {\n if(resource_dep.envs) for(var key in resource_dep.envs) {\n envs[key] = resource_dep.envs[key];\n }\n });\n\n async.series([\n function(next) {\n common.progress(task.progress_key+\".prep\", {name: \"Task Prep\", status: 'running', progress: 0.05, msg: 'Installing sca install script', weight: 0});\n conn.exec(\"mkdir -p ~/.sca && cat > ~/.sca/install.sh && chmod +x ~/.sca/install.sh\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write ~/.sca/install.sh\");\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n fs.createReadStream(__dirname+\"/install.sh\").pipe(stream);\n });\n },\n function(next) {\n common.progress(task.progress_key+\".prep\", {progress: 0.3, msg: 'Running sca install script (might take a while for the first time)'});\n conn.exec(\"cd ~/.sca && ./install.sh\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to run ~/.sca/install.sh\");\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n\n function(next) {\n common.progress(task.progress_key+\".prep\", {progress: 0.5, msg: 'Installing/updating '+service+' service'});\n var repo_owner = service.split(\"/\")[0];\n //var cmd = \"ls .sca/services/\"+service+ \" >/dev/null 2>&1 || \"; //check to make sure if it's already installed\n var cmd = \"ls \"+servicedir+ \" >/dev/null 2>&1 || \"; //check to make sure if it's already installed\n cmd += \"(\";\n cmd += \"mkdir -p .sca/services/\"+repo_owner+\" && LD_LIBRARY_PATH=\\\"\\\" \";\n cmd += \"git clone \";\n if(task.service_branch) cmd += \"-b \"+task.service_branch+\" \";\n cmd += service_detail.git.clone_url+\" \"+servicedir;\n cmd += \")\";\n logger.debug(cmd);\n conn.exec(cmd, function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to git clone. code:\"+code);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n\n function(next) {\n logger.debug(\"making sure requested service is up-to-date\");\n //-q to prevent git to send log to stderr\n //conn.exec(\"cd \"+servicedir+\" && LD_LIBRARY_PATH=\\\"\\\" git reset --hard && git pull -q\", function(err, stream) {\n conn.exec(\"cd \"+servicedir+\" && git reset --hard && git pull -q\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to git pull in \"+servicedir);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n\n function(next) {\n common.progress(task.progress_key+\".prep\", {progress: 0.7, msg: 'Preparing taskdir'});\n logger.debug(\"making sure taskdir(\"+taskdir+\") exists\");\n conn.exec(\"mkdir -p \"+taskdir, function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed create taskdir:\"+taskdir);\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n },\n\n //install resource keys\n function(next) {\n if(!task.resource_deps) return next();\n async.forEach(task.resource_deps, function(resource, next_dep) {\n logger.info(\"storing resource key for \"+resource._id+\" as requested\");\n common.decrypt_resource(resource);\n\n //now handle things according to the resource type\n switch(resource.type) {\n case \"hpss\":\n //now install the hpss key\n var key_filename = \".sca/keys/\"+resource._id+\".keytab\";\n conn.exec(\"cat > \"+key_filename+\" && chmod 600 \"+key_filename, function(err, stream) {\n if(err) return next_dep(err);\n stream.on('close', function(code, signal) {\n if(code) return next_dep(\"Failed to write keytab\");\n logger.info(\"successfully stored keytab for resource:\"+resource._id);\n next_dep();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n var keytab = new Buffer(resource.config.enc_keytab, 'base64');\n stream.write(keytab);\n stream.end();\n });\n break;\n default:\n next_dep(\"don't know how to handle resource_deps with type:\"+resource.type);\n }\n }, next);\n },\n\n //make sure dep task dirs are synced\n function(next) {\n if(!task.deps) return next(); //skip\n async.forEach(task.deps, function(dep, next_dep) {\n //if resource is the same, don't need to sync\n if(task.resource_id.toString() == dep.resource_id.toString()) return next_dep();\n db.Resource.findById(dep.resource_id, function(err, source_resource) {\n if(err) return next_dep(err);\n if(!source_resource) return next_dep(\"couldn't find dep resource:\"+dep.resource_id);\n //var source_path = common.gettaskdir(task.instance_id, dep._id, source_resource);\n //var dest_path = common.gettaskdir(task.instance_id, dep._id, resource);\n var source_path = common.gettaskdir(dep.instance_id, dep._id, source_resource);\n var dest_path = common.gettaskdir(dep.instance_id, dep._id, resource);\n logger.debug(\"syncing from source:\"+source_path+\" to dest:\"+dest_path);\n\n //TODO - how can I prevent 2 different tasks from trying to rsync at the same time?\n common.progress(task.progress_key+\".sync\", {status: 'running', progress: 0, weight: 0, name: 'Transferring source task directory'});\n _transfer.rsync_resource(source_resource, resource, source_path, dest_path, function(err) {\n if(err) {\n common.progress(task.progress_key+\".sync\", {status: 'failed', msg: err.toString()});\n next_dep(err);\n } else {\n common.progress(task.progress_key+\".sync\", {status: 'finished', msg: \"Successfully synced\", progress: 1});\n\n //register new resource_id where the task_dir is synced to\n if(!~task.resource_ids.indexOf(resource._id)) task.resource_ids.push(resource._id);\n task.save(next_dep);\n }\n }, function(progress) {\n common.progress(task.progress_key+\".sync\", progress);\n });\n });\n }, next);\n },\n\n //install config.json in the taskdir\n function(next) {\n if(!task.config) {\n logger.info(\"no config object stored in task.. skipping writing config.json\");\n return next();\n }\n logger.debug(\"installing config.json\");\n logger.debug(task.config);\n conn.exec(\"cat > \"+taskdir+\"/config.json\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write config.json\");\n else next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(JSON.stringify(task.config, null, 4));\n stream.end();\n });\n },\n\n //write _status.sh\n function(next) {\n //not all service has status\n if(!service_detail.pkg.scripts.status) return next();\n\n logger.debug(\"installing _status.sh\");\n conn.exec(\"cd \"+taskdir+\" && cat > _status.sh && chmod +x _status.sh\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write _status.sh -- code:\"+code);\n next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(\"#!/bin/bash\\n\");\n //console.dir(envs);\n for(var k in envs) {\n var v = envs[k];\n if(typeof v !== 'string') {\n logger.warn(\"skipping non string value:\"+v+\" for key:\"+k);\n continue;\n }\n var vs = v.replace(/\\\"/g,'\\\\\"')\n stream.write(\"export \"+k+\"=\\\"\"+vs+\"\\\"\\n\");\n }\n //stream.write(servicedir+\"/\"+service_detail.pkg.scripts.status);\n stream.write(\"$SERVICE_DIR/\"+service_detail.pkg.scripts.status);\n stream.end();\n });\n },\n\n //write _stop.sh\n function(next) {\n //not all service has stop\n if(!service_detail.pkg.scripts.stop) return next();\n\n logger.debug(\"installing _stop.sh\");\n conn.exec(\"cd \"+taskdir+\" && cat > _stop.sh && chmod +x _stop.sh\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write _stop.sh -- code:\"+code);\n next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(\"#!/bin/bash\\n\");\n for(var k in envs) {\n var v = envs[k];\n var vs = v.replace(/\\\"/g,'\\\\\"')\n stream.write(\"export \"+k+\"=\\\"\"+vs+\"\\\"\\n\");\n }\n //stream.write(servicedir+\"/\"+service_detail.pkg.scripts.stop);\n stream.write(\"$SERVICE_DIR/\"+service_detail.pkg.scripts.stop);\n stream.end();\n });\n },\n\n //write _boot.sh\n function(next) {\n if(!service_detail.pkg.scripts.run && !service_detail.pkg.scripts.start) {\n //console.dir(service_detail.pkg.scripts);\n return next(\"pkg.scripts.run nor pkg.scripts.start defined in package.json\");\n }\n\n logger.debug(\"installing _boot.sh\");\n conn.exec(\"cd \"+taskdir+\" && cat > _boot.sh && chmod +x _boot.sh\", function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) return next(\"Failed to write _boot.sh -- code:\"+code);\n next();\n })\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n stream.write(\"#!/bin/bash\\n\");\n for(var k in envs) {\n var v = envs[k];\n if(v.replace) {\n var vs = v.replace(/\\\"/g,'\\\\\"')\n } else {\n //probably number\n var vs = v;\n }\n stream.write(\"export \"+k+\"=\\\"\"+vs+\"\\\"\\n\");\n }\n //if(service_detail.pkg.scripts.run) stream.write(servicedir+\"/\"+service_detail.pkg.scripts.run+\"\\n\");\n if(service_detail.pkg.scripts.run) stream.write(\"$SERVICE_DIR/\"+service_detail.pkg.scripts.run+\"\\n\");\n //if(service_detail.pkg.scripts.start) stream.write(servicedir+\"/\"+service_detail.pkg.scripts.start+\"\\n\");\n if(service_detail.pkg.scripts.start) stream.write(\"$SERVICE_DIR/\"+service_detail.pkg.scripts.start+\"\\n\");\n stream.end();\n });\n },\n\n //end of prep\n function(next) {\n common.progress(task.progress_key+\".prep\", {status: 'finished', progress: 1, msg: 'Finished preparing for task'}, next);\n },\n\n //finally, start the service\n function(next) {\n if(!service_detail.pkg.scripts.start) return next(); //not all service uses start\n\n logger.debug(\"starting service: \"+servicedir+\"/\"+service_detail.pkg.scripts.start);\n common.progress(task.progress_key, {status: 'running', msg: 'Starting Service'});\n\n task.run++;\n task.status = \"running\";\n task.status_msg = \"Starting service\";\n task.start_date = new Date();\n\n //temporarily set next_date to some impossible date so that we won't run status.sh prematuely\n task.next_date = new Date();\n task.next_date.setDate(task.next_date.getDate() + 30);\n task.save(function(err) {\n if(err) return next(err);\n update_instance_status(task.instance_id, function(err) {\n if(err) return next(err);\n conn.exec(\"cd \"+taskdir+\" && ./_boot.sh > boot.log 2>&1\", {\n /* BigRed2 seems to have AcceptEnv disabled in sshd_config - so I can't pass env via ssh2*/\n }, function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) {\n //I should undo the impossible next_date set earlier..\n task.next_date = new Date();\n //TODO - I should pull more useful information (from start.log?)\n return next(\"failed to start (code:\"+code+\")\");\n } else {\n //good.. now set the next_date to now so that we will check for its status\n task.status_msg = \"Service started\";\n task.next_date = new Date();\n task.save(next);\n }\n });\n\n //NOTE - no stdout / err should be received since it's redirected to boot.log\n stream.on('data', function(data) {\n logger.info(data.toString());\n });\n stream.stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n });\n\n });\n },\n\n //TODO - DEPRECATE THIS\n //short sync job can be accomplished by using start.sh to run the (short) process and\n //status.sh checking for its output (or just assume that it worked)\n function(next) {\n if(!service_detail.pkg.scripts.run) return next(); //not all service uses run (they may use start/status)\n\n logger.debug(\"running_sync service: \"+servicedir+\"/\"+service_detail.pkg.scripts.run);\n common.progress(task.progress_key, {status: 'running', msg: 'Running Service'});\n\n task.run++;\n task.status = \"running_sync\"; //mainly so that client knows what this task is doing (unnecessary?)\n task.status_msg = \"Running service\";\n task.start_date = new Date();\n task.save(function(err) {\n if(err) return next(err);\n update_instance_status(task.instance_id, function(err) {\n if(err) return next(err);\n conn.exec(\"cd \"+taskdir+\" && ./_boot.sh > boot.log 2>&1 \", {\n /* BigRed2 seems to have AcceptEnv disabled in sshd_config - so I can't use env: { SOMETHING: 'whatever', }*/\n }, function(err, stream) {\n if(err) return next(err);\n stream.on('close', function(code, signal) {\n if(code) {\n return next(\"failed to run (code:\"+code+\")\");\n } else {\n load_products(task, taskdir, resource, function(err) {\n if(err) return next(err);\n common.progress(task.progress_key, {status: 'finished', /*progress: 1,*/ msg: 'Service Completed'});\n task.status = \"finished\";\n task.status_msg = \"Service ran successfully\";\n task.finish_date = new Date();\n task.save(function(err) {\n if(err) return next(err);\n //clear next_date on dependending tasks so that it will be checked immediately\n db.Task.update({deps: task._id}, {$unset: {next_date: 1}}, {multi: true}, function(err) {\n if(err) return next(err);\n update_instance_status(task.instance_id, next);\n });\n });\n });\n }\n })\n\n //NOTE - no stdout / err should be received since it's redirected to boot.log\n .on('data', function(data) {\n logger.info(data.toString());\n }).stderr.on('data', function(data) {\n logger.error(data.toString());\n });\n });\n });\n });\n },\n ], function(err) {\n cb(err);\n });\n });\n });\n}", "initManager() {\n debug('Initializing tasks')\n return new Promise((resolve, reject) => {\n Util.FileIO.readDataFile({ fileName: this.fileName })\n .then((data) => {\n const { tasks } = data\n if (tasks && Array.isArray(tasks)) {\n tasks.forEach(task => {\n this.taskMap[task.id] = this.createTask({ ...task, save: false, addAsDevice: true })\n })\n resolve()\n } else {\n debug('Tasks not available in data file')\n reject()\n }\n })\n .catch((error) => {\n debug('Error initializing tasks', error)\n reject(error)\n })\n })\n }", "function _createTasks () {\n\n\t\tvar TaskCreator = require( './taskCreator' );\n\t\tvar taskCreator = new TaskCreator( gulp, plugins, config );\n\t}", "async prepare() {\n // TODO: implement this as soon the esm registry becomes available\n }", "constructor() { \n \n Task.initialize(this);\n }", "init() {\n this.taskContainer.buildAllTasks();\n for (const taskName in this.taskContainer.getTasks()) {\n this.taskTimeouts[taskName] = 0;\n }\n }", "constructor(task /*: TaskConfig */) {\n this._task = task;\n this._process = undefined;\n this._completion = () => {};\n }", "function initializeTasks() {\n $scope.tasks = TaskService.all();\n $scope.newTask = {id: $scope.tasks.length, name: \"\", type: 0, duration: 0, from: \"\", to: \"\"};\n }", "async __prepareWorkflowManager () {\n\n\t\t// Inject the dependencies the workflow manager requires.\n\t\tthis.workflowManager.inject(`sharedLogger`, sharedLogger);\n\t\tthis.workflowManager.inject(`MessageObject`, MessageObject);\n\t\tthis.workflowManager.inject(`analytics`, this.analytics);\n\t\tthis.workflowManager.inject(`database`, this.database);\n\t\tthis.workflowManager.inject(`nlp`, this.nlp);\n\t\tthis.workflowManager.inject(`scheduler`, this.scheduler);\n\n\t\t// Start the workflow manager.\n\t\tawait this.workflowManager.start(this.options.directories);\n\n\t}", "static async _create() {\n\t\tconst serviceName = Config.str(\"serviceName\");\n\n\t\t// Create the service if it does not exist - otherwise, throw an error\n\t\tlet service = await ECSManager.describeService(serviceName);\n\t\tif (service && service.status !== \"INACTIVE\") {\n\t\t\tthrow new Error(\"Service already exists: \" + serviceName + \". Delete or update instead.\");\n\t\t}\n\n\t\t// Register the task definition first\n\t\tconsole.log(\"CREATE 1) Register Task Definition\");\n\t\tconst taskDefinition = await ECSManager.registerTaskDefinition();\n\t\tconst taskDefinitionArn = taskDefinition.taskDefinition.taskDefinitionArn;\n\n\t\t// Creating a new service\n\t\t// We create a target group to associate this service with an Elastic Load Balancer\n\t\tconsole.log(\"CREATE 2) Create Target Group\");\n\t\tconst targetGroupResponse = await ELBManager.createTargetGroup();\n\t\tconsole.log(\"TargetGroupResponse: \" + JSON.stringify(targetGroupResponse, null, 2));\n\t\tconst targetGroupArn = targetGroupResponse.TargetGroups[0].TargetGroupArn;\n\n\t\t// We create a rule that tells our load balancer when to send requests to our new service\n\t\t// By default, it forwards <SERVICE_NAME>.bespoken.io to the service\n\t\t// This can be changed online in the ECS console\n\t\tconsole.log(\"CREATE 3) Create Rule\");\n\t\tconst rules = await ELBManager.createRule(targetGroupArn);\n\t\tconsole.log(\"Rules: \" + JSON.stringify(rules, null, 2));\n\n\t\t// Create the service\n\t\tconsole.log(\"CREATE 4) Create Service\");\n\t\tservice = await ECSManager.createService(targetGroupArn, taskDefinitionArn);\n\t\treturn service;\n\t}", "run() {\n // First, we'll create the interface object and run all our\n // collected tasks through it.\n this.taskInterface = new TaskInterface(this.opts);\n\n }", "initializeSplinterAgentPoolTask(doneCallback) {\n logger_1.default.system.log(\"FINSEMBLE CONFIG\", this.finsembleConfig);\n let splinterAgents = [];\n if (this.finsembleConfig.splinteringConfig && this.finsembleConfig.splinteringConfig.splinterAgents) {\n splinterAgents = this.finsembleConfig.splinteringConfig.splinterAgents.filter(agent => {\n return agent.services && agent.services.length > 0;\n });\n }\n // If any services are configured to run in a splinter agent then create the pool\n // If not, then we skip creating the pool in order to save resources (the pool creates an extra electron process which uses 50mb+)\n if (splinterAgents.length) {\n let poolConfig = {\n manifest: this.manifest,\n finsembleConfig: this.finsembleConfig,\n agentList: splinterAgents,\n defaultAgentLabel: \"defaultServiceAgent\"\n };\n // save splintering agent for use in creating new services; also needed for clean shutdown so pass into shutdown manager\n this.splinterAgentPool = new SplinterAgentPool_1.default(poolConfig);\n this.shutdownManager.setSplinterAgentPool(this.splinterAgentPool);\n }\n doneCallback(\"testTask_initializeSplinterAgentPool\", \"bootTasks\", \"completed\");\n }", "function createTask(v,t){\r\n \r\n }", "constructor(@Inject(Task) taskComponent) {\n this.task = taskComponent.task;\n }", "function initTasks()\n\t{\n\t\ttasksDomain.exec(\"setProjectPath\", ProjectManager.getProjectRoot().fullPath);\n\t\ttasksDomain.exec(\"getTaskList\")\n\t\t.done(function(tasks)\n\t\t{\n\t\t\tvar gulpTasks = '';\n\t\t\tif(tasks.gulp.length > 0)\n\t\t\t{\n\t\t\t\tgulpTasks = $(Mustache.render(TEMPLATE_TASK_LIST_GULP, tasks.gulp));\n\t\t\t}\n\n\t\t\tvar gruntTasks = '';\n\t\t\tif(tasks.grunt.length > 0)\n\t\t\t{\n\t\t\t\tgruntTasks = $(Mustache.render(TEMPLATE_TASK_LIST_GRUNT, tasks.grunt));\n\t\t\t}\n\n\t\t\tif(tasks.grunt.length > 0 || tasks.gulp.length > 0)\n\t\t\t{\n\t\t\t\ttasksPanel.show();\n\t\t\t} else\n\t\t\t{\n\t\t\t\ttasksPanel.hide();\n\t\t\t}\n\n\t\t\t$(\"#task-list\", $tasksPanelContent).append(gulpTasks);\n\t\t\t$(\"#task-list\", $tasksPanelContent).append(gruntTasks);\n\t\t\t$(\".gulp.task\", $tasksPanelContent).click(gulpTaskButtonClickHandler);\n\t\t\t$(\".grunt.task\", $tasksPanelContent).click(gruntTaskButtonClickHandler);\n\n\t\t});\n\t}", "constructor (currentId=0) {\n this.tasks = [];\n \n this.currentId = currentId;\n \n // this.addTask();\n \n // this.getTaskById();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes profileData with the contents of the profileentries file, and load synonyms from synonyms.json.
function initializeData() { const profileContents = fs.readFileSync(profileEntriesFile, 'utf8'); const data = jsonic(profileContents); _.each(data, function (entry) { profileData.push(entry); }); filterInterest.initData(); }
[ "function LoadMetadata() {\n if (settings.metadata.hasOwnProperty('members')) {\n settings.member_lines = settings.metadata.members;\n PopulateMembersTable();\n }\n }", "function loadData() {\n var fileContent = fs.readFileSync('./data.json');\n members = JSON.parse(fileContent);\n}", "function loadSayings() {\n for (var user in userDict) {\n var userFile = usersFilePath+user+'.txt';\n userDict[user].sayings = fs.readFileSync(userFile).toString().split(\"\\n\");\n }\n}", "function initializeData() {\n \tconsole.log(\"Initializing data from session.json...\")\n \tvar rawData = fs.readFileSync(dataFile);\n \tdata = JSON.parse(rawData);\n\n \t// Reads in current collections located in data/corpus-files\n \tlet collections = fs.readdirSync('./data/corpus-files').filter(function (file) {\n\t\treturn fs.statSync('./data/corpus-files/' + file).isDirectory();\n\t});\n\n\t// Deletes any collections in the data JSON structure that don't appear\n\t// within our folder and prints a warning message.\n\tvar remove = [];\n\tfor (var c in data['collections']) {\n\t\tif (!collections.includes(c)) {\n\t\t\tremove.push(c);\n\t\t}\n\t}\n\tfor (var i in remove) {\n\t\tdelete data[remove[i]];\n\t\tconsole.log('WARNING: ' + remove[i] + ' collection doesn\\'t exist in data/corpus-files. Please either add the files or delete the entry from session.json.');\n\t}\n\n\tconsole.log(\"Initialized data:\");\n\tconsole.log(JSON.stringify(data) + '\\n');\n }", "function initializeData() {\n \tconsole.log(\"Initializing data from session.json...\")\n \tvar rawData = fs.readFileSync(dataFile);\n \tdata = JSON.parse(rawData);\n\n \t// Reads in current collections located in data/corpus-files\n \tlet collections = fs.readdirSync('./data/corpus-files').filter(function (file) {\n\t\treturn fs.statSync('./data/corpus-files/' + file).isDirectory();\n\t});\n\n\t// Deletes any collections in the data JSON structure that don't appear\n\t// within our folder and prints a warning message.\n\tvar remove = [];\n\tfor (var c in data['collections']) {\n\t\tif (!collections.includes(c)) {\n\t\t\tremove.push(c);\n\t\t}\n\t}\n\tfor (var i in remove) {\n\t\tdelete data[remove[i]];\n\t\tconsole.log('WARNING: ' + remove[i] + ' collection doesn\\'t exist in data/corpus-files. Please either add the files or delete the entry from session.json.');\n\t}\n }", "loadTypeMappings() {\n var content = fs.readFileSync(\"type_mapping.json\", \"UTF-8\");\n this.typeMappings = JSON.parse(content);\n }", "function loadUsers() {\n fs.readdir(usersFilePath, function(err, files) {\n if (err) {\n // failed to read the dir. Maybe logout error?\n }\n else {\n files.forEach(function(file) {\n var nick = file.split(\".\")[0];\n userDict[nick] = {};\n });\n loadSayings(); // go ahead an do an inital load for the sayings\n }\n });\n}", "function loadStudents() {\n var empty = \"[]\";\n readFile(\"students.txt\", empty, function(err, data) {\n students = JSON.parse(data)\n });\n}", "function ETFProfileData() {\n _classCallCheck(this, ETFProfileData);\n\n ETFProfileData.initialize(this);\n }", "function main()\n{\n var data = {};\n\n ldap.check_inst_data(null, function(ldap_data) {\n\n // create dict indexed by org - that should be more stable than realm\n for(var i in ldap_data) {\n\n if(ldap_data[i].org) { // only if org is present\n if(!Array.isArray(ldap_data[i].realms)) // single realm\n ldap_data[i].realms = [ ldap_data[i].realms ]; // convert to array\n\n else // multiple realms\n data[ldap_data[i].realms[0]] = ldap_data[i];\n\n var org = ldap_data[i].org.replace(/^dc=/,'').replace(/,ou=Organizations,dc=cesnet,dc=cz$/, '').replace(/ /g, '_') // get just org identifier, replace all ' ' with '_'\n data[org] = ldap_data[i];\n }\n }\n\n read_json_files(data);\n });\n}", "function loadPitData() {\n // loads through each file in manifest\n for (let data_id in manifest_pit) {\n let file_name = manifest_pit[data_id]; // e.g. 1540.json\n if (fs.existsSync(\"./data/pit/\" + file_name)) {\n let data_point = JSON.parse(fs.readFileSync(\"./data/pit/\" + file_name));\n let team_name = data_point[\"info\"][\"team\"];\n // sets defaults if values are non-existent\n setDefaultsForPit(data_point);\n // adds data point to pit_data\n pit_data[team_name] = data_point;\n }\n }\n}", "function loadFiles () {\n\t\tvar language;\n\t\tfor (i=0; i <= languages.length; i++) {\n\t\t\t\n\t\t\tif (i == languages.length) {\n\t\t\t\t//singal initDataCompleted\n\t\t\t\tconsole.log('initDataCompleted!');\n\t\t\t\tinitDataCompleted = true;\n\t\t\t\tconsole.log('data[language]', data.en);\n\t\t\t\tconsole.log('data[language][name]', data.en['Traits-Summary']);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tlanguage = languages[i];\n\t\t\t\n\t\t\t//addition: also load the traits-summary/info which is not specific to perspective (perspective independent) \n\t\t\tInitFileProvider.initData(language, 'Traits-Summary', 'info/suggestion/' +language + '/Traits-Summary.json');\t\t\t\n\t\t\t\n\t\t\tvar perspective;\n\t\t\t\n\t\t\tfor (j=0; j< perspectives.length; j++) {\n\t\t\t\tperspective = perspectives[j];\n\t\t\t\tInitFileProvider.initData(language, perspective, 'info/suggestion/'+language+'/' + perspective + '/traits.json');\n\t\t\t\t//console.log('info/suggestion/'+language+'/' + perspective + '/traits.json');\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t}", "function loadUserInfo() {\n\tuserInfo = JSON.parse(fs.readFileSync(userInfoFullPath, 'utf8'));\n}", "function loadUserAvatars() {\n\tuserAvatars = JSON.parse(fs.readFileSync(userAvatarsFullPath, 'utf8'));\n}", "function loadGPProfiles() {\n if (gpProfileData.length == 0) {\n $.getJSON('./gpProfiles.json', function (data) {\n gpProfileData = data;\n updateGPProfile(focusGroup);\n })\n }\n}", "function loadProfileInfo(userdata) {\n\tvar firstname = getUserdata(userdata, \"firstname\");\n\tvar familyname = getUserdata(userdata, \"familyname\");\n\tvar gender = getUserdata(userdata, \"gender\");\n\tvar country = getUserdata(userdata, \"country\");\n\tvar city = getUserdata(userdata, \"city\");\n\tvar email = getUserdata(userdata, \"email\");\n\tvar registerDate = getUserdata(userdata, \"registerDate\");\n\n\taddProfileInfo(firstname, familyname, gender, country, city, email, registerDate);\n}", "mapProfileData(data) {\n if (data) {\n if (data.DisplayName) this.name = data.DisplayName;\n if (\n data.PictureUrl &&\n (!this.photoUrl || this.photoUrl == PLACEHOLDER_PHOTO_URL)\n )\n this.photoUrl = data.PictureUrl;\n if (data.Email) this.email = data.Email;\n if (data.AccountName) this.username = data.AccountName;\n else if (this.email) this.username = ACCOUNT_NAME_PREFIX + this.email;\n if (data.PersonalUrl) this.profileUrl = data.PersonalUrl;\n if (data.Title) this.rank = data.Title;\n\n this.isLoaded = true;\n }\n }", "function metadataInit(password) {\n // Initialize the metadata of folders\n g_folders = {};\n g_folders[g_homeFolderName] = { 'name': g_homeFolderName, 'files': [], 'folders': [] };\n // Initialize the metadata of files\n g_files = {};\n g_files[g_metadataName] = { 'name': g_metadataName, 'password': password, 'chunks': [] };\n g_providers.forEach(function (p) {\n g_files[g_metadataName].chunks.push({ 'provider': p, 'info': [{ 'name': metadataChunkName(p) }] });\n });\n g_files[g_metadataName]['nb_chunks'] = g_providers.length;\n}", "initVars() {\n const ref = this;\n this.saveOnCloseEvent();\n\n this.logmodule.writelog('debug', \"initVars called\");\n\n require('fs').readFile('/userdata/owntracks.json', 'utf8', function (err, data) {\n if (err) {\n ref.logmodule.writelog('error', \"Retreiving userArray failed: \"+ err);\n } else {\n try {\n ref.userArray = JSON.parse(data);\n } catch (err) {\n ref.logmodule.writelog('error', \"Parsing userArray failed: \"+ err);\n ref.userArray = [];\n ref.logmodule.writelog('debug', data);\n }\n }\n });\n require('fs').readFile('/userdata/owntracks_fences.json', 'utf8', function (err, data) {\n if (err) {\n ref.logmodule.writelog('error', \"Retreiving fenceArray failed: \"+ err);\n } else {\n try {\n ref.fenceArray = JSON.parse(data);\n } catch(err) {\n ref.logmodule.writelog('error', \"Parsing fenceArray failed: \"+ err);\n ref.fenceArray = [];\n }\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clear tasks from all local storage
function clearTasksFromLocalStorage(){ localStorage.clear(); }
[ "function clearAllTasksFromStorage() {\n localStorage.clear();\n}", "function clearAllTasksFromLocalStorage() {\n localStorage.clear();\n}", "function clearingAllTasksFromLocalStorage() {\n localStorage.clear();\n}", "function clearAllTaskFromLocalStorage() {\n localStorage.clear();\n}", "function clearTasksFromStorage(){\n localStorage.clear();\n}", "function clearTasksFromLocalStorage(){\n localStorage.clear();\n}", "function clearTasksFromStorage() {\n localStorage.removeItem('tasks');\n /**\n * Traversy method: \n * localStorage.clear();\n */\n}", "function clearTasksFromLS(){\n localStorage.clear();\n}", "function clearAll() {\n while (taskContainer.firstChild) {\n taskContainer.removeChild(taskContainer.firstChild);\n }\n browser.storage.local.clear();\n}", "function clearAllStorageTask() {\n localStorage.clear();\n}", "function clearTaskFromLocalStorage() {\r\n localStorage.clear();\r\n}", "function clearTasks() {\r\n //CLEAR TASKS FROM THE DOM\r\n while (taskList.firstChild) {\r\n taskList.removeChild(taskList.firstChild);\r\n }\r\n //CLEAR TASKS FROM LOCAL STORAGE\r\n clearAllLS();\r\n}", "deleteAllTasks() {\n this.store.tasks.length = 0;\n Helper.saveStore(this.store);\n }", "function clearTasks(){\n\n if (confirm(\"Clear all tasks?\") === true){\n //Get current project from local storage\n let currentProject = JSON.parse(localStorage[displayedIndex]);\n\n //Clear tasks of current project\n currentProject.tasks = [];\n\n //Update local storage\n let currentProject_serialized = JSON.stringify(currentProject);\n localStorage.setItem(displayedIndex, currentProject_serialized);\n\n //Update display\n displayTasks();\n }\n}", "function clearTasks() {\n if (confirm('Are you sure that you want to delete all tasks?')) {\n while (taskList.firstChild) {\n taskList.removeChild(taskList.firstChild)\n }\n // Remove all tasks from local storage\n clearTasksFromLocalStorage();\n }\n}", "function clearComTasks() {\r\n //CLEAR TASKS FROM THE DOM\r\n while (completed.firstChild) {\r\n completed.removeChild(completed.firstChild);\r\n }\r\n //CLEAR TASKS FROM LOCAL STORAGE\r\n clearAllLS();\r\n}", "clearAll() {\n localStorage.clear();\n }", "clear() {\n this._tasks = [];\n }", "function clearTasks(tasks){\n tasks.length = 0;\n return tasks;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether this list item should show a ripple effect when clicked.
_isRippleDisabled() { return !this._isInteractiveList || this.disableRipple || !!(this._list && this._list.disableRipple); }
[ "function RippleTarget() { }", "_isRippleDisabled() {\n return this.disabled || this.disableRipple || this.selectionList.disableRipple;\n }", "function RippleTarget() {}", "get disableRipple() {\n return (this.disabled ||\n this._disableRipple ||\n this._noopAnimations ||\n !!this._listBase?.disableRipple);\n }", "_isShowingRipple(rippleRef) {\n return (rippleRef === null || rippleRef === void 0 ? void 0 : rippleRef.state) === 0 /* FADING_IN */ || (rippleRef === null || rippleRef === void 0 ? void 0 : rippleRef.state) === 1 /* VISIBLE */;\n }", "_showActiveRipple() {\n var _a;\n if (!this._isShowingRipple(this._activeRippleRef)) {\n this._activeRippleRef = this._showRipple({ enterDuration: 225, exitDuration: 400 });\n (_a = this._activeRippleRef) === null || _a === void 0 ? void 0 : _a.element.classList.add('mat-mdc-slider-active-ripple');\n }\n }", "_showFocusRipple() {\n var _a;\n // Show the focus ripple event if noop animations are enabled.\n if (!this._isShowingRipple(this._focusRippleRef)) {\n this._focusRippleRef = this._showRipple({ enterDuration: 0, exitDuration: 0 });\n (_a = this._focusRippleRef) === null || _a === void 0 ? void 0 : _a.element.classList.add('mat-mdc-slider-focus-ripple');\n }\n }", "function setRippleEffect() {\n if ( Waves.displayEffect() ) {\n Waves.displayEffect(); \n }\n }", "_showHoverRipple() {\n var _a;\n if (!this._isShowingRipple(this._hoverRippleRef)) {\n this._hoverRippleRef = this._showRipple({ enterDuration: 0, exitDuration: 0 });\n (_a = this._hoverRippleRef) === null || _a === void 0 ? void 0 : _a.element.classList.add('mat-mdc-slider-hover-ripple');\n }\n }", "_showRipple(animation) {\n if (this.disableRipple) {\n return;\n }\n return this._ripple.launch({\n animation: this._slider._noopAnimations ? { enterDuration: 0, exitDuration: 0 } : animation,\n centered: true,\n persistent: true,\n });\n }", "isClickable() {\n return this.isUnlocked() && this.isAffordable();\n }", "isClicked() {\n return this.isSelected() && mouseIsPressed;\n }", "function ripple()\n{\n kony.print(\"\\n**********in ripple*******\\n\");\n //\"rippleBackground\" : Defines the ripple background for a widget. \n //If both rippleBackground & normal/focus skins are set through constructor then rippleBackground will take priority. \n //If skin/focusSkins/pressedSkins/disabledSkins skins are set dynamically the skin/focusSkins/pressedSkins/disabledSkins will take priority.\n //We set the ripple color property also for coloered ripples.\n frmRipple.flxRipple1.rippleBackground ={\n rippleColor:\"5a65e000\",\n \t contentLayers:[\n {\n background:\"9e9e9e00\",\n backgroundType:constants.RIPPLE_CONTENT_LAYER_COLOR\n }\n ]\n };\n}", "isActive() {\n return this.getOpacity() !== 0;\n }", "activateLineRipple() {}", "_createRipple() {\n this._rippleContainer = this.$.checkbox;\n const ripple = PaperRippleBehavior._createRipple();\n ripple.id = 'ink';\n ripple.setAttribute('recenters', '');\n ripple.classList.add('circle', 'toggle-ink');\n return ripple;\n }", "get rippleDisabled() {\n return this.disabled || this.disableRipple || this._animationsDisabled ||\n !!this.rippleConfig.disabled;\n }", "favoriteListItem(ev) {\n \n //the li element to be styled\n const item = ev.target.parentNode.parentNode\n const itemID = item.dataset.id\n\n const flickObj = this.getFlickItem(itemID)\n flickObj.fav = !(flickObj.fav)\n \n\n if (flickObj.fav) {\n item.style.backgroundColor = '#dfdfdf'\n }\n else {\n item.style.backgroundColor = '#ffffff'\n }\n\n }", "function isRippleable(event, disableSpacebarClick) {\n\t switch (event.type) {\n\t case \"mousedown\":\n\t return (document.querySelector(\".rmd-states--touch\") === null &&\n\t event.button === 0);\n\t case \"keydown\":\n\t return ((!disableSpacebarClick && event.key === \" \") ||\n\t (event.key === \"Enter\" &&\n\t !/checkbox|radio/i.test(event.currentTarget.getAttribute(\"type\") || \"\")));\n\t case \"touchstart\":\n\t case \"click\":\n\t return true;\n\t default:\n\t return false;\n\t }\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PAN MOVE A GROUP
panMoveGroup(event){ var that = this; var transform = getTransformation(d3.select('#group-'+that.panGroup.id).attr('transform')); var offsetX = event.srcEvent.x - that.lastPosition.x; var offsetY = event.srcEvent.y - that.lastPosition.y; var X = offsetX + transform.translateX; var Y = offsetY + transform.translateY; d3.select('#group-'+that.panGroup.id).attr('transform', 'translate('+X+','+Y+')') var linesAttached = that.panGroup['lines']; // console.log(linesAttached) linesAttached.forEach((groupLine)=>{ groupLine.forEach((lineId)=>{ var id = 'item-'+lineId; var transform = getTransformation(d3.select('#'+id).attr('transform')); var X = offsetX + transform.translateX; var Y = offsetY + transform.translateY; d3.select('#'+id).attr('transform', 'translate('+X+','+Y+')') }) }) if (that.allBoundingBox) findIntersectionRecursive(that.allBoundingBox, event, this.lastPosition, that.panGroup.id, this.props.groupLines); that.lastPosition = {'x': event.srcEvent.x, 'y':event.srcEvent.y} }
[ "function myMove(group) {\n\tlet c = group[group.length-1];\n\tc.position.x = mouseX;\n\tc.position.y = mouseY;\n}", "function moveToGroup(obj, target, x, y) {\n // move object from its current to the target container\n var oldContainer= obj.parentNode;\n try {\n target.appendChild(obj);\n } catch (e) {\n\t// ignore circular insertion due to event race\n\tlayout(obj);\n\treturn;\n }\n \n // default position at the cursor\n if (target.getAttributeNS(topns,\"container\")==\"true\") {\n\tvar m= obj.getScreenCTM();\n\tvar p= target.getScreenCTM().inverse();\n\tm.e= x;\n\tm.f= y;\n\tsetTransform(obj, p.multiply(m));\n }\n \n // layout old and new container\n if (oldContainer!=target) {\n\tsetTimeout(function() {layout(oldContainer);}, 1);\n\teval(obj.getAttributeNS(topns,\"layout\"));\n\tlayout(target);\n }\n}", "function moveGroupOrigin(){\n\n var width = topRight.x() - topLeft.x(),\n height = bottomLeft.y() - topLeft.y();\n\n squareGroup.x(topLeft.getAbsolutePosition().x);\n squareGroup.y(topLeft.getAbsolutePosition().y);\n\n topRight.position({\n x: width,\n y: 0\n });\n\n bottomRight.position({\n x: width,\n y: height\n });\n\n bottomLeft.position({\n x: 0,\n y: height\n });\n\n topLeft.position({\n x: 0,\n y: 0\n });\n\n cropArea.position({\n x: 0,\n y: 0\n });\n\n\n }", "function ungroup(target, group) {\r\tfor (i=group.pageItems.length-1; i>=0; i--) {\r\t\tgroup.pageItems[i].move(target, ElementPlacement.PLACEATBEGINNING);\r }\r}", "function copyGroupAndAlignItToFacePin(groupName, facePinPosition) {\n var originalGroup = findGroupItemByName(groupName);\n if (originalGroup) {\n var groupCopy = originalGroup.duplicate();\n\n groupCopy.name = originalGroup.name + \"_copy\";\n\n var copyGroupPosition = calculateGroupPositionAccordingToFacePin(groupCopy, facePinPosition);\n groupCopy.position = copyGroupPosition;\n groupCopy.zOrder(ZOrderMethod.BRINGTOFRONT);\n\n return groupCopy;\n }\n}", "function animateUngrouping(group) {\n var GAP = 10; //we want a 10 pixel gap between objects to show that they're no longer grouped together.\n //Figure out which is the left most and which is the right most object. The left most object will move left and the right most object will move right. TODO: What implications does this have for the rest of the scene? For example, when the left most object is also one connected to an object to its right. Do we want to put in additional rules to deal with this, or are we going to calculate the \"left-most\" and \"right-most\" objects as whatever groups of objects we'll need to move. Should we instead move the smaller of the two objects away from the larger of the two. What about generalizability? What happens when we've got 2 groups of objects that need to ungroup, or alternately what if the object is connected to multiple things at once, how do we move it away from the object that it was just ungrouped from, while keeping it connected to the objects it's still grouped with. Do we animate both sets of objects or just one set of objects?\n \n //Lets start with the simplest case and go from there. 2 objects are grouped together and we just want to move them apart.\n //There are 2 possibilities. Either they are partially overlapping (or connected on the edges), or one object is contained within the other.\n //Figure out which one is the correct one. Then figure out which direction to move them and which object we're moving if we're not moving both.\n //If object 1 is contained within object 2.\n if(objectContainedInObject(group.obj1, group.obj2)) {\n //alert(\"check 1\" + group.obj1.id + \" contained in \" + group.obj2.id);\n //For now just move the object that's contained within the other object toward the left until it's no longer overlapping.\n //Also make sure you're not moving it off screen.\n while((group.obj1.offsetLeft + group.obj1.offsetWidth + GAP > group.obj2.offsetLeft) &&\n (group.obj1.offsetLeft - STEP > 0)) {\n move(group.obj1, group.obj1.offsetLeft - STEP, group.obj1.offsetTop, false);\n }\n }\n //If object 2 is contained within object 1.\n else if(objectContainedInObject(group.obj2, group.obj1)) {\n //alert(\"check 2\" + group.obj2.id + \" contained in \" + group.obj1.id);\n //For now just move the object that's contained within the other object toward the left until it's no longer overlapping.\n //Also make sure you're not moving it off screen.\n \n while((group.obj2.offsetLeft + group.obj2.offsetWidth + GAP > group.obj1.offsetLeft) &&\n (group.obj2.offsetLeft - STEP > 0)) {\n move(group.obj2, group.obj2.offsetLeft - STEP, group.obj2.offsetTop, false);\n }\n }\n //Otherwise, partially overlapping or connected on the edges.\n else {\n //Figure out which is the leftmost object.\n if(group.obj1.offsetLeft < group.obj2.offsetLeft) {\n //Move obj1 left by STEP and obj2 right by STEP until there's a distance of 10 pixels between them.\n //Also make sure you're not moving either object offscreen.\n while(group.obj1.offsetLeft + group.obj1.offsetWidth + GAP > group.obj2.offsetLeft) {\n if(group.obj1.offsetLeft - STEP > 0)\n move(group.obj1, group.obj1.offsetLeft - STEP, group.obj1.offsetTop, false);\n \n if(group.obj2.offsetLeft + group.obj2.offsetWidth + STEP < window.innerWidth)\n move(group.obj2, group.obj2.offsetLeft + STEP, group.obj1.offsetTop, false);\n }\n }\n else {\n //Move obj2 left by STEP and obj1 right by STEP until there's a distance of 10 pixels between them.\n //Change the location of the object.\n while(group.obj2.offsetLeft + group.obj2.offsetWidth + GAP > group.obj1.offsetLeft) {\n if(group.obj1.offsetLeft + group.obj1.offsetWidth + STEP < window.innerWidth)\n move(group.obj1, group.obj1.offsetLeft + STEP, group.obj1.offsetTop, false);\n \n if(group.obj2.offsetLeft - STEP > 0)\n move(group.obj2, group.obj2.offsetLeft - STEP, group.obj2.offsetTop, false);\n }\n }\n }\n}", "move(group) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.connected) {\n return this.wrapper.moveUsers([this], group);\n }\n else {\n this.setGroup(group);\n return;\n }\n });\n }", "function onMoveToGroup() {\r\r\n\r\r\n let selectedNodeData = gridOptions.api.getSelectedNodes()\r\r\n let selectedRowData = gridOptions.api.getSelectedRows()\r\r\n\r\r\n // create a list of the items to choose from or enter your own\r\r\n groupBy = selectedNodeData.length == 0 ? '' : selectedNodeData[0].parent.field\r\r\n\r\r\n let key = []\r\r\n let group = []\r\r\n let newValue\r\r\n\r\r\n if (isNullOrEmpty(groupBy)) {\r\r\n //change to a swal alert for prettiness\r\r\n alert(`Check to be sure you've selected at least one row and a groupBy has been enabled for a column.`)\r\r\n } else {\r\r\n gridOptions.api.forEachLeafNode(function (rowNode, index) {\r\r\n key.push(rowNode.parent.key)\r\r\n })\r\r\n\r\r\n group = Array.from(new Set(key)).sort()\r\r\n newValue = prompt(`Please select a value and enter it`, `${group[0]}`)\r\r\n }\r\r\n\r\r\n selectedRowData.forEach(function (dataItem, index) {\r\r\n\r\r\n dataItem[groupBy] = newValue\r\r\n dataItem.is_edited = 'edited'\r\r\n })\r\r\n\r\r\n gridOptions.api.updateRowData({\r\r\n update: selectedRowData\r\r\n })\r\r\n}", "function moveLabelGroupHook(label,dest_coords){\n\t\t\t\n\n\t\t\t\tvar oldCoords = label.coords;\n\t\t\t\t//distance the label will be moved (and the group will move) in x/y direction\n\t\t\t\tvar deltaX = dest_coords.x - oldCoords.x;\n\t\t\t\tvar deltaY = dest_coords.y - oldCoords.y;\n\t\t\t\t\n\t\t\t\t//encapsulate delta distance into 2d point\n\t\t\t\t//var deltaCoord = {x:deltaX,y:deltaY};\n\t\t\t\t \n\n\t\t\t\tvar playerLabelNameList = document.getElementById('label_sel');\n\t\t\t\tvar otherLabelNameList = document.getElementById('label_sel2');\n\t\t\t\t//var labelNameList = $('#'+optionSelectionPaneId);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t//get the selected/highlighted label names from player select\n\t\t\t\tvar selectedLabels = getSelectValues(playerLabelNameList);\n\t\t\t\t//also add the select targets/enemies to highlighted list\n\t\t\t\tvar otherSelectedLabels = getSelectValues(otherLabelNameList);\n\t\t\t\t\n\t\t\t\t//merge arrays\n\t\t\t\tfor(var i = 0;i<otherSelectedLabels.length;i++){\n\t\t\t\t\tselectedLabels.push(otherSelectedLabels[i]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//player will have to click + ctrl key to unselect labels\n\t\t\t\t\n\t\t\t\t//iterate all labels, and move them the delta distance as a group\n\t\t\t\t//for(labelName in selectedLabels){\n\t\t\t\tfor(var i=0;i<selectedLabels.length;i++){\n\t\t\t\t\tvar labelName = selectedLabels[i];\n\t\t\t\t\t//skip over the label used as anchor to move group (already moving it)\n\t\t\t\t\tif (labelName == label.label){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t//eraseMapLabel(labelName);\n\t\t\t\t\t\t\n\t\t\t\t\tvar l = labelMap[labelName]\n\t\t\t\t\t\n\t\t\t\t\t//don't move labels that aren't on map and are highlighted\n\t\t\t\t\tif (l == undefined || l.coords === undefined){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tl.coords.x = l.coords.x + deltaX\n\t\t\t\t\tl.coords.y = l.coords.y + deltaY\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//now that we moved te labels, repaitn the map to redner the changes on canvas\n\t\t\t\trepaintAllLabels()\n\t\t\t}", "panStartGroup(ev){\n var that = this;\n this.startPosition = {'x': ev.srcEvent.x, 'y':ev.srcEvent.y, 'time': Date.now()};\n this.lastPosition = {'x': ev.srcEvent.x, 'y':ev.srcEvent.y}\n // console.log(that.panGroup)\n var getPan = getTransformation(d3.select('#panItems').attr('transform'));\n _getBBoxPromise('group-' + that.panGroup.id).then((BB)=> {\n // showBboxBB(BB, 'red')\n that.allBoundingBox = BB;\n // that.allBoundingBox.x += getPan.translateX - 20;\n // that.allBoundingBox.y += getPan.translateY - 20;\n that.allBoundingBox.width += 40;\n that.allBoundingBox.height += 40;\n })\n }", "function moveObjects(src, dst){\n\t\t\t \n\t\tvar activeObj = src.getActiveObject() == null ? src.getActiveGroup() : src.getActiveObject();\n\t \n\t\tif(activeObj != null){\n\n\t\t if(activeObj.type == 'group'){\n\t\t \n\t\t\tvar objectsInGroup = activeObj.getObjects();\n\t\t\t\tsrc.discardActiveGroup();\n\n\t\t\tobjectsInGroup.forEach(function(object) {\n\t\t\t\tobject.clone(function(c) {\n\t\t\t\t\tdst.add(c.set({\n\t\t\t\t\t\tleft: Mouse.posX + (c.left - activeObj.left),\n\t\t\t\t\t\ttop: Mouse.posY + (c.top - activeObj.top)\n\t\t\t\t\t}));\n\t\t\t\t});\n\t\t\t\tsrc.remove(object);\n\t\t\t});\n\t\t\t\t\t\n\t\t }else{\n\t\t \n\t\t\tactiveObj.clone(function(c) {\n\t\t\t\tdst.add(c.set({ left: Mouse.posX, top: Mouse.posY }));\n\t\t\t});\n\t\t\t\n\t\t\tsrc.remove(activeObj);\n\t\t \n\t\t }\n\t\t}\n\t\t\n\t}", "function groupSelected() {\r\n rot.group = that.surface.createGroup().moveToFront();\r\n for (var i in that.pieces) {\r\n var piece = that.pieces[i];\r\n if (that.selection.isPieceSelected(piece)) {\r\n that.drawPiece(rot.group, piece);\r\n piece.shape.removeShape();\r\n }\r\n }\r\n }", "function handleMoveRecipientGroupsAround() {\n var outer = $('#sms-recipient-groups');\n\n var all = outer.find('.recipient-groups .all-groups .inner');\n var selected = outer.find('.recipient-groups .selected-groups .inner');\n\n outer.find('.recipient-groups input:checkbox').change(function () {\n if ($(this).is(':checked')) {\n $(this).parents('label').appendTo(selected)\n } else {\n $(this).parents('label').appendTo(all)\n }\n });\n }", "function placeCenterGroup(group){\n\t\t\tfunction place(){\n\t\t\t\tvar cellsToPlace = sortByConstraint(group);\n\t\t\t\tvar index = Math.floor(Math.random() * cellsToPlace.length);\n\t\t\t\tvar originCell = cellsToPlace[index];\n\t\t\t\tvar options = originCell.options;\n\n\t\t\t\tvar index2 = Math.floor(Math.random() * options.length);\n\t\t\t\tvar destinationCell;\n\t\t\t\tvar failures = 0;\n\t\t\t\tdo{\n\t\t\t\t\tdestinationCell = options[index2];\n\t\t\t\t\tif(destinationCell.valid){\n\t\t\t\t\t\tsetValue(originCell,destinationCell);\n\t\t\t\t\t\tvar dex = group.findIndex(function(element){\n\t\t\t\t\t\t\treturn (element.value === originCell.value)\n\t\t\t\t\t\t})\n\t\t\t\t\t\tgroup.splice(dex, 1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tif(index2 === options.length - 1){\n\t\t\t\t\t\t\tindex2 = 0;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tindex2++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfailures++\n\t\t\t\t\t}\n\t\t\t\t}while(failures < options.length);\n\n\t\t\t\tif(failures === options.length){\n\t\t\t\t\tconsole.log('unable to place ' + originCell.coords)\n\t\t\t\t//this is a temporary fix\n\t\t\t\titsAllOver = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar iterations = group.length;\n\t\t\tfor(i=0;i<iterations;i++){\n\t\t\t\tplace();\n\t\t\t}\n\t\t\treturn;\n\t\t}", "function handleMoveRecipientGroupsAround()\n {\n var outer = $('#sms-recipient-groups');\n\n var all = outer.find('.recipient-groups .all-groups .inner');\n var selected = outer.find('.recipient-groups .selected-groups .inner');\n\n outer.find('.recipient-groups input:checkbox').change(function() {\n if ($(this).is(':checked')) {\n $(this).parents('label').appendTo(selected)\n } else {\n $(this).parents('label').appendTo(all)\n }\n });\n }", "function ORDERED(movepoint) {\n\t target = movepoint.transform;\n}", "function tvGroup_onNodeBeforeMove(sender, eventArgs) {\n var p = eventArgs.get_newParentNode();\n var n = eventArgs.get_node();\n if (n.ParentNode == null) {\n alert(\"不能转移分类!\");\n eventArgs.set_cancel(true);\n return;\n }\n if (p.ParentNode == null) {\n if (confirm(\"您确定要移动该组吗?\")) {\n return true;\n }\n else {\n eventArgs.set_cancel(true);\n }\n }\n else {\n alert(\"只能向分类转移!\");\n eventArgs.set_cancel(true);\n }\n}", "function moveCloudGroup(pageWidth, id, speed, currentPosition) {\n var elem = document.getElementById(\"cloud-group-\" + id);\n\n // Motion interval for cloud group movement\n var motionInterval = setInterval(function() {\n currentPosition += speed;\n if (currentPosition > pageWidth) {\n switch (id) {\n // Small single cloud group\n case \"1\":\n currentPosition = -125;\n break;\n // Large cloud cluster group\n case \"2\":\n currentPosition = -800;\n break;\n // Large single cloud group\n case \"3\":\n currentPosition = -300;\n break\n // No cloud group (shouldn't ever happen)\n default:\n currentPosition = 0;\n break\n }\n elem.style.top = Math.floor(Math.random() * 30) + \"%\";\n }\n elem.style.left = currentPosition + \"px\";\n },20);\n}", "function rotate(type) {\n log.info(\"PANES - Rotate group (\" + type +\")\");\n\n // get the group and current active pane\n var group = $(\".group.\" + type);\n if(group.length > 0){\n var active = group.find(\".pane.active\");\n\n // get the next pane\n var next = active.next();\n if (next.length == 0) {\n next = group.find(\".pane\").first();\n }\n\n // show next pane\n show(next.data(\"id\"));\n }else{\n log.warn(\"PANES - Non existing group: \" + type);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function clears everything under buttons div. Was going to use it before but decided not to
function clear() { $("#buttons").empty() }
[ "function clearButtons() {\n const childList = buttonContainer.getElementsByTagName(\"button\");\n for (let i = childList.length - 1; i >= 0; i--) {\n buttonContainer.removeChild(childList[i]);\n }\n}", "function clearApendix()\r\n {let p = document.getElementsByClassName('specificButtons'); \r\n while(p.length > 0){\r\n p[0].parentNode.removeChild(p[0]);}}", "function clearExistingButtons() {\n $(\"#trending\").empty();\n}", "function clearButtons() {\n $(\".characterMenu\").empty();\n $(\".selectedCharacter\").empty();\n $(\".enemies\").empty();\n $(\".defender\").empty();\n}", "function clearButtons() {\n $(\"#listButtons\").empty();\n}", "function clearbtns() {\n topics = [];\n $(\"#gif-btns\").empty();\n }", "function removeAllActionButtons() {\n $(barSelector).empty();\n }", "function clearbtn() {\r\n //Just clears the creen.\r\n reset();\r\n}", "function clearButtons(){\n\t\t\t$('.selected').toggleClass('selected');\n\t\t}", "function resetButtons() {\n basicAIButton.remove();\n userButton.remove();\n portKey.remove();\n left.remove();\n right.remove();\n fire.remove();\n setupButtons();\n}", "function cleanupButtons () {\r\n removeEl(switchActionUnblockId);\r\n removeEl(switchActionBlockId);\r\n removeEl(switchButtonId);\r\n}", "function button_clear()\n{\n\tbutton_backTo1Gen();\n init_canvas();\n init_simulation();\n}", "function clearAll() {\n\n clearAllHasBeenClicked = 1;\n\n hoverInterestsButtons = 1;\n hoverEducationButtons = 1\n hoverProfileButtons = 1;\n hoverExperienceButtons = 1;\n\n clearProfile();\n clearEducation();\n clearExperience();\n clearSkills();\n clearInterests();\n\n clearAllHasBeenClicked = 0;\n\n refreshAllBars();\n\n}", "clearButtonData() {\n\t\t\tthis.clearBadge();\n\n\t\t\tthis.sButton.iconNode.src = this.sButton.icon;\n\t\t\tthis.removeClass(this.sButton.coverNode, 'sc-show-button-message');\n\t\t\tthis.removeClass(this.sButton.node, 'sc-broadcast-button-message');\n\t\t\tthis.sButton.coverNode.style.cssText = null;\n\t\t}", "function clearAutomatically(){\r\n\tbtn0.value = \" \";\r\n btn1.value = \" \";\r\n btn2.value = \" \";\r\n btn3.value = \" \";\r\n btn4.value = \" \";\r\n btn5.value = \" \";\r\n btn6.value = \" \";\r\n btn7.value = \" \";\r\n btn8.value = \" \";\r\n click_count = 0;\t\r\n}", "function clearButtons() {\n for ( let i = 0; i < lis.length; i++ )\n while (lis[i].lastElementChild) {\n lis[i].removeChild( lis[i].lastElementChild );\n }\n}", "function clearingElements() {\n main.innerHTML = \"\";\n formingElements();\n}", "function clearAll() {\r\n\t\t$('#listelem').empty();\r\n\t\t$('#listelem').buttonset();\r\n\t\tselected_index = undefined;\r\n\t\tsirikata.event(\"clearAll\");\r\n\t}", "function setup_clearButtons() {\n let clearButtons = document.getElementsByClassName(\"clear-next\");\n for (const button of clearButtons) {\n button.addEventListener(\"click\", function () {\n button.nextElementSibling.innerHTML = \"\";\n })\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configuration NIET GEIMPLEMENTEERD!!!!!!!! save configuration to cookie
function SaveConfiguration() { var cookievalue = ''; // get added wms layers var wmslayers = mapPanel.layers.queryBy(function (record, id) { return record.get("layer").CLASS_NAME.indexOf("WMS") > -1 && !record.get("layer").isBaseLayer; }); var count = wmslayers.getCount(); if (count > 0) { cookievalue += 'wms,'; for (i = 0; i < count; i++) { cookievalue += Ext.util.JSON.encode(wmslayers.itemAt(i).data); // werkt niet! Een layer blijkt te complex om te serializeren... ("too much recursion") if (i < count - 1) { cookievalue += ','; } } cookievalue += ';'; } // TODO: get wmsSourcesStore? // TODO: get current zoom values? // save cookie Set_Cookie('mapconfig', cookievalue, '', '/', '', ''); if (Get_Cookie('mapconfig')) { msg('Configuratie bewaren', 'Configuratie is bewaard.\n\n' + cookievalue); } else { msg('Configuratie bewaren', 'Configuratie is NIET bewaard.\n\nZijn cookies uitgeschakeld in uw browser?'); } }
[ "static _saveConfig() {\n console.log(\"Enregistre le json de config des casques\",Casque.configJson);\n fs.writeFileSync(window.machine.jsonCasquesConfigPath, JSON.stringify(Casque.configJson,undefined, 2));\n }", "writeConfigToCookies() { \r\n\r\n var configString = \"\";\r\n\r\n configString += this.isCookieLatestBackup() ? \"1\" : \"0\";\r\n\r\n var currentConfig, currentZone, currentDir;\r\n for(var config = 0; config < NUM_INTERSECTION_CONFIGS; config++) {\r\n\r\n if(!PROJECT.getIntersectionByIndex(config).isEnabled())\r\n continue;\r\n else\r\n configString += this._break_char + this.getConfigId(config);\r\n\r\n currentConfig = PROJECT.getIntersectionByIndex(config);\r\n for(var zone = MIN_EFFECTIVE_ZONE; zone < NUM_ZONES; zone++) {\r\n\r\n if(!currentConfig.getZoneByIndex(zone).isEnabled()) {\r\n continue;\r\n }\r\n\r\n currentZone = currentConfig.getZoneByIndex(zone);\r\n for(var dir = 0; dir < 4; dir++) {\r\n currentDir = currentZone.getDirectionByIndex(dir);\r\n\r\n configString += this.TMtoCHAR(zone, dir, currentDir.getSharedLeft(), currentDir.getSharedRight(),\r\n currentDir.getchannelizedRight(), currentDir.getThrough(), currentDir.getLeftTurn(),\r\n currentDir.getRightTurn(), 0);\r\n }\r\n }\r\n }\r\n\r\n this._cookie = configString;\r\n\r\n var date = new Date();\r\n date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));\r\n var expires = \"; expires=\" + date.toUTCString();\r\n document.cookie = this._cookie_id + \"=\" + this._cookie + expires + \"; path=/\";\r\n }", "save() {\n for(const name in this.cookie)\n if (this.cookie[name] !== 'undefined')\n document.cookie = `${name} = ${this.cookie[name]}; expires = ${this.cookie.expires}`;\n }", "function LoadConfiguration() {\n var cookievalue = Get_Cookie('mapconfig');\n if (cookievalue) {\n // TODO: load settings from cookie\n msg('Configuratie inladen', 'Configuratie is ingeladen.');\n }\n else {\n msg('Configuratie inladen', 'Geen configuratie gevonden...');\n }\n}", "function saveConfig(){\n\t\tconsole.log(config)\n\t\tlocalStorage.config = JSON.stringify(config)\n\t}", "function setConfig(key,value) {\n//\tconsole.log('setConfig, key: '+key+', value: '+value+', cookie: '+getCookie(myName));\n\tsetCookie(myName, setURLParam(getCookie(myName),key,value),999999);\n}", "function saveConfiguration() {\n // save the current configuration in the \"chair\" object\n updateChairObject();\n // update local storage\n updateLocalStarage(\"chair\", chair);\n}", "function cookie_adcknowledge() {\n \"use strict\";\n localStorage.setItem(\"cookie_acknowledge\", true);\n}", "function saveCookie() {\n $.cookie(cookieID, cookie.join(''), {\n expires: 6\n });\n }", "function setConfig(key,value) {\n\tsetCookie(myName, setURLParam(getCookie(myName),key,value));\n//\tconsole.log('setConfig, key: '+key+', value: '+value+', cookie: '+getCookie(myName));\n}", "awakeStatusFromCookies() {\n\n let savedArea = this.loadCookie( cookieNameArea, areaId_Ecublens ); // Default is Ecublens\n this.setArea( savedArea );\n\n let savedJoin = this.loadCookie( cookieNameJoin, false ); // Default is false\n this.setJoin( savedJoin );\n\n }", "readConfigFromCookies() {\r\n\r\n // Check if there exists any content stored in a field ID'd _cookie_id.\r\n // If not, don't do anything of value.\r\n if(!(document.cookie.indexOf(this._cookie_id + \"=\") >= 0))\r\n console.log(\"No cookies found. Not updating configuration from backup.\");\r\n // If so, decode the cookies and read the project configuration into this session's project object.\r\n else {\r\n console.log(\"Cookies found! Check if they're the latest backup...\");\r\n this._startup_cookies_found = true;\r\n console.log(true);\r\n // If the \"cookies as latest backup\" flag is set to true, continue reading cookies to the project config.\r\n // If not, there's nothing to do. Function will complete with no further action.\r\n if(document.cookie.charAt(this._cookie_id.length + 1) === \"1\") {\r\n console.log(\"Cookies identified as latest backup, writing them to the project configuration...\");\r\n this.setCookieAsLatestBackup();\r\n\r\n this._cookie = document.cookie.substring(this._cookie_id.length + 2);\r\n var records = [];\r\n var char_index = 1;\r\n var sub_start = 0;\r\n var sub_end = 0;\r\n while(char_index != this._cookie.length) {\r\n if(this._cookie.charAt(char_index) === this._break_char) {\r\n sub_end = char_index;\r\n records.push(this._cookie.substring(sub_start + 1, sub_end));\r\n sub_start = sub_end;\r\n }\r\n if(char_index == this._cookie.length - 1) {\r\n records.push(this._cookie.substring(sub_start + 1));\r\n break;\r\n }\r\n char_index++;\r\n }\r\n \r\n var currentConfig;\r\n var configKeyEnum = this._ConfigKeyEnum;\r\n var _this = this;\r\n records.forEach(function(record){\r\n currentConfig = PROJECT.getIntersectionByIndex(objectKeyByValue(configKeyEnum, record.charAt(0)));\r\n // Credit to StackOverflow's David TanG\r\n record.substring(1).match(/.{2}/g).forEach(function(infopack) {\r\n var configDetails = _this.CHARtoTM(infopack);\r\n //if(objectKeyByValue(configKeyEnum, record.charAt(0)) == 0) console.log(\"Setting zone \" + configDetails[0] + \", direction \" + configDetails[1] + \" to \" + [configDetails[6], configDetails[5], configDetails[7], configDetails[2], configDetails[3], configDetails[4] ]); \r\n currentConfig.getZoneByIndex(configDetails[0]).getDirectionByIndex(configDetails[1]).setEntryArray( [configDetails[6], configDetails[5], configDetails[7], configDetails[2], configDetails[3], configDetails[4] ]);\r\n });\r\n });\r\n }\r\n }\r\n }", "function _saveUserOptions () {\n var data = {\n mode: selected_travel_mode,\n latlng: visitor_location,\n location: current_visitor_location\n };\n var save = $.cookie('map_options', data, {expires: 7, path: '/'});\n }", "static save(cookies, teamname) {\n const data = {\n cookies,\n teamname,\n }\n fs.writeFileSync(`${path.dirname(require.main.filename)}/config/cookies.json`, JSON.stringify(data));\n }", "function saveSettings(key, value)\r\n{\r\n\t// put the new value in the object\r\n\tpanelsStatus[key] = value;\r\n\t\r\n\t// create an array that will keep the key:value pairs\r\n\tvar panelsData = [];\r\n\tfor (var key in panelsStatus)\r\n\t\tpanelsData.push(key+\":\"+panelsStatus[key]);\r\n\t\t\r\n\t// set the cookie expiration date 1 year from now\r\n\tvar today = new Date();\r\n\tvar expirationDate = new Date(today.getTime() + 365 * 1000 * 60 * 60 * 24);\r\n\t// write the cookie\r\n\tdocument.cookie = PANEL_COOKIE_NAME + \"=\" + escape(panelsData.join(\"|\")) + \";expires=\" + expirationDate.toGMTString();\r\n}", "function saveState() {\n // https://www.w3schools.com/js/js_cookies.asp\n function setCookie(cname, cvalue, exdays) {\n var d = new Date();\n d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));\n var expires = \"expires=\" + d.toUTCString();\n document.cookie = cname + \"=\" + cvalue + \";\" + expires + \";path=/\";\n }\n cookie = JSON.stringify(state.selectedSections);\n setCookie('ycui_' + state.semester, cookie, 256);\n }", "function saveSettings(key, value) {\n\t\t// put the new value in the object\n\t\tpanelsStatus[key] = value;\n\n\t\t// create an array that will keep the key:value pairs\n\t\tvar panelsData = [];\n\t\tfor ( var key in panelsStatus)\n\t\t\tpanelsData.push(key + \":\" + panelsStatus[key]);\n\n\t\t// set the cookie expiration date 1 year from now\n\t\tvar today = new Date();\n\t\tvar expirationDate = new Date(today.getTime() + 365 * 1000 * 60 * 60 * 24);\n\t\t// write the cookie\n\t\tdocument.cookie = PANEL_COOKIE_NAME + \"=\" + escape(panelsData.join(\"|\"))\n\t\t\t\t+ \";expires=\" + expirationDate.toGMTString();\n\t}", "function guardarDatos(alias, nombre, pass, sexo, fechaNaci, aficiones) {\n var fechaNacimiento = fechaNaci.selectedIndex;\n var textoCookie = \"\";\n var tamSexo = sexo.length;\n var tamAficiones = aficiones.length;\n\n for(i=0; i<tamSexo;i++){\n if(sexo[i].checked==true){\n textoCookie += sexo[i].value + \"#\";\n }\n }\n textoCookie += fechaNacimiento + \"#\";\n for(i=0;i<tamAficiones;i++){\n if(aficiones[i].checked){\n textoCookie += aficiones[i].value + \"#\";\n }\n }\n\n var tamanio = textoCookie.length -1;\n textoCookie = textoCookie.substring(0, tamanio);\n\n if(debug){\n console.log(\"Cookie: \"+textoCookie);\n }\n document.cookie = textoCookie;\n\n if(debug){\n console.log(\"Esta es la cookie => \" +document.cookie);\n }\n\n\n\n}", "saveStateToCookie() {\n cookies = cookies || new Cookies();\n\n const stateToSave = {};\n STATE_KEYS_SAVE.forEach(key => {\n stateToSave[key] = this.state[key];\n });\n\n cookies.set(STORYTELLER_COOKIE, stateToSave, {\n path: '/',\n expires: new Date(COOKIE_EXP),\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
actualizarCurso('5f39da72b416ba1ca8c83138'); Otro metodo para poder actualizar pagina de mongo db su documentacion
async function actualizarCurso2(id){ const curso = await Curso.findById(id); const resultado = await Curso.update({_id : id}, { $set: { autor: 'Emanuel', publicado: true } }); console.log(resultado); }
[ "function leerDatosCurso(curso) {\n //Nos creamos un objeto con los datos del curso que vamos a comprar\n const infoCurso = {\n imagen: curso.querySelector('img').src,\n titulo: curso.querySelector('h4').textContent,\n precio: curso.querySelector('.precio span').textContent,\n id: curso.querySelector('a').getAttribute('data-id'),\n }\n insertarEnCarrito(infoCurso);\n}", "function leerDatosCurso(curso) {\n const infoCurso = {\n imagen: curso.querySelector('img').src,\n titulo: curso.querySelector('h4').textContent,\n precio: curso.querySelector('.precio span').textContent,\n id: curso.querySelector('a').getAttribute('data-id')\n }\n\n insertarCarrito(infoCurso);\n }", "function leerDatosCurso(curso) {\n const infoCurso = {\n imagen: curso.querySelector(\"img\").src,\n titulo: curso.querySelector(\"h4\").textContent,\n precio: curso.querySelector(\".precio span\").textContent,\n id: curso.querySelector(\"a\").getAttribute(\"data-id\"),\n };\n insertarCarrito(infoCurso);\n}", "async function listarCurso(){\n // api/Cursos?numeroPage=4&sizePage=10\n const numeroPage = 2; \n const sizePage = 10;\n\n // -----------------------------------------------------------------------------------\n // OPERADORES DE COMPARACION\n // eq (equal, igual)\n // ne (not equal, no igual)\n // gt (greater than, mayor o igual que)\n // gte (greater than or equal to, mayor o igual que)\n // lt (less than, menor que)\n // lte (less than or equal to, menor o igual que)\n // in \n // nin (not in)\n // ----------------------------------------------------------------------------------\n // OPERADORES LOGICOS\n // or\n // and\n const cursos = await Curso\n // OPERADORES DE COMPARACION\n // {mayor a 10 menor a 30}\n // .find({precio : {$gte: 10, lte: 30}})\n // Se le dice unicamente los precios que desea [10, 15, 25]\n // .find({precio: {$in: [10, 15, 25]}})\n\n // OPERADORES LOGICOS \n // .find()\n // .or([{autor : 'Emanuel'}, {publicado : true}])\n // .and([{autor : 'Emanuel'}, {publicado : true}])\n\n // Expresiones regulares\n // Cuando empiece en\n // .find({ autor:/^Ju/})\n // Cuando termine en\n // .find({autor: /uan$/}) \n // Cuando un campo tiene contenido especifico \n // .find({ autor: /.*Ju*/})\n \n\n // {adentro se le puede dar procesos para mostrar dicha informacion}\n // .find({autor: 'Emanuel'})\n .find()\n .skip((numeroPage - 1) * sizePage)\n // Limite de datos\n .limit(sizePage)\n // 1 muestra el dato de forma ascendente y -1 de forma descendente.\n .sort({autor: 1})\n // unicamente muestra los datos que se coloquen\n .select({autor : 1, nombre: 1, etiquetas:1});\n console.log(cursos); \n}", "function viewDB(){\r\n MongoClient.connect(url, function (err, db) {\r\n assert.equal(null, err);\r\n console.log(\"Connected successfully to server database\");\r\n console.log(\"contenu de la db\");\r\n findDocuments(db, function () {\r\n db.close();\r\n });\r\n });\r\n\r\n}", "function cargarDoc(){\n onRequest({ opcion : 4 ,doc:\"\"}, respDoc);\n \n}", "async function actualizarCurso3(id){ \n const resultado = await Curso.findByIdAndUpdate(id,{ \n $set: { \n autor: 'Juan Solis',\n publicado: false\n }\n },/*Con este {new: true} se muestran los datos actualizados \n sin el se muestran los datos antes de actualizar*/ {new: true});\n console.log(resultado);\n}", "function saveDocumentosTraslado(req,res){\n var estudianteId = req.params.id;\n var params = req.body;\n\n EstudianteMdl.findOne({_id:estudianteId},(err,estudiante)=>{\n if(err){\n res.status(500).send({message:'Error en la actulizacion'})\n }else{\n if(!estudiante){\n res.status(400).send({message:'Estudiante no existe'});\n }else{\n estudiante.documentos.traslado.certificado = params.certificado;\n estudiante.documentos.traslado.resolucion = params.resolucion;\n estudiante.documentos.traslado.boleta_notas = params.boleta_notas;\n \n EstudianteMdl.findByIdAndUpdate(estudianteId,estudiante,{new:true},(err,estudianteUpdate)=>{\n if(err){\n res.status(500).send({message:'Error en la actualizacion'});\n }else{\n if(!estudianteUpdate){\n res.status(404).send({message:'Estudiante no existe'});\n }else{\n res.status(200).send(estudianteUpdate);\n }\n }\n });\n }\n }\n });\n}", "static getCursoConIC(idanio_lectivo) {\n return db.query(`\n SELECT\n curso.idcurso,\n curso.idcurso,\n curso.cur_curso,\n inspector.anio_lectivo_idanio_lectivo,\n inspector.tipo,\n inspector.idinspector,\n inspector.user_iduser,\n user.iduser,\n inspector.estado\n FROM\n inspector\n JOIN curso ON inspector.curso_idcurso = curso.idcurso\n JOIN user ON inspector.user_iduser = user.iduser\n WHERE\n inspector.anio_lectivo_idanio_lectivo = ?\n AND inspector.estado = 1 \n `, [idanio_lectivo]);\n }", "saveInMongo(datos)\n\t{\n\t\tmongoClient.connect(this.urlDB, function(err, db)\n\t\t{\n\t\t if (err) \n\t\t console.log('Sorry unable to connect to MongoDB Error:', err);\n\t\t else\n\t\t { \n\t\t \t//Grabo todo el lote de datos.\n\t\t var collection = db.collection('colectivos');\n\t\t \n\t\t collection.insertMany(datos, { w: 1 }, function(err, records) {\n\t\t console.log(\"Record added :- \" + records);\n\t\t });\n\t\t \n\t\t db.close();\n\t\t }\n\t\t});\n\t}", "async editarCurso({ commit, dispatch}, { curso, id }) {\n \n commit(\"isLoading\", true);\n Firebase\n .firestore()\n .collection(\"curso\")\n .doc(id)\n .set(curso)\n .then(() => {\n dispatch(\"getCursos\");\n });\n }", "function leerDatosCurso(curso){\n console.log(curso);\n}", "function connect() {\n //uris : adresse serveur mongo\n mongoose.connect('mongodb://localhost:27017/miw', { autoReconnect: true, useNewUrlParser: true });\n}", "async function getCursosSe(req, res){\r\n var institucion=req.user.institucion;\r\n var secundaria=\"secundaria\";\r\n Curso.find({institucion:institucion, nivel:secundaria}).exec((err, curso) => {\r\n if(err){\r\n res.status(500).send({message:'Se ha producido un error en la peticion'});\r\n }else{\r\n if(!curso){\r\n res.status(404).send({message:'No se ha encontrado un listado de cursos'});\r\n }else{\r\n res.status(200).send({curso});\r\n }\r\n }\r\n });\r\n}", "function searchDB(numb,res){\n MongoClient.connect(dbUrl,function(err,db){\n if(err){\n console.log('Search database err :-- '+err);\n } else{\n var collection = db.collection('test');\n collection.findOne({\"urlNum\" : numb},function(err,doc){\n if(err){\n console.log('Find error :-- '+err);\n } else {\n if(doc){\n console.log('Redirecting to :-- '+doc.orgiUrl);\n res.redirect(doc.orgiUrl);\n db.close();\n } else {\n res.json({\n \"ERROR\" : \"This url is not in the database\"\n });\n }\n\n }\n });\n }\n });\n}", "function getCursos(req, res){\r\n var institucion=req.user.institucion;\r\n Curso.find({institucion:institucion}).sort({nivel:1}).exec((err, curso) => {\r\n if(err){\r\n res.status(500).send({message:'Se ha producido un error en la peticion'});\r\n }else{\r\n if(!curso){\r\n res.status(404).send({message:'No se ha encontrado un listado de cursos'});\r\n }else{\r\n res.status(200).send({curso});\r\n }\r\n }\r\n });\r\n}", "getCompraPorId(id, cb) {\n this.connection.collection(\"compras\").findOne({ \"_id\": ObjectId(id) }, function (err, compraBanco) {\n var compra = null;\n if(compraBanco){\n compra = new Compra(compraBanco);\n }\n cb(err, compra)\n });\n }", "function getImagen(req,res,next){\n //Conexion a Mongo\n MongoClient.connect(url, function(err, db) {\n //Condicion para entrar a Mongo\n if (err) throw err;\n //Se consiguen todos los documentos de la coleccion de imagenes con find\n db.collection(\"imagenes\").find({}).toArray(function(err, result) {\n //Condicion en caso de error\n if (err) throw err;\n //Si todo procede bien se imprime en consola el resultado\n console.log(result);\n //Se guarda en el paquete de respuesta el resultado\n res.send(result);\n db.close();//Cierre de la conexion\n });\n});\n next();\n}", "mongo() {\n this.mongoConnection = mongoose.connect(process.env.MONGO_URL, {\n useNewUrlParser: true,\n useFindAndModify: true,\n });\n\n // DO NOT FORGET to execute it in this.init()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description Removed an element attribute of a specified markup element that has been bound to this view. = Parameters +_partName+:: The identifier of the markup element. +_key+:: The attribute to remove. = Returns +self+
unsetAttrOfPart(_partName, _key) { const _elemId = this._getMarkupElemIdPart(_partName, 'HView#setAttrOfPart'); if (this.isntNull(_elemId)) { ELEM.delAttr(_elemId, _key); } return this; }
[ "unsetAttr(_key) {\n ELEM.delAttr(this.elemId, _key)\n return this;\n }", "unsetAttr(_key) {\n ELEM.delAttr(this.elemId, _key);\n return this;\n }", "removeAttribute(key) {\n this.setAttribute(key, undefined);\n }", "removeAttribute(name) {\n if ('attributes' in this.fieldNode) {\n const attrindex = this._givenAttrs.indexOf(name);\n if (attrindex !== -1) {\n this.fieldNode.attributes[name].deleteNode();\n }\n } else {\n this._removeVirtualAttribute(name);\n }\n }", "function removePropertyFromElement(element, key) {\n if (hasData(element)) {\n delete data(element)[key];\n }\n }", "removeAttribute(name) {\n delete this._attribs[name];\n return this;\n }", "function removePart(element, part) {\n var _a;\n if (!element)\n return;\n const current = (_a = element.getAttribute('part')) !== null && _a !== void 0 ? _a : '';\n if (current.includes(part)) {\n element.setAttribute('part', current.replace(new RegExp('\\\\bs*' + part + 's*\\\\b', 'g'), ''));\n }\n}", "removeAttribute(name) {\n var attName, j, len;\n // Also defined in DOM level 1\n // removeAttribute(name) removes an attribute by name.\n if (name == null) {\n throw new Error(\"Missing attribute name. \" + this.debugInfo());\n }\n name = getValue(name);\n if (Array.isArray(name)) { // expand if array\n for (j = 0, len = name.length; j < len; j++) {\n attName = name[j];\n delete this.attribs[attName];\n }\n } else {\n delete this.attribs[name];\n }\n return this;\n }", "setAttrOfPart(_partName, _key, _value, _force) {\n const _elemId = this._getMarkupElemIdPart(_partName, 'HView#setAttrOfPart');\n if (this.isntNull(_elemId)) {\n ELEM.setAttr(_elemId, _key, _value, _force);\n }\n return this;\n }", "function TagEdit_removeAttribute(attributeName)\n{\n this.changedAttribute = true;\n \n for (var i=0; i < this.tagAttributes.length; i++)\n {\n if (this.tagAttributes[i].name.toUpperCase() == attributeName.toUpperCase())\n {\n this.tagAttributes[i].remove = true;\n break;\n }\n else if (this.tagAttributes[i].code &&\n this.tagAttributes[i].code == attributeName)\n {\n this.tagAttributes[i].remove = true;\n break;\n }\n }\n}", "removePart(part) {\n const node = this.nodeFromElement(part);\n invariant(node, 'expected a matching node');\n delete this.nodes2parts[node.uuid];\n delete this.parts2nodes[part];\n delete this.partTypes[part];\n node.parent.removeChild(node);\n return node;\n }", "function removeAttributeOfElement(attributeName,ElementXpath)\n\t{\n\t\tvar alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);\n\t\tfor (i=0; i<alltags.snapshotLength; i++)\n\t\t{\n\t\t\talltags.snapshotItem(i).removeAttribute(attributeName);\n\t\t}\n\t}", "function removeattr(Selector, Attribute){\n return select(Selector, function (element, index) {\n element.removeAttribute(Attribute);\n });\n}", "function removeAttributeOfElement(attributeName,ElementXpath) {\n var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);\n for (i=0; i<alltags.snapshotLength; i++) alltags.snapshotItem(i).removeAttribute(attributeName);\n}", "function scripts_nodeDatasetRemove() {\n\tvar el = arguments[0],\n\t key = arguments[1];\n\tif (el == null || key == null) {\n\t\treturn;\n\t}\n\tif (el.dataset) {\n\t\tdelete el.dataset[key];\n\t\treturn;\n\t}\n\tel.removeAttribute(key);\n}", "function scripts_nodeDatasetRemove() {\n\tvar el = arguments[0],\n\t key = arguments[1];\n\tif (el == null || key == null) {\n\t\treturn;\n\t}\n\tel.removeAttribute(key);\n}", "function removeAttr(name){\n\t\treturn this.forEach(function(elem){\n\t\t\telem.removeAttribute(name);\n\t\t});\n\t}", "remove_attribute(attr_key, attr_value) {\n\t\tvar found = false;\n\t\tfor (var key in this.attributes) {\n\t\t\tif (key == attr_key) {\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (found) {\n\t\t for (var idx in this.attributes[attr_key]) {\n\t\t\t if (this.attributes[attr_key][idx] == attr_value) {\n\t\t\t\t this.attributes[attr_key].splice(idx, 1);\n\t\t\t }\n\t\t }\n\t\t}\n\t\tconsole.log(this.attributes[attr_key]);\n\t\tvar updated_attribute_value = \"\"\n\t\tfor (var item in this.attributes[attr_key]) {\n\t\t\tupdated_attribute_value += this.attributes[attr_key][item] + \" \";\n\t\t}\n\t\tthis.element.setAttribute(attr_key, updated_attribute_value);\n\t}", "function Xml_RemoveAttribute(objNode,strAttribute)\r\n{\r\n objNode.removeAttribute(strAttribute);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the BLAKE2B hash of a string or byte array Returns an nbyte hash in hex, all lowercase Parameters: input the input bytes, as a string, Buffer, or Uint8Array key optional key Uint8Array, up to 64 bytes outlen optional output length in bytes, default 64
function blake2bHex (input, key, outlen) { const output = blake2b(input, key, outlen) return util.toHex(output) }
[ "function blake2bHex (input, key, outlen) {\n var output = blake2b(input, key, outlen)\n return util.toHex(output)\n}", "function sha256_encode_bytes() {\r\n let j = 0;\r\n const output = new Array(32);\r\n for (let i = 0; i < 8; i++) {\r\n output[j++] = (ihash[i] >>> 24) & 0xff;\r\n output[j++] = (ihash[i] >>> 16) & 0xff;\r\n output[j++] = (ihash[i] >>> 8) & 0xff;\r\n output[j++] = ihash[i] & 0xff;\r\n }\r\n return output;\r\n}", "function blake2sHex (input, key, outlen) {\n var output = blake2s(input, key, outlen)\n return util.toHex(output)\n}", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n}", "function calculateHashBytes (data) {\n let shaObj = new jsSHA(\"SHA-256\", \"ARRAYBUFFER\");\n shaObj.update(data);\n hash = \"0x\" + shaObj.getHash(\"HEX\");\n return hash;\n}", "function blake2sHex (input, key, outlen) {\n const output = blake2s(input, key, outlen)\n return util.toHex(output)\n}", "function sha256_encode_bytes() {\n var j=0;\n var output = new Array(32);\n for(var i=0; i<8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n}", "function blake2bInit (outlen, key) {\n if (outlen === 0 || outlen > 64) {\n throw new Error('Illegal output length, expected 0 < length <= 64')\n }\n if (key && key.length > 64) {\n throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64')\n }\n\n // state, 'param block'\n const ctx = {\n b: new Uint8Array(128),\n h: new Uint32Array(16),\n t: 0, // input count\n c: 0, // pointer within buffer\n outlen: outlen // output length in bytes\n }\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n ctx.h[i] = BLAKE2B_IV32[i]\n }\n const keylen = key ? key.length : 0\n ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen\n\n // key the hash, if applicable\n if (key) {\n blake2bUpdate(ctx, key)\n // at the end\n ctx.c = 128\n }\n\n return ctx\n}", "function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n\n for (var i = 0; i < 8; i++) {\n output[j++] = ihash[i] >>> 24 & 0xff;\n output[j++] = ihash[i] >>> 16 & 0xff;\n output[j++] = ihash[i] >>> 8 & 0xff;\n output[j++] = ihash[i] & 0xff;\n }\n\n return output;\n}", "function sha256_encode_bytes () {\n var j = 0\n var output = new Array(32)\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff)\n output[j++] = ((ihash[i] >>> 16) & 0xff)\n output[j++] = ((ihash[i] >>> 8) & 0xff)\n output[j++] = (ihash[i] & 0xff)\n }\n return output\n}", "function blake2bInit (outlen, key) {\n if (outlen === 0 || outlen > 64) {\n throw new Error('Illegal output length, expected 0 < length <= 64')\n }\n if (key && key.length > 64) {\n throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64')\n }\n\n // state, 'param block'\n const ctx = {\n b: new Uint8Array(128),\n h: new Uint32Array(16),\n t: 0, // input count\n c: 0, // pointer within buffer\n outlen: outlen // output length in bytes\n };\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n ctx.h[i] = BLAKE2B_IV32[i];\n }\n const keylen = key ? key.length : 0;\n ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen;\n\n // key the hash, if applicable\n if (key) {\n blake2bUpdate(ctx, key);\n // at the end\n ctx.c = 128;\n }\n\n return ctx\n }", "function blake2bInit (outlen, key) {\n if (outlen === 0 || outlen > 64) {\n throw new Error('Illegal output length, expected 0 < length <= 64')\n }\n if (key && key.length > 64) {\n throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64')\n }\n\n // state, 'param block'\n var ctx = {\n b: new Uint8Array(128),\n h: new Uint32Array(16),\n t: 0, // input count\n c: 0, // pointer within buffer\n outlen: outlen // output length in bytes\n }\n\n // initialize hash state\n for (var i = 0; i < 16; i++) {\n ctx.h[i] = BLAKE2B_IV32[i]\n }\n var keylen = key ? key.length : 0\n ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen\n\n // key the hash, if applicable\n if (key) {\n blake2bUpdate(ctx, key)\n // at the end\n ctx.c = 128\n }\n\n return ctx\n}", "function blake2bInit(outlen, key) {\n if (outlen === 0 || outlen > 64) {\n throw new Error('Illegal output length, expected 0 < length <= 64');\n }\n if (key && key.length > 64) {\n throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64');\n }\n\n // state, 'param block'\n const ctx = {\n b: new Uint8Array(128),\n h: new Uint32Array(16),\n t: 0, // input count\n c: 0, // pointer within buffer\n outlen: outlen, // output length in bytes\n };\n\n // initialize hash state\n for (let i = 0; i < 16; i++) {\n ctx.h[i] = BLAKE2B_IV32[i];\n }\n const keylen = key ? key.length : 0;\n ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen;\n\n // key the hash, if applicable\n if (key) {\n blake2bUpdate(ctx, key);\n // at the end\n ctx.c = 128;\n }\n\n return ctx;\n }", "function sha256Multihash(bytes) {\n const digest = fast_sha256_1.default(bytes);\n const code = 0x12; // sha2-256\n return multihash(digest, code);\n}", "function SHA256_hash(msg) {\n var res;\n SHA256_init();\n SHA256_write(msg);\n res = SHA256_finalize();\n return array_to_hex_string(res);\n}", "function simpleHash(input) {\n return ethUtil.sha256(input);\n}", "function blake2b_init (outlen, key) {\n if (outlen === 0 || outlen > 64) {\n throw new Error('Illegal output length, expected 0 < length <= 64')\n }\n if (key && key.length > 64) {\n throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64')\n }\n\n // state, 'param block'\n var ctx = {\n b: new Uint8Array(128),\n h: new Uint32Array(16),\n t: 0, // input count\n c: 0, // pointer within buffer\n outlen: outlen // output length in bytes\n }\n\n // initialize hash state\n for (var i = 0; i < 16; i++) {\n ctx.h[i] = BLAKE2B_IV32[i]\n }\n var keylen = key ? key.length : 0\n ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen\n\n // key the hash, if applicable\n if (key) {\n blake2b_update(ctx, key)\n // at the end\n ctx.c = 128\n }\n\n return ctx\n}", "function sha256(bytes) {\n return browser$3('sha256').update(bytes).digest();\n}", "function newHash() {\n return (0, _blakejs.blake2bInit)(32, null);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse the url parameter and extract the filetype
getUrlFileType(url){ //get the path porion of the url let urlInstance = new URL(url); let urlPath = urlInstance.pathname; //get the fileType from the urlPath return path.extname(urlPath); }
[ "function mime_type (url)\r\n{\r\n var u = url.split (\".\"), n = u.length - 1;\r\n var mime = mime_list [u[n]]; return (mime ? mime : \"\");\r\n}", "function mime_type (url)\r\n{\r\n var u = url.split (\".\"), n = u.length - 1; if (n < 0) return (\"\");\r\n var mime = mime_list [u[n]]; return (mime ? mime : \"\");\r\n}", "function getType(type){\n\ttype=decodeURIComponent(type);\n\ttype=type.split(\";\")[0];\n\n\tif(type.toLowerCase()==\"video/x-flv\")\n\t\treturn \"flv\";\n\tif(type.toLowerCase()==\"video/mp4\")\n\t\treturn \"mp4\";\n\tif(type.toLowerCase()==\"video/3gpp\")\n\t\treturn \"3gpp\";\n\tif(type.toLowerCase()==\"video/webm\")\n\t\treturn \"webm\";\n}", "function urlType(url) {\n\t\tif (/(\\.mp3(?!\\w)|\\.ogg(?!\\w)|\\.wav(?!\\w)|#audio$)/.test(url))\n\t\t\treturn \"audio\";\n\t\tif (/(\\.mp4(?!\\w)|#video$)/.test(url))\n\t\t\treturn \"video\";\n\t\treturn \"image\";\n\t}", "function getTypeFromFileExtension(url) {\n\turl = url.toLowerCase().split('?')[0];\n\tvar _ext = url.substring(url.lastIndexOf('.') + 1);\n\tvar _av = /mp4|m4v|ogg|ogv|m3u8|webm|webmv|wmv|mpeg|mov/gi.test(_ext) ? 'video/' : 'audio/';\n\n\tswitch (_ext) {\n\t\tcase 'mp4':\n\t\tcase 'm4v':\n\t\tcase 'm4a':\n\t\t\treturn _av + 'mp4';\n\t\tcase 'webm':\n\t\tcase 'webma':\n\t\tcase 'webmv':\n\t\t\treturn _av + 'webm';\n\t\tcase 'ogg':\n\t\tcase 'oga':\n\t\tcase 'ogv':\n\t\t\treturn _av + 'ogg';\n\t\tcase 'm3u8':\n\t\t\treturn 'application/x-mpegurl';\n\t\tcase 'ts':\n\t\t\treturn _av + 'mp2t';\n\t\tdefault:\n\t\t\treturn _av + _ext;\n\t}\n}", "getFileType() {\n const [fileType] = this.state.file.type.split(\"/\");\n return fileType;\n }", "function getExpectedContentType(mimeType, url) {\n var extensionMap = {\n codap: 'application/vnd.codap+json',\n json: 'application/json',\n geojson: 'application/geo+json',\n csv: 'application/csv',\n txt: 'application/csv'\n };\n var parsedURL = url && parseURL(url);\n var path = parsedURL && parsedURL.pathname;\n if (mimeType) {\n return mimeType;\n }\n if (path) {\n return extensionMap[path.replace(/.*\\./g, '')];\n }\n }", "extractFileType() {\n if (this.state.currentImageURL == \"\") {\n return \"\";\n }\n var fileName = this.parseURLForName(this.state.currentImageURL);\n var fileExtension = fileName.substring(fileName.indexOf(\".\") + 1);\n\n if (fileExtension == undefined || fileExtension == null || fileExtension == \"\") {\n return \"\";\n }\n\n fileExtension = fileExtension.toLowerCase();\n if (fileExtension === \"jpg\" || fileExtension === \"jpeg\") {\n return \"jpeg\";\n } else if (fileExtension === \"png\") {\n return \"png\";\n } else {\n return \"\";\n }\n }", "function getFileMimeType(){\n var type = fileSelected.type || '/';\n var fName = fileSelected.name;\n return type.split('/')[1] || fName.split('.')[fName.split('.').length - 1];\n }", "function getUrlType(fragURL) {\n var type;\n var types = {\n \"live\": \"https:\\/\\/www.canada.ca\\/(.*?).html\",\n \"preview\": \"https:\\/\\/canada-preview.adobecqms.net\\/(.*?).html\",\n \"editor\": \"https:\\/\\/author-canada-prod.adobecqms.net\\/editor.html(.*?).html\",\n \"aemUrl\": \"https:\\/\\/author-canada-prod.adobecqms.net\\/sites.html(.*?)\\s\"\n };\n $.each(types, function(key, value) {\n var testingForType = fragURL.match(value);\n if (testingForType != null) {\n type = key;\n }\n });\n if (type == null) type = \"type is not defined\";\n return type;\n }", "function findMediaType( url ){\n var regexResult = __urlRegex.exec( url );\n if ( regexResult ) {\n _mediaType = regexResult[ 1 ];\n // our regex only handles youtu ( incase the url looks something like youtu.be )\n if ( _mediaType === \"youtu\" ) {\n _mediaType = \"youtube\";\n }\n }\n else {\n // if the regex didn't return anything we know it's an HTML5 source\n _mediaType = \"object\";\n }\n return _mediaType;\n }", "function getMimeType(format) {\r\n return format.match(/\\s*([\\w-]+\\/[\\w-]+)(;|\\s|$)/)[1];\r\n }", "function parseFileExtensionFromURL(url, loaders) {\n const parts = url.split(\".\");\n const ext = parts[parts.length - 1];\n if (!loaders.has(ext)) {\n console.warn('Trying to load url: ' + url + ' with an unknown filetype. Assuming \"text\".');\n }\n return loaders.has(ext) ? ext : 'text';\n}", "function getContentType(url) {\n url = trimUrlQuery(url);\n let dot = url.lastIndexOf(\".\");\n if (dot >= 0) {\n let name = url.substring(dot + 1);\n if (name in contentMap) {\n return contentMap[name];\n }\n }\n return \"text/plain\";\n}", "function get_mime(filename){\nvar type=\"\";\nswitch(getExtension(filename)){\ncase \"css\":\n type=\"text/css\";\nbreak;\ncase \"htm\":\ncase \"html\":\n type=\"text/html\";\nbreak;\ncase \"json\":\n type=\"application/json\";\nbreak;\ncase \"js\":\n type=\"application/javascript\";\nbreak;\ncase \"jpeg\":\ncase \"jpg\":\n type=\"image/jpeg\";\nbreak;\ncase \"png\":\n type=\"image/png\";\nbreak;\ncase \"gif\":\n type=\"image/gif\";\nbreak;\n};\nreturn type;\n}", "function getContentType(url) {\n url = trimUrlQuery(url);\n const dot = url.lastIndexOf(\".\");\n\n if (dot >= 0) {\n const name = url.substring(dot + 1);\n\n if (name in contentMap) {\n return contentMap[name];\n }\n }\n\n return \"text/plain\";\n}", "function getMimeType(format) {\n return format.match(/\\s*([\\w-]+\\/[\\w-]+)(;|\\s|$)/)[1];\n }", "static sanitizeMimeType(type) {\n return type.split(';')[0];\n }", "function guessContentTypeFromURL(url) {\n if (url.indexOf('.pdf') !== -1) {\n return CONTENT_TYPE_PDF;\n } else {\n return CONTENT_TYPE_HTML;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================================================== [author] Dodzi Y. Dzakuma [summary] Dynamically loads an image to be used to mark an action on the board. [parameters] 1) a marker used to determine which player made the move 2) the type of resource to use (line|box) 3) the x coordinate of the resource to replace 4) the y coordinate of the resource to replace [return] 1) a path to the resource if coordinates are valid 2) a blank string if the resource coordinates are invalid ==========================================================
function replaceResource(playerMarker, resourceType, xCoordinate, yCoordinate) { //-------------------------------------- // safety check //-------------------------------------- if (!coordinatesWithinRange(xCoordinate, yCoordinate)) { return ""; } //-------------------------------------- // initializations //-------------------------------------- var resourceSelector = "." + resourceType.toLowerCase() + "-" + xCoordinate + "-" + yCoordinate + " > img"; var resourcePath = IMAGES_FOLDER + playerMarker + "-" + resourceType + ".svg"; var tagToReplace = "<img>"; var imageExists = false; //-------------------------------------- // replace the image //-------------------------------------- var loadedImage = $(tagToReplace).attr("src", resourcePath).load(function() { //image exists replace the image on the board $(resourceSelector).first().replaceWith(loadedImage); }); return resourcePath; }
[ "static updateImagePath() {\r\n if (game.user.isGM) {\r\n let tile = canvas.tiles.placeables.find(t => t.data.flags.turnMarker == true);\r\n if (tile) {\r\n canvas.scene.updateEmbeddedEntity('Tile', {\r\n _id: tile.id,\r\n img: Settings.getImagePath()\r\n });\r\n }\r\n }\r\n }", "function mapaToImg(x, y) {\n //Apareix un objecte\n if (mapa[x][y] == \"O\") {\n random_obj = getRandomObject ();\n while (random_obj == \"llave\") {\n random_obj = getRandomObject ();\n }\n return (\"path_\" + random_obj + \".png\");\n }\n //Apareix la paret\n if (mapa[x][y] == \"#\") {\n return \"dungeon_wall.png\";\n }\n //Hi ha el jugador o un espai buit\n if (mapa[x][y] == \".\" || mapa[x][y] == \"P\") {\n return \"dungeon_step.png\";\n }\n //Apareix la porta\n if (mapa[x][y] == \"D\") {\n return \"dungeon_door.png\";\n }\n //Apareix un enemic\n if (mapa[x][y] == \"E\") {\n //Afegeix la vida i una arma aleatòria a l'enemic\n addWeaponEnemy();\n return enemigo.img;\n }\n //Apareix la clau\n if (mapa[x][y] == \"K\") {\n return \"path_llave.png\";\n }\n}", "function checker_image(y, x, type){\n return \"<img onClick='vbrbasic();pos(\"+y+\",\"+x+\");dots(this);' name=p\"+y+\"\"+x+\" id=p\"+y+\"\"+x+\" src='\" + type + \".png' style='width:\"+dims+\"px;height:\"+dims+\"px'>\";\n}", "updateMarker(box) {\n let position = box.data('pos');\n if (game.isPlayerAt(Board.X_MARKER, position.row, position.col)) {\n $(box).html(`<img class='marker' src=${this.X_IMG_PATH}>`);\n } else if (game.isPlayerAt('O', position.row, position.col)) {\n $(box).html(`<img class='marker' src=${this.O_IMG_PATH}>`);\n }\n }", "function createCustomMarker(point, options, insertAtIndex) {\r\n \r\n //If options is undefined it should be set as an empty object to be used on $.extend. \r\n if (options == undefined) {\r\n options = {};\r\n }\r\n \r\n var defaultValues = {\r\n imageSize: {x: 11, y: 11},\r\n imageNormalStatePath: '/images/square.png',\r\n imageHoverStatePath: '/images/square_over.png',\r\n imageOrigin: {x: 0, y: 0},\r\n imageAnchor: {x: 6, y: 6}\r\n };\r\n defaultValues = $.extend({}, defaultValues, options);\r\n \r\n defaultValues.imageSize = new google.maps.Size(defaultValues.imageSize.x, defaultValues.imageSize.y);\r\n defaultValues.imageOrigin = new google.maps.Point(defaultValues.imageOrigin.x, defaultValues.imageOrigin.x);\r\n defaultValues.imageAnchor = new google.maps.Point(defaultValues.imageAnchor.x, defaultValues.imageAnchor.x);\r\n \r\n imageNormalState = new google.maps.MarkerImage(defaultValues.imageNormalStatePath, defaultValues.imageSize, defaultValues.imageOrigin, defaultValues.imageAnchor);\r\n imageHoverState = new google.maps.MarkerImage(defaultValues.imageHoverStatePath, defaultValues.imageSize, defaultValues.imageOrigin, defaultValues.imageAnchor);\r\n \r\n var marker = new google.maps.Marker({\r\n position: point,\r\n map: options.setMap ? map : null,\r\n icon: imageNormalState,\r\n draggable: true\r\n });\r\n \r\n //If this is an editable marker, events for edition should be set properly.\r\n if (opts.editable) {\r\n google.maps.event.addListener(marker, \"mouseover\", function() {\r\n marker.setIcon(imageHoverState);\r\n });\r\n \r\n google.maps.event.addListener(marker, \"mouseout\", function() {\r\n marker.setIcon(imageNormalState);\r\n });\r\n \r\n //Removes a point.\r\n google.maps.event.addListener(marker, \"click\", function() {\r\n for (var index = 0; index < pathMarkers.length; index++) {\r\n if (pathMarkers[index] == marker) {\r\n marker.setMap(null);\r\n pathMarkers.splice(index, 1);\r\n polyline.getPath().removeAt(index);\r\n break;\r\n }\r\n }\r\n \r\n if (opts.callbackPathChanged != null) {\r\n opts.callbackPathChanged(convertPositionsToNormalForm(pathMarkers), false);\r\n }\r\n });\r\n \r\n //Change the position of a point.\r\n google.maps.event.addListener(marker, \"drag\", function() {\r\n for (var index = 0; index < pathMarkers.length; index++) {\r\n if (pathMarkers[index] == marker) {\r\n polyline.getPath().setAt(index, marker.getPosition());\r\n break;\r\n }\r\n }\r\n //TODO Not changing the value of array pathMarkers\r\n if (opts.callbackPathChanged != null) {\r\n opts.callbackPathChanged(convertPositionsToNormalForm(pathMarkers), true);\r\n }\r\n });\r\n \r\n \r\n }\r\n //TODO Try to get the markers from the map object keep saving these markers in separated\r\n //arrays is not good.\r\n if (insertAtIndex == undefined) {\r\n pathMarkers.push(marker);\r\n } \r\n else {\r\n pathMarkers.splice(0, 0, marker);\r\n }\r\n \r\n if (opts.callbackPathChanged != null) {\r\n opts.callbackPathChanged(convertPositionsToNormalForm(pathMarkers), true);\r\n }\r\n return marker;\r\n }", "function getMissionIcon(resourceId, missionConditionType, overrideIcon = \"\", overrideDirectory = \"\") {\n let iconConfig = overrideIcon || localStorage.getItem(\"IconConfig\");\n let imgDirectory = overrideDirectory || currentMode;\n if (iconConfig == \"none\") {\n return \"\";\n } else if (iconConfig == \"emoji\") {\n return MISSION_EMOJI[missionConditionType];\n } else {\n return `<span style=\"background-image: url('img/${imgDirectory}/${resourceId}.png');\" class=\"resourceIcon\">&nbsp;</span>`;\n }\n}", "function handleImageLoad() {\n // data about the organization of the sprite sheet\n var spriteData = {\n images: [\"/images/cakerush/cake.png\", \"/images/cakerush/fatBlue.png\", \"/images/cakerush/fatRed.png\",\n \"/images/cakerush/fatYellow.png\", \"/images/cakerush/fatGreen.png\"],\n frames: [\n //startx, starty, sizex, sizey, which file in the array, registrationx, registrationy\n //[0, 0, 80, 80, 0, 40, 0],\n //[80, 0, 80, 80, 0, 40, 0],\n //[160, 0, 80, 80, 0, 40, 0],\n //[240, 0, 80, 80, 0, 40, 0],\n //[320, 0, 80, 80, 0, 40, 0],\n\n //cake\n [0, 0, 360, 360, 0, 180, 220], //0\n //blue\n [0, 0, 69, 191, 1, 34, 191], // 1 side step 1\n [69, 0, 69, 191, 1, 34, 191], // 2 side step 2\n [138, 0, 69, 191, 1, 34, 191], // 3 side stand\n [0, 191, 69, 191, 1, 34, 191], // 4 front stand\n [69, 191, 69, 191, 1, 34, 191], // 5 front step 1\n [138, 191, 69, 191, 1, 34, 191], // 6 front step 2\n [0, 382, 69, 191, 1, 34, 191], // 7 back stand\n [69, 382, 69, 191, 1, 34, 191], // 8 back step 1\n [138, 382, 69, 191, 1, 34, 191], // 9 back step 2\n //red\n [0, 0, 69, 191, 2, 34, 191], // 10 side step 1\n [69, 0, 69, 191, 2, 34, 191], // 11 side step 2\n [138, 0, 69, 191, 2, 34, 191], // 12 side stand\n [0, 191, 69, 191, 2, 34, 191], // 13 front stand\n [69, 191, 69, 191, 2, 34, 191], // 14 front step 1\n [138, 191, 69, 191, 2, 34, 191], // 15 front step 2\n [0, 382, 69, 191, 2, 34, 191], // 16 back stand\n [69, 382, 69, 191, 2, 34, 191], // 17 back step 1\n [138, 382, 69, 191, 2, 34, 191], // 18 back step 2\n //yellow\n [0, 0, 69, 191, 3, 34, 191], // 19 side step 1\n [69, 0, 69, 191, 3, 34, 191], // 20 side step 2\n [138, 0, 69, 191, 3, 34, 191], // 21 side stand\n [0, 191, 69, 191, 3, 34, 191], // 22 front stand\n [69, 191, 69, 191, 3, 34, 191], // 23 front step 1\n [138, 191, 69, 191, 3, 34, 191], // 24 front step 2\n [0, 382, 69, 191, 3, 34, 191], // 25 back stand\n [69, 382, 69, 191, 3, 34, 191], // 26 back step 1\n [138, 382, 69, 191, 3, 34, 191], // 27 back step 2\n //green\n [0, 0, 69, 191, 4, 34, 191], // 28 side step 1\n [69, 0, 69, 191, 4, 34, 191], // 29 side step 2\n [138, 0, 69, 191, 4, 34, 191], // 30 side stand\n [0, 191, 69, 191, 4, 34, 191], // 31 front stand\n [69, 191, 69, 191, 4, 34, 191], // 32 front step 1\n [138, 191, 69, 191, 4, 34, 191], // 33 front step 2\n [0, 382, 69, 191, 4, 34, 191], // 34 back stand\n [69, 382, 69, 191, 4, 34, 191], // 35 back step 1\n [138, 382, 69, 191, 4, 34, 191] // 36 back step 2\n ],\n animations: {\n //bluestand: 0,\n //bluewalk: { frames: [1, 0, 2, 0], frequency: 6 },\n //blueattack: { frames: [0, 3, 4, 3], frequency: 6 },\n\n cake: 0,\n bluesidestand:3,\n bluefrontstand:4,\n bluebackstand:7,\n bluesidewalk: { frames: [3,1,3,2], frequency: 6},\n bluefrontwalk: { frames: [4,5,4,6], frequency: 6},\n bluebackwalk: { frames: [7,8,7,9], frequency: 6},\n redsidestand:12,\n redfrontstand:13,\n redbackstand:16,\n redsidewalk: { frames: [12,10,12,11], frequency: 6},\n redfrontwalk: { frames: [13,14,13,15], frequency: 6},\n redbackwalk: { frames: [16,17,16,18], frequency: 6},\n yellowsidestand:21,\n yellowfrontstand:22,\n yellowbackstand:25,\n yellowsidewalk: { frames: [21,19,21,20], frequency: 6},\n yellowfrontwalk: { frames: [22,23,22,24], frequency: 6},\n yellowbackwalk: { frames: [25,26,25,27], frequency: 6},\n greensidestand:30,\n greenfrontstand:31,\n greenbackstand:34,\n greensidewalk: { frames: [30,28,30,29], frequency: 6},\n greenfrontwalk: { frames: [31,32,31,33], frequency: 6},\n greenbackwalk: { frames: [34,35,34,36], frequency: 6}\n\n\n }\n };\n\n // initialize the spritesheet object\n spriteSheet = new createjs.SpriteSheet(spriteData);\n}", "function getIcon(type) {\n\tswitch(type) {\n\t\tcase \"food\": return greenMarker;\n\t\tcase \"attraction\": return redMarker;\n case \"museum\": return blueMarker;\n case \"bar\": return orangeMarker;\n\t\t//default: return \"icons/footprint.png\";\n\t}\n}", "function loadLocImg(loc,request) {\n var service = new google.maps.places.PlacesService(map);\n service.textSearch(request, function(res){\n if (res){\n var url_small = res[0].photos[0].getUrl({'maxWidth': 100, 'maxHeight': 100});\n var url_large = res[0].photos[0].getUrl({'maxWidth': 400, 'maxHeight': 400});\n loc.img_small(url_small);\n loc.img_large(url_large);\n loc.contentString('<div class=\"container infowindow\">'+\n '<div class=\"row iw-title\">'+\n '<h4>'+loc.title()+'</h4>'+\n '</div>'+\n '<div class=\"row\">'+\n '<img class=\"img-responsive\" src=\"'+url_small+'\">'+\n '</div>'+\n '<div class=\"row iw-description\">'+\n '<div class=\"col-xs-8 col-xs-offset-2\">'+\n '<p>'+loc.description()+'</p>'+\n '</div>'+\n '</div>'+\n '</div>');\n }\n else {\n loc.img_small('img/error.png');\n loc.contentString('<h1>Error retrieving location info</h1>');\n }\n loc.infowindow = new google.maps.InfoWindow({\n content: loc.contentString()\n });\n var icon = 'images/square.png';\n console.log(loc.type());\n switch(loc.type()){\n case 'Museum':\n icon = 'images/museum.png';\n break;\n case 'Building':\n icon = 'images/building.png';\n break;\n }\n loc.marker = new google.maps.Marker({\n position: loc.latlng(),\n map: map,\n title: loc.title(),\n icon: icon,\n animation: google.maps.Animation.DROP\n });\n loc.marker.addListener(\"click\", function(){\n loc.infowindow.open(map, this);\n toggleAnimation(this);\n });\n markers.push(loc.marker);\n });\n }", "function drawSlot(file, x, y) {\n var reelImg = new Image();\n reelImg.src = \"./SlotsImages/\" +file;\n reelImg.onload = function(){\n ctx.drawImage(reelImg, x, y);\n }\n}", "function place(path,x,y) {\n game.canvas[1].drawImage(getImage(path),x ,y);\n }", "function addMachine(type, xGrid, yGrid, id) {\n\n if (type == 'C0') {\n var img = carImages[0][0];\n var shadowImg = carImages[0][1];\n } else if (type == 'C1') {\n var img = carImages[1][0];\n var shadowImg = carImages[1][1];\n } else if (type == 'C2') {\n var img = carImages[2][0];\n var shadowImg = carImages[2][1];\n } else if (type == 'R') {\n var img = robotImg;\n var shadowImg = robotShadowImg;\n } else {\n console.log('Problem with types in addMachine()');\n }\n\n var x = yGrid * GRID_WIDTH;\n var y = xGrid * GRID_HEIGHT + (GRID_HEIGHT / 2);\n\n //console.log(xGrid, yGrid, x,y, id);\n\n if (type == 'C0' || type == 'C1' || type == 'C2') {\n var car = sprite({\n context: canvas.getContext('2d'),\n width: GRID_WIDTH,\n height: GRID_HEIGHT,\n image: img,\n shadow: shadowImg,\n x: x,\n y: y,\n shadowX: x,\n shadowY: y,\n id: id,\n });\n\n cars.push(car);\n } else if (type == 'R') {\n var robot = sprite({\n context: canvas.getContext('2d'),\n width: GRID_WIDTH,\n height: GRID_HEIGHT,\n image: img,\n shadow: shadowImg,\n x: x,\n y: y,\n shadowX: x,\n shadowY: y,\n id: id,\n });\n\n robots.push(robot);\n }\n}", "function getMissionIcon(resourceId, missionConditionType, overrideIcon = \"\", overrideDirectory = \"\") {\n let imgDirectory = getImageDirectory(overrideDirectory);\n \n let iconConfig = overrideIcon || getGlobal(\"IconConfig\");\n if (iconConfig == \"none\") {\n return \"\";\n } else if (iconConfig == \"emoji\") {\n return MISSION_EMOJI[missionConditionType];\n } else {\n return `<span style=\"background-image: url('${imgDirectory}/${resourceId}.png');\" class=\"resourceIcon\">&nbsp;</span>`;\n }\n}", "function setImage(marker, options, category, expr, conditions) {\n\tif (!marker) {\n\t\tlog(true, 'Marker is not defined');\n\t\treturn;\n\t}\n var imageName;\n\tvar cached = marker.maps[category];\n\tif (expr.isScheduleDependent && cached && cached[selections.schedule]) {\n \t\timageName = cached[selections.schedule];\n\t} else if (cached && !expr.isScheduleDependent) {\n \t\timageName = cached;\n\t} else {\n\t\tvar value = expr.evaluate(marker.info, null);\n\t\timageName = 'white';\n\t\tfor (var color in conditions) {\n\t \t\ttry {\n\t\t\t\tif (eval(conditions[color].replace(/x/g, value))) {\n\t\t\t\t\timageName = color;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch (e) { }\n\t\t}\n\t\tif (expr.isScheduleDependent) {\n \t\t\tif (!marker.maps[category]) {\n\t\t\t\tmarker.maps[category] = {};\n\t\t\t}\n\t\t\tmarker.maps[category][selections.schedule] = imageName;\n\t\t} else {\n\t\t\tmarker.maps[category] = imageName;\n\t\t}\n\t}\n\n var zoom = map.getZoom();\n var factor = 40000 / (zoom / 7) / (zoom / 7) / (zoom / 7);\n\tif (isNaN(fieldIndices.facility['fi_tot_pop'])) {\n\t\tlog(true, 'No population field');\n\t}\n var pop = marker.info[fieldIndices.facility['fi_tot_pop']];\n var scale = pop / factor;\n if (!selections.considerSize) {\n scale = (zoom - 7) * 3 + 6;\n } else if (pop < factor * ((zoom - 7) * 3 + 3)) {\n scale = (zoom - 7) * 3 + 3;\n } else if (pop > factor * ((zoom - 7) * 8 + 15)) {\n scale = (zoom - 7) * 8 + 15;\n\t}\n\n imageName = 'assets/' + imageName + '.png';\n var image = new google.maps.MarkerImage(imageName, new google.maps.Size(\n scale, scale),\n // The origin for this image is 0,0.\n new google.maps.Point(0, 0), new google.maps.Point(scale / 2, scale / 2),\n new google.maps.Size(scale, scale));\n\tmarker.setIcon(image);\n}", "function img(ref){ return pack_grafico + \"img/\" + idioma + \"/\" + ref; }", "function setIconImage(info, key) {\n var value, iconDiv, iconDivUrl, iconName;\n value = weatherMethods[info]();\n iconDiv = document.getElementById('iconDiv' + key);\n if (action.savedElements.iconName) {\n iconName = action.savedElements.iconName;\n } else {\n iconName = 'simply';\n }\n if (iconDiv) {\n iconDivUrl = 'https://junesiphone.com/weather/IconSets/' + iconName + '/' + value + '.png';\n if (iconDiv.src != iconDivUrl) {\n var img = new Image();\n img.onload = function(){\n iconDiv.src = iconDivUrl;\n //set opacity to 1 after loaded\n iconDiv.style.opacity = 1;\n }; \n img.src = iconDivUrl;\n }\n }\n}", "function loadSymbol(x,y,name){\n\t\tvar r = 10;\n\t\tvar $img = $('<img>', { src: \"skins/\"+name+\".png\" });\n\t\t$img.load(function(){\n\t\t\tsymbols.ctx.drawImage(this, x, y, r, r);\n\t\t});\t\n\t}", "function getImagePath(type)\n{\n var src = '';\n if (type == QuadTypeEnum.GRASS)\n src = \"icon2/grass_1.png\";\n else if (type == QuadTypeEnum.BUG)\n src = \"icon2/bug.png\";\n else if (type == QuadTypeEnum.ROCK)\n src = \"icon2/rock.png\";\n else if (type == QuadTypeEnum.GOAL)\n src = \"icon2/apple_1.png\";\n return src;\n}", "define(name, x, y, width = 16, height = 16) {\n const { image, } = this;\n const buffer = document.createElement('canvas');\n buffer.width = width;\n buffer.height = height;\n buffer.getContext('2d').drawImage(\n image,\n x,\n y,\n width,\n height, // what part of the image to draw\n 0, 0, width, height); // where to draw it\n this.tiles.set(name, buffer); // store the info about the tile in our map\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
schedule a new fetch every 30 minutes
function scheduleRequest() { js_logger_1.default.info('schedule refresh alarm to 30 minutes...'); chrome.alarms.create('refresh', { periodInMinutes: 2 }); }
[ "function scheduleRequest() {\n\t\tconsole.log('schedule refresh alarm to 30 minutes...');\n\t\tchrome.alarms.create('refresh', { periodInMinutes: 30 });\n\t}", "polling() {\n // let hourInSec = 3600;\n let hourInSec = 32; // For testing purposes make an hour 16 seconds\n\n // Poll every 15 minutes in the first hour\n this.getLatestResponse();\n let numPolls = 1;\n let context = this;\n let polling = setInterval(function() {\n context.getLatestResponse();\n numPolls += 1;\n if (numPolls >= 4 || context.getClaimResponse().outcome != \"queued\") {\n clearInterval(polling);\n context.poll(hourInSec * 1000);\n }\n }, (hourInSec * 1000) / 4);\n }", "function repeateGet() {\n setInterval(function() { \n getHackerNews();\n }, 300000); //every 5 mins\n}", "function scheduleConfigRefreshJob() {\n if (configRefreshInterval == undefined || !Number.isInteger(Number(configRefreshInterval)) ||\n configRefreshInterval < 1 || configRefreshInterval > 59) {\n configRefreshInterval = 10\n console.log('Warning: \"CONFIG_REFRESH_INTERVAL\" should be a valid integer between 1 to 59')\n }\n cron.schedule('0 */' + configRefreshInterval + ' * * * *', () => {\n fetchConfig().then(function (configStatus) {\n console.log('Refreshed configurations from config service')\n })\n })\n cacheRefreshEnabled = true\n}", "startPeriodicRefresh() {\n this.refreshInterval = setInterval(\n () => this.props.dispatch(refreshAuthToken()),\n 60 * 60 * 1000 // one hour\n );\n }", "startPeriodicRefresh() {\n this.refreshInterval = setInterval(\n () => this.props.dispatch(refreshAuthToken()),\n 60 * 60 * 1000 // One hour\n );\n }", "fetchInterval_() {\n setInterval(async () => {\n await this.getAllLineData_();\n await this.getLineSubscriptions_();\n this.order_();\n }, FETCH_INTERVAL);\n }", "refreshApiTokenEveryFewMinutes() {\n this.lastRefreshedApiTokenAt = moment();\n\n setInterval(() => {\n this.refreshApiToken();\n }, 240000);\n\n setInterval(() => {\n if (moment().diff(this.lastRefreshedApiTokenAt, 'minutes') >= 5) {\n this.refreshApiToken();\n }\n }, 5000);\n }", "schedulePoll() {\n // Return early if polling is not enabled or it has already been scheduled.\n if (!this[_private.isPollingEnabled] ||\n this[_private.nextPollTimeout]) {\n return;\n }\n\n this[_private.nextPollTimeout] = setTimeout(() => {\n this.refreshServicesByPolling()\n .catch((e) => {\n console.error('Polling has failed, scheduling one more attempt: ', e);\n })\n .then(() => {\n this[_private.nextPollTimeout] = null;\n\n this.schedulePoll();\n });\n }, settings.pollingInterval);\n }", "_schedulePing () {\n this._keepAlive = setInterval(\n async () => {\n // check if there are any pending requests\n // no ping needed as long as there is traffic on the channel\n if (!this._pendingRequests()) {\n // request top page\n const request = {\n url: 'ping'\n }\n await this.get(request)\n }\n },\n 1000 // every second\n )\n }", "scheduleRefresh() {}", "function refreshLoop(){\n refreshInterval = setInterval(function(){ \n mlurl = matchlistURL+user;\n postRequest(createMatches,mlurl, true)\n }, 45000);\n}", "tick() {\n let now = new Date(Date.now());\n let remaining = (30 - (now.getMinutes() % 30)) * 60 * 1000;\n window.setTimeout(() => {\n this.forceUpdate();\n }, remaining);\n }", "polling() {\n const hourInSec = PASConfig.pollingTimeDevelop || 3200; // Use develop value if available for this RI\n const hourInMS = hourInSec * 1000;\n const fiveMin = hourInMS / 12;\n\n // Poll every 5 minutes in the first half hour\n let numPolls = 1;\n let context = this;\n let polling = setInterval(function () {\n context.getLatestResponse();\n if (numPolls >= 6 || context.getClaimResponse().outcome != \"queued\") {\n clearInterval(polling);\n numPolls += 1;\n }\n }, fiveMin);\n\n // Poll every hour until claim comes back\n polling = setInterval(function () {\n context.getLatestResponse();\n if (context.getClaimResponse().outcome != \"queued\")\n clearInterval(polling);\n }, hourInMS);\n }", "function scheduleRequest() {\n\tconsole.log(\"schedule refresh alarm to 1440 minutes...\");\n\tchrome.alarms.create(\"refresh\", { periodInMinutes: 60 });\n}", "schedule() {\n setInterval(this.executeTask , time);\n }", "dailyTransactions() {\n let job = schedule.scheduleJob('0 0 12 * * *', apiHandler.usersDailyTransactions)\n return job\n }", "function cronJob() {\n\t\t//Schedule Synchronized Loop, so we dont get of sync \n\t\tnextMinute(function () {\n util.log(\"Exec loop\"); \n MomoInstance.execCronsNow(); \n cronJob();\n\t\t});\n\t}", "_startPolling() {\n this._timer = setInterval(this._fetchArticles.bind(this), 30000);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var numArray = []; var newString = numbers.split(" "); console.log('newString:: ', newString); var maxVAlue = Math.max(...newString); numArray.push(maxVAlue); console.log('maxVAlue:: ', maxVAlue); var minValue = Math.min(...newString); numArray.push(minValue); console.log('minValue:: ', minValue); console.log('numArray:: ', numArray); var joined = numArray.join(" "); console.log('joined:: ', joined); return joined; }
function highAndLow(numbers) { numbers = numbers.split(" ").map(Number); console.log('numbers:: ', numbers); console.log('max and min:: ', `${Math.max(...numbers)} ${Math.min(...numbers)}`); return `${Math.max(...numbers)} ${Math.min(...numbers)}`; }
[ "function highAndLow(numbers){\nvar arr = numbers.split(' ');\nreturn Math.max.apply(Math, arr) + ' ' + Math.min.apply(Math, arr);\n}", "function ReturnArrayOf_MaxMin() {\r\n let numbers = EntryCheckForManyNumbers();\r\n let max = numbers [0]; \r\n let min = numbers [numbers.length-1] ;\r\n for (let i = 0; i < numbers.length; i++){\r\n if (max < numbers[i]) {\r\n max = numbers[i];\r\n }\r\n if ( min > numbers[i]) {\r\n min = numbers[i];\r\n }\r\n } \r\n let arrayFor_2_values = [];\r\n arrayFor_2_values.push(max);\r\n arrayFor_2_values.push(min);\r\n //console.log(numbers);\r\n //console.log(min, max);\r\n return arrayFor_2_values;\r\n }", "function minMax(arr){\n let smallestLargest = []\n let smallest = Math.min(...arr)\n let largest = Math.max(...arr)\n smallestLargest.push(smallest, largest)\n return smallestLargest;\n }", "function minMaxSum(str) {\n \n\t// Split the Input String into different String values in an array\n\tvar arr = str.split(\" \");\n\n\t// Convert all the String values in the array into Integer values\n\tfor (var i = arr.length - 1; i >= 0; i--) {\n\t\tarr[i] = Number(arr[i]);\n\t}\n\n\t// Sort the Integer values in the array in Ascending way\n\tarr.sort(function(a, b){return a-b});\n\n\t// Calculate Min of sorted array\n\tvar min = 0;\n\tfor (var i = arr.length - 2; i >= 0; i--) { min += arr[i]; }\n\n\t// Calculate Max of sorted array\n\tvar max = 0;\n\tfor (var i = arr.length - 1; i >= 1; i--) { max += arr[i]; }\n\n\n console.log(arr);\n\tconsole.log(\"Min: \" + min);\n\tconsole.log(\"Max: \" + max);\n\n\n // NodeJS Output\n\t// process.stdout.write(min + \" \" + max);\n}", "function test(array) {\r\n let sum = 0;\r\n let join = '';\r\n let product = array[0];\r\n\r\n for (let i = 0; i < array.length; i++) {\r\n sum += array[i];\r\n join += array[i];\r\n }\r\n\r\n for (let i = 1; i < array.length; i++) {\r\n product *= array[i];\r\n }\r\n\r\n array.sort((a,b) => a - b);\r\n\r\n console.log('Sum = ' + sum);\r\n console.log('Min = ' + array[0]);\r\n console.log('Max = ' + array[array.length - 1]);\r\n console.log('Product = ' + product);\r\n console.log('Join = ' + join);\r\n}", "function minMax() {\n \"use strict\";\n var stringNum;\n stringNum = window.prompt(\"please enter FIVE numbers separated by commas\");\n window.console.log(\"The greatest number is of these is \" + Math.max(parseInt(stringNum)));\n window.console.log(\"The smallest number is \" + Math.min(parseInt(stringNum)));\n}", "function smallestToBiggest(arr){\n\tvar a = arr.sort((x,y) => x - y) //the given input array is sorted and stored in a var a \n\tvar min = Math.min(...a)//from the sorted array we get the min value using min() stored in min \n\tvar max = Math.max(...a) //same process repeated to get max value max() function used and stored in max \n\tvar finalVal =[] // A empty array named finalVal is created to get the min and max values from the array\n\tif (min < max )// condition to check whether the min val is less than max val \n\t{\n\t\tfinalVal.push(min,max)//both values pushed in array and displayed\n\t\t\n\t}\n\treturn finalVal\n}", "function highAndLow(numbers) {\n const split = numbString.split(' ').map(i => Number(i))\n const max = Math.max(...split)\n const min = Math.min(...split)\n return max.toString() + \" \" + min.toString()\n}", "function highAndLow(numbers) {\n numbers = numbers.split(' ').map(Number);\n var min = Math.min.apply(null,numbers);\n var max = Math.max.apply(null,numbers);\n \n return max + ' ' + min;\n}", "function highAndLow(numbers){\n var numbersArr = numbers.split(' ').map(function(item) {\n return parseInt(item, 10);\n });\n var highest = numbersArr[0];\n var lowest = numbersArr[0];\n \n for (var i = 1 ; i <= numbersArr.length ; i++) {\n if (highest < numbersArr[i]) {\n highest = numbersArr[i];\n }\n if (lowest > numbersArr[i]) {\n lowest = numbersArr[i];\n }\n }\n return (highest + ' ' + lowest); \n}", "function highAndLow(numbers){\n let intoArray = numbers.split(' ');\n if(intoArray.length === 1){\n return numbers + ' ' + numbers;\n }\n let orderedArray = intoArray.sort((a,b) => a-b);\n let largest = orderedArray.pop();\n let smallest = orderedArray.shift();\n let highestToLowest = largest + ' ' + smallest;\n return highestToLowest;\n}", "function myArray(array) {\n\n var arrayConcat = [];/*facem o variabila care va fi concatenarea array-ului*/\n\n for (i = 0; i < array.length; i++) {/*facem un for care (i) este intre 0 si nu mai mare de cat atirbutul (array) ca lungime\n si i cfeste exponential */\n\n var separator = array[i];/*facem o variabila unde ii spumen ca sa faca array-urile primite in array-uri mai marunte */\n var largestNumber = separator[0];/*facem o variabila de cel mai mai mare numar*/\n for (j = 0; j < separator.length; j++) {/*facem un for cu (j) unde j este egal cu 0 si nu mai mare decat (separattor) ca \n lungime adica sa afuseze cel mai mare numar din variabila (separator) */\n if (largestNumber < separator[j]) {/*comparam numerele din fiecare array dat*/\n largestNumber = separator[j];\n }\n }\n arrayConcat = arrayConcat.concat(largestNumber);/*introducem valoarea cea mai mare intr-un array final*/\n }\n return arrayConcat;/*returneaza valorile cele mai mari ale array-urilor */\n}", "function maximum() {\r\nvar mini = Math.max.apply(null, numbers);\r\nconsole.log(\"maximum cherez matem funchii-\",mini);\r\n}", "function findMinAndMax(arr){\n var result=\"\";\n var minNumber=arr[0];\n var maxNumber=arr[0];\n var i;\n var length=arr.length;\n \n for(i=0; i<length; i++){\n if(minNumber>arr[i]){\n minNumber=parseInt(arr[i]);\n }\n if(maxNumber<=arr[i]){\n maxNumber=parseInt(arr[i]);\n }\n }\n \n result=\"Min-> \"+minNumber+\"</br>\"+\"Max-> \"+maxNumber;\n document.getElementById('content').innerHTML =result;\n }", "function miniMaxSum(arr) {\n let newArr = [...arr].sort()\n let sum = 0;\n for (let i = 0; i < newArr.length; i++) {\n sum += newArr[i]\n }\n let minValue = sum - newArr[newArr.length - 1]\n let maxValue = sum - newArr[0]\n console.log(minValue, maxValue)\n }", "function highAndLow(numbers){\n let splitNum = numbers.split(' ') //[\"4, 5, 29, 54, 4 ,0, -214, 542, -64, 1, -3, 6, -6\"]\n\n let splitNumSort = splitNum.sort((a, b) => a - b)\n let low = splitNumSort[0].toString()\n let high = splitNumSort[splitNumSort.length -1].toString()\n console.log(high)\n\n return high + ' ' + low\n \n }", "function highAndLow(numbers){\n // split the string to array of strings\n stringArray = numbers.split(' ');\n\n // convert strings in array to numbers\n numArray = stringArray.map(i => Number(i));\n\n // define highest and lowest at array[0]\n highest = numArray[0];\n lowest = numArray[0];\n\n // loop to change highest and lowest if needed through array\n for (i = 1; i < numArray.length; i++) {\n if (numArray[i] > highest) {\n highest = numArray[i];\n }\n if (numArray[i] < lowest) {\n lowest = numArray[i];\n }\n }\n // return appropriate string\n return `${highest} ${lowest}`\n}", "function findMinAndMax(numbers) {\n var minVal = Number.MAX_VALUE;\n var maxVal = Number.MIN_VALUE;\n for (var i = 0; i < numbers.length; i++) {\n if (numbers[i] <= minVal) {\n minVal = numbers[i];\n }\n if (numbers[i] >= maxVal) {\n maxVal = numbers[i];\n }\n }\n return \"Min -> \" + minVal + \"\\nMax -> \" + maxVal;\n}", "function sumMaxMin(){\n var x11 = document.getElementById(\"number13\").value;\n var x12 = document.getElementById(\"number14\").value;\n var x13 = document.getElementById(\"number15\").value;\n var x14 = document.getElementById(\"number16\").value;\n var xArray = [];\n if ( x11 > 0 ){\n xArray.push(x11);\n }\n if ( x12 > 0 ){\n xArray.push(x12);\n }\n if ( x13 > 0 ){\n xArray.push(x13);\n }\n if ( x14 > 0 ){\n xArray.push(x14);\n }\n // afisare\n var y = Math.max(...xArray);\n var z = Math.min(...xArray);\n var x = y + z;\n document.getElementById(\"demo13\").innerHTML = \"Rezultat:</br> \"+ \"Valoarea minima introdusa este \"+z;\n document.getElementById(\"demo14\").innerHTML = \"Valoarea maxima introdusa este \"+y;\n document.getElementById(\"demo15\").innerHTML = \"Suma dintre max si min este: \"+x;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the gravatar url
function updateGravatar() { var gravatarOptions = currentAttrs(); var gravatarUrl = gravatar.generateUrl(gravatarOptions); element.attr('src', gravatarUrl); }
[ "function updateGravatar(email) {\n blockUi(true, $(\"#gravatar\"), \"throbber\");\n $.post(\"/ajax/get-gravatar\",\n {\"email\": email},\n function (response) {\n $(\"#gravatar\").html(response);\n blockUi(false, $(\"#gravatar\"));\n }, \"json\");\n}", "async function proxiedGravatarURL(user) {\n if (user.metadata.gravatarProxyId) {\n return `/avatar/${user.metadata.gravatarProxyId}`;\n }\n\n const avatarId = uuid.v4();\n try {\n await UserModel.update(\n { id: user.id },\n {\n $set: {\n 'metadata.gravatarProxyId': avatarId,\n },\n }\n );\n\n return `/avatar/${avatarId}`;\n } catch (error) {\n return null;\n }\n}", "updateAvatar (avatarUrl) {\n $(\"#dominantSpeakerAvatar\").attr('src', avatarUrl);\n }", "function setProfilePicture(email) {\n var gravatarHash = md5(email.trim().toLowerCase());\n $(\".userProfile img\").attr(\"src\", \"http://www.gravatar.com/avatar/\"+gravatarHash+\"?s=150&d=mm\");\n }", "function toGravatarUrl(email) {\n var emailHash = hex_md5(email);\n return \"http://www.gravatar.com/avatar/\" + emailHash + \"?size=40&d=mm\";\n}", "function gravatar(user, size) {\n if (!size) size = 200;\n if (!user.email) return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';\n var md5 = crypto.createHash('md5').update(user.email).digest('hex');\n return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';\n}", "SetUserAvatar() {\n // console.log(\">_ \"+window.CacheRefreshCode);\n $(\"[name='UserAvatarImg']\").attr(\"src\", \"/Home/GetAvatar?random=\" + Math.floor(Math.random() * 100 + 1));// ?random=\" + window.CacheRefreshCode);\n }", "function createGravatarUrl(username) {\n let userhash = md5(username);\n return `http://www.gravatar.com/avatar/${userhash.toString()}`;\n}", "function gravatar(user, size) {\n if (!size) {\n size = 200;\n }\n if (!this.email) {\n return `https://gravatar.com/avatar/?s=${size}&d=retro`;\n }\n const md5 = crypto.createHash('md5').update(this.email).digest('hex');\n return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`;\n}", "function gravatarURL(user) {\n let hash;\n if (user && user.profiles && user.profiles[0] && user.profiles[0].id) {\n hash = md5Sum(user.profiles[0].id);\n } else {\n hash = '00000000000000000000000000000000';\n }\n return `https://www.gravatar.com/avatar/${hash}`;\n}", "async function updateUserImage() {\n var url = prompt('please enter the link to your new image');\n await updateUser('image_url', url);\n getHeroImage();\n }", "function getGravatarUrl(email, args) {\n\n\tvar md5 = function(str) {\n\t str = str.toLowerCase().trim();\n\t var hash = crypto.createHash(\"md5\");\n\t hash.update(str);\n\t return hash.digest(\"hex\");\n\t};\n\n args = args || \"\";\n var BASE_URL = \"//www.gravatar.com/avatar/\";\n \n return (BASE_URL + md5(email) + args).trim();\n}", "function getGravatarUrl(email) {\n return $gravatar.generate(email);\n }", "static getAvatarURL(email)\n {\n return gravatar.url(email);\n }", "get avatarURL() {\n if (this.avatar.startsWith('a_')) {\n return `${Constants.CDN_URL}/avatars/${this.id}/${this.avatar}.gif`;\n } else {\n return `${Constants.CDN_URL}/avatars/${this.id}/${this.avatar}.png`;\n }\n }", "update () {\n const url = this.options_.user.avatar;\n const timecode = formatTime(this.timecode, this.player_.duration());\n this.setSrc(url);\n this.tcEl_.innerHTML = `${timecode} ${this.user.nickname ? '- ' + this.user.nickname : ''}`;\n // If there's no poster source we should display:none on this component\n // so it's not still clickable or right-clickable\n if (url) {\n this.show();\n } else {\n this.hide();\n }\n }", "function make_gravatar(user) {\n\t\tvar md5 \t= crypto.createHash('md5').update(user.displayname+user.name).digest(\"hex\");\n\t\tgrav_url \t= 'http://www.gravatar.com/avatar.php/'+md5\n\t\tgrav_url\t+= \"?s=32&d=identicon\"\n\t\tconsole.log(\"Made gravatar:\", grav_url)\n\t\treturn grav_url\n\t}", "function testGravatar()\n{\n\tmailGravatar = document.getElementById(\"champsEmail\").value.toString();\n \tdocument.getElementById(\"logo\").src = getGravatar(mailGravatar, 278);\n}", "function Tpl_myAccountSetAvatar(){\n tmpDate = new Date();\n Cala.say(\"Changing the avatar\");\n $(\"#myAccountMyAvatar\").attr(\"src\", \"tpl/img/loader_100.gif\");\n $(\"#myAccountMyAvatar\").attr(\"src\", Tpl_userGetAvatarPath(keyGet(VAR_CURRENT_USER_NAME, \"---\"), \"250\") + \"&\" + tmpDate.getTime());\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate orders Delivery city field
function ordersDeliveryCityValid(dc_str) { var result = true; if (isEmpty(dc_str)) { alert("Please enter a delivery city for the order."); return false; } if (!isAlphaName(dc_str)) { alert("Please enter valid alphabetics for city name. You entered " + dc_str); return false; } return result; }
[ "function ordersDeliveryCountryValid(dco_str) {\n\tvar result = true;\n\tif (isEmpty(dco_str))\n\t{\n\t\talert(\"Please enter a delivery country for the order.\");\n\t\treturn false\n\t}\n\tif (!isAlphaName(dco_str))\n\t{\n\t\talert(\"Please enter valid alphabetics for country name. You entered \" + dco_str);\n\t\treturn false;\n\t}\n\treturn result;\n}", "function validateCity()\n{\n\tvar x=document.forms[\"input\"][\"city\"].value;\n\tif (x==null || x==\"\")\n\t\t{\t\n\t\talert(\"City must be filled out!\");\n\t\treturn false;\n\t\t}\n}", "function ordersDeliveryNoValid(dn_str) {\n\tvar result = true;\n\tif (isEmpty(dn_str))\n\t{\n\t\talert(\"Please enter a delivery address number for the order.\");\n\t\treturn false;\n\t}\n\tif (!isNumericStreetNum(dn_str) || dn_str == \"/\")\n\t{\n\t\talert(\"Please enter either 'unit / street number', or 'street number' for the order.\");\n\t\treturn false;\n\t}\n\treturn result;\n}", "static checkCity(city) {\n try {\n NonEmptyString.validate(city, CITY_CONSTRAINTS);\n return \"\";\n }\n catch (error) {\n console.error(error);\n return \"The address' city should not be empty or larger than 120 letters\";\n }\n }", "function ordersDeliveryStreetValid(ds_str) {\n\t//alert(\"ds: \" + ds_str);\n\tvar result = true;\n\tvar init = \"eg. Main Road\";\n\tif (isEmpty(ds_str))\n\t{\n\t\talert(\"Please enter a delivery street name for the order.\");\n\t\treturn false;\n\t}\n\tif (!isAlphaName(ds_str))\n\t{\n\t\talert(\"Please enter valid alphabetics for street name. You entered \" + ds_str);\n\t\treturn false;\n\t}\n\tif (ds_str == init)\n\t{\n\t\talert(\"Please enter a valid street name. You entered \" + ds_str);\n\t\treturn false;\n\t}\n\treturn result;\n}", "function checkCity() {\r\n const cityValue = city.value.trim();\r\n\r\n if (cityValue === '') {\r\n setErrorFor(city, 'City cannot be empty');\r\n isValid &= false;\r\n return;\r\n }\r\n\r\n isValid &= true;\r\n setSuccess(city);\r\n}", "function validateCity() {\n var city = document.getElementById(\"city\");\n var cityError = document.getElementById(\"cityRequirements\");\n\n //If the city field is empty, or contains characters other than alphabetic characters, period or space,\n //return false.\n if (isEmpty(city.value) || (!cityPattern.test(city.value))) {\n styleError(city, cityError, false);\n return false;\n }\n else {\n styleError(city, cityError, true);\n return true;\n }\n}", "validateCity(city) {\n if (city.name === '') {\n this.errorEl.innerHTML = constants.alertMessageForCity;\n return false;\n }\n if (city.country === '') {\n this.errorEl.innerHTML = constants.alertMessageForCountry;\n return false;\n }\n if (city.name.length > constants.maxLengthForCityName) {\n city.name = city.name.slice(0, constants.maxLengthForCityName);\n }\n if (city.name === this.name) {\n this.name = undefined;\n return true;\n }\n const bool = app.cities.every((item) => {\n return item.name.toUpperCase() !== city.name.toUpperCase();\n });\n if (!bool) {\n this.errorEl.innerHTML = constants.alertMessageForExistingCity;\n return false;\n }\n return true;\n }", "function valid_city()\n\t{\n\t\t// Retrieves the title value from the text field\n\t\tvar title_val=document.getElementById(\"cust_city\").value;\n\t\t// alert(title_val);\n\t\tif(title_val==-1)\n\t\t{\n\t\t\talert(\"Select a City\");\n\t\t\treturn false;\n\t\t}\n\t\telse \n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t}", "function validateNewShippingAddress (required) {\n\n document.getElementById(\"shippingAddressInput\").required = required;\n document.getElementById(\"shippingCityInput\").required= required;\n document.getElementById(\"shippingProvinceInput\").required= required;\n document.getElementById(\"shippingCountryInput\").required = required;\n\n }", "function ordersDeliveryPostcodeValid(pc_str) {\n\t\n\tvar result = true;\n\tif (!isEmpty(pc_str))\n\t{\n\t\tif (!isNumeric(pc_str)) // Don't check postcode length in case overseas order\n\t\t/*{\n\t\t\tif (!isLengthOkay(pc_str, 4))\n\t\t\t{\n\t\t\t\talert(\"Postcode needs to be 4 digits. You entered \" + pc_str);\n\t\t\t\tresult = false;\n\t\t\t}\n\t\t}\n\t\telse*/\n\t\t{\n\t\t\talert(\"Delivery postcode must be all digits. You entered \" + pc_str);\n\t\t\tresult = false;\n\t\t}\n\t}\n\telse\n\t{\n\t\talert(\"Delivery postcode is empty. Please enter a value.\");\n\t\tresult = false;\n\t}\n\treturn result;\n}", "function validateCity() {\n let city = document.getElementById('city').value;\n\n var cityReg = new RegExp(/^[A-Za-zâéèêûô-]*$/i);\n var valid = cityReg.test(city);\n\n\n if (!valid || city == \"\") {\n return false;\n } else {\n return true;\n }\n }", "function citytNameValidity()\n {\n const cityNameValid = contact.city;\n if(regExForNameCity(cityNameValid))\n {\n city.style.border = 'solid 2px green'\n city.style.boxShadow = '0px 0px 4px green'\n return true;\n }\n else\n {\n city.style.border = 'solid 2px red'\n city.style.boxShadow = '0px 0px 4px red'\n alertWindow(cityNameValid);\n return false;\n }\n }", "function validate(city) {\n debugger;\n if(dataRecieved.cod === \"404\") {\n alert('Enter correct city name'); \n } \n cityName = dataRecieved.name;\n name = cityName.toLowerCase();\n if (name.indexOf(city) === -1 || city === \" \") {\n alert('Enter correct city name');\n clear();\n } else {\n return true;\n }\n}", "function isCityValid(city) {\r\n if (/^([a-zA-Z\\u0080-\\u024F]+(?:. |-| |'))*[a-zA-Z\\u0080-\\u024F]+$/.test(city)) {\r\n document.getElementById(\"cityErrorMsg\").innerText = \"\";\r\n return true;\r\n }\r\n else {\r\n document.getElementById(\"cityErrorMsg\").innerText = \"Entrez une ville valide\";\r\n return false;\r\n }\r\n}", "get deliveryCityAndPostalCode() {\n const address = this.order.fulfillments[0].shipmentDetails.recipient\n .address;\n return `${address.locality}, ${address.administrativeDistrictLevel1}, ${address.postalCode}`;\n }", "function ordersDeliveryStateValid(dst_str) {\n\tvar result = true;\n\tif (isEmpty(dst_str))\n\t{\n\t\talert(\"Please enter a delivery state for the order.\");\n\t\treturn false;\n\t}\n\tif (!isAlphaName(dst_str))\n\t{\n\t\talert(\"Please enter valid alphabetics for state name. You entered \" + dst_str);\n\t\treturn false;\n\t}\n\treturn result;\n}", "function validateAddress(){\n var res = false\n if (myForm.F00000035h.toLowerCase() !== \"berlin\"){\n return false;\n }else if (myForm.F00000035h.toLowerCase() == \"berlin\") {\n if (myForm.bzrnr != '') {\n res = true;\n }\n }else{\n res = false\n } \n\treturn res;\n}", "function validateOrder(order) {\n\tconst schema = {\n\t\tcustomerId: Joi.objectId().required(),\n\t\tfood: Joi.array().required(),\n\t\tstatus: Joi.string()\n\t};\n\treturn Joi.validate(order, schema);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy range replacing specific value.
function replace_copy(first, last, output, old_val, new_val) { return replace_copy_if(first, last, output, function (elem) { return comparators_1.equal_to(elem, old_val); }, new_val); }
[ "function replaceValue_(sheetObject, value, rowID, columnID) {\n var tempRange = sheetObject.getRange(rowID, columnID);\n //var values = [ value ];\n tempRange.setValue(value);\n return;\n}", "replaceRangeWith(from2, to, node) {\n replaceRangeWith(this, from2, to, node);\n return this;\n }", "overwrite(start: number, end: number, content: string) {\n if (typeof start !== 'number' || typeof end !== 'number') {\n throw new Error(\n `cannot overwrite non-numeric range [${start}, ${end}) ` +\n `with ${JSON.stringify(content)}`\n );\n }\n this.log(\n 'OVERWRITE', `[${start}, ${end})`,\n JSON.stringify(this.context.source.slice(start, end)),\n '→', JSON.stringify(content)\n );\n this.editor.overwrite(start, end, content);\n }", "copy (value) {\n\treturn new Selection().expand(value);\n}", "set_valueRange(newval)\n {\n this.liveFunc.set_valueRange(newval);\n return this._yapi.SUCCESS;\n }", "replaceRange(from2, to, slice2) {\n replaceRange(this, from2, to, slice2);\n return this;\n }", "function changeRange(){\n range.value = num.value;\n console.log(\"number changed!\")\n}", "setOnRange(value, callback){\n /* DEBUG */\n this.debug && this.log(\"[ZIPAC] > Method setOnRange\", value, this.debugContext);\n\n if(value){\n this.setOn(this.backupValue, callback);\n }else{\n this.setOn(0,callback);\n }\n }", "function copyOldData() {\n myValueFromPast = myValue;\n}", "function setSlice(orig, replacement, indexFrom, indexTo) {\r\n if(typeof indexTo == \"undefined\") {\r\n return orig.slice(0, indexFrom) + replacement;\r\n }\r\n return orig.slice(0, indexFrom) + replacement + orig.slice(indexTo);\r\n}", "copy() {\n return new Range(this._min, this._max); // eslint-disable-line no-html-constructors\n }", "function moveValuesOnly2 () {\r\n var tabs =[\"159\",\"160\",\"161\",\"162\",\"163\",\"164\",\r\n \"165\",\"166\",\"167\",\"168\",\"169\",\"170\",\"180-181\",\"182-183\",\"184-186\",\"187-189\",\"190-192\"\r\n ,\"193-195\",\"196-198\",\"199\",\"200\",\"201\",\"202\",\"203\",\"204\",\"205\",\"206\",\"207\",\"208\",\r\n \"212-213\",\"214-215\",\"216-218\",\"219-221\",\"222-224\",\"225-227\",\"228-230\",\"231\",\"232\",\"233\",\"234\",\r\n \"235\",\"236\",\"237\",\"238\",\"239\",\"240\",\"272-273\",\"274-275\",\"276-278\"]\r\n var ss = SpreadsheetApp.getActiveSheet()\r\n var sss = SpreadsheetApp.getActiveSpreadsheet ();\r\n var range = ss.getLastRow();\r\n var i;\r\n for (i=0; i<tabs.length; i++){\r\n var source = ss.getRange (tabs[i]+\"!A25:\"+range);\r\n var destSheet = sss.getSheetByName(\"Data_Base\");\r\n var destRange = destSheet.getRange(destSheet.getLastRow()+1,1);\r\n source.copyTo (destRange, {contentsOnly: true})+\"<br>\";\r\n }\r\n}", "_removeRangeValue() {\n const seriesOption = snippet.pick(this.options, 'series') || {};\n const allowRange = predicate.isAllowRangeData(this.chartType) &&\n !predicate.isValidStackOption(seriesOption.stackType) && !seriesOption.spline;\n\n if (allowRange || this.isCoordinateType) {\n return;\n }\n\n Object.values(this.rawSeriesData).forEach(rawItem => {\n if (!snippet.isArray(rawItem.data)) {\n return;\n }\n rawItem.data.forEach((value, index) => {\n if (snippet.isExisty(value)) {\n ([rawItem.data[index]] = concat.apply(value));\n }\n });\n });\n }", "function replaceRange (text, from, to) {\n // Precondition: to \">\" from\n var strLines = text.slice(0); // copy\n var pre = lines[from.line].slice(0, from.ch);\n var post = lines[to.line].slice(to.ch);\n strLines[0] = pre + strLines[0];\n strLines[strLines.length-1] += post;\n\n strLines.unshift(to.line - from.line + 1); // 2nd positional parameter\n strLines.unshift(from.line); // 1st positional parameter\n lines.splice.apply(lines, strLines);\n }", "function setSourceMapRange(node,range){getOrCreateEmitNode(node).sourceMapRange=range;return node;}", "function replace_copy_if(first, last, result, pred, new_val) {\r\n for (; !first.equals(last); first = first.next()) {\r\n if (pred(first.value))\r\n result.value = new_val;\r\n else\r\n result.value = first.value;\r\n result = result.next();\r\n }\r\n return result;\r\n}", "function replace(range, newText, annotation) {\n return {\n range: range,\n newText: newText,\n annotationId: annotation\n };\n }", "setValueRange(_value, _minValue, _maxValue) {\n this.minValue = _minValue;\n this.maxValue = _maxValue;\n if (this.isNumber(_value)) {\n _value = (_value < _minValue) ? _minValue : _value;\n _value = (_value > _maxValue) ? _maxValue : _value;\n this.setValue(_value);\n }\n return this;\n }", "function ReplicateValue(table, table_off, step, end,\n code) {\n do {\n end -= step;\n table[table_off+end].bits = code.bits;\n table[table_off+end].value = code.value;\n } while (end > 0);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gera um personagem a partir das classes e niveis.
function GeraPersonagem(modo, submodo) { if (!submodo) { submodo = 'tabelado'; } var classe_principal = gPersonagem.classes[0]; if (tabelas_geracao[classe_principal.classe] == null) { Mensagem(Traduz('Geração de ') + Traduz(tabelas_classes[gPersonagem.classes[0].classe].nome) + ' ' + Traduz('não disponível')); return; } var tabelas_geracao_classe = tabelas_geracao[classe_principal.classe]; // So pode limpar aqui, pois isso zerara as classes. PersonagemLimpaGeral(); gPersonagem.classes.push(classe_principal); _GeraAtributos(modo, submodo); _GeraPontosDeVida(modo, submodo); // Atualiza aqui para ja ter alguns numeros usados abaixo. AtualizaGeralSemConverterEntradas(); if (tabelas_geracao_classe.por_nivel == null || tabelas_geracao_classe.por_nivel[gPersonagem.classes[0].nivel] == null) { Mensagem(Traduz('Geração avançada de ') + Traduz(tabelas_classes[gPersonagem.classes[0].classe].nome) + ' ' + Traduz('não disponível')); return; } var tabela_geracao_classe_por_nivel = tabelas_geracao_classe.por_nivel[gPersonagem.classes[0].nivel]; _GeraEquipamentos(tabela_geracao_classe_por_nivel); _GeraArmaduras(tabela_geracao_classe_por_nivel); _GeraArmas(tabela_geracao_classe_por_nivel); var tipos_items = [ 'aneis', 'amuletos', 'capas', 'bracaduras', 'chapeus' ]; for (var i = 0; i < tipos_items.length; ++i ) { _GeraItens(tipos_items[i], tabela_geracao_classe_por_nivel); } /* _GeraEstilosDeLuta(); */ _GeraTalentos(gPersonagem.classes[0].classe, tabelas_classes[gPersonagem.classes[0].classe], tabelas_geracao_classe, gPersonagem.classes[0].nivel); _GeraPericias(tabelas_classes[gPersonagem.classes[0].classe], tabelas_geracao_classe, gPersonagem.classes[0].nivel); _GeraFeiticos(); // Importante regerar aqui para evitar duplicacoes. gPersonagem.especiais = {}; AtualizaGeralSemConverterEntradas(); LeEntradas(); // importante, pois as entradas estao vazias. Isso efetivamente salva o personagem. }
[ "function _GeraFeiticos() {\n for (var i = 0; i < gPersonagem.classes.length; ++i) {\n var classe_personagem = gPersonagem.classes[i];\n var chave_classe = gPersonagem.classes[i].classe;\n // Tabela de geracao da classe.\n if (!(chave_classe in tabelas_geracao)) {\n continue;\n }\n // Tabela de feiticos da classe.\n if (!(chave_classe in tabelas_feiticos)) {\n continue;\n }\n if (!(chave_classe in gPersonagem.feiticos)) {\n continue;\n }\n _GeraFeiticosClasse(\n classe_personagem, gPersonagem.feiticos[chave_classe], tabelas_geracao[chave_classe], tabelas_lista_feiticos[chave_classe]);\n }\n}", "function _GeraFeiticosClasse(classe_personagem, feiticos_classe, tabela_geracao_classe, lista_feiticos_classe) {\n for (var nivel in feiticos_classe.slots) {\n if (!('ordem_magias' in tabela_geracao_classe) || !(nivel in tabela_geracao_classe.ordem_magias)) {\n continue;\n }\n _GeraFeiticosClasseNivel(classe_personagem,\n nivel,\n feiticos_classe.conhecidos[nivel],\n feiticos_classe.slots[nivel],\n tabela_geracao_classe.ordem_magias[nivel],\n (lista_feiticos_classe != null) && (nivel in lista_feiticos_classe) ? lista_feiticos_classe[nivel] : {});\n }\n}", "function ConverteEntradasParaPersonagem() {\n // Limpa tudo antes de comecar.\n PersonagemLimpaGeral();\n\n gPersonagem.modo_mestre = gEntradas.modo_mestre;\n gPersonagem.modo_visao = gEntradas.modo_visao;\n gPersonagem.nome = gEntradas.nome;\n gPersonagem.raca = gEntradas.raca;\n gPersonagem.template = gEntradas.template || '';\n _ConverteTamanho();\n\n gPersonagem.alinhamento = gEntradas.alinhamento;\n gPersonagem.divindade = gEntradas.divindade;\n gEntradas.classes.forEach(function(classe_entrada) {\n gPersonagem.classes.push({ classe: classe_entrada.classe, nivel: classe_entrada.nivel || 0 });\n });\n gPersonagem.dominios = PersonagemNivelClasse('clerigo') > 0 && gEntradas.dominios && gEntradas.dominios.slice(0) || [];\n _ConverteFamiliar();\n _ConverteCompanheiroAnimal();\n gPersonagem.niveis_negativos = gEntradas.niveis_negativos || 0;\n\n gPersonagem.experiencia = gEntradas.experiencia;\n\n // Equipamentos podem afetar todo o resto.\n _ConverteEquipamentos();\n\n // Dados de vida afetam quase tudo.\n _ConverteDadosVida();\n\n // Atributos dependem dos dados de vida (incrementos).\n _ConverteAtributos();\n\n // Talentos dependem dos dados de vida.\n _ConverteTalentos();\n\n _ConvertePontosVida();\n\n // Tem que ser depois de conferir pre requisitos.\n _ConvertePericias();\n\n _ConverteListaArmas();\n _ConverteListaArmaduras();\n\n // Estilos tem que vir apos a atualizacao das armas do gPersonagem, talentos e lista de armas.\n _ConverteEstilos();\n\n _ConverteHabilidadesEspeciais();\n\n // Feiticos.\n _ConverteFeiticos();\n\n gPersonagem.notas = gEntradas.notas;\n}", "function getPersons() {\n\n class Person {\n constructor(firstName, lastName, age, email) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.email = email;\n }\n static sayHello() {\n console.log(`Hello`);\n }\n\n toString() {\n return `${this.firstName} ${this.lastName} (age: ${this.age}, email: ${this.email})`;\n }\n }\n\n let persons = [];\n\n persons.push(new Person('Anna', 'Simpson', 22, 'anna@yahoo.com'));\n persons.push(new Person('SoftUni'));\n persons.push(new Person('Stephan', 'Johnson', 25));\n persons.push(new Person('Gabriel', 'Peterson', 24, 'g.p@gmail.com'));\n\n return persons;\n}", "function Profesor(nombre,cargo,nomina){\n\tPersona.call(this,nombre,cargo,nomina)\n}", "function creacionClasesPerros(){\n\tfor (var i =0; i<numeroperros; i++){\n\t\tperro[i] = new Perro();\n\t\tperro[i].posx;\n\t\tperro[i].posy;\n\t\tperro[i].direccion;\n\t\tperro[i].velocidad;\n\t\tperro[i].numeroperros = 10;\n\t\tperro[i].tempx;\n\t\tperro[i].tempy; \n\t}\n}", "function _AtualizaClasses() {\n var classes_desabilitadas = [];\n var div_classes = Dom('classes');\n var divs_classes = DomsPorClasse('classe');\n var maior_indice = divs_classes.length > gPersonagem.classes.length ?\n divs_classes.length : gPersonagem.classes.length;\n for (var i = 0; i < maior_indice; ++i) {\n var div_classe = divs_classes[i];\n if (i < gPersonagem.classes.length) {\n if (!div_classe) {\n AdicionaClasse(i, div_classes);\n }\n _AtualizaClasse(\n classes_desabilitadas, gPersonagem.classes[i].classe,\n gPersonagem.classes[i].nivel, gPersonagem.classes[i].nivel_conjurador, i);\n classes_desabilitadas.push(gPersonagem.classes[i].classe);\n } else {\n RemoveFilho(div_classe.id, div_classes);\n }\n }\n\n // Desabilita selects.\n var selects_classes = DomsPorClasse('selects-classes');\n for (var i = 0; i < selects_classes.length - 1; ++i) {\n selects_classes[i].disabled = true;\n }\n selects_classes[selects_classes.length - 1].disabled = false;\n}", "function main(){\n\n class Person {\n constructor(firstName, lastName, age, email) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.email = email;\n }\n\n toString() {\n return `${this.firstName} ${this.lastName} (age: ${this.age}, email: ${this.email})`;\n }\n }\n \n return [\n new Person (\"Anna\", \"Simpson\", 22, \"anna@yahoo.com\"),\n new Person (\"Kingsland University\"),\n new Person (\"Stephan\", \"Johnson\", 25),\n new Person (\"Gabriel\", \"Peterson\", 24, \"g.p@gmail.com\")\n ];\n}", "function getPersonsFull() {\n\t//TODO\n}", "function persona(nombre, edad) {\n //let this ={}\n //Atributos privados\n let n = nombre\n //Atributos publicos\n this.nombre = nombre\n this.edad = edad\n //metodo publico de instancia\n this.getNombre = function () {\n console.log(n)\n }\n\n //Metodo publico de clase. lo tiene toda la clase persona.\n persona.prototype.getNombreProto = function () {\n console.log(n)\n }\n //return this\n}", "getPersonas() {\n return this.personas;\n }", "function _DependenciasHabilidadesEspeciais() {\n var especiais_antes = gPersonagem.especiais;\n var especiais_nivel_classe = [];\n for (var i = 0; i < gPersonagem.classes.length; ++i) {\n var entrada_classe = gPersonagem.classes[i];\n if (tabelas_classes[entrada_classe.classe].especiais == null) {\n continue;\n }\n especiais_nivel_classe.push(\n { nivel: PersonagemNivelClasse(entrada_classe.classe), especiais_classe: tabelas_classes[entrada_classe.classe].especiais });\n }\n if ('especiais' in tabelas_raca[gPersonagem.raca]) {\n especiais_nivel_classe.push({ nivel: PersonagemNivel(), especiais_classe: tabelas_raca[gPersonagem.raca].especiais });\n }\n var template_pc = PersonagemTemplate();\n if (template_pc != null && 'especiais' in template_pc) {\n especiais_nivel_classe.push({ nivel: PersonagemNivel(), especiais_classe: template_pc.especiais });\n }\n\n for (var i = 0; i < especiais_nivel_classe.length; ++i) {\n var dados_nivel_classe = especiais_nivel_classe[i];\n for (var nivel = 1; nivel <= dados_nivel_classe.nivel; ++nivel) {\n var especiais_por_nivel = dados_nivel_classe.especiais_classe;\n if (!(nivel in especiais_por_nivel)) {\n continue;\n }\n for (var j = 0; j < especiais_por_nivel[nivel].length; ++j) {\n _DependenciaHabilidadeEspecial(especiais_por_nivel[nivel][j]);\n }\n }\n }\n gPersonagem.dominios.forEach(function(dominio) {\n if ('habilidade_especial' in tabelas_dominios[dominio]) {\n _DependenciaHabilidadeEspecial(tabelas_dominios[dominio].habilidade_especial);\n }\n });\n\n // Atualiza o numero de usos de cada especial.\n for (var chave_especial in gPersonagem.especiais) {\n if (chave_especial in especiais_antes) {\n gPersonagem.especiais[chave_especial].usado = especiais_antes[chave_especial].usado || 0;\n } else {\n gPersonagem.especiais[chave_especial].usado = 0;\n }\n }\n}", "function Person()\r\n{\r\n //properties\r\n this.title = '';\r\n this.firstName = '';\r\n this.surname = '';\r\n this.name = '';\r\n this.nick = '';\r\n this.email = '';\r\n this.homePage = '';\r\n this.workplaceHomepage = '';\r\n this.workInfoHomepage = '';\r\n this.schoolHomepage = '';\r\n this.depiction = '';\r\n this.phone = '';\r\n this.seealso = '';\r\n\r\n this.friends = new Array();\r\n\r\n //methods\r\n this.getName = getName;\r\n this.mbox = mbox;\r\n this.mboxSha1 = mboxSha1;\r\n this.getPhone = getPhone;\r\n this.dumpToTextArea = dumpToTextArea;\r\n this.toFOAF = toFOAF;\r\n this.addFriend = addFriend;\r\n}", "gerPersonas() {\n return this.personas;\n }", "function ClassMate(name, age, gender, hobby) {\n var x = {};\n x.name = name;\n x.age = age;\n x.gender = gender;\n x.hobby = hobby;\n x.displayFriend = displayFriend;\n x.addFriend = addFriend;\n return x;\n}", "function _GeraEquipamentos(tabela_geracao_classe_por_nivel) {\n for (var chave_moeda in tabela_geracao_classe_por_nivel.moedas) {\n gPersonagem.moedas[chave_moeda] = tabela_geracao_classe_por_nivel.moedas[chave_moeda];\n }\n if ('pocoes' in tabela_geracao_classe_por_nivel) {\n for (var i = 0; i < tabela_geracao_classe_por_nivel.pocoes.length; ++i) {\n gPersonagem.pocoes.push({chave: tabela_geracao_classe_por_nivel.pocoes[i]});\n }\n }\n}", "function _GeraPontosDeVida(modo, submodo) {\n if (modo != 'personagem' && modo != 'elite' && modo != 'comum') {\n Mensagem(Traduz('Modo') + ' ' + modo + ' ' + Traduz('invalido') + '. ' + Traduz('Deve ser elite, comum ou personagem.'));\n return;\n }\n // Para cada classe, rolar o dado.\n var total_pontos_vida = 0;\n // Primeiro eh diferente na elite e personagem.\n var primeiro = (modo == 'comum') ? false : true;\n for (var i = 0; i < gPersonagem.classes.length; ++i) {\n var info_classe = gPersonagem.classes[i];\n for (var j = 0; j < info_classe.nivel; ++j) {\n var pontos_vida_nivel = 0;\n var template_personagem = PersonagemTemplate();\n var dados_vida = template_personagem != null && 'dados_vida' in template_personagem ?\n template_personagem.dados_vida :\n tabelas_classes[info_classe.classe].dados_vida;\n if (primeiro) {\n if (modo == 'elite') {\n pontos_vida_nivel = dados_vida;\n } else if (modo == 'personagem') {\n // O modificador de constituicao eh subtraido aqui pq sera adicionado\n // no calculo de pontos de vida, nos bonus.\n pontos_vida_nivel = dados_vida +\n gPersonagem.atributos['constituicao'].valor -\n gPersonagem.atributos['constituicao'].modificador;\n } else {\n pontos_vida_nivel = submodo == 'tabelado' ? dados_vida / 2 : Rola(1, dados_vida);\n }\n primeiro = false;\n } else {\n pontos_vida_nivel = submodo == 'tabelado' ? dados_vida / 2 : Rola(1, dados_vida);\n\n }\n // Nunca pode ganhar menos de 1 ponto por nivel.\n if (pontos_vida_nivel < 1) {\n pontos_vida_nivel = 1;\n }\n total_pontos_vida += pontos_vida_nivel;\n }\n }\n gPersonagem.pontos_vida.total_dados = Math.floor(total_pontos_vida);\n}", "function _GeraFeiticosClasseNivel(classe_personagem, nivel, conhecidos_nivel, slots_nivel, ordem_magias, lista_feiticos_classe_nivel) {\n // Preenche conhecidos para ter referencia.\n if (!tabelas_feiticos[classe_personagem.classe].precisa_conhecer) {\n conhecidos_nivel.length = ordem_magias.length;\n }\n for (var i = 0; i < conhecidos_nivel.length && i < ordem_magias.length; ++i) {\n conhecidos_nivel[i] = ordem_magias[i] in lista_feiticos_classe_nivel ? lista_feiticos_classe_nivel[ordem_magias[i]].nome : ordem_magias[i];\n }\n // Preenche os slots, fazendo referencia aos conhecidos.\n var indice_geracao = 0;\n for (var i = 0; i < slots_nivel.feiticos.length; ++i) {\n slots_nivel.feiticos[i].nivel_conhecido = nivel;\n slots_nivel.feiticos[i].indice_conhecido = indice_geracao++;\n indice_geracao = indice_geracao % ordem_magias.length;\n }\n}", "function Person(firstName, lastName, favoriteColor, favoriteNumber, favoriteFoods) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.favoriteColor = favoriteColor;\n this.favoriteNumber = favoriteNumber;\n this.favoriteFoods = favoriteFoods || [];\n this.family = []; // moved up here from prototype below\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
methods setFaceColor(face, RGB) inputs face: "All" (String) RBG: [float, float, float]
setFaceColor( face, RGB) { // debug //console.log("atomicGLSphere("+this.name+")::setFaceColor"); var r = RGB[0]; var g = RGB[1]; var b = RGB[2]; // switch face switch(face){ case "All": this.colorsArray = []; for (var latNumber=0; latNumber <= this.latitudeBands; latNumber++) { for (var longNumber = 0; longNumber <= this.longitudeBands; longNumber++) { // color this.colorsArray.push(r); this.colorsArray.push(g); this.colorsArray.push(b); } } break; } }
[ "setFaceColor ( face, RGB) {\n\t\t// debug\n\t\t//console.log(\"atomicGL(\"+this.name+\")::setFaceColor\");\n\t\tvar r = RGB[0];\n\t\tvar g = RGB[1];\n\t\tvar b = RGB[2];\n\n\t\t// switch face\n\t\tswitch(face)\n\t\t{\n\t\t\tcase \"All\":\n\t\t\t\tthis.colorsArray = [];\n\t\t\t\tfor(var i=0;i<=this.yrow;i++)\n\t\t\t\t{\n\t\t\t\t\tfor(var j=0;j<= this.xrow;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.colorsArray.push(r);\n\t\t\t\t\t\tthis.colorsArray.push(g);\n\t\t\t\t\t\tthis.colorsArray.push(b);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}", "setFaceColor( face, RGB) {\r\n\t\t// debug\r\n\t\t//console.log(\"atomicGL2Cylinder(\"+this.name+\")::setFaceColor\");\r\n\t\tvar r = RGB[0];\r\n\t\tvar g = RGB[1];\r\n\t\tvar b = RGB[2];\r\n\r\n\t\t// switch face\r\n\t\tswitch(face){\r\n\t\t\tcase \"All\":\r\n\t\t\t\tvar nbc = this.colorsArray.length / 3 ;\r\n\t\t\t\tthis.colorsArray = [] ;\r\n\t\t\t\tfor (var i=0; i <nbc; i++) {\r\n \tthis.colorsArray.push(r);\r\n \tthis.colorsArray.push(g);\r\n \tthis.colorsArray.push(b);\r\n \t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}", "setFaceColor( face, RGB) {\n\t\t// debug\n\t\t//console.log(\"atomicGLCube(\"+this.name+\")::setFaceColor\");\n\t\tvar r = RGB[0];\n\t\tvar g = RGB[1];\n\t\tvar b = RGB[2];\n\n\t\t// switch face\n\t\tswitch(face){\n\t\t\tcase \"Front\":\n\t\t\t\tthis.colorsArray[0] =r;\n\t\t\t\tthis.colorsArray[1] =g;\n\t\t\t\tthis.colorsArray[2] =b;\n\n\t\t\t\tthis.colorsArray[3] =r;\n\t\t\t\tthis.colorsArray[4] =g;\n\t\t\t\tthis.colorsArray[5] =b;\n\n\t\t\t\tthis.colorsArray[6] =r;\n\t\t\t\tthis.colorsArray[7] =g;\n\t\t\t\tthis.colorsArray[8] =b;\n\n\t\t\t\tthis.colorsArray[9] =r;\n\t\t\t\tthis.colorsArray[10] =g;\n\t\t\t\tthis.colorsArray[11] =b;\n\t\t\tbreak;\n\n\t\t\tcase \"Back\":\n\t\t\t\tthis.colorsArray[12+0] =r;\n\t\t\t\tthis.colorsArray[12+1] =g;\n\t\t\t\tthis.colorsArray[12+2] =b;\n\n\t\t\t\tthis.colorsArray[12+3] =r;\n\t\t\t\tthis.colorsArray[12+4] =g;\n\t\t\t\tthis.colorsArray[12+5] =b;\n\n\t\t\t\tthis.colorsArray[12+6] =r;\n\t\t\t\tthis.colorsArray[12+7] =g;\n\t\t\t\tthis.colorsArray[12+8] =b;\n\n\t\t\t\tthis.colorsArray[12+9] =r;\n\t\t\t\tthis.colorsArray[12+10] =g;\n\t\t\t\tthis.colorsArray[12+11] =b;\n\t\t\tbreak;\n\t\t\tcase \"Top\":\n\t\t\t\tthis.colorsArray[24+0] =r;\n\t\t\t\tthis.colorsArray[24+1] =g;\n\t\t\t\tthis.colorsArray[24+2] =b;\n\n\t\t\t\tthis.colorsArray[24+3] =r;\n\t\t\t\tthis.colorsArray[24+4] =g;\n\t\t\t\tthis.colorsArray[24+5] =b;\n\n\t\t\t\tthis.colorsArray[24+6] =r;\n\t\t\t\tthis.colorsArray[24+7] =g;\n\t\t\t\tthis.colorsArray[24+8] =b;\n\n\t\t\t\tthis.colorsArray[24+9] =r;\n\t\t\t\tthis.colorsArray[24+10] =g;\n\t\t\t\tthis.colorsArray[24+11] =b;\n\t\t\tbreak;\n\t\t\tcase \"Bottom\":\n\t\t\t\tthis.colorsArray[36+0] =r;\n\t\t\t\tthis.colorsArray[36+1] =g;\n\t\t\t\tthis.colorsArray[36+2] =b;\n\n\t\t\t\tthis.colorsArray[36+3] =r;\n\t\t\t\tthis.colorsArray[36+4] =g;\n\t\t\t\tthis.colorsArray[36+5] =b;\n\n\t\t\t\tthis.colorsArray[36+6] =r;\n\t\t\t\tthis.colorsArray[36+7] =g;\n\t\t\t\tthis.colorsArray[36+8] =b;\n\n\t\t\t\tthis.colorsArray[36+9] =r;\n\t\t\t\tthis.colorsArray[36+10] =g;\n\t\t\t\tthis.colorsArray[36+11] =b;\n\t\t\tbreak;\n\t\t\tcase \"Left\":\n\t\t\t\tthis.colorsArray[48+0] =r;\n\t\t\t\tthis.colorsArray[48+1] =g;\n\t\t\t\tthis.colorsArray[48+2] =b;\n\n\t\t\t\tthis.colorsArray[48+3] =r;\n\t\t\t\tthis.colorsArray[48+4] =g;\n\t\t\t\tthis.colorsArray[48+5] =b;\n\n\t\t\t\tthis.colorsArray[48+6] =r;\n\t\t\t\tthis.colorsArray[48+7] =g;\n\t\t\t\tthis.colorsArray[48+8] =b;\n\n\t\t\t\tthis.colorsArray[48+9] =r;\n\t\t\t\tthis.colorsArray[48+10] =g;\n\t\t\t\tthis.colorsArray[48+11] =b;\n\t\t\tbreak;\n\t\t\tcase \"Right\":\n\t\t\t\tthis.colorsArray[60+0] =r;\n\t\t\t\tthis.colorsArray[60+1] =g;\n\t\t\t\tthis.colorsArray[60+2] =b;\n\n\t\t\t\tthis.colorsArray[60+3] =r;\n\t\t\t\tthis.colorsArray[60+4] =g;\n\t\t\t\tthis.colorsArray[60+5] =b;\n\n\t\t\t\tthis.colorsArray[60+6] =r;\n\t\t\t\tthis.colorsArray[60+7] =g;\n\t\t\t\tthis.colorsArray[60+8] =b;\n\n\t\t\t\tthis.colorsArray[60+9] =r;\n\t\t\t\tthis.colorsArray[60+10] =g;\n\t\t\t\tthis.colorsArray[60+11] =b;\n\t\t\tbreak;\n\t\t\tcase \"All\":\n\t\t\t\tthis.colorsArray = [\n\t\t\t\t\t// Front face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Back face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Top face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Bottom face : floor\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Left face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Right face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t];\n\t\t\tbreak;\n\t\t}\n\t}", "function setfacecolor(color, face){\n\n\tsetcolor(color, face, \"tr\");\n\tsetcolor(color, face, \"tm\");\n\tsetcolor(color, face, \"tl\");\n\n\tsetcolor(color, face, \"mr\");\n\tsetcolor(color, face, \"mm\");\n\tsetcolor(color, face, \"ml\");\n\n\tsetcolor(color, face, \"br\");\n\tsetcolor(color, face, \"bm\");\n\tsetcolor(color, face, \"bl\");\n}", "function setcolor(color, face, square){\n var sq = color;\n\tvar faceo\n\n\tif(face === \"front\"){\n\t\tfaceo = \"face-front\";\n\t}\n\n\telse if(face === \"back\"){\n\t\tfaceo = \"face-back\";\n\t}\n\n\telse if(face === \"right\"){\n\t\tfaceo = \"face-right\";\n\t}\n\n\telse if(face === \"left\"){\n\t\tfaceo = \"face-left\";\n\t}\n\n\telse if(face === \"bottom\"){\n\t\tfaceo = \"face-bottom\";\n\t}\n\n\telse if(face === \"top\"){\n\t\tfaceo = \"face-top\";\n\t}\n\n\telse{\n\t\tconsole.log(\"=== Error: face parameter for setcolor() is not valid\");\n\t\treturn;\n\t}\n\n\tvar yo = \"#\";\n\tyo += square;\n\n\tdocument.getElementById(faceo).querySelector(yo).style.backgroundColor = sq.color;\n\tdocument.getElementById(faceo).querySelector(yo).querySelector(\".squarel\").innerHTML = sq.letter;\n\n\tif(face === \"front\"){\n\t\tdocument.getElementById(\"modelcube\").querySelector(yo).style.backgroundColor = sq.color;\n\t document.getElementById(\"modelcube\").querySelector(yo).querySelector(\".squarel\").innerHTML = sq.letter;\n\t}\n\n\treturn;\n}", "function colorFace(face, index) {\n\tvar triangle = globe.triangles[index];\n\n\tif (!triangle) {\n\t\treturn;\n\t}\n\n\tvar points = [\n\t\tglobe.points[triangle.p1],\n\t\tglobe.points[triangle.p2],\n\t\tglobe.points[triangle.p3]\n\t];\n\tswitch(config.triangle_coloring) {\n\t\tcase \"max\":\n\t\t\tvar color = points.reduce((p1, p2) => p1.elevation > p2.elevation ? p1 : p2).color;\n\n\t\t\tface.vertexColors[0] = color;\n\t\t\tface.vertexColors[1] = color;\n\t\t\tface.vertexColors[2] = color;\n\t\t\tbreak;\n\t\tcase \"min\":\n\t\t\tvar color = points.reduce((p1, p2) => p1.elevation < p2.elevation ? p1 : p2).color;\n\n\t\t\tface.vertexColors[0] = color;\n\t\t\tface.vertexColors[1] = color;\n\t\t\tface.vertexColors[2] = color;\n\t\t\tbreak;\n\t\tcase \"avg\":\n\t\t\tvar color = color_gradient.getColor(points.map(p => p.elevation).reduce((e1, e2) => e1 + e2) / points.length);\n\t\t\tface.vertexColors[0] = color;\n\t\t\tface.vertexColors[1] = color;\n\t\t\tface.vertexColors[2] = color;\n\t\t\tbreak;\n\t\tcase \"all\":\n\t\t\tface.vertexColors[0] = points[0].color;\n\t\t\tface.vertexColors[1] = points[1].color;\n\t\t\tface.vertexColors[2] = points[2].color;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.error(\"bad triangle color setting\");\n\t}\n}", "function setface(face, position){\n\n\tsetcolor(face.tr, position, \"tr\");\n\tsetcolor(face.tm, position, \"tm\");\n\tsetcolor(face.tl, position, \"tl\");\n\n\tsetcolor(face.mr, position, \"mr\");\n\tsetcolor(face.mm, position, \"mm\");\n\tsetcolor(face.ml, position, \"ml\");\n\n\tsetcolor(face.br, position, \"br\");\n\tsetcolor(face.bm, position, \"bm\");\n\tsetcolor(face.bl, position, \"bl\");\n}", "function turnFace(face) {\n var x,y,z;\n var direction,value;\n var mainAxis;\n var oldMat;\n switch (face) {\n case \"L\":\n mainAxis = 0; value = -1; direction = \"L\";\n break;\n case \"R\":\n mainAxis = 0; value = 1; direction = 0;\n break;\n case \"U\":\n mainAxis = 1;value = 1;direction = 0;\n break;\n case \"D\":\n mainAxis = 1;value = -1;direction = \"D\";\n break;\n case \"F\":\n mainAxis = 2;value = 1;direction = 0;\n break;\n case \"B\":\n mainAxis = 2;value = -1;direction = \"B\";\n break;\n case \"M\":\n mainAxis = 0;value = 0; direction = \"M\";\n break;\n case \"E\":\n mainAxis = 1;value = 0;direction = \"E\";\n break;\n case \"S\":\n mainAxis = 2;value = 0;direction = 0;\n break;\n case \"l\":\n mainAxis = 0; value = -1; direction = 0;\n break;\n case \"r\":\n mainAxis = 0; value = 1; direction = \"r\";\n break;\n case \"u\":\n mainAxis = 1;value = 1;direction = \"u\";\n break;\n case \"d\":\n mainAxis = 1;value = -1;direction = 0;\n break;\n case \"f\":\n mainAxis = 2;value = 1;direction = \"f\";\n break;\n case \"b\":\n mainAxis = 2;value = -1;direction = 0;\n break;\n case \"m\":\n mainAxis = 0;value = 0;direction = 0;\n break;\n case \"e\":\n mainAxis = 1;value = 0;direction = 0;\n break;\n case \"s\":\n mainAxis = 2;value = 0;direction = \"s\";\n break;\n }\n for (x = -1; x < 2; x++) {\n for (y = -1; y < 2; y++) {\n for (z = -1; z < 2; z++) {\n if (cubeState[x+1][y+1][z+1][mainAxis] === value) {\n oldMat = getRotationMatrix(x,y,z);\n if (!direction) \n oldMat = mult(oldMat,rotate(rotationAngle,getRotationAxes(x,y,z)[mainAxis]));\n else \n oldMat = mult(oldMat,rotate(rotationAngle,negateVec(getRotationAxes(x,y,z)[mainAxis])));\n setRotationMatrix(x,y,z,oldMat);\n }\n }\n }\n }\n}", "function assignColorsToCube(cube) {\n // Create an array of colors using rgb values\n var colors = [\n new THREE.Color(\"rgb(255,0,0)\"),\n new THREE.Color(\"rgb(0,255,0)\"),\n new THREE.Color(\"rgb(0,0,255)\"),\n new THREE.Color(\"rgb(255,255,0)\"),\n new THREE.Color(\"rgb(255,0,255)\")\n ];\n\n /// Loop over the colors array with a for loop and assign colors to verticies\n for (var i = 0; i < 12; i += 2) {\n // Comment\n var color = colors[i / 2];\n\n cube.geometry.faces[i].color = color;\n cube.geometry.faces[i + 1].color = color;\n }\n }", "setColour(...args) {\r\n this.native.setColour.apply(this.native, args)\r\n }", "setFaceFeature(...args) {\r\n this.native.setFaceFeature.apply(this.native, args)\r\n }", "function update_colors(listin, reset_color = true) {\n listin.forEach(function(d) {\n //console.log(d)\n if (d.faces) {\n d.faces.forEach(function(f) {\n face = mesh.geometry.faces[f];\n\n if (reset_color) {\n face.color.set(d.color);\n } else {\n face.color.set(d.color_g);\n }\n });\n }\n });\n\n mesh.geometry.elementsNeedUpdate = true;\n render();\n drawfillBars();\n} // update", "function SetFgColor(elem,color){\n elem.style.color = color.GetRGBColorString();\n}", "setColorFilter(cr, cg, cb) {\n this.colorFilter = [cr, cg, cb];\n }", "function changeBGColor(element, red, green, blue) {\n rgbVal = [red, green, blue].join(',') \n element.style.backgroundColor = 'rgb(' + rgbVal + ')';\n}", "function setFaces(index){\n\n\tif(index == 2){\n\t\tgeometryList[edgeType][index].faces[0].color.setHex(0x000000);\n\t\tgeometryList[edgeType][index].faces[1].color.setHex(0x000000);\n\t} else { // front\n\t\tgeometryList[edgeType][index].faces[0].color.setHex(0xff0000);\n\t\tgeometryList[edgeType][index].faces[1].color.setHex(0xff0000);\n\t}\n\tif(index == 3){\n\t\tgeometryList[edgeType][index].faces[2].color.setHex(0x000000);\n\t\tgeometryList[edgeType][index].faces[3].color.setHex(0x000000);\n\t} else {// right\n\t\tgeometryList[edgeType][index].faces[2].color.setHex(0x008000);\n\t\tgeometryList[edgeType][index].faces[3].color.setHex(0x008000);\n\t}\n\tif(index == 0){\n\t\tgeometryList[edgeType][index].faces[4].color.setHex(0x000000);\n\t\tgeometryList[edgeType][index].faces[5].color.setHex(0x000000);\n\t} else {// back\n\t\tgeometryList[edgeType][index].faces[4].color.setHex(0x0000ff);\n\t\tgeometryList[edgeType][index].faces[5].color.setHex(0x0000ff);\n\t}\n\tif(index == 1){\n\t\tgeometryList[edgeType][index].faces[6].color.setHex(0x000000);\n\t\tgeometryList[edgeType][index].faces[7].color.setHex(0x000000);\n\t} else {// left\n\t\tgeometryList[edgeType][index].faces[6].color.setHex(0xffff00);\n\t\tgeometryList[edgeType][index].faces[7].color.setHex(0xffff00);\n\t}\n\tif(index == 5){\n\t\tgeometryList[edgeType][index].faces[8].color.setHex(0x000000);\n\t\tgeometryList[edgeType][index].faces[9].color.setHex(0x000000);\n\t} else {// top\n\t\tgeometryList[edgeType][index].faces[8].color.setHex(0x800080);\n\t\tgeometryList[edgeType][index].faces[9].color.setHex(0x800080);\n\t}\n\tif(index == 4){\n\t\tgeometryList[edgeType][index].faces[10].color.setHex(0x000000);\n\t\tgeometryList[edgeType][index].faces[11].color.setHex(0x000000);\n\t} else {// bottom\n\t\tgeometryList[edgeType][index].faces[10].color.setHex(0xff5733);\n\t\tgeometryList[edgeType][index].faces[11].color.setHex(0xff5733);\n\t}\n}", "function setColorValues () {\n // CONVERT RGB AND SET HEXIDECIMAL\n hex = rgbToHex(r, g, b);\n\n // CONVERT RGB AND SET HSL\n var hslvalues = rgbToHsl(r, g, b);\n h = hslvalues[0];\n s = hslvalues[1];\n l = hslvalues[2];\n}", "ChangeColor(int, int, int, int, int) {\n\n }", "function setColour(pix,r,g,b,a) {\r\n var data = pix.data;\r\n for (var i = 0; i < data.length;i += 4) {\r\n\tif(data[i+3] != 0){\r\n \r\n data[i]= r;\r\n data[i+1] = g;\r\n data[i+2] = b;\r\n data[i+3] = a;\r\n }\r\n }\r\n pix.data = data;\r\n return pix; \r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts saved places from database and displays them
function displaySavedPlaces() { const placesSnapshot = firebase.database().ref('users/'+ firebase.auth().currentUser.uid + '/places').once('value', function(placesSnapshot){ let placeArray = []; placesSnapshot.forEach((placesSnapshot) => { let place = placesSnapshot.val(); placeArray.push(place); savedPlacesSet.add(place.place_id); }); populatePlaces(placeArray, true); }); }
[ "function getPlaces(res, mysql, context, complete){\n\t\tmysql.pool.query('SELECT id, name FROM lotr_place', function(error, results, fields){\n\t\t\tif(error){\n\t\t\t\tres.write(JSON.stringify(error));\n\t\t\t\tres.end();\n\t\t\t}\n\t\t\tcontext.places = results;\n\t\t\tcomplete();\n\t\t});\n\t}", "function getPlaces() {\n fetch('http://localhost:3000/places')\n .then(function (response) {\n // Trasform server response to get the places\n response.json().then(function (places) {\n appendPlacesToDOM(places);\n });\n });\n}", "getAllPlaces() {\n try {\n const places = db.get('places').value();\n return places;\n } catch (error) {\n throw error;\n }\n }", "function fetchPlaces(tx) {\n tx.executeSql('SELECT * FROM places', [], placesSuccess, errorCB);\n }", "function Places() {}", "function fetchPlace(property, value, parseFetch){\n\t\t$('#view').empty();\n\t\t$('#view').append('<div id=\"place-list\"><h1 id=\"typeLabel\">' + value + '</h1></div>')\n\t\tparseFetch.equalTo(property, value)\n\t\t\t\t\t.find({\n\t\t\t\t\t\tsuccess: function(obj) {\n\t\t\t\t\t\t\tconsole.log(obj);\n\t\t\t\t\t\t\tobj.forEach(function(item){\n\t\t\t\t\t\t\t\t// what to do with each object\n\t\t\t\t\t\t\t\tconsole.log(item.get('Name'));\n\t\t\t\t\t\t\t\tvar name = item.get('Name');\n\t\t\t\t\t\t\t\tvar type = item.get('Type');\n\t\t\t\t\t\t\t\tvar address = item.get('Address');\n\t\t\t\t\t\t\t\tvar phone = item.get('phoneNumber');\n\t\t\t\t\t\t\t\tvar lat = item.get('Lat');\n\t\t\t\t\t\t\t\tvar lng = item.get('Lng');\n\n\t\t\t\t\t\t\t\t// console.log('lat: ' + lat);\n\t\t\t\t\t\t\t\t// console.log('lng: ' + lng);\n\n\t\t\t\t\t\t\t\tmapData(name, address, phone, lat, lng);\n\t\t\t\t\t\t\t\tappendData(name, type, address, phone);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t},\n\t\t\t\t\t\terror: function(err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t}", "listPlace(){\n let google=this.google;\n let map=this.map\n var service;\n // Create the search box and link it to the UI element.\n var input = document.getElementById('address');\n var searchBox = new google.maps.places.SearchBox(input);\n\n // Bias the SearchBox results towards current map's viewport.\n map.addListener('bounds_changed', function() {\n searchBox.setBounds(map.getBounds());\n });\n var locate;\n var mapData;\n // Listen for the event fired when the user selects a prediction and retrieve\n // more details for that place.\n searchBox.addListener('places_changed', function() {\n var request = {\n query: input.value,\n fields: ['name', 'geometry','formatted_address', 'icon','photos','place_id'],\n };\n\n service = new google.maps.places.PlacesService(this.map);\n service.findPlaceFromQuery(request, function (results, status) {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n let property=results[0];\n locate = property.geometry.location;\n var addrRequest={\n place_id: property.place_id,\n fields: ['address_components' ]\n }\n service.getDetails(addrRequest, function(addressBreakdown,addrStatus){\n\n var streetNumber;\n var streetName;\n var suburb;\n var state;\n var postcode;\n var country;\n for(var i = 0; i < addressBreakdown.address_components.length; i++){\n let addr=addressBreakdown.address_components[i];\n for(var k = 0; k < addr.types.length; k++){\n if (addr.types[k] === \"street_number\")\n streetNumber = addr.short_name;\n else if (addr.types[k] === \"route\")\n streetName = addr.short_name;\n else if (addr.types[k] === \"administrative_area_level_2\")\n suburb = addr.short_name;\n else if (addr.types[k] === \"administrative_area_level_1\")\n state = addr.short_name;\n else if (addr.types[k] === \"postal_code\")\n postcode = addr.long_name;\n else if (addr.types[k] === \"country\")\n country = addr.long_name;\n }\n }\n mapData={\n street: streetName,\n suburb: suburb,\n state: state,\n postcode: postcode,\n country: country,\n }\n });\n this.place=locate;\n }\n });\n });\n\n return JSON.stringify(mapData);\n }", "function populatePlacesList(){\n\t\t//PLACES\n\t\tvar data = s.placesGeoJson;\n\t\tvar additionalFeatures = s.featureGeoJson;\n\t\tfor(var i=0; i<data.features.length;i++){\n\t\t\tvar feature = data.features[i];\n\t\t\ts.controls.featuresList.push(feature.properties);\n\t\t}\n\t\tfor(var i = 0; i < additionalFeatures.features.length; i++) {\n\t\t\tvar feature = additionalFeatures.features[i];\n\t\t\ts.controls.featuresList.push(feature.properties);\n\t\t}\n\n\t\ts.controls.featuresList = alphabetize('features',s.controls.featuresList);\n\n\t\ts.controls.featuresListLookup = {};\n\t\tfor (var k = 0; k < s.controls.featuresList.length; k++) {\n\t\t\ts.controls.featuresListLookup[s.controls.featuresList[k].id] = s.controls.featuresList[k];\n\t\t}\n\n\t\tfor (var j = 0; j < s.controls.featuresList.length; j++) {\n\t\t\tvar thisFeature = s.controls.featuresList[j];\n\t\t\tvar markup = \n\t\t\t\t'<li role=\"menuitem\">'+\n\t\t\t\t\t'<a class=\"wc-item-link wc-mc-place-button wc-mc-button\" data-show-place=\"{\\'placeId\\'\\:\\''+thisFeature.id+'\\'}\" title=\"'+thisFeature.name+'\">'+\n\t\t\t\t\t\t'<span class=\"wc-text\">'+thisFeature.name+'</span>'+\n\t\t\t\t\t\t'<svg class=\"wc-icon\" viewbox=\"0 0 32 32\"><use xlink:href=\"'+Globals.s.svgFilePath+'#icon-arrow-right\" /></svg>'+\n\t\t\t\t\t'</a>'+\n\t\t\t\t'</li>';\n\t\t\ts.controls.placesDOMList.append(markup);\n\t\t}\n\t}", "function getAllPlaces(place) {\n var myPlace = {};\n myPlace.place_id = place.place_id;\n myPlace.position = place.geometry.location.toString();\n myPlace.name = place.name;\n myPlace.address = address;\n self.allPlaces.push(myPlace);\n }", "function getPlaces(){\n // Get places : this function is useful to get the ID of a PLACE\n // Ajust filters, launch search and view results in the log\n // https://developers.jivesoftware.com/api/v3/cloud/rest/PlaceService.html#getPlaces(List<String>, String, int, int, String)\n\n // Filters\n // ?filter=search(test,report)\n // recentlyviewed\n // ?filter=type() = space, blog, group ...\n \n var result = fetch( BASEURL + \"/places/?filter=type(group)&filter=search(test collaboration)&count=100\" , options(\"get\")).list; \n for(var i in result){\n Logger.log(i + \" \" + result[i].name + \" \" + result[i].placeID); \n }\n}", "function loadPlaces() {\n window.Places = {};\n dbLoadPlaces(function (placeArray) {\n log(\"places loaded\");\n placeArray.forEach(function (place) {\n if (!place.deleted) {\n window.Places[place.id] = place;\n window.index.addGroupsAvailable(place);\n }\n });\n addAllPlacesToMap();\n window.tracker = new Tracker();\n splashScreen.enableCloseButtons();\n setGroupOptions();\n index.showIndex();\n clearTimeout(window.restartTimer);\n splashScreen.permitDrop(\"places loaded\");\n if (window.location.queryParameters.place || window.location.queryParameters.signin) {\n splashScreen.permitDrop(\"parameter goto\");\n }\n });\n}", "function displayPlaces(places, dom) {\n var markup = '<div class=\"data-header\">Nearby locations:</div>';\n \n for (var i=0; i < places.length && i < 5; i++) {\n var place = places[i];\n \n markup += '<div class=\"place\">'\n + '<div class=\"picture\"><img src=\"http://graph.facebook.com/' + place.id + '/picture\"></div>'\n + '<div class=\"info\">'\n + ' <div class=\"name\">' + place.name + '</div>'\n + ' <div class=\"check-in-button\"><input type=\"button\" value=\"Check in\" onclick=\"checkin(' + place.id + ')\" /></div>'\n + '</div>'\n + '</div>';\n }\n \n dom.innerHTML = markup;\n}", "function listPlaces() {\n//Implement print check, so that list gets printed ONCE, not spammed\n if(localStorage['places']){\n a = JSON.parse(localStorage.getItem('places'));\n $('#list').text(\"\");\n for (n=0; n<a.length; n++) {\n var appendConstructor = '<img src='+'\"'+a[n].iconType+'\">' + \" \" + a[n].placeTitle + \"@\" + a[n].lat + \" and \" + a[n].lng + \" added on \" + a[n].dateAdded;\n $('#list').append(\"<li>\"+appendConstructor+\"</li>\");\n $('#list').show();\n }\n } else {\n document.getElementById(\"status\").innerHTML = \"You have no saved places yet. GG\"\n }\n }", "fillMapWithPlacesFromDb() {\n\n const jsonUrl = '/api/get-places';\n\n const getMethod = {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n }\n }\n\n fetchApi(jsonUrl, getMethod, json => {\n for (const p of json) {\n const place = new Place(p.name, p.lon, p.lat);\n this.addPlaceToDom(place);\n }\n });\n }", "function displayPlaces(places, dom) {\n var markup = '<div class=\"data-header\">Nearby locations:</div>';\n \n for (var i=0; i < places.length && i < 5; i++) {\n var place = places[i];\n \n markup += '<div class=\"place\">'\n + '<div class=\"picture\"><img src=\"https://graph.facebook.com/' + place.id + '/picture\"></div>'\n + '<div class=\"info\">'\n + ' <div class=\"name\">' + place.name + '</div>'\n + ' <div class=\"check-in-button\"><input type=\"button\" value=\"Check in\" onclick=\"checkin(' + place.id + ')\" /></div>'\n + '</div>'\n + '</div>';\n }\n \n dom.innerHTML = markup;\n}", "function getPlaceDetails(marker) {\n var service = new google.maps.places.PlacesService(map);\n service.getDetails({\n placeId: marker.placeID\n }, function (place, status) {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n var placeDetails = {};\n placeDetails.name = place.name || \"No Name Information Available\";\n placeDetails.address = place.formatted_address || \"No Address Information Available\";\n if (place.opening_hours) {\n if (place.opening_hours.open_now) {\n placeDetails.open_now = \"Currently Open\";\n } else {\n placeDetails.open_now = \"Currently Closed\";\n }\n } else { placeDetails.open_now = \"No Opening Hours Information Available\"; }\n if (place.website) {\n placeDetails.website = '<a href=\"' + place.website + '\">' + place.name + '<a>';\n } else { placeDetails.website = \"No Website Information Available\"; }\n if (place.photos) {\n placeDetails.photo = '<img class=\"place-img\" src=\"' + place.photos[0].getUrl(\n { maxHeight: 300, maxWidth: 300 }) + '\">';\n } else {\n placeDetails.photo = \"\";\n }\n if (place.types.indexOf(\"restaurant\") == -1 && place.types.indexOf(\"gym\") == -1) {\n getWikipediaSnippet(place.name);\n } else {\n self.wikiExtract(\"\");\n }\n self.placeDetails(placeDetails);\n } else {\n alert(\"Failed to load Google Place Details. Check the Console for details.\");\n console.log(status);\n }\n }\n );\n\n // Request Wikipedia articles related to the selected place and store a snippet of the most relevant article it in the KO variable \"wikiExtract\"\n function getWikipediaSnippet(title) {\n $.ajax({\n url: 'https://de.wikipedia.org/w/api.php',\n data: {\n action: 'query',\n list: 'search',\n srsearch: title,\n format: 'json',\n formatversion: 2\n },\n dataType: 'jsonp'\n }).done(function (json) {\n var html;\n if (json.query.search[0].snippet) {\n html = '[...] ' + json.query.search[0].snippet + ' [...] <a target=\"_blank\" href=https://de.wikipedia.org/?curid=' + json.query.search[0].pageid + '\">Wikipedia</a>';\n self.wikiExtract(html);\n } else {\n html = \"\";\n self.wikiExtract(html);\n }\n }).fail(function(requestObject, error, errorThrown) {\n alert(\"Failed to load Wikipedia Snippet. Check the Console for details.\");\n console.log(requestObject);\n });\n }\n }", "function getDetailsFromPlacesAPI() {\n // If the searchedSpace isn't set yet\n if (!searchedSpace || searchedSpace === \"\") {\n // Dispatch error\n const errorAction = {\n type: \"error/set\",\n data: \"Please select a valid place to save\",\n };\n\n store.dispatch(errorAction);\n\n return;\n }\n\n // Get place details from google places\n const request = {\n placeId: searchedSpace.value.place_id,\n fields: [\n \"name\",\n \"formatted_address\",\n \"photo\",\n \"type\",\n \"website\",\n \"opening_hours\",\n \"rating\",\n \"geometry\",\n ],\n };\n\n const service = new google.maps.places.PlacesService(\n document.createElement(\"div\")\n );\n\n service.getDetails(request, savePlacesResult);\n }", "function populateArea() {\n\n var service = new google.maps.places.PlacesService(map);\n\n//finds the current selected option from the HTML\n var chosenPlace = document.getElementById(\"chooseArea\");\n var chosenPlaceSelection= chosenPlace.options[chosenPlace.selectedIndex].value;\n console.log(chosenPlaceSelection);\n if (chosenPlaceSelection ==\"monuments\")\n {\n selectedArray = monumentArray;\n }\n else if (chosenPlaceSelection ==\"stadiums\"){\n selectedArray = stadiumArray;\n }\n else{\n selectedArray = stadiumArray.concat(monumentArray);\n }\n //iterates through the user selection and uses get details method to find info about the location\nfor (var i =0; i<selectedArray.length;i++){\n service.getDetails({\n placeId: selectedArray[i]\n }, function(place, status) {\n if (status === google.maps.places.PlacesServiceStatus.OK) { //creating marker at each location in array\n var marker = new google.maps.Marker({\n map: map,\n animation: google.maps.Animation.DROP,\n title:place.vicinity,\n position: place.geometry.location\n });\n\n\n google.maps.event.addListener(marker, 'click', function() {\n //adding content to the markers infowindow using the places library\n infowindow.setContent('<div id =\"locationText\" >' + place.formatted_address + place.geometry.location + '<div id =\"ndiv\"> </div> </div>');\n //adding streetview of the selected location\n var sv = new google.maps.StreetViewService();\n sv.getPanorama({location:(place.geometry.location),radius:50},processSVData);\n\n\n infowindow.open(map, this);\n });\n }\n });\n}\n}", "function getPlaceDetails(place){\n service.getDetails( \n {placeId: place.place_id},\n function(placeDet, status){\n if (status === google.maps.places.PlacesServiceStatus.OK){\n renderDisplay(placeDet);\n }\n }\n );\n //end place details\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for SUI segmented button control component
function suiSegmentedButtons() { const segmentedControls = document.querySelectorAll('.sui-segmented-button'); for (let segControl of segmentedControls) { //initialize the first option as the selected option segControl.children[0].classList.add('sui-segmented-button-selected'); // assign a click event listener to control the selected state for (let segment of segControl.children) { segment.addEventListener('click', () => { let selected = segControl.querySelector('.sui-segmented-button-selected'); if (selected !== segment) { selected.classList.remove('sui-segmented-button-selected'); segment.classList.add('sui-segmented-button-selected'); } }); } } }
[ "static hostBtnSingleStep_click(btn) {\n /// Must do this first so the text label updates properly\n _SingleStepMode = !_SingleStepMode;\n /// Single Step Mode active\n if (_SingleStepMode) {\n /// Enable the \"Next Step\" button\n document.getElementById(\"btnNextStep\").disabled = false;\n document.getElementById(\"btnNextStep\").style.backgroundColor = \"#007acc\";\n /// Show user that single step mode is ON\n document.getElementById(\"btnSingleStepMode\").value = \"Single Step OFF\";\n } /// if\n /// Single Step Mode \n else {\n /// Enable the \"Next Step\" button\n document.getElementById(\"btnNextStep\").disabled = true;\n document.getElementById(\"btnNextStep\").style.backgroundColor = '#143e6c';\n /// Visually show user that single step mode is OFF\n document.getElementById(\"btnSingleStepMode\").value = \"Single Step ON\";\n } /// else\n _KernelInterruptPriorityQueue.enqueueInterruptOrPcb(new TSOS.Interrupt(SINGLE_STEP_IRQ, []));\n }", "function B_MBButton(x, y){\n //ReporterBlock.call(this,x,y,DeviceMicroBit.getDeviceTypeId());\n PredicateBlock.call(this, x, y, DeviceMicroBit.getDeviceTypeId());\n this.deviceClass = DeviceMicroBit;\n this.displayName = Language.getStr(\"Button\");\n this.numberOfPorts = 1;\n this.draggable = true;\n this.addPart(new DeviceDropSlot(this,\"DDS_1\", this.deviceClass));\n this.addPart(new LabelText(this,this.displayName));\n\n\n const choice = new DropSlot(this, \"SDS_1\", null, null, new SelectionData(\"A\", \"buttonA\"));\n choice.addOption(new SelectionData(\"A\", \"buttonA\"));\n choice.addOption(new SelectionData(\"B\", \"buttonB\"));\n this.addPart(choice);\n\n}", "actionOnClick(){\n continueButton.setStyle({ color: '#ff0'});\n }", "function ShaderControlBtn (posX : int, posY : int) {\n\tvar btnName : String;\n\tif(shaderIdx == 0) btnName = \"Material : Specular\";\n\telse if(shaderIdx == 1) btnName = \"Material : Diffuse\";\n\tif ( GUI.Button(new Rect(posX, posY, btnSize.x, btnSize.y), btnName) ){\n\t\tChangeShader();\n\t}\n}", "emitClick() {\n clearTimeout(this.styleTmr);\n this.styleTmr = setTimeout(() => {\n this.ionClick.emit({ segmentButton: this });\n });\n }", "handleButton() {}", "get buttonClass() {\n return `sb-button sb-${this.theme}`;\n }", "bPadSouthPressed() {\n return this.buttonPressed(0)\n }", "get superscriptButton() {\n return {\n command: \"superscript\",\n icon: \"mdextra:superscript\",\n label: \"Superscript\",\n radio: true,\n type: \"rich-text-editor-button\",\n };\n }", "function toolThrSegment() {\n tool = document.getElementById('t');\n while (tool.firstChild) {\n tool.removeChild(tool.firstChild);\n }\n\n var pmIndexLabel = document.createElement('LABEL');\n pmIndexLabel.innerHTML = 'Class of Pixels to Segment';\n pmIndexLabel.style.left = 10;\n pmIndexLabel.style.top = 10;\n tool.appendChild(pmIndexLabel);\n\n var selectmenu = document.createElement('SELECT');\n selectmenu.setAttribute('name','selectmenu');\n selectmenu.setAttribute('id','selectmenu');\n var classLabels = ['Dark Pixels','Bright Pixels'];\n for (var i = 0; i < 2; i++) {\n var option = document.createElement('OPTION');\n option.value = i+1;\n option.innerHTML = classLabels[i];\n selectmenu.appendChild(option);\n }\n selectmenu.style.top = 30;\n tool.appendChild(selectmenu);\n\n // var labelStrings = ['Smoothness','Threshold','Fragmentation'];\n labelStrings = ['Smoothness','Threshold'];\n // var defaultSliderPositions = [50,33,67];\n var defaultSliderPositions = [0,50];\n for (var i = 0; i < labelStrings.length; i++) {\n var toolLabel = document.createElement('LABEL');\n toolLabel.innerHTML = labelStrings[i];\n toolLabel.style.left = 10;\n toolLabel.style.top = 70+i*45;\n tool.appendChild(toolLabel);\n var toolSlider = document.createElement('INPUT');\n toolSlider.setAttribute('type','range');\n toolSlider.setAttribute('min','0');\n toolSlider.setAttribute('max','100');\n toolSlider.setAttribute('value',defaultSliderPositions[i].toString());\n toolSlider.style.top = 80+i*45;\n tool.appendChild(toolSlider);\n }\n\n var buttonWidth = (tool.clientWidth-30)/2\n\n var buttonCompute = document.createElement('INPUT');\n buttonCompute.setAttribute('type','button');\n $(buttonCompute).button();\n buttonCompute.style.top = 80+labelStrings.length*45;\n buttonCompute.style.width = buttonWidth;\n buttonCompute.value = 'Compute';\n buttonCompute.onclick = function () { thrSegmentButtonClick('compute'); }\n tool.appendChild(buttonCompute);\n\n var buttonDone = document.createElement('INPUT');\n buttonDone.setAttribute('type','button');\n $(buttonDone).button();\n buttonDone.style.top = 80+labelStrings.length*45;\n buttonDone.style.width = buttonWidth;\n buttonDone.style.left = buttonWidth+20;\n buttonDone.value = 'Done';\n buttonDone.onclick = function () { thrSegmentButtonClick('done'); }\n tool.appendChild(buttonDone);\n\n tool.style.height = 80+labelStrings.length*45+40;\n\n showTool();\n}", "function indicatorSelect(indicateBtn)\n{\n change(indicateBtn.id);\n update(indicateBtn.id);\n}", "get scriptButtonGroup() {\n return {\n type: \"simple-toolbar-button-group\",\n subtype: \"script-button-group\",\n \"aria-label\": \"Subscript and Superscript\",\n buttons: [this.subscriptButton, this.superscriptButton],\n };\n }", "function buttonToggle(state)\n{\n\t//clear any existing selection and its outline\n\tif(selected != null)\n\t{\n\t\tselected.style.outline = 'none';\n\t\tselected = null;\n\t}\n\t\n\t//toggle button state class and value\n\tif(state == 'on')\n\t{\n\t\tbutton.className = 'on';\n\t\tbutton.innerHTML = 'Inspect <em>= ON</em>';\n\t}\n\telse\n\t{\n\t\tbutton.className = 'off';\n\t\tbutton.innerHTML = 'Inspect <em>= OFF</em>';\n\t}\n}", "get buttonContainer() {}", "_updateButtons() {\n var upButton = this.getChildControl(\"upbutton\");\n var downButton = this.getChildControl(\"downbutton\");\n var value = this.getValue();\n\n if (!this.getEnabled()) {\n // If Spinner is disabled -> disable buttons\n upButton.setEnabled(false);\n downButton.setEnabled(false);\n } else {\n if (this.getWrap()) {\n // If wraped -> always enable buttons\n upButton.setEnabled(true);\n downButton.setEnabled(true);\n } else {\n // check max value\n if (value !== null && value < this.getMaximum()) {\n upButton.setEnabled(true);\n } else {\n upButton.setEnabled(false);\n }\n\n // check min value\n if (value !== null && value > this.getMinimum()) {\n downButton.setEnabled(true);\n } else {\n downButton.setEnabled(false);\n }\n }\n }\n }", "function EBX_ButtonUtils() {}", "static get BUTTON_START() {\n return \"start\";\n }", "function createOpBtns() {\n\n}", "function EBX_ButtonUtils() {\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle NPC movement on map
npcMovement() { this.game.npcs.map((npc) => { // Next movement allowed in 2.5 seconds const nextActionAllowed = npc.lastAction + 2500; if (npc.lastAction === 0 || nextActionAllowed < Date.now()) { // Are they going to move or sit still this time? const action = UI.getRandomInt(1, 2) === 1 ? 'move' : 'nothing'; // NPCs going to move during this loop? if (action === 'move') { // Which way? const direction = ['up', 'down', 'left', 'right']; const going = direction[UI.getRandomInt(0, 3)]; // What tile will they be stepping on? const tile = { background: UI.getFutureTileID(this.game.map.background, npc.x, npc.y, going), foreground: UI.getFutureTileID(this.game.map.foreground, npc.x, npc.y, going), }; switch (going) { default: case 'up': if ((npc.y - 1) >= (npc.spawn.y - npc.range)) { if (UI.tileWalkable(tile.background) && UI.tileWalkable(tile.foreground)) { npc.y -= 1; } } break; case 'down': if ((npc.y + 1) <= (npc.spawn.y + npc.range)) { if (UI.tileWalkable(tile.background) && UI.tileWalkable(tile.foreground)) { npc.y += 1; } } break; case 'left': if ((npc.x - 1) >= (npc.spawn.x - npc.range)) { if (UI.tileWalkable(tile.background) && UI.tileWalkable(tile.foreground)) { npc.x -= 1; } } break; case 'right': if ((npc.x + 1) <= (npc.spawn.x + npc.range)) { if (UI.tileWalkable(tile.background) && UI.tileWalkable(tile.foreground)) { npc.x += 1; } } break; } } // Register their last action npc.lastAction = Date.now(); } return npc; }); }
[ "function move() {\n //moving map around\n loc.lat = map.getCenter().lat();\n loc.lng = map.getCenter().lng();\n loc.lat += dir.lat;\n loc.lng += dir.lng;\n map.panTo(loc);\n\n encounter(); //checking if player has walked over heatmap\n\n //checking if player has walked away enough to spawn new heatmap points, if so, spawns\n if (google.maps.geometry.spherical.computeDistanceBetween(\n map.getCenter(), lastLoc) > 500) {\n lastLoc = map.getCenter();\n spawnHeatmaps();\n }\n\n //checking to see if player has walked away from an open infoWindow and closes it\n if (infoWindow != null && google.maps.geometry.spherical.computeDistanceBetween(\n map.getCenter(), infoWindow.position) > 100) {\n infoWindow.close();\n infoWindow = null;\n }\n}", "static movement() {\n world.npcs.map((npc) => {\n // Next movement allowed in 2.5 seconds\n const nextActionAllowed = npc.lastAction + 2500;\n\n if (npc.lastAction === 0 || nextActionAllowed < Date.now()) {\n // Are they going to move or sit still this time?\n const action = UI.getRandomInt(1, 2) === 1 ? 'move' : 'nothing';\n\n // NPCs going to move during this loop?\n if (action === 'move') {\n // Which way?\n const direction = ['up', 'down', 'left', 'right'];\n const going = direction[UI.getRandomInt(0, 3)];\n\n // What tile will they be stepping on?\n const tile = {\n background: UI.getFutureTileID(world.map.background, npc.x, npc.y, going),\n foreground: UI.getFutureTileID(world.map.foreground, npc.x, npc.y, going) - 252,\n };\n\n // Can the NPCs walk on that tile in their path?\n const walkable = {\n background: UI.tileWalkable(tile.background),\n foreground: UI.tileWalkable(tile.foreground, 'foreground'),\n };\n\n const canWalkThrough = walkable.background && walkable.foreground;\n\n switch (going) {\n default:\n case 'up':\n if ((npc.y - 1) >= (npc.spawn.y - npc.range) && canWalkThrough) {\n npc.y -= 1;\n }\n break;\n case 'down':\n if ((npc.y + 1) <= (npc.spawn.y + npc.range) && canWalkThrough) {\n npc.y += 1;\n }\n break;\n case 'left':\n if ((npc.x - 1) >= (npc.spawn.x - npc.range) && canWalkThrough) {\n npc.x -= 1;\n }\n break;\n case 'right':\n if ((npc.x + 1) <= (npc.spawn.x + npc.range) && canWalkThrough) {\n npc.x += 1;\n }\n break;\n }\n }\n\n // Register their last action\n npc.lastAction = Date.now();\n }\n\n return npc;\n });\n\n // Tell the clients of the new NPCs\n Socket.broadcast('npc:movement', world.npcs);\n }", "function updateNPC(){\n\t\tnpc.lookAt(avatar.position);\n\n\t\t// moves the NPC to the avatar if it comes close\n\t\tif(avatar.position.distanceTo(npc.position)<20){\n\t\t\tnpc.setLinearVelocity(npc.getWorldDirection().multiplyScalar(5));\n\t\t\t// events in case of contact with the NPC\n\t\t\tif(gameState.collide == true){\n\t\t\t\tnpc.__dirtyPosition = true;\n\t\t\t\tnpc.position.set(randN(50),5,randN(50)); // no neg values yet\n\t\t\t\tgameState.collide = false;\n\t\t\t\tvar velocity = avatar.getLinearVelocity();\n\t\t\t\tvelocity.x=velocity.z=0;\n\t\t\t\tavatar.setLinearVelocity(velocity);\n\t\t\t}\n\t\t}\n\t}", "le_movement() {\n\t\t// lets the editor navigate the map\n\t\tlet ePos = this.editor.getComponent(\"transform\").pos;\n\t\tlet eSpeed = this.editor.getComponent(\"transform\").speed;\n\t\tlet eUI = this.entityManager.getEntities(\"editUI\");\n\t\tif (this.editor.getComponent(\"input\").up === true) {\n\t\t\tePos.y -= eSpeed.y;\n\t\t\tfor (let i = 0; i < eUI.length; i++) {\n\t\t\t\teUI[i].getComponent(\"transform\").pos.y -= eSpeed.y;\n\t\t\t}\n\t\t}\n\t\tif (this.editor.getComponent(\"input\").down === true) {\n\t\t\tePos.y += eSpeed.y;\n\t\t\tfor (let i = 0; i < eUI.length; i++) {\n\t\t\t\teUI[i].getComponent(\"transform\").pos.y += eSpeed.y;\n\t\t\t}\n\t\t}\n\t\tif (this.editor.getComponent(\"input\").right === true) {\n\t\t\tePos.x += eSpeed.x;\n\t\t\tfor (let i = 0; i < eUI.length; i++) {\n\t\t\t\teUI[i].getComponent(\"transform\").pos.x += eSpeed.x;\n\t\t\t}\n\t\t}\n\t\tif (this.editor.getComponent(\"input\").left === true) {\n\t\t\tePos.x -= eSpeed.x;\n\t\t\tfor (let i = 0; i < eUI.length; i++) {\n\t\t\t\teUI[i].getComponent(\"transform\").pos.x -= eSpeed.x;\n\t\t\t}\n\t\t}\n\t\t// tile and enemy movement\n\t\tlet t = this.entityManager.getEntities(\"tile\");\n\t\tlet e = this.entityManager.getEntities(\"enemy\");\n\t\tlet mEnts = t.concat(e);\n\t\tfor (let i = 0; i < mEnts.length; i++) {\n\t\t\tif (mEnts[i].hasComponent(\"movingTile\")) {\n\t\t\t\tif (mEnts[i].getComponent(\"transform\").pos.x >= mEnts[i].getComponent(\"movingTile\").p2) {\n\t\t\t\t\tmEnts[i].getComponent(\"movingTile\").speed = -mEnts[i].getComponent(\"movingTile\").speed;\n\t\t\t\t}\n\t\t\t\telse if (mEnts[i].getComponent(\"transform\").pos.x < mEnts[i].getComponent(\"movingTile\").p1) {\n\t\t\t\t\tmEnts[i].getComponent(\"movingTile\").speed = -mEnts[i].getComponent(\"movingTile\").speed;\n\t\t\t\t}\n\t\t\t\tmEnts[i].getComponent(\"transform\").pos.x += mEnts[i].getComponent(\"movingTile\").speed;\n\t\t\t}\n\t\t}\n\t}", "#move(){\n // collission condition\n let canMove = !this.tileMap.willCollideWith(WALL,this.j,this.i,this.chkNxtMovDir)\n\n //check if pacman wants to move in a new dir\n if(this.currMovDir !== this.chkNxtMovDir){\n //alert(\"wants to move...\");\n //if yes,check for collission and change dir\n if(canMove){\n //alert(\"No collission..\");\n //if no collission,then change currdir to new dir\n this.currMovDir = this.chkNxtMovDir;\n }// else alert(\"Collision...\"); \n } \n\n //move if no collission:- doesnt matter if its new dir or old dir the movement is in\n if(canMove){\n //move the pacman in the currDir\n //alert(\"Curr mov dir \" + this.currMovDir)\n switch(this.currMovDir){\n case up:\n this.i -= velocity;\n break;\n case down:\n this.i += velocity;\n break;\n case left:\n //console.log(\"Moving left...\");\n this.j -= velocity;\n break;\n case right:\n //alert(\"Moving right...\");\n this.j += velocity;\n break;\n default:\n // console.log(\"No way this is possible...\");\n break;\n }\n }\n }", "function MoveMainCharacter()\n{\n\tvar MoveDeltaX=DeltaX;\n\tvar MoveDeltaY=DeltaY;\n\t//x axis out of the map\n\tif(parseInt(-(Map.x-DeltaX-(ClientWidth/2-2*(57/2))))>=6195||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2)))>=6195||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2)))>=6195||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2-2*(57/2))))>=6195||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2-2*(57/2))))<=5||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2)))<=5||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2)))<=5||\n\t parseInt(-(Map.x-DeltaX-(ClientWidth/2-2*(57/2))))<=5)\n\t{\n\t\tMoveDeltaX=0;\n\t}\n\t//y axis out of the map, already success\n\tif(parseInt(-(Map.y-DeltaY-(ClientHeight/2-2*(67/2))))>=3568||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2)))>=3568||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2-2*(67/2))))>=3568||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2)))>=3568||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2-2*(67/2))))<=0||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2)))<=0||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2-2*(67/2))))<=0||\n\t parseInt(-(Map.y-DeltaY-(ClientHeight/2)))<=0)\n\t{\n\t\tMoveDeltaY=0;\n\t}\n\tif(MainCharacterType=='police')\n\t{\n\t\tfor(var i=1;i<=4;i++)\n\t\t{\n\t\t\tif(TrashCanStatus[i])\n\t\t\t{\n\t\t\t\tif(TrashCanPosition['rotation']==Math.PI/2)\n\t\t\t\t{\n\t\t\t\t\tvar PositionY1=TrashCanPosition[i]['y']-110;\n\t\t\t\t\tvar PositionY2=TrashCanPosition[i]['y']+110;\n\t\t\t\t\tvar PositionX=TrashCanPosition[i]['x'];\n\t\t\t\t\t\n\t\t\t\t\tvar PlayerPositionX=parseInt(ClientWidth/2-(57/2)-Map.x);\n\t\t\t\t\tvar PlayerPositionY=parseInt(ClientHeight/2-(67/2)-Map.y);\n\t\t\t\t\tif(show)\n\t\t\t\t\t\talert(Math.abs(PlayerPositionX+MoveDeltaX-PositionX)<200);\n\t\t\t\t\tif(Math.abs(PlayerPositionX+MoveDeltaX-PositionX)<=200)\n\t\t\t\t\t{\n\t\t\t\t\t\talert('true');\n\t\t\t\t\t\tMoveDeltaX=0;\n\t\t\t\t\t}\n\t\t\t\t\t// if(Math.abs(PlayerPositionX-PositionX)<=67&&\n\t\t\t\t\t// PlayerPositionY+MoveDeltaY>=PositionY1&&\n\t\t\t\t\t// PlayerPositionY+MoveDeltaY<=PositionY2)\n\t\t\t\t\t// {\n\t\t\t\t\t// \tMoveDeltaY=0;\n\t\t\t\t\t// }\n\t\t\t\t\t// if(Math.abs(PlayerPositionX+MoveDeltaX-PositionX)<=67&&\n\t\t\t\t\t// PlayerPositionY+MoveDeltaY>=PositionY1&&\n\t\t\t\t\t// PlayerPositionY+MoveDeltaY<=PositionY2)\n\t\t\t\t\t// {\n\t\t\t\t\t// \tMoveDeltaX=0;\n\t\t\t\t\t// \tMoveDeltaY=0;\n\t\t\t\t\t// }\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//still have some bug on it so just comment them.\n\t//have collision with other players\n\n\t//arrayname.forEach(function(e){});is a way to look all members in the array\n\tdataSync.forEach(function(e)\n\t{\n\t\t//not me and not the thing I hold\n\t\tif(e['ID']!=ID&&e['ID']!=HoldID)\n\t\t{\n\t\t\t\t//caculate the dis\n\t\t\t\tvar MainCharacterPositionX=parseInt(ClientWidth/2-(57/2)-Map.x)+MoveDeltaX;\n\t\t\t\tvar MainCharacterPositionY=parseInt(ClientHeight/2-(67/2)-Map.y);\n\t\t\t\tvar OtherCharacterPositionX=e['x'];\n\t\t\t\tvar OtherCharacterPositionY=e['y'];\n\t\t\t\tvar DistanceMainCharacterOtherCharacter = Distance(MainCharacterPositionX,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MainCharacterPositionY,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t OtherCharacterPositionX,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t OtherCharacterPositionY\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\t\t//if to close don't go\n\t\t\t\tif(DistanceMainCharacterOtherCharacter<57)\n\t\t\t\t\tMoveDeltaX=0;\n\t\t}\n\n\t});\n\n\t//same with the upper one\n\tdataSync.forEach(function(e)\n\t{\n\t\tif(e['ID']!=ID&&e['ID']!=HoldID)\n\t\t{\n\t\t\t//caculate the dis\n\t\t\tvar MainCharacterPositionX=parseInt(ClientWidth/2-(57/2)-Map.x);\n\t\t\tvar MainCharacterPositionY=parseInt(ClientHeight/2-(67/2)-Map.y)+MoveDeltaY;\n\t\t\tvar OtherCharacterPositionX=e['x'];\n\t\t\tvar OtherCharacterPositionY=e['y'];\n\t\t\tvar DistanceMainCharacterOtherCharacter = Distance(MainCharacterPositionX,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MainCharacterPositionY,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t OtherCharacterPositionX,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t OtherCharacterPositionY\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\tif(DistanceMainCharacterOtherCharacter<57)\n\t\t\t\tMoveDeltaY=0;\n\t\t}\n\n\t});\n\tif(MoveDeltaY&&MoveDeltaX)\n\t{\n\t\tif(MoveDeltaY>0)\n\t\t\tMoveDeltaY=5*Sqrt_2/2;\n\t\telse\n\t\t\tMoveDeltaY=-(5*Sqrt_2/2);\n\t\tif(MoveDeltaX>0)\n\t\t\tMoveDeltaX=5*Sqrt_2/2;\n\t\telse\n\t\t\tMoveDeltaX=-(5*Sqrt_2/2);\n\t}\n\t//if go x will get into the wall, stop the require\n\tif(!WallCollisionBox[parseInt(-(Map.x-DeltaX-(ClientWidth/2-2*(57/2))))][parseInt(-(Map.y-(ClientHeight/2-2*(67/2))))]\n\t &&!WallCollisionBox[parseInt(-(Map.x-DeltaX-(ClientWidth/2)))][parseInt(-(Map.y-(ClientHeight/2)))]\n\t &&!WallCollisionBox[parseInt(-(Map.x-DeltaX-(ClientWidth/2)))][parseInt(-(Map.y-(ClientHeight/2-2*(67/2))))]\n\t &&!WallCollisionBox[parseInt(-(Map.x-DeltaX-(ClientWidth/2-2*(57/2))))][parseInt(-(Map.y-(ClientHeight/2)))])\n\t{\n\t\tMap.x-=MoveDeltaX;\n\t\tdataSync.forEach(function(e){\n\t\t\tif(e['ID']!=ID)//not yourself\n\t\t\t{\n\t\t\t\t//if you are not exist create other player\n\t\t\t\tif(!OtherPlayersNormal[e['ID']])\n\t\t\t\t\tDrawOtherCharacter(e);\n\n\t\t\t\t//set position\n\t\t\t\tOtherPlayersNormal[e['ID']].x-=MoveDeltaX;\n\t\t\t\tOtherPlayersLean[e['ID']].x-=MoveDeltaX;\n\t\t\t}\n\t\t});\n\t}\n\n\t//if go y will get into the wall, stop the require\n\tif(!WallCollisionBox[parseInt(-(Map.x-(ClientWidth/2-2*(57/2))))][parseInt(-(Map.y-DeltaY-(ClientHeight/2-2*(67/2))))]\n\t &&!WallCollisionBox[parseInt(-(Map.x-(ClientWidth/2)))][parseInt(-(Map.y-DeltaY-(ClientHeight/2)))]\n\t &&!WallCollisionBox[parseInt(-(Map.x-(ClientWidth/2)))][parseInt(-(Map.y-DeltaY-(ClientHeight/2-2*(67/2))))]\n\t &&!WallCollisionBox[parseInt(-(Map.x-(ClientWidth/2-2*(57/2))))][parseInt(-(Map.y-DeltaY-(ClientHeight/2)))])\n\t{\n\t\tMap.y-=MoveDeltaY;\n\t\tdataSync.forEach(function(e){\n\t\t\tif(e['ID']!=ID)//not yourself\n\t\t\t{\n\t\t\t\t//if you are not exist create other player\n\t\t\t\tif(!OtherPlayersNormal[e['ID']])\n\t\t\t\t\tDrawOtherCharacter(e);\n\n\t\t\t\t//set position\n\t\t\t\tOtherPlayersNormal[e['ID']].y-=MoveDeltaY;\n\t\t\t\tOtherPlayersLean[e['ID']].y-=MoveDeltaY;\n\t\t\t}\n\t\t});\n\t}\n\t//caculate the real position and send to the server.\n\tvar PositionX;\n\tvar PositionY;\n\tPositionX=parseInt(ClientWidth/2-(57/2)-Map.x);\n\tPositionY=parseInt(ClientHeight/2-(67/2)-Map.y);\n\tSendToServer(\"SyncData\",{\"name\":Name,\"ID\":ID,\"x\":PositionX,\"y\":PositionY,\"rotation\":MouseAngle,\"action\":MainCharaLeanStatus,\"type\":MainCharacterType});\n}", "async function moveNPC() {\n await npc.walkNorth(1400)\n await npc.walkEast(1200)\n await npc.walkSouth(300)\n await npc.walkEast(1500)\n await npc.walkSouth(1500)\n await npc.walkWest(2700)\n await npc.walkNorth(400)\n}", "customMovement(){}", "function pacMove() {\n if (directionPM == 1) {\n if (maze[pacman.y][pacman.x-1] ==7 || maze[pacman.y][pacman.x-1] ==9 || maze[pacman.y][pacman.x-1] ==10 || maze[pacman.y][pacman.x-1] ==11) {\n pacman.x = 14;\n pacman.y = 23;\n lives--;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y][pacman.x-1] ==6) {\n maze[pacman.y][pacman.x] = 3;\n pacman.x = 26;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y][pacman.x-1] ==4) {\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y][pacman.x-1] !==1) {\n if (maze[pacman.y][pacman.x-1] ==2) {\n maze[pacman.y][pacman.x] = 3;\n pacman.x = pacman.x - 1;\n maze[pacman.y][pacman.x] = 5;\n score += 100;\n drawMaze();\n } else {\n maze[pacman.y][pacman.x] = 3;\n pacman.x = pacman.x - 1;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n }\n }\n } else if (directionPM == 2) {\n $(\".pacman\").css(\"transform\",\"rotate(270deg)\");\n if (maze[pacman.y-1][pacman.x] ==7 || maze[pacman.y-1][pacman.x] ==9 || maze[pacman.y-1][pacman.x] ==10 || maze[pacman.y-1][pacman.x] ==11) {\n pacman.x = 14;\n pacman.y = 23;\n lives--;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y-1][pacman.x] ==4) {\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y-1][pacman.x] !==1) {\n if (maze[pacman.y-1][pacman.x] ==2) {\n maze[pacman.y][pacman.x] = 3;\n pacman.y = pacman.y - 1;\n maze[pacman.y][pacman.x] = 5;\n score += 100;\n drawMaze();\n } else {\n maze[pacman.y][pacman.x] = 3;\n pacman.y = pacman.y - 1;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n }\n }\n } else if (directionPM == 3) {\n $(\".pacman\").css(\"transform\",\"rotate(0deg)\");\n if (maze[pacman.y][pacman.x+1] ==7 || maze[pacman.y][pacman.x+1] ==9 || maze[pacman.y][pacman.x+1] ==10 || maze[pacman.y][pacman.x+1] ==11) {\n pacman.x = 14;\n pacman.y = 23;\n lives--;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y][pacman.x+1] ==4) {\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y][pacman.x+1] ==6) {\n maze[pacman.y][pacman.x] = 3;\n pacman.x = 1;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y][pacman.x+1] !==1) {\n if (maze[pacman.y][pacman.x+1] ==2) {\n maze[pacman.y][pacman.x] = 3;\n pacman.x = pacman.x + 1;\n maze[pacman.y][pacman.x] = 5;\n score += 100;\n drawMaze();\n } else {\n maze[pacman.y][pacman.x] = 3;\n pacman.x = pacman.x + 1;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n }\n }\n } else if (directionPM == 4) {\n $(\".pacman\").css(\"transform\",\"rotate(90deg)\");\n if (maze[pacman.y+1][pacman.x] ==7 || maze[pacman.y+1][pacman.x] ==9 || maze[pacman.y+1][pacman.x] ==10 || maze[pacman.y+1][pacman.x] ==11) {\n pacman.x = 14;\n pacman.y = 23;\n lives--;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y+1][pacman.x] ==4) {\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else if (maze[pacman.y+1][pacman.x] !==1) {\n if (maze[pacman.y+1][pacman.x] ==2) {\n maze[pacman.y][pacman.x] = 3;\n pacman.y = pacman.y + 1;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n } else {\n maze[pacman.y][pacman.x] = 3;\n pacman.y = pacman.y + 1;\n maze[pacman.y][pacman.x] = 5;\n drawMaze();\n }\n }\n }\n }", "moveActor() {\n // used to work as tunnel if left and right are empty pacman/ghosts can easily move in tunnel\n if (this.tileTo[0] < -1) {\n this.tileTo[0] = this.gameMap.layoutMap.column;\n }\n if (this.tileTo[0] > this.gameMap.layoutMap.column) {\n this.tileTo[0] = -1;\n }\n\n // used to work as tunnel if top and bottom are empty pacman/ghosts can easily move in tunnel\n if (this.tileTo[1] < -1) {\n this.tileTo[1] = this.gameMap.layoutMap.row;\n }\n if (this.tileTo[1] > this.gameMap.layoutMap.row) {\n this.tileTo[1] = -1;\n }\n\n // as our pacman/ghosts needs to move constantly widthout key press,\n // also pacman/ghosts should stop when there is obstacle the code has become longer\n\n // if pacman/ghosts is moving up check of upper box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.UP) {\n if (this.isBlockUpperThanActorEmpty()) {\n this.tileTo[1] -= 1;\n }\n }\n\n // if pacman/ghosts is moving down check of down box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.DOWN) {\n if (this.isBlockLowerThanActorEmpty()) {\n this.tileTo[1] += 1;\n }\n }\n\n // if pacman/ghosts is moving left check of left box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.LEFT) {\n if (this.isBlockLeftThanActorEmpty()) {\n this.tileTo[0] -= 1;\n }\n }\n\n // if pacman/ghosts is moving right check of right box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.RIGHT) {\n if (this.isBlockRightThanActorEmpty()) {\n this.tileTo[0] += 1;\n }\n }\n }", "move() {\n //Move the kid to the determined location\n this.x = this.nextMoveX;\n this.y = this.nextMoveY;\n //Check in case the kid touches the edges of the map,\n // if so, prevent them from leaving.\n this.handleConstraints();\n }", "movePlayer(direction){\n console.log(\"Moving \" + direction);\n\n this.movement = [0,0];\n\n switch (direction) {\n case \"west\":\n this.movement = [-1,0];\n break;\n case \"east\":\n this.movement = [1,0];\n break;\n case \"north\":\n this.movement = [0,-1];\n break;\n case \"south\":\n this.movement = [0,1];\n break;\n default:\n console.log(direction + \" is not a valid direction.\");\n }\n\n //If the square that he player is trying to move in to is a wall, do not move\n if(this.randomMap[this.currentLocation[0]+this.movement[0]][this.currentLocation[1] + this.movement[1]] == -1){\n return;\n }\n\n //Itterate the counter\n this.timeInCave++;\n console.log(\"Time in cave: \" + this.timeInCave);\n\n //Move the player in hte desired direction\n this.currentLocation[0] += this.movement[0];\n this.currentLocation[1] += this.movement[1];\n\n console.log(this.currentLocation + \" -- \" + this.initialLocation);\n\n this.updateScreen();\n\n }", "move(){\n if(this.checkPosition()){ //checks if pacman is facing a wall\n this.pos.add(this.vel);//moves pacman\n }\n }", "changePos(delta) {\r\n var deltaTime = delta/20;\r\n if (deltaTime > 5) {\r\n deltaTime = 0;\r\n }\r\n this.position.y += this.movement.y*deltaTime;\r\n this.position.x += this.movement.x*deltaTime;\r\n if(this.game.player.unit === this && this.moving) { //Sends player's unit position to the server\r\n this.socket.emit('Change position', this.number, this.position.x, this.position.y);\r\n }\r\n //Restricts walkable zone\r\n this.checkBorder();\r\n\r\n if(!this.alive) { //Removes unit outside of the map while being dead\r\n this.position.y = -100;\r\n }\r\n }", "function move_event(dir){\r\n\t\t// crash wall\r\n\t\tif( stat.map[stat.pos].movable[dir] == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\t\r\n\t\t//dir\r\n\t\tvar x = [1,-1,0,0];\r\n\t\tvar y = [0,0,1,-1];\r\n\t\t\r\n\t\t//target\r\n\t\tvar targetPoint = stat.pos + x[dir] + y[dir] * stat.map.size;\r\n\t\t\r\n\t\tif(targetPoint == stat.map.size * stat.map.size - 1){\r\n\t\t\tvar enemy = {atk : 20,\r\n\t\t\t\t\t\thp : 100,\r\n\t\t\t\t\t\tspd : 3,\r\n\t\t\t\t\t\texp : 0,\r\n\t\t\t\t\t\tpos : targetPoint,\r\n\t\t\t\t\t\tstat : 0,\r\n\t\t\t\t\t\tboss : true};\r\n\t\t\tfighting(enemy,stat,dir);\r\n\t\t\tstat.pos = targetPoint ;\r\n\t\t\treturn 2;\r\n\t\t}\r\n\t\t\r\n\t\t// space\r\n\t\telse if( stat.map[targetPoint].thing == 0 ){ \r\n\t\t\tstat.pos = targetPoint ;\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\t\r\n\t\t// enemy\r\n\t\telse if( stat.map[targetPoint].thing > 0) {\r\n\t\t\tvar enemy = stat.map.enemyInfo[stat.map[targetPoint].thing - 1];\r\n\t\t\t// exist\r\n\t\t\tif( enemy.stat == 0){ \r\n\t\t\t\tfighting(enemy,stat,dir);\r\n\t\t\t\tstat.pos = targetPoint;\r\n\t\t\t\treturn 2;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tstat.pos = targetPoint ;\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if( stat.map[targetPoint].thing < 0){\r\n\t\t\tvar chest = stat.map.chestInfo[-stat.map[targetPoint].thing - 1];\r\n\t\t\t// exist\t\r\n\t\t\tif( chest.stat == 0 ){ \r\n\t\t\t\tItemGet(stat.pc,chest);\r\n\t\t\t\tstat.pos = targetPoint ;\r\n\t\t\t\treturn 3;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tstat.pos = targetPoint ;\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function moveNpc (direction) {\n\tnpc.newSpriteX = npc.spriteX;\n\tnpc.newSpriteY = npc.spriteY;\n\tif (direction == \"Up\") {npc.newSpriteY = npc.newSpriteY - 44}\n\tif (direction == \"Down\") {npc.newSpriteY = npc.newSpriteY + 44}\n\tif (direction == \"Left\") {npc.newSpriteX = npc.newSpriteX - 44}\n\tif (direction == \"Right\") {npc.newSpriteX = npc.newSpriteX + 44}\n\tmoveElement (npc.divId, npc.newSpriteX, npc.newSpriteY);\n}", "move() {\n if (this.moving) {\n if (!this.behavior) {\n // TODO: check map to see if we can move\n this.x += this.vx;\n this.y += this.vy;\n\n // gravity impacts velocity\n this.vy -= this.gravity;\n } else {\n this.behavior.onMove();\n }\n\n if (this.children.length) {\n this.children.forEach((child) => {\n child.move();\n });\n }\n\n // TODO: check map to see if we can move\n /* this.x += this.vx;\n this.y += this.vy; */\n }\n }", "function entitiesMove(pos, PM) {\n\tentities.forEach(function(ele) {\n\t\tif (pos == 'x') {\n\t\t\tif (PM == 'P') {\n\t\t\t\tele.pos.x -= 1;\n\t\t\t} else if (PM == 'M') {\n\t\t\t\tele.pos.x += 1;\n\t\t\t}\n\t\t} else if (pos == 'y') {\n\t\t\tif (PM == 'P') {\n\t\t\t\tele.pos.y -= 1;\n\t\t\t} else if (PM == 'M') {\n\t\t\t\tele.pos.y += 1;\n\t\t\t}\n\t\t}\n\t});\n\tplayerList.forEach(function(ele) {\n\t\tif (pos == 'x') {\n\t\t\tif (PM == 'P') {\n\t\t\t\tele.pos.x -= 1;\n\t\t\t} else if (PM == 'M') {\n\t\t\t\tele.pos.x += 1;\n\t\t\t}\n\t\t} else if (pos == 'y') {\n\t\t\tif (PM == 'P') {\n\t\t\t\tele.pos.y -= 1;\n\t\t\t} else if (PM == 'M') {\n\t\t\t\tele.pos.y += 1;\n\t\t\t}\n\t\t}\n\t});\n\tif (currentStage.enemies != undefined) {\n\t\tcurrentStage.enemies.forEach(function(ele) {\n\t\t\tif (pos == 'x') {\n\t\t\t\tif (PM == 'P') {\n\t\t\t\t\tele.pos.x -= 1;\n\t\t\t\t} else if (PM == 'M') {\n\t\t\t\t\tele.pos.x += 1;\n\t\t\t\t}\n\t\t\t} else if (pos == 'y') {\n\t\t\t\tif (PM == 'P') {\n\t\t\t\t\tele.pos.y -= 1;\n\t\t\t\t} else if (PM == 'M') {\n\t\t\t\t\tele.pos.y += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}", "function resetPlayerPositionOnMap() {\n if (playerCoords.ValBeforeUpdate == goal.Val || playerCoords.ValBeforeUpdate == blockInGoal.Val) { // check if element that player is located at, is a goal or block in the goal\n tileMap.mapGrid[playerCoords.Row][playerCoords.Col] = goal.Val;\n EditDrawnElement(goal.Val, playerCoords);\n } else {\n tileMap.mapGrid[playerCoords.Row][playerCoords.Col] = space.Val;\n EditDrawnElement(space.Val, playerCoords);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a page for setting moderator
function load_add_remove_moderator_page() { page = 'add_remove_moderator'; load_page(); }
[ "function _settings_page() {\n}", "function loadPrivilegeSettingsPage(clearMsgs){\n clearMessages(clearMsgs);\n loadPageData(\"showAcessesPrivilegePage.html\",\"Privilege Settings\");\n}", "function ShowModeratorPage() {\r\n\tBuildApplications();\r\n\tdocument.getElementById(\"formSelector\").style.display = \"none\";\r\n\tdocument.getElementById(\"applicationForm\").style.display = \"none\";\r\n\tdocument.getElementById(\"dataForm\").style.display = \"none\";\r\n\tdocument.getElementById(\"moderatorPage\").style.display = \"block\";\r\n}", "function loadPage() {\n //checks if the user has correct permissions first\n if (data.admin || data.lead) {\n document.getElementById('admin').style.visibility = \"initial\";\n generateList();\n } else {\n window.location.replace(\"home.html\");\n }\n}", "settingsPage() {\r\n Actions.settingsPage()\r\n }", "function staffMemberOnLoad() {\n setMenu(\"Staff\", \"Admin\")\n var pageParams = getParams(window.location.href)\n\n if (\"StaffID\" in pageParams) {\n loadStaffMember(pageParams[\"StaffID\"])\n } else {\n document.getElementById(\"edits\").style.display = \"none\"\n }\n}", "function loadEditingPage(groupId){\n editorGroupId = groupId;\n buildGroupInfoHTML(groupId);\n buildParticipantListHTML(groupId);\n buildEditingPageButtonsHTML(groupId);\n groupListPageDOM.hide();\n groupEditingPageDOM.show();\n}", "function load_update_user_page() {\n page = 'update_user';\n load_page(load_update_user_data);\n}", "function loadSettings() {\n\t$.ajax({\n\t\turl: \"/settings\",\n\t\tcontext: document.body\n\t}).done(function(response) {\n\t\t$('.settings-form').html(response);\n\t});\n}", "function loadAdminUX ()\n{\n let toLoad = 'admin.html';\n $.when($.get(toLoad)).done(function (page)\n {$('#body').empty();\n $('#body').append(page);\n updatePage('admin');\n listMemRegistries();\n });\n}", "function onModuleSettingsSaveSuccess() {\n\t$(\"#popup\").find('.content').load('?action=edit_module_settings');\n\treloadEverything(function() { showFlash('Modulinnstillinger lagret', 'success')});\n}", "openEditPage(sid) {\n ipcRenderer.send('load', {page: 'teachers_edit', id: sid, type: 'teacher', currentPage: 'teachers'})\n }", "function loadAdmin() {\n\tvar city = getSelectedCity();\n\tloadNews(city);\n}", "function loadEditModal() {\n // spin('user-right-side');\n // Populate dishes tab on page load\n let getUrl = `${server}/user/profile-edit`;\n\n goGet(getUrl).then((res) => {\n $(\"#edit-modal-container\").html(res);\n }).catch((err) => {\n //spin('user-right-side');\n });\n}", "function mjk_gt_edit_page($page) {\n $pid = mjk_gt_read_dropdown($page, 'pid');\n window.open(MJKGTSchedulerAjax.home_url.concat('/wp-admin/post.php?post=',\n $pid, '&action=edit'), '_blank');\n}", "function loadHelpPage(page) {\n $('#helpPageContent').load(page);\n $('#helpPageContent').css(\"display\", \"none\");\n $('#helpPageContent').fadeIn(600);\n //Make active sidebar link highlighted\n //$('#managingUsers').css(\"color\", \"white\");\n //Reset all sidenav colors\n $('.sidenav > a').css(\"color\", \"grey\");\n $('.sidenav > a[href=\"#' + page + '\"]').css(\"color\", \"white\");\n}", "function setStoryModule()\n{\n var storyID = $('#story').val();\n if(storyID)\n {\n var link = createLink('story', 'ajaxGetModule', 'storyID=' + storyID);\n $.get(link, function(moduleID)\n {\n $('#module').val(moduleID);\n });\n }\n}", "function loadTopicsPage() {\n\t\twindow.location.href = 'topics.html'\n\t\tsetUserID()\n\t}", "function load_report_page() {\n page = 'user_help';\n load_page();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by AgtypeParseragType.
exitAgType(ctx) { }
[ "exitParse(ctx) {\n\t}", "exitElementType(ctx) {\n\t}", "exitCompile_type_clause(ctx) {\n\t}", "exitReportGroupTypeClause(ctx) {\n\t}", "endParsing() {\n\n\t\t// Skip ending whitespace\n\t\tthis.skipWhitespace();\n\n\t\t// Check for container to select it as the value\n\t\tif (this.container) {\n\t\t\tthis.value = this.container;\n\t\t}\n\n\t\t// Validate parser state\n\t\tif (this.chunk[this.index] || this.stack.length) {\n\t\t\tthis.stopParsing();\n\t\t} else {\n\t\t\tthis.result = this.value;\n\t\t\tthis.emit('result', this.result);\n\t\t}\n\t}", "exitType_declaration(ctx) {\n\t}", "exitNestedExpressionAtom(ctx) {\n\t}", "exitTypeAnnotation(ctx) {\n }", "exitSubprog_decl_in_type(ctx) {\n\t}", "exitTypeSpecifier(ctx) {\n\t}", "exitCompilationUnit(ctx) {\n\t}", "exitSubtype_declaration(ctx) {\n\t}", "exitNested_table_type_def(ctx) {\n\t}", "exitType_body(ctx) {\n\t}", "exitReportGroupTypeDetail(ctx) {\n\t}", "exitTypeQualifier(ctx) {\n\t}", "exitAnalyze(ctx) {\n\t}", "exitType_definition(ctx) {\n\t}", "exitStructOrUnion(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
options: object with text: string pitch: optional number between 0 and 2. prompt: optional boolean (default false), whether to listen for a response after speaking
speak(options, callback) { const utterance = new SpeechSynthesisUtterance(options.text); // Workaround for Chrome garbage collection causing "end" event to fail to fire. // https://bugs.chromium.org/p/chromium/issues/detail?id=509488#c11 window.utterance = utterance; if (typeof options.pitch !== "undefined") { utterance.pitch = options.pitch; } utterance.onend = () => { if (options.prompt) { this.waiting_for_input = true; this.resume_listening(); } if (callback) { callback(); } }; this.pause_listening(); window.speechSynthesis.speak(utterance); }
[ "function speakPolitely(option) {\n option = Object.create(option);\n option.polite = true;\n speak(option);\n }", "function speakHanlder() {\n // Object for speech synthesis\n const utterThis = new SpeechSynthesisUtterance(text.value);\n // Get the voice selected by the user\n const selectedOption = voiceSelect.selectedOptions[0].getAttribute(\n 'data-name'\n );\n\n // Configure the voice by setting up it's required values\n utterThis.voice = voices.find((value) => value.name === selectedOption);\n utterThis.rate = rate.value;\n utterThis.pitch = pitch.value;\n // Function that performs speak action\n synth.speak(utterThis);\n}", "function speakText() {\nsynth.speak(message)\n}", "function CLC_Say(messagestring, pitch) {\r\n if (CLC_TTS_ENGINE == 0){\r\n return;\r\n }\r\n if ((pitch > 2) || (pitch < -2)){\r\n alert(\"Invalid pitch\");\r\n return;\r\n }\r\n if (CLC_TTS_ENGINE == 1){\r\n pitch = pitch * 5;\r\n messagestring = CLC_SAPI5_FixMessage(messagestring);\r\n var SAPI5_XML_STR = '<pitch middle=\"' + pitch + '\">' + messagestring + '</pitch>';\r\n //Set language\r\n var langid = CLC_SAPI5_FindLangID(CLC_LANG);\r\n if (langid){\r\n SAPI5_XML_STR = '<lang langid=\"' + langid + '\">' + SAPI5_XML_STR + '</lang>'; \r\n }\r\n CLC_SAPI5_OBJ.Speak(SAPI5_XML_STR,1);\r\n }\r\n if (CLC_TTS_ENGINE == 2){\r\n pitch = (pitch * 25) + 100; \r\n CLC_FREETTS_OBJ.Speak(messagestring, pitch, CLC_FreeTTS_DefaultRange, CLC_FreeTTS_DefaultRate, CLC_FreeTTS_DefaultVolume, \"\");\r\n }\r\n if (CLC_TTS_ENGINE == 3){\r\n //Orca cannot do pitch, just ignore that for now\r\n CLC_Orca_Prep();\r\n CLC_ORCA_OBJ.send(\"speak: \" + messagestring); \r\n }\r\n if (CLC_TTS_ENGINE == 4){\r\n //Emacspeak cannot do pitch, just ignore that for now\r\n CLC_Emacspeak_CleanUp();\r\n CLC_Emacspeak_Prep();\r\n CLC_EMACSPEAK_OBJ.send(\"speak: \" + messagestring); \r\n }\r\n if (CLC_TTS_ENGINE == 5){\r\n var speechProperties = new Array();\r\n var pitchProperty = new Array();\r\n pitchProperty.push(pitch);\r\n pitchProperty.push(2);\r\n speechProperties.push(pitchProperty);\r\n CLC_SayWithProperties(messagestring, speechProperties, new Array());\r\n }\r\n }", "Speak(string, SpeechVoiceSpeakFlags) {\n\n }", "function speakText(response) {\n\n // setup synthesis\n var msg = new SpeechSynthesisUtterance();\n var voices = window.speechSynthesis.getVoices();\n msg.voice = voices[2];\t\t\t\t\t// Note: some voices don't support altering params\n msg.voiceURI = 'native';\n msg.volume = 1;\t\t\t\t\t\t\t// 0 to 1\n msg.rate = 1;\t\t\t\t\t\t\t// 0.1 to 10\n msg.pitch = 2;\t\t\t\t\t\t\t// 0 to 2\n msg.text = response;\n msg.lang = 'en-US';\n\n speechSynthesis.speak(msg);\n }", "outputPrompt(){\n return ['<speak>'].concat(this.get('speech')).concat(this.get('prompts.last')).concat('</speak>').join('\\n');\n }", "function CLC_Shout(messagestring, pitch) {\r\n if (CLC_TTS_ENGINE == 0){\r\n return;\r\n }\r\n if ((pitch > 2) || (pitch < -2)){\r\n alert(\"Invalid pitch\");\r\n return;\r\n }\r\n if (CLC_TTS_ENGINE == 1){\r\n pitch = pitch * 5;\r\n messagestring = CLC_SAPI5_FixMessage(messagestring);\r\n var SAPI5_XML_STR = '<pitch middle=\"' + pitch + '\">' + messagestring + '</pitch>';\r\n //Set language\r\n var langid = CLC_SAPI5_FindLangID(CLC_LANG);\r\n if (langid){\r\n SAPI5_XML_STR = '<lang langid=\"' + langid + '\">' + SAPI5_XML_STR + '</lang>'; \r\n }\r\n CLC_SAPI5_OBJ.Speak(SAPI5_XML_STR,3);\r\n }\r\n if (CLC_TTS_ENGINE == 2){\r\n pitch = (pitch * 25) + 100; \r\n CLC_FREETTS_SPEECHBUFFER = messagestring;\r\n CLC_FREETTS_PITCHBUFFER = pitch;\r\n window.setTimeout('CLC_FREETTS_OBJ.Shout(CLC_FREETTS_SPEECHBUFFER, CLC_FREETTS_PITCHBUFFER, CLC_FreeTTS_DefaultRange, CLC_FreeTTS_DefaultRate, CLC_FreeTTS_DefaultVolume, \"\")',0);\r\n }\r\n if (CLC_TTS_ENGINE == 3){\r\n //Orca cannot do pitch, just ignore that for now\r\n CLC_Interrupt();\r\n CLC_Orca_Prep();\r\n CLC_ORCA_OBJ.send(\"speak: \" + messagestring); \r\n }\r\n if (CLC_TTS_ENGINE == 4){\r\n //Emacspeak cannot do pitch, just ignore that for now\r\n CLC_Interrupt();\r\n CLC_Emacspeak_Prep();\r\n CLC_EMACSPEAK_OBJ.send(\"speak: \" + messagestring); \r\n }\r\n if (CLC_TTS_ENGINE == 5){\r\n var speechProperties = new Array();\r\n var pitchProperty = new Array();\r\n pitchProperty.push(pitch);\r\n pitchProperty.push(2);\r\n speechProperties.push(pitchProperty);\r\n CLC_ShoutWithProperties(messagestring, speechProperties, new Array());\r\n }\r\n }", "function heardSpeech(options) {\n // Get the least likely thing they said by using pop() to get the last element\n // in the array of options\n let worstAnswer = options.pop();\n // Set that as the answer to the current question\n data[currentQuestion].answer = worstAnswer;\n // Go to the next question\n currentQuestion++;\n // If that was the last question already (we went to the end of the array)\n // then stop listening to the user by removing the callback\n if (currentQuestion >= data.length) {\n annyang.removeCallback(`result`);\n }\n}", "function speakText(response,clear) {\r\n\tif (clear == undefined)\r\n\t\t$(\".response\").text(response);\r\n\telse\r\n\t\t$(\".response\").text($(\".response\").text()+\" \"+response);\r\n\t// setup synthesis\r\n\tif (!msg) {\r\n\t\tmsg = new SpeechSynthesisUtterance();\r\n\t\tvar voices = window.speechSynthesis.getVoices();\r\n\t\tmsg.voice = voices[1];\t\t\t\t\t// Note: some voices don't support altering params\r\n\t\tmsg.voiceURI = 'native';\r\n\t\tmsg.volume = 1;\t\t\t\t\t\t\t// 0 to 1\r\n\t\tmsg.rate = 1;\t\t\t\t\t\t\t// 0.1 to 10\r\n\t\tmsg.pitch = 1;\t\t\t\t\t\t\t// 0 to 2\r\n\t\tmsg.lang = 'fr-FR';\r\n\t}\r\n\tmsg.text = response;\r\n\tspeechSynthesis.speak(msg);\r\n}", "say(){\n\t\tvar _this = this;\n\t\tvar log = log4js.getLogger(_this.chan);\n\t\tlog.setLevel(config.debug_level);\n\n\t\tif(!arguments || arguments.length < 1) return;\n\n\t\tvar msg = arguments[0];\n\t\tvar options = {};\n\t\tvar level = 1;\n\n\t\tif(arguments.length > 1){\n\t\t\tlevel = typeof arguments[1] === \"number\" ? arguments[1] : (msg.succ || msg.err ? 2 : 1);\n\t\t\toptions = typeof arguments[1] === \"object\" ? arguments[1] : {};\n\t\t\tif(arguments.length > 2){\n\t\t\t\toptions = typeof arguments[2] === \"object\" ? arguments[2] : {};\n\t\t\t}\n\t\t}\n\n\t\tvar lines_orj = options.lines;\n\n\t\toptions = Object.assign({}, {\n\t\t\tis_pm: _this.is_pm,\n\t\t\tis_cmd: false, //set true if this is a reply to a command\n\t\t\tnick: null, //nick that initated speak\n\t\t\tchan: _this.chan, //chan spoken from\n\t\t\tto: null, //send message to user/chan\n\t\t\turl: '', //if you have a url you want tacked on to the end of message after it's been verified (like a read more)\n\t\t\tskip_verify: false, //will attempt to say the message AS IS\n\t\t\tignore_bot_speak: false, //doesn't update bot speak interval, and ignores limit_bot_speak_when_busy if true\n\t\t\tskip_buffer: false, //if true, says string without adding it to buffer\n\t\t\tcopy_buffer_to_user: false, //if true, copy buffer from chan to nick before speaking to user\n\t\t\tpage_buffer: false, //if true, instead of saying message, pages the buffer\n\t\t\tjoin: ' ', //join buffer\n\t\t\tlines: 5, //lines to display from buffer\n\t\t\tforce_lines: false, //if true, then overrides any line setting options\n\t\t\tellipsis: null, //if true add ... after text in buffer cutoff\n\t\t\ttable: false, //if true, tries to take an array of object and convert them to a table\n\t\t\ttable_opts: {} //set table = true, these are the options for tabeling, see this.table\n\t\t}, options);\n\n\t\tif(msg && msg.err){ //if this is an error\n\t\t\tmsg = this.t.fail('Error: ' + msg.err);\n\t\t\toptions.skip_verify = true;\n\t\t\toptions.skip_buffer = true;\n\t\t\toptions.ignore_bot_speak = true;\n\t\t\toptions.ellipsis = false;\n\t\t}\n\n\t\tif(msg && msg.succ){ //if this is a success\n\t\t\tmsg = this.t.success(msg.succ);\n\t\t\toptions.skip_verify = true;\n\t\t\toptions.skip_buffer = true;\n\t\t\toptions.ignore_bot_speak = true;\n\t\t\toptions.ellipsis = false;\n\t\t}\n\n\t\t//if level = 2, and we want less chan spam, send to PM\n\t\tif(level === 2 && this.config.less_chan_spam){\n\t\t\tlevel = 3;\n\t\t} else if (level === 2 && !this.config.less_chan_spam){ //otherwise send to chan\n\t\t\tlevel = 1;\n\t\t}\n\n\t\tif(options.table && Array.isArray(msg)){\n\t\t\tmsg = _this.table(msg, options.table_opts);\n\t\t\toptions.join = '\\n';\n\t\t}\n\n\t\t//we're not forcing this to go anywhere in specific\n\t\tif(options.to === null){\n\t\t\tif(options.chan === null && options.nick !== null){ //this is a pm, send to the nick\n\t\t\t\toptions.to = options.nick;\n\t\t\t\toptions.is_pm = true;\n\t\t\t\tlevel = 3;\n\t\t\t} else if(options.chan === null && options.nick === null){ //nowhere to send this\n\t\t\t\tlog.error(1, 'No where to send message: ' + msg);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t if(level === 1){ //send to chan\n\t\t\t\t\tif(options.chan === null){ //well this should go to a chan, but we don't have a chan\n\t\t\t\t\t\tlog.error('No chan to send message to: ' + msg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\toptions.to = options.chan;\n\t\t\t\t\t\toptions.is_pm = false;\n\t\t\t\t\t\tlevel = 1;\n\t\t\t\t\t}\n\t\t\t } else { //send to pm\n\t\t\t\t\tif(options.nick === null){ //well this should go to a pm, but we don't have a nick\n\t\t\t\t\t\tlog.error('No user to send pm to: ' + msg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\toptions.to = options.nick;\n\t\t\t\t\t\toptions.is_pm = true;\n\t\t\t\t\t\tlevel = 3;\n\t\t\t\t\t}\n\t\t\t }\n\t\t\t}\n\t\t}\n\n\t\tif(level === 1 && options.force_lines === false) options.lines = 2;\n\t\tif(lines_orj === undefined && options.is_pm === true && options.force_lines === false) options.lines = 5;\n\n\t\t//if there is nothing set to add after buffer text, add ...\n\t\toptions.ellipsis = options.ellipsis === null && options.join !== '\\n' && options.skip_buffer !== true ? true : options.ellipsis;\n\n\t\t//if we're paging the buffer, we've already got it in the buffer verified, so skip those things\n\t\tif(options.page_buffer){\n\t\t\toptions.skip_buffer = true;\n\t\t\toptions.skip_verify = true;\n\t\t}\n\n\t\tlog.trace(msg, level);\n\t\tlog.trace(options);\n\n\t\tif(options.copy_buffer_to_user === true && options.is_pm === false && options.nick !== null && options.chan !== null){\n\t\t\tlevel = 3;\n\t\t\toptions.to = options.nick;\n\t\t\tcopy_buffer(options.chan, options.nick, init_speak);\n\t\t} else {\n\t\t\tif(options.copy_buffer_to_user === true && options.is_pm === false && (options.nick === null || options.chan === null)){\n\t\t\t\tlog.warn('This should likely be coppied to a user buffer, but options.nick or options.chan is null. chan:', options.chan, 'nick:', options.nick, 'msg:', msg);\n\t\t\t}\n\n\t\t\tinit_speak();\n\t\t}\n\n\t\tfunction init_speak(){\n\t\t\tget_buffer(function(data){\n\t\t\t\tif(data) msg = data;\n\t\t\t\tcheck_chan_busy_status(function(){\n\t\t\t\t\tupdate_chan_speak_status();\n\t\t\t\t\tcheck_skip_buffer();\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tfunction get_buffer(callback){\n\t\t\tif(options.page_buffer === true){\n\t\t\t\tpage_buffer(callback);\n\t\t\t} else {\n\t\t\t\tcallback();\n\t\t\t}\n\t\t}\n\n\t\t//when chan is busy, send bot speak to notice, unless user is owner, or ignore_bot_speak = true\n\t\tfunction check_chan_busy_status(callback){\n\t\t\tb.users.owner(false, function(owner_nicks){\n\t\t\t\tif(options.ignore_bot_speak === false &&\n\t\t\t\t _this.config.limit_bot_speak_when_busy &&\n\t\t\t\t _this.config.wait_time_between_commands_when_busy &&\n\t\t\t\t (owner_nicks === null || owner_nicks.indexOf(options.to) < 0) &&\n\t\t\t\t options.is_pm === false){\n\n\t\t\t\t\tx.check_busy(_this.chan, function(busy_status){\n\t\t\t\t\t\tlog.warn('busy_status', busy_status);\n\t\t\t\t\t\tif (busy_status !== false){\n\n\t\t\t\t\t\t\t//check how long it's been since a user has used a command\n\t\t\t\t\t\t\tx.check_speak_timeout(_this.chan + '/cmd/' + options.nick, _this.config.wait_time_between_commands_when_busy, function(wait_ms){\n\t\t\t\t\t\t\t\tif(wait_ms){\n\t\t\t\t\t\t\t\t\tlog.warn(options.chan, 'busy, wait', x.ms_to_time(wait_ms), 'sending to notice.');\n\t\t\t\t\t\t\t\t\tlog.warn(options.chan, 'avr time between chan speak', x.ms_to_time(busy_status));\n\t\t\t\t\t\t\t\t\t_this.say({err: 'busy, wait ' + x.ms_to_time(wait_ms) + ' before you can use a command in chat.'}, 3, options)\n\n\t\t\t\t\t\t\t\t\toptions.is_pm = false;\n\n\t\t\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}, options.nick);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tcallback();\n\t\t\t\t}\n\n\t\t\t});\n\t\t}\n\n\t\t//update command speak status IF we are not ignoring chan speak\n\t\t//this is a reply to a command, this is not from the owner, and\n\t\t//this is not in a pm\n\t\tfunction update_chan_speak_status(){\n\t\t\tb.users.owner(false, function(owner_nicks){\n\t\t\t\tif(options.ignore_bot_speak === false &&\n\t\t\t\t options.is_cmd === true &&\n\t\t\t\t (owner_nicks === null || owner_nicks.indexOf(options.nick) < 0) &&\n\t\t\t\t options.is_pm === false){\n\t\t\t\t x.update_speak_time(_this.chan + '/cmd/' + options.nick, 5, options.nick);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t//if we are not skipping add to buffer, add to buffer first\n\t\t//otherwise attempt to say the string\n\t\tfunction check_skip_buffer(){\n\t\t\tif(options.skip_buffer === true){\n\t\t\t\tlog.trace('skip_buffer true')\n\t\t\t\tif(typeof msg !== 'string' && Array.isArray(msg)) {\n\t\t\t\t\tvar str = msg.join(options.join + '\\u000f');\n\t\t\t\t} else {\n\t\t\t\t\tvar str = msg === null || msg === undefined ? '' : msg;\n\t\t\t\t}\n\n\t\t\t\tstr = options.skip_verify === true ? str : x.verify_string(str, options.url);\n\t\t\t\tsay_str(str);\n\t\t\t} else {\n\t\t\t\tlog.trace('skip_buffer false')\n\t\t\t\tadd_to_buffer(msg, function(data, opt){\n\t\t\t\t\tsay_str(data);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tfunction randomizeWordsFromString(words) {\n\t\t\treturn words.split(' ').sort(function(){return 0.5-Math.random()}).join(' ');\n\t\t}\n\n\t\tfunction say_str(str){\n\t\t\tstr = str.trim();\n\n\t\t\tif (options.stroke) {\n\t\t\t\tstr = randomizeWordsFromString(str)\n\t\t\t}\n\n\t\t\tlog.trace('say_str', str);\n\n\t\t\tvar more = '';\n\n\t\t\tif(options.ellipsis && options.skip_buffer !== undefined && options.skip_buffer !== true){\n\t\t\t\tif(options.join === '\\n'){\n\t\t\t\t\tstr += '...';\n\t\t\t\t} else {\n\t\t\t\t\tstr += '...\\n';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar end = more + (options.url === '' ? '' : options.url) + (options.next_info ? ' ' + options.next_info : '');\n\t\t\tif(end.trim() !== '') str += '\\n' + end;\n\n\t\t\tvar do_action = false;\n\t\t\tif(str.indexOf('/me') === 0){\n\t\t\t\tdo_action = true;\n\t\t\t\tstr = str.slice(3, str.length);\n\t\t\t\tstr = str.trim();\n\t\t\t}\n\n\t\t\tif(_this.config.disable_colors){\n\t\t\t\tstr = c.stripColorsAndStyle(str);\n\t\t\t}\n\n\t\t\tif(!options.ignore_bot_speak && !options.is_pm) x.update_speak_time(_this.chan + '/chan', 5);\n\n\t\t\tdo_action ? bot.action(options.to, str) : bot.say(options.to, str);\n\t\t}\n\n\t\t//add a large amount of data to user buffer\n\t\t//good if you need the bot to say a huge amount of data\n\t\t//overwites current user buffer\n\t\t//data_obj should be an array. Array items over options.max_str_len chars are converted to another array item\n\t\tfunction add_to_buffer(data, callback){\n\t\t\tif(!options.to || options.to === 'undefined'){\n\t\t\t\tlog.error('undefined to');\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlog.trace('add_to_buffer data', data);\n\n\t\t\tvar new_data_obj = [];\n\n\t\t\tfunction split_string(str){\n\t\t\t\tif(options.join !== '\\n' && options.skip_verify !== true) str = x.verify_string(str);\n\t\t\t\tvar pat = new RegExp('.{' + _this.max_str_len + '}\\w*\\W*|.*.', 'g');\n\t\t\t\tstr.match(pat).forEach(function(entry) {\n\t\t\t\t\tif(entry === '' || entry === null || entry === undefined) return;\n\t\t\t\t\tentry = options.skip_verify ? entry : x.verify_string(entry);\n\t\t\t\t\tnew_data_obj.push(entry);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif(data === undefined || data === null || data === false || data === '' || data.length < 1){ //no data\n\t\t\t\tnew_data_obj = [];\n\t\t\t} else if (typeof data === 'string'){ //string\n\t\t\t\tsplit_string(data);\n\t\t\t} else if(typeof data === 'object' && Array.isArray(data)){ //array\n\t\t\t\tdata.forEach(function(item, i){\n\t\t\t\t\tsplit_string(item);\n\t\t\t\t});\n\t\t\t} else if(typeof data === 'object' && !Array.isArray(data)){ //object\n\t\t\t\toptions.join = '\\n';\n\t\t\t\tvar data_arr = format_obj(data);\n\t\t\t\tdata_arr.forEach(function(item, i){\n\t\t\t\t\tsplit_string(item);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlog.error('verify_string: str is a', typeof data, data)\n\t\t\t\tsplit_string(JSON.stringify(data));\n\t\t\t}\n\n\t\t\tlog.trace('add_to_buffer new_data_obj', new_data_obj);\n\n\t\t\tif(new_data_obj.length <= options.lines){\n\t\t\t\toptions.ellipsis = false;\n\t\t\t\tcallback(new_data_obj.join(options.join + '\\u000f'));\n\t\t\t} else {\n\t\t\t\tnew_data_obj.unshift({\n\t\t\t\t\tfirst_len: new_data_obj.length,\n\t\t\t\t\tjoin: options.join,\n\t\t\t\t\tid: x.guid(),\n\t\t\t\t\tellipsis: options.ellipsis\n\t\t\t\t});\n\n\t\t\t\tlog.trace('adding buffer to', '/buffer/' + options.to, new_data_obj.slice(0,3), '...');\n\t\t\t\tdb.update('/buffer/' + options.to, new_data_obj, true, function(act){\n\t\t\t\t\tif(act === 'add'){\n\t\t\t\t\t\tpage_buffer(function(data){\n\t\t\t\t\t\t if(options.is_pm){\n\t\t\t\t\t\t\t\tdata = _this.t.highlight('To page through buffer, type ' + config.command_prefix + 'next. (type ' + config.command_prefix + 'next help for more info)\\n') + data;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tlog.trace('added to ' + options.to + '\\'s buffer!')\n\t\t\t\t\t\t\tcallback(data);\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.trace('cleared ' + options.to + '\\'s buffer!')\n\t\t\t\t\t}\n\t\t\t\t}, options.to);\n\t\t\t}\n\t\t}\n\n\t\t//activated when user sends !next in PM to bot\n\t\t//pages thru buffer, removes paged buffer lines\n\t\tfunction page_buffer(callback){\n\t\t\tif(options.join === '\\n'){\n\t\t\t\toptions.lines = options.lines !== undefined && +options.lines < 11 && +options.lines > 0 ? options.lines : options.force_lines ? options.lines : 5;\n\t\t\t} else if(options.join === ' ') {\n\t\t\t\toptions.lines = options.lines !== undefined && +options.lines < 21 && +options.lines > 0 ? options.lines : options.force_lines ? options.lines : 5;\n\t\t\t} else {\n\t\t\t\toptions.join = ' ' + _this.t.highlight(options.join) + ' ';\n\t\t\t\toptions.lines = options.lines !== undefined && +options.lines < 21 && +options.lines > 0 ? options.lines : options.force_lines ? options.lines : 5;\n\t\t\t}\n\n\t\t\tlog.trace('page_buffer', options);\n\n\t\t\tdb.get_data('/buffer/' + options.to, function(old_buffer){\n\t\t\t\tlog.trace('get buffer from', '/buffer/' + options.to, old_buffer === null ? null : old_buffer.slice(0, 3) +'...');\n\t\t\t\tif(old_buffer !== null && old_buffer.length > 1){\n\t\t\t\t\toptions.join = options.join === ' ' && old_buffer[0].join !== ' ' ? old_buffer[0].join : options.join;\n\n\t\t\t\t\t//if we're joining with a space, then lines becomes about send messages, instead of data lines\n\t\t\t\t\t//by default the bot splits messages at 512 characters, so we'll round down to 400\n\t\t\t\t\tif(options.join === ' ') {\n\t\t\t\t\t\tvar send_data = [];\n\t\t\t\t\t\tvar send_data_i = 0;\n\n\t\t\t\t\t\tfunction add_to(buff){\n\t\t\t\t\t\t\tif(send_data.length < options.lines){\n\t\t\t\t\t\t\t\tif(!send_data[send_data_i]){ //send data arr doesn't have this val yet\n\t\t\t\t\t\t\t\t\tif(buff.length <= _this.max_str_len){ //buffer data is less than max char per line\n\t\t\t\t\t\t\t\t\t\tsend_data.push(buff);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tsend_data.push(buff.slice(0, _this.max_str_len));\n\t\t\t\t\t\t\t\t\t\tadd_to(buff.slice((_this.max_str_len + 1), buff.length));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else { //send data has existing data in this iteration\n\t\t\t\t\t\t\t\t\tif(send_data[send_data_i].length < _this.max_str_len){ //data is under cutoff length\n\t\t\t\t\t\t\t\t\t\tif(buff.length <= _this.max_str_len){ //buffer data is less than max char per line\n\t\t\t\t\t\t\t\t\t\t\tsend_data[send_data_i] = send_data[send_data_i] + buff;\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tsend_data[send_data_i] = send_data[send_data_i] + buff.slice(0, _this.max_str_len);\n\t\t\t\t\t\t\t\t\t\t\tadd_to(buff.slice((_this.max_str_len + 1), buff.length));\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tsend_data_i++;\n\t\t\t\t\t\t\t\t\t\tadd_to(buff);\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\treturn true;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar spliced = false;\n\t\t\t\t\t\tfor(var i = 1; i < old_buffer.length; i++){\n\t\t\t\t\t\t\tif(!add_to(old_buffer[i] + ' ')){\n\t\t\t\t\t\t\t\tlog.trace('splice part old buffer 1 -> ', i);\n\t\t\t\t\t\t\t\told_buffer.splice(1, i);\n\t\t\t\t\t\t\t\tspliced = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(spliced === false){\n\t\t\t\t\t\t\tlog.trace('splice full old buffer 1 -> ', old_buffer.length);\n\t\t\t\t\t\t\told_buffer.splice(1, old_buffer.length);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar send_data = old_buffer.splice(1, options.lines);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(old_buffer.length === 1){\n\t\t\t\t\t\told_buffer = '';\n\t\t\t\t\t\toptions.next_info = '';\n\t\t\t\t\t\toptions.ellipsis = false;\n\t\t\t\t\t\toptions.skip_buffer = true;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\toptions.next_info = _this.t.highlight('(' + (old_buffer[0].first_len - (old_buffer.length - 1)) + '/' + old_buffer[0].first_len + ')');\n\t\t\t\t\t\toptions.ellipsis = old_buffer[0].ellipsis !== undefined && old_buffer[0].ellipsis !== null ? old_buffer[0].ellipsis : options.ellipsis;\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.trace('update to buffer', '/buffer/' + options.to, old_buffer.slice(0, 3), '...');\n\n\t\t\t\t\tdb.update('/buffer/' + options.to, old_buffer, true, function(act){\n\t\t\t\t\t\tif(act === 'add'){\n\t\t\t\t\t\t\tlog.trace('updated ' + options.to + '\\'s buffer!')\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.trace('cleared ' + options.to + '\\'s buffer!')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcallback(send_data.join(options.join + '\\u000f'));\n\t\t\t\t\t}, options.to);\n\t\t\t\t} else {\n\t\t\t\t\t_this.say({'err': 'No buffer to page through.'}, 2, {to: options.to});\n\t\t\t\t}\n\t\t\t}, options.to);\n\t\t}\n\n\t\tfunction copy_buffer(from, to, callback){\n\t\t\tlog.trace('copy_buffer', from, '->', to);\n\t\t\tif(!from || from === 'undefined' || !to || to === 'undefined'){\n\t\t\t\tlog.error('from and to required');\n\t\t\t\tcallback();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tdb.get_data('/buffer/' + from, function(from_buffer){\n\t\t\t\tlog.trace('/buffer/' + from, from_buffer === null ? null : from_buffer.slice(0, 3), '...');\n\t\t\t\tif(from_buffer === null){\n\t\t\t\t\tlog.trace('no buffer to copy from', from);\n\t\t\t\t\tcallback();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tdb.get_data('/buffer/' + to, function(to_buffer){\n\t\t\t\t\tlog.trace('copy_buffer from:', from, 'to:', to, 'from_buffer_id:', from_buffer[0].id, 'to_buffer_id:', to_buffer && to_buffer[0] && to_buffer[0].id ? to_buffer[0].id : null);\n\n\t\t\t\t\t//don't copy buffer again if it's already got the same buffer id\n\t\t\t\t\tif(to_buffer !== null && from_buffer[0].id === to_buffer[0].id){\n\t\t\t\t\t\tlog.trace('skipping copy, buffer from ', from, 'already coppied to ', to);\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if there is a from buffer, set coppied to true, and update user buffer\n\t\t\t\t\tif(from_buffer.length > 1){\n\t\t\t\t\t\tvar new_buffer = from_buffer.slice(0);\n\t\t\t\t\t\tnew_buffer[0].coppied = true;\n\t\t\t\t\t\tdb.update('/buffer/' + to, new_buffer, true, function(act){\n\t\t\t\t\t\t\tif(act === 'add'){\n\t\t\t\t\t\t\t\tlog.trace('copied ' + from + ' to ' + to + '\\'s buffer!')\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.trace('cleared ' + to + '\\'s buffer!')\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcallback();\n\t\t\t\t\t\t}, to);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcallback({'err': 'No buffer to page through.'});\n\t\t\t\t\t}\n\t\t\t\t}, to);\n\t\t\t}, from);\n\t\t}\n\n\t\t//color arr/obj levels\n\t\tfunction c_obj(level, str){\n\t\t\tif(_this.config.disable_colors){\n\t\t\t\treturn str;\n\t\t\t} else {\n\t\t\t\tvar col_arr = [13,4,7,8,9,12];\n\t\t\t\tif(col_arr[level] < 0){\n\t\t\t\t\treturn str;\n\t\t\t\t} else if(level >= col_arr.length){\n\t\t\t\t\tvar l = level % col_arr.length;\n\t\t\t\t\tvar c = '\\u0003' + col_arr[l];\n\t\t\t\t\treturn c + str + '\\u000f';\n\t\t\t\t} else {\n\t\t\t\t\tvar c = '\\u0003' + col_arr[level];\n\t\t\t\t\treturn c + str + '\\u000f';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//if say is an obj instead of string, int, etc\n\t\tfunction format_obj(obj, level) {\n\t\t\tlevel = level || 1;\n\t\t\tobj = obj || {};\n\n\t\t\tvar ret_arr = [];\n\t\t\tvar indent = Array(level).join(' ');\n\n\t\t\tif(Array.isArray(obj)){\n\t\t\t\tvar first = indent + c_obj(level, '[ ');\n\t\t\t} else {\n\t\t\t\tvar first = indent + c_obj(level, '{ ');\n\t\t\t}\n\n\t\t\tvar i = 0;\n\t\t\tvar arr_key = 0;\n\t\t\tfor(var key in obj)\t{\n\t\t\t\tvar k = c_obj(level, (Array.isArray(obj) ? '[' + arr_key + '] ' : key + ': '));\n\n\t\t\t\tif(i === 0){\n\t\t\t\t\tvar str = first + k;\n\t\t\t\t} else {\n\t\t\t\t\tvar str = indent + ' ' + k;\n\t\t\t\t}\n\n\t\t\t\tif(typeof obj[key] === 'function'){\n\t\t\t\t\tstr += '\\u000310function()\\u000f';\n\t\t\t\t\tret_arr.push(str);\n\t\t\t\t} else if(obj[key] == null){\n\t\t\t\t\tstr += '\\u000314NULL\\u000f';\n\t\t\t\t\tret_arr.push(str);\n\t\t\t\t} else if(obj[key] == undefined){\n\t\t\t\t\tstr += '\\u000314UNDEFINED\\u000f';\n\t\t\t\t\tret_arr.push(str);\n\t\t\t\t} else if(!isNaN(obj[key]) && +obj[key] > 1000000000000){\n\t\t\t\t\tstr += '\\u000310\\uFEFF' + obj[key] + ' (' + x.epoc_to_date(obj[key]) + ')\\u000f';\n\t\t\t\t\tret_arr.push(str);\n\t\t\t\t} else if(typeof obj[key] === 'string'){\n\t\t\t\t\tstr += '\\u000315\"' + obj[key] + '\"\\u000f';\n\t\t\t\t\tret_arr.push(str);\n\t\t\t\t} else if(typeof obj[key] === 'object'){\n\t\t\t\t\tvar comb_arr = format_obj(obj[key], level + 1);\n\t\t\t\t\tif(comb_arr.length < 2) {\n\t\t\t\t\t\tstr += comb_arr.join(' ').trim();\n\t\t\t\t\t\tret_arr.push(str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tret_arr.push(str);\n\t\t\t\t\t\tret_arr = ret_arr.concat(comb_arr);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstr += '\\u000310\\uFEFF' + obj[key] + '\\u000f';\n\t\t\t\t\tret_arr.push(str);\n\t\t\t\t}\n\n\t\t\t\ti++;\n\t\t\t\tarr_key++;\n\t\t\t}\n\n\t\t\tif(Array.isArray(obj)){\n\t\t\t\tvar last = (i < 2 ? ' ' : indent) + c_obj(level, ']');\n\t\t\t} else {\n\t\t\t\tvar last = (i < 2 ? ' ' : indent) + c_obj(level, '}');\n\t\t\t}\n\n\t\t\tif(i < 2){\n\t\t\t\tret_arr[ret_arr.length - 1] = ret_arr[ret_arr.length - 1] + last;\n\t\t\t} else {\n\t\t\t\tret_arr.push(last);\n\t\t\t}\n\n\t\t\treturn ret_arr;\n\t\t}\n\t}", "async textWithOptions(string, options) {\n\t\t// Return if HUD refresh is locked\n\t\tif (this.hud_locked !== false) return;\n\t\t// Bounce if override is active\n\t\tif (options.override === false && this.text_override_status.active === true) {\n\t\t\tlog.module(`NOT sending IKE text message: '${string}'`);\n\t\t\treturn;\n\t\t}\n\n\t\tlet layoutValue;\n\t\tswitch (options.layout) {\n\t\t\tcase 'checkcontrol' : layoutValue = 0x24; break;\n\t\t\tcase 'cluster' : layoutValue = 0x50; break;\n\t\t\tcase 'display' : layoutValue = 0x40; break;\n\t\t\tcase 'phone' : layoutValue = 0x00; break;\n\t\t\tcase 'radio1' : layoutValue = 0x41; break;\n\t\t\tcase 'radio2' : layoutValue = 0x62;\n\t\t}\n\n\t\tlet flagsBitmask = 0x00;\n\n\t\tif (options.flags.bit0 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[0]);\n\t\tif (options.flags.bit1 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[1]);\n\t\tif (options.flags.bit2 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[2]);\n\t\tif (options.flags.bit3 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[3]);\n\t\tif (options.flags.bit4 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[4]);\n\t\tif (options.flags.bit5 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[5]);\n\t\tif (options.flags.bit6 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[6]);\n\t\tif (options.flags.bit7 === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[7]);\n\n\t\tif (options.flags.clearScreen === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[5]);\n\t\tif (options.flags.partTx === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[6]);\n\t\tif (options.flags.setCursor === true) flagsBitmask = bitmask.set(flagsBitmask, bitmask.bit[7]);\n\n\n\t\tlet messageHex;\n\n\t\t// messageHex = [ layoutValue, flagsBitmask, 0x30 ];\n\t\t// messageHex = [ layoutValue, flagsBitmask, 0x30, 0x07 ];\n\t\tmessageHex = [ layoutValue, flagsBitmask, 0x10, 0x07 ];\n\n\t\tmessageHex = messageHex.concat(this.text_prepare(string));\n\n\t\tmessageHex = messageHex.concat(0x04);\n\t\t// messageHex = messageHex.concat(0x66);\n\n\t\tawait bus.data.send({\n\t\t\tsrc : 'RAD',\n\t\t\tdst : 'IKE',\n\t\t\tmsg : messageHex,\n\t\t});\n\t}", "function speakingParameters(text) {\n let randomPitch = Math.random();\n let randomVolume = Math.random();\n let randomRate = Math.random();\n\n let voiceParameters = {\n pitch: randomPitch,\n rate: randomRate,\n volume: 5\n };\n responsiveVoice.speak(text, voice, voiceParameters);\n}", "function showSpeaking() {\n speaking = phrase;\n}", "function reply(text, lang = 'en'){\n speak('on');\n\n $('#reply').html('<h1 class=\"reply-content\">'+text+'</h1>');\n\n var u = new SpeechSynthesisUtterance();\n u.text = text;\n u.lang = lang;\n u.rate = 1.2;\n u.onend = function(event) {\n speak('off');\n }\n}", "static set speakerMode(value) {}", "function help(event, response, model) {\n let speech;\n let reprompt;\n\n let activeQuestion = model.getActiveQuestion();\n if (activeQuestion) {\n speech = speaker.getQuestionSpeech(activeQuestion, 'help');\n reprompt = speaker.getQuestionSpeech(activeQuestion, 'reprompt');\n \n // ensure the help counter is reset -- it's n/a for question help \n // messages (see defaultActions's help action for details)\n model.clearAttr(\"helpCtr\");\n }\n else {\n // shouldn't reach this point\n speech = speaker.get(\"Help\");\n }\n\n response.speak(speech);\n if (reprompt) {\n response.listen(reprompt);\n }\n response.send();\n}", "function speakit(text){\n var msg = new SpeechSynthesisUtterance();\n var voices = window.speechSynthesis.getVoices();\n msg.voice = voices[0]; // Note: some voices don't support altering params\n msg.voiceURI = 'native';\n msg.volume = 1; // 0 to 1\n msg.rate = 1; // 0.1 to 10\n msg.pitch = 0.5; //0 to 2\n msg.text = text;\n msg.lang = 'en-GB';\n try {\n window.speechSynthesis.speak(msg);\n } catch (err) {\n console.log('speech synthesis failed:', err);\n }\n}", "function speak(message){\n // set the content of the spoken message\n speech.text = message;\n\n // speak\n stopListening();\n window.speechSynthesis.speak(speech);\n\n log(\"verbal response given\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HELPER funcitons Googel Map service, location to geocode
function loc2geocode(query, flag) { console.log(query); $http.get('https://maps.googleapis.com/maps/api/geocode/json?key='+ GOOG_TOKEN+"&address="+query.loc).success(function(data) { // hack around var geocode = data.results[0].geometry.location; // lat, lng //console.log("loc2geocode: "); //console.log(geocode); instLocSearch(query, geocode, flag); }); }
[ "function locationToGeoCode() {\n\n }", "function geoCode(lugar){\n //usasmos la funcion axios con su parametro get (en la que hacemos peticion get \"obviously\") y le\n // pasamos nuestra URL de la que consumiremos el servicio, y concatenamos por medio de objetos\n //los parametros\n axios.get('https://maps.googleapis.com/maps/api/geocode/json?',{\n params:{\n address:lugar,\n key:'AIzaSyDmlJky0d55y9q9i7XY9oyIvxJoYfUv5_I'\n }\n })\n .then(function(response) { // then es lo que hara si resive la respuesta correctamente\n //imprimir respuesta total // catcha lo que realizara en caso de que halla algun error\n console.log(response);\n //imprimir respuesta address_components\n console.log(response.data.results[0].address_components[0].long_name)\n //agregar valor a las variables\n coords = response.data.results[0].geometry.location\n })\n .catch(function (error){\n console.log(error)\n })\n}", "function initMap(){\n var geocoder = new google.maps.Geocoder();\n // Hago geocoding de la dirección buscada\n geocodeAddress(geocoder);\n}", "function Geocoder() {\n}", "function GeoHelper(){}", "async function geocode(location) {\n const { host, path } = config.mapQuest;\n const url = new URL(path, host);\n\n url.searchParams.set('location', location);\n url.searchParams.set('key', secrets[config.mapQuest.key]);\n\n const options = {\n method: 'get',\n url: url.toString(),\n };\n\n log.info(`Calling geocode function for location ${location}`);\n return axios(options);\n }", "function getLatLng(){\n var address = document.getElementById('addressInput').value;\n geocode(address)\n .then(function(response){\n\t\t// var l = response.data.results[0].geometry.location;\n setLocation(response.data.results[0].geometry.location,true);\n })\n .catch(function(error){\n console.log(error)\n });\n}", "function codeLatLng(latlng) {\n\tgeocoder = new google.maps.Geocoder();\n\tgeocoder.geocode({\n\t\t'latLng': latlng\n\t}, function(results, status) {\n\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\tconsole.log(results)\n\t\t\tif (results[1]) {\n\t\t\t\t//find country name\n\t\t\t\tfor (var i = 0; i < results[0].address_components.length; i++) {\n\t\t\t\t\tfor (var b = 0; b < results[0].address_components[i].types.length; b++) {\n\t\t\t\t\t\t//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate\n\t\t\t\t\t\tif (results[0].address_components[i].types[b] == \"locality\") {\n\t\t\t\t\t\t\t//this is the object you are looking for\n\t\t\t\t\t\t\tconsole.log(results[0].address_components[i].long_name);\n\t\t\t\t\t\t\tcity = results[0].address_components[i].long_name;\n\t\t\t\t\t\t\tupdateMessage(\"How&#39;re you feelin&#39; over in <span id='city'>\" + city + \"</span> today?\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgeoFallback();\n\t\t\t}\n\t\t} else {\n\t\t\talert(\"Geocoder failed due to: \" + status);\n\t\t}\n\t});\n}", "function codeLocation(type, latId, lngId, addressId, scopeId, eid, viewFlag) {\n if (typeof google == \"undefined\")\n {\n //geocoder didnt load correctly, so do nothing\n return -1;\n }\n console.log(\"coding a %s\", type);\n console.log(\"latId=%s, lngId=%s, addressId=%s\", latId, lngId, addressId);\n switch (type)\n {\n case 'address':\n var address = document.getElementById(addressId).value;\n geocoder.geocode( {'address': address}, function (results, status) {\n console.log(\"executing callback\");\n processGeocode(results, status, latId, lngId, addressId, scopeId, eid, viewFlag);\n });\n break;\n case 'latlng':\n var lat = document.getElementById(latId).value;\n var lng = document.getElementById(lngId).value;\n var latlng = new google.maps.LatLng(lat, lng);\n geocoder.geocode( {'latLng': latlng}, function (results, status) {\n console.log(\"executing callback\");\n\t processGeocode(results, status, latId, lngId, addressId, scopeId, eid, viewFlag);\n });\n break;\n default:\n alert(\"Not a valid request\");\n };\n}", "function geoCode(){\n\t/* Initialise Reverse Geocode API Client */\n var reverseGeocoder=new BDCReverseGeocode();\n\t/* You can also set the locality language as needed */\n reverseGeocoder.localityLanguage='pt';\n /* Get the current user's location information, based on the coordinates provided by their browser */\n /* Fetching coordinates requires the user to be accessing your page over HTTPS and to allow the location prompt. */\n reverseGeocoder.getClientLocation(function(result) {\n \tconsole.log(\"Free Reverse Geocode API:\")\n console.log(result);\n saida.innerHTML=\"Latitude: \" + result.latitude +\n \"<br>Longitude: \" + result.longitude +\n \"<br>Cidade: \" + result.city +\n \" - \" + result.principalSubdivision +\n \" - \" + result.countryName;\n\t\tlatitude = result.latitude;\n\t\tlongitude = result.longitude;\n\t\tcidade = result.city;\n\t});\n}", "function codeLatLng(lat, lng, callBack) {\n\n var geocoder = new google.maps.Geocoder();\n\n var latlng = new google.maps.LatLng(lat, lng);\n geocoder.geocode({'latLng': latlng}, function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n\n if (results[1]) {\n for (var j = 0; j < results.length; j++) {\t//use record with type of locality.\n if (results[j].types[0] == 'locality' || results[j].types[0] == 'postal_code') {\n break;\n }\n }\n if (j < results.length) {\n for (var i = 0; i < results[j].address_components.length; i++) {\n if (results[j].address_components[i].types[0] == \"locality\") {\n city = results[j].address_components[i];\n }\n if (results[j].address_components[i].types[0] == \"administrative_area_level_1\") {\n\n region = results[j].address_components[i];\n }\n if (results[j].address_components[i].types[0] == \"country\") {\n country = results[j].address_components[i];\n }\n }\n\n locCity = typeof city != 'undefined' ? city.long_name : '';\n locRegion = typeof region != 'undefined' ? region.long_name : '';\n if (typeof country != 'undefined') {\n if (country.long_name) {\n locCountry = country.long_name;\n } else if (country.short_name) {\n locCountry = country.short_name;\n }\n }\n\n loc = {'lat': lat, 'long': lng, 'city': locCity, 'region': locRegion, 'country': locCountry};\n\n callBack(loc);\n return;\n }\n }\n $.alert(\"City and Country could not be found for coordinates \" + lat + ', ' + lng);\n } else {\n $.alert(\"Geocoder failed due to: \" + status);\n }\n });\n}", "function OpenStreetMapNominatimGeocoder() {\n}", "function getAddress(lat,lon,action=false)\n{\n // get address by lati longi\n const geocoder = new google.maps.Geocoder();\n const infowindow = new google.maps.InfoWindow();\n if (typeof(map) != \"undefined\"){var map=null;}\n geocodeLatLng(geocoder, map, infowindow,lat,lon,action);\n\n return true;\n}", "function codeLatLng2() {\n\tvar latlng = new google.maps.LatLng(kordterdekat);\n\tgeocoder.geocode({\n\t\t'latLng' : kordterdekat\n\t}, function (results, status) {\n\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\tif (results[0]) {\n\n\t\t\t\t// processAddress(latlng);\n\t\t\t\tprocessAddress2(results[0].formatted_address);\n\t\t\t} else {\n\t\t\t\talert(\"No results found\");\n\t\t\t}\n\t\t} else {\n\t\t\talert(\"Geocoder failed due to: \" + status);\n\t\t}\n\t});\n}", "function getGeocode(query, callback) { \r\n\tvar res = ''; \r\n\t// create a client and send request to Google Maps\r\n\tvar client = http.createClient(80, 'maps.googleapis.com');\r\n\tvar request = client.request('GET', '/maps/api/geocode/json?address=' + query + '&sensor=false');\r\n\trequest.end();\r\n\t\r\n\trequest.on('response', function (response) {\r\n\t\tresponse.on('data', function (chunk) {\r\n\t\t\tres += chunk;\r\n\t\t});\r\n\t\t\r\n\t\tresponse.on('end', function() {\r\n\t\t\tcallback(res); \r\n\t\t}); \r\n\t}); \t\r\n}", "function searchLocations() {\n var address = document.getElementById('addressInput').value;\n \n // Address was given, use it...\n //\n if (address != '') {\n geocoder.getLatLng(escapeExtended(address), \n function(latlng) {\n if (!latlng) {\n var theMessage = ''; \n if (slplus.debug_mode) {\n theMessage = 'Google geocoder could not find ' + escape (address) + ' :: ';\n }\n theMessage += address + ' not found'; \n alert(theMessage);\n } else {\n if (slplus.debug_mode) {\n alert('Searching near ' + address + ' ' + latlng);\n }\n searchLocationsNear(latlng, address); \n }\n }\n );\n\n // No Address, Use Current Map Center\n //\n } else {\n searchLocationsNear(map.getCenter(), ''); \n } \n \n jQuery('#map_box_image').hide();\n jQuery('#map_box_map').show();\n map.checkResize();\n}", "function getsGeo() {\n var currentPage;\n E.map.setGpsPoi({lon: lon, lat: lat});\n\n currentPage = E.navigation.getCurrentPage();\n\n if (E.map.hasMap() !== true &&\n (currentPage === E.page.name.search ||\n currentPage === E.page.name.companyResult ||\n currentPage === E.page.name.companyDetails ||\n currentPage === E.page.name.personResult ||\n currentPage === E.page.name.companyDetails ||\n currentPage === E.page.name.locationResult)) {\n E.map.setPosition(lon, lat);\n if (currentPage !== E.page.name.search) {\n E.display.content.showToggle();\n }\n }\n if (currentPage === E.page.name.companyResult) {\n E.companyResult.updateDistances(getPos());\n E.display.content.menu.result.showProximity();\n }\n if (currentPage === E.page.name.routeSearch) {\n E.routeSearch.getsGeo();\n }\n }", "function addrFromLatLng( latLngPoint, longpress ) {\n clearMapElements();\n clearMapFilters();\n searchtype = \"address\";\n\n geocoder.geocode( {\n 'latLng': latLngPoint\n }, function ( results, status ) {\n if ( status == google.maps.GeocoderStatus.OK ) {\n if ( results[ 0 ] ) {\n\n geoaddress = ( results[ 0 ].formatted_address );\n radiusLoc = results[ 0 ].geometry.location;\n map.setZoom( 12 );\n if ( addrMarker ) {\n addrMarker.setMap( null );\n }\n addrMarker = new google.maps.Marker( {\n position: results[ 0 ].geometry.location,\n map: map,\n icon: addrMarkerImage,\n animation: google.maps.Animation.DROP,\n title: geoaddress\n } );\n\n $( '#autocomplete' ).val( results[ 0 ].formatted_address );\n //radiusSearch(\"nozoom\");\n\n if ( longpress ) {\n _trackClickEventWithGA( \"Search\", \"LongPress\", geoaddress );\n //map.setZoom(12);\n map.setCenter( results[ 0 ].geometry.location );\n positionMarkersOnMap();\n } else {\n _trackClickEventWithGA( \"Search\", \"FindMe\", geoaddress );\n // map.setCenter(results[0].geometry.location);\n // map.setZoom(13);\n map.panTo( addrMarker.position );\n positionMarkersOnMap();\n\n }\n whereClause = \" WHERE \"\n whereClause += \"Boundary = 'Attendance Area School' \";\n //whereClause += \" AND Boundary not equal to 'Citywide' \";\n whereClause += \" AND ST_INTERSECTS('Polygon', CIRCLE(LATLNG\" + results[ 0 ].geometry.location.toString() + \",\" + .00001 + \"))\";\n whereClause += \" ORDER BY 'School'\";\n var query = \"SELECT ID, School, Address, City, Phone, Type, Classification, BoundaryGrades, Grades, Boundary, Uniqueid,\" +\n \" Zip, Marker, Typenum, ProgramType, Lat, Long, Rating, \" +\n \" Count, Growth, Attainment, Culture, Graduation, Mobility, Dress, Reading, Math, SAT, ADA, College \" +\n \" FROM \" + fusionTableId + whereClause;\n //console.log(query);\n encodeQuery( query, resultListBuilder );\n\n }\n\n } else {\n alert( \"Geocoder failed due to: \" + status );\n }\n } );\n\n}", "function geocodify(geocoder_this) {\n // Geocodify our geocoders\n geocoder_this.geocodify({\n onSelect: function (result) {\n // Extract the location from the geocoder result\n var location = result.geometry.location;\n\n // Call function and place markers, circle on map\n geocodePlaceMarkersOnMap(location);\n },\n initialText: 'Enter your address...',\n regionBias: 'US',\n // Lat, long information for Cedar Valley enter here\n viewportBias: new google.maps.LatLngBounds(\n new google.maps.LatLng(41.896016,-95.223999),\n new google.maps.LatLng(43.749935, -90.175781)\n ),\n width: 300,\n height: 26,\n fontSize: '14px',\n filterResults: function (results) {\n var filteredResults = [];\n $.each(results, function (i, val) {\n var location = val.geometry.location;\n if (location.lat() > minY && location.lat() < maxY) {\n if (location.lng() > minX && location.lng() < maxX) {\n filteredResults.push(val);\n }\n }\n });\n return filteredResults;\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
objectLens(k) Creates a total `lens` over an object for the `k` key.
function objectLens(k) { return lens(function(o) { return store(function(v) { return extend( o, singleton(k, v) ); }, o[k]); }); }
[ "function objectLens(k) {\n return lens(function(o) {\n return store(function(v) {\n return extend(\n o,\n singleton(k, v)\n );\n }, o[k]);\n });\n}", "function lensReduce(obj, keys) {\n const val = keys.reduce(\n (val, key) => (val === undefined || val === null ? null : val[key]),\n obj\n );\n return val === undefined ? null : val;\n}", "function lens(f) {\n if(!(this instanceof lens))\n return new lens(f);\n \n this.run = function(x) {\n return f(x);\n };\n \n this.compose = function(l) {\n var t = this;\n return lens(function(x) {\n var ls = l.run(x),\n ts = t.run(ls.getter);\n \n return store(\n compose(ls.setter, ts.setter),\n ts.getter\n );\n });\n };\n }", "isLensView() {\n return this.lens !== '' && this.lens != undefined && this.lens != null\n }", "get lens() {\n let get = tree => {\n let found = tree.treeAt(this.path);\n invariant(found instanceof Tree, `Tree at path [${this.path.join(', ')}] does not exist. Is path wrong?`);\n return found.prune();\n }\n\n let set = (tree, root) => {\n let nextValue = lset(lensPath(this.path), tree.value, root.value);\n let bottom = { tree: tree.graft(this.path, root), parentPath: this.path.slice(0, -1) };\n\n /**\n * Navigate the tree from bottom to the top and update\n * value of each tree in the path. Does not\n * change the children that are uneffected by this change.\n */\n return foldr(({ tree, parentPath }, name) => {\n let parent = root.treeAt(parentPath);\n return {\n parentPath: parentPath.slice(0, -1),\n tree: parent.assign({\n meta: {\n children() {\n return map((child, key) => key === name ? tree : child, parent.children);\n }\n },\n data: {\n value() {\n return view(lensPath(parentPath), nextValue);\n }\n }\n })\n }\n }, bottom, this.path).tree;\n }\n\n return lens(get, set);\n }", "function peekObj(o, depth, re, typeRe) {\n if ('string' === typeof o || 'object RegExp' === typeOf(o)) {\n var flags = o.ignoreCase === true ? 'i' : '';\n if ('string' != typeof o) o = o.toSource().replace(/^\\/|\\/[a-z]*$/g, '');\n o = '^object '+ (o.replace(/^(?!\\^)/, '.*').replace(/^\\^/, ''));\n return peekObj(depth, re, typeRe, new RegExp(o, flags));\n }\n return peek(o, depth || 0, re, typeRe || /^object /);\n}", "function pathToLens(path) {\r\n return lensPath(parsePath(path));\r\n}", "function taggedObject(obj, key) {\n var keys = objectKeys(obj);\n return keys.reduce(function (collection, k) {\n var _a;\n var inner = obj[k];\n collection[k] = __assign((_a = {}, _a[key] = k, _a), inner);\n return collection;\n }, {});\n}", "function Lens(get, set) {\n\t\tthis.get = get;\n\t\tthis.set = function(target, newValue) {\n\t\t\t// 2nd lens law: putting back what you got doesn't change anything\n\t\t\t// so we should preserve object references whenever possible.\n\t\t\tif (get.call(this, target) === newValue) {\n\t\t\t\treturn target;\n\t\t\t}\n\t\t\treturn set.call(this, target, newValue);\n\t\t};\n\t}", "objectAt(idx) {\n if (_canaryFeatures.EMBER_METAL_TRACKED_PROPERTIES) {\n this._revalidate();\n }\n\n if (this._objects === null) {\n this._objects = [];\n }\n\n if (this._objectsDirtyIndex !== -1 && idx >= this._objectsDirtyIndex) {\n var arrangedContent = (0, _metal.get)(this, 'arrangedContent');\n\n if (arrangedContent) {\n var length = this._objects.length = (0, _metal.get)(arrangedContent, 'length');\n\n for (var i = this._objectsDirtyIndex; i < length; i++) {\n this._objects[i] = this.objectAtContent(i);\n }\n } else {\n this._objects.length = 0;\n }\n\n this._objectsDirtyIndex = -1;\n }\n\n return this._objects[idx];\n }", "function objectFunctionLuki1(){\n const log = console.log;\n const baseObject = {\n name: \"Luki\",\n surname: \"Kowalski\",\n age: 18,\n cars: ['golf','a4','astra'],\n colors: [\n {name: 'red', number: 1},\n {name: 'blue', number: 2},\n {name: 'pink', number: 3},\n {name: 'yellow', number: 4},\n {name: 'green', number: 5}\n ],\n work: 'Frontend Developer',\n wife: true\n }\n\n log(Object.keys(baseObject));//['name', 'surname', 'age', 'cars', 'colors', 'work', 'wife']\n log(Object.values(baseObject));//['Luki', 'Kowalski', 18, Array(3), Array(5), 'Frontend Developer', true]\n log(Object.entries(baseObject));//[['name', 'Luki'],['surname', 'Kowalski'],['age', 18],['cars', Array(3)],['colors', Array(5)],['work', 'Frontend Developer'],['wife', true]]\n}", "function accessObject(object, key) {\n return object[key];\n}", "function reducekv(object, next, value) {\n var keys = Object.keys(object);\n for (var i = 0; i < keys.length; i++) value = next(value, keys[i], object[keys[i]]);\n return value;\n}", "function deepReduce(obj, reducer, reduced, path, thisArg) {\n if (reduced === void 0) { reduced = {}; }\n if (path === void 0) { path = ''; }\n if (thisArg === void 0) { thisArg = {}; }\n var pathArr = path === '' ? [] : path.split('.');\n var root = obj; // keep value of root object, for recursion\n if (pathArr.length) {\n // called with path, traverse to that path\n for (var _i = 0, pathArr_1 = pathArr; _i < pathArr_1.length; _i++) {\n var key = pathArr_1[_i];\n obj = obj[key];\n if (obj === undefined) {\n throw new Error(\"Path \" + path + \" not found in object.\");\n }\n }\n }\n for (var key in obj) {\n if (!obj.hasOwnProperty(key)) {\n continue;\n }\n pathArr.push(key);\n path = pathArr.join('.');\n var value = obj[key];\n reduced = reducer.call(thisArg, reduced, value, path, root);\n if (typeof value === 'object') {\n reduced = deepReduce(root, reducer, reduced, path, thisArg);\n }\n pathArr.pop();\n }\n return reduced;\n}", "function getObjectLength(object) {\n //use .length() property to find number of key/value pairs.\n return Object.keys(object).length;\n}", "function get_object_by_key(key) {\n\n var objectDict;\n\n if (type_metaData.indexGetFunction) {\n\n objectDict =\n type_metaData.indexGetFunction.call(\n this, type_metaData, indexKey, key, object_by_key);\n\n } else {\n\n objectDict =\n object_by_key[key];\n\n }\n\n if (objectDict &&\n objectDict.handleIndexGetFunction) {\n\n objectDict.handleIndexGetFunction.call(\n this, type_metaData, indexKey, key, object_by_key, objectDict);\n\n }\n\n return objectDict;\n\n }", "function objectLength(obj) {\n if (isMap(obj)) {\n return obj.size;\n }\n else {\n return Object.keys(obj).length;\n }\n}", "function v2k(val, inObject, defReturn) {\n for (let k of Object.keys(inObject)) {\n if (inObject[k] === val) {\n return k;\n }\n }\n return defReturn === undefined ? null : defReturned;\n}", "function flatMapKeys(obj, fn) {\n return mapKeys(obj, fn).reduce(flattenObject);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the smallest width this node can be.
get minWidth() { let width = Math.max(this.tree.theme.nodeMinWidth, this.input.minWidth); let title = 0; { let c = this.tree.canvas; let ctx = c.getContext("2d"); ctx.save(); ctx.font = this.tree.theme.headerFontSize + 'px ' + this.tree.theme.headerFontFamily; title = ctx.measureText(this.name).width + 20; ctx.restore(); } return Math.max(width, title); }
[ "function widthOf(node) {\n return valOf(node, `.size.width`) * valOf(node, `.scale.x`);\n}", "function getWidth (node) {\n return parseInt(window.getComputedStyle(node).width, 10);\n }", "function getMinWidth(element){\n var thisMinWidth = getStyle(element, \"minWidth\");\n return toInt(thisMinWidth);\n }", "calculateMinWidth() {\n const me = this,\n width = me.measureSize(me.width),\n minWidth = me.measureSize(me.minWidth);\n\n let minChildWidth = 0;\n\n if (me.children) {\n minChildWidth = me.children.reduce((result, column) => {\n return result + column.calculateMinWidth();\n }, 0);\n }\n\n return Math.max(width, minWidth, minChildWidth);\n }", "calculateMinWidth() {\n const me = this,\n width = me.measureSize(me.width),\n minWidth = me.measureSize(me.minWidth);\n let minChildWidth = 0;\n\n if (me.children) {\n minChildWidth = me.children.reduce((result, column) => {\n return result + column.calculateMinWidth();\n }, 0);\n }\n\n return Math.max(width, minWidth, minChildWidth);\n }", "calculateMinWidth() {\n const\n me = this,\n width = me.measureSize(me.width),\n minWidth = me.measureSize(me.minWidth);\n\n let minChildWidth = 0;\n\n if (me.children) {\n minChildWidth = me.children.reduce((result, column) => {\n return result + column.calculateMinWidth();\n }, 0);\n }\n\n return Math.max(width, minWidth, minChildWidth);\n }", "width() {\n return this._node.getBoundingClientRect().width;\n }", "function getOptimalMinimumWidth(aXULElement) {\n return getSummarizedStyleValues(aXULElement, [\n \"min-width\",\n \"padding-left\",\n \"padding-right\",\n \"margin-left\",\n \"margin-top\",\n \"border-left-width\",\n \"border-right-width\",\n ]);\n}", "getWhitespaceMinWidth() {\n this._checkPendingChanges();\n if (this._minWidth === -1) {\n let minWidth = 0;\n for (let i = 0, len = this._arr.length; i < len; i++) {\n minWidth = Math.max(minWidth, this._arr[i].minWidth);\n }\n this._minWidth = minWidth;\n }\n return this._minWidth;\n }", "function widestChild(parent) {\n\t\tlet ret = 35;\t/* min width: 35 px */\n\n\t\td3.select(parent)\n\t\t\t.selectAll('* > span')\n\t\t\t.each(function() {\n\t\t\t\tlet tmp = Number(this.offsetWidth);\n\t\t\t\tif (tmp > ret) {\n\t\t\t\t\tret = tmp;\n\t\t\t\t}\n\t\t\t});\n\n\t\treturn ret;\n\t}", "width () {\n\tfor (var i=0 ; i < this.length ; i++ ) {\n\t\tvar node=this[i];\n\t\tvar nb = node.getBoundingClientRect();\n\t\treturn nb.right - nb.left;\n\t}\n\treturn 0;\n}", "function getWidthOfWidestElement() {\n // Get all body children.\n var list = document.body.children;\n // Convert pool of dom elements to array.\n var domElemArray = [].slice.call(list);\n\n // The width of the widest child.\n var widthOfWidestChild = 0;\n function compareChildWidth(child) {\n // Store original display value.\n var originalDisplayValue = child.style.display;\n // Set display to inline so the width \"fits\" the child's content.\n child.style.display = 'inline';\n\n if(child.offsetWidth > widthOfWidestChild) {\n // If this child is wider than the currently widest child, update the value.\n widthOfWidestChild = child.offsetWidth;\n }\n\n // Restore the original display value.\n child.style.display = originalDisplayValue;\n }\n\n // Call `compareItemWidth` on each child in `domElemArray`.\n domElemArray.forEach(compareChildWidth);\n // Return width of widest child.\n return widthOfWidestChild;\n}", "getMinTotalWidth() {\n if (!this.hasMinTotalWidth) {\n throw new Vex.RERR(\n 'NoMinTotalWidth',\n \"Call 'preCalculateMinTotalWidth' or 'preFormat' before calling 'getMinTotalWidth'\"\n );\n }\n\n return this.minTotalWidth;\n }", "getCurrentWidth() {\n if (this.state.pattern[\"args\"].includes(\"width\")) {\n // TODO: Implement width entry UI component\n return 10;\n }\n return null;\n }", "get NMWidthShort() {\n return this._NMWidth * Math.min(this._ratio, 1 / this._ratio);\n }", "min() {\n\t\treturn this._getFarthestNode('left')\n\t}", "get defaultMinWidth() {\n if (!this.grid) {\n return '80';\n }\n switch (this.grid.displayDensity) {\n case DisplayDensity.cosy:\n return '64';\n case DisplayDensity.compact:\n return '56';\n default:\n return '80';\n }\n }", "get width() { return domElement.width() }", "function getWidth() {\n return width;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new FilterAndSort.
constructor() { FilterAndSort.initialize(this); }
[ "function AndFilter() {\n this.subFilters = [];\n}", "function createFilters() {\n\n}", "function SourceFilterParser(filterText) {\n // Final output will be stored here.\n this.filter = null;\n this.sort = {};\n this.filterTextWithoutSort = '';\n var filterList = parseFilter_(filterText);\n\n // Text filters are stored here as strings and then added as a function at\n // the end, for performance reasons.\n var textFilters = [];\n\n // Filter functions are first created individually, and then merged.\n var filterFunctions = [];\n\n for (var i = 0; i < filterList.length; ++i) {\n var filterElement = filterList[i].parsed;\n var negated = filterList[i].negated;\n\n var sort = parseSortDirective_(filterElement, negated);\n if (sort) {\n this.sort = sort;\n continue;\n }\n\n this.filterTextWithoutSort += filterList[i].original;\n\n var filter = parseRestrictDirective_(filterElement, negated);\n if (!filter)\n filter = parseStringDirective_(filterElement, negated);\n if (filter) {\n if (negated) {\n filter = (function(func, sourceEntry) {\n return !func(sourceEntry);\n }).bind(null, filter);\n }\n filterFunctions.push(filter);\n continue;\n }\n textFilters.push({text: filterElement, negated: negated});\n }\n\n // Create a single filter for all text filters, so they can share a\n // TabePrinter.\n filterFunctions.push(textFilter_.bind(null, textFilters));\n\n // Create function to go through all the filters.\n this.filter = function(sourceEntry) {\n for (var i = 0; i < filterFunctions.length; ++i) {\n if (!filterFunctions[i](sourceEntry))\n return false;\n }\n return true;\n };\n }", "function FilterList(andFilters, orFilters) {\n if (andFilters === void 0) { andFilters = []; }\n if (orFilters === void 0) { orFilters = []; }\n this.andFilters = andFilters;\n this.orFilters = orFilters;\n }", "function initSorters() {\n // Set filter by name\n _fo = DecisionSharedService.getFilterObject();\n _fo.pagination.totalDecisions = vm.decisions.totalDecisionMatrixs;\n vm.fo = angular.copy(_fo.sorters);\n // Set Criteria for Hall of fame\n var copyCriteria = _.filter(vm.criteriaGroups, function(criteriaGroupsArray) {\n _.map(criteriaGroupsArray.criteria, function(el) {\n if (_.includes(_fo.selectedCriteria.sortCriteriaIds, el.id)) {\n el.isSelected = true;\n // Set criteria coefficient el.coefficient.\n _.filter(_fo.selectedCriteria.sortCriteriaCoefficients, function(value, key) {\n if (el.isSelected && parseInt(key) === el.id) {\n var coefficientNew = findCoefNameByValue(value);\n el.coefficient = coefficientNew;\n }\n });\n } else {\n el.isSelected = false;\n }\n return el;\n });\n return criteriaGroupsArray;\n });\n\n vm.criteriaGroups = angular.copy(copyCriteria);\n }", "constructor() {\n this.filterRules = {};\n }", "static newFilter() {\n return new ODataFilter();\n }", "function makeFilterListSortable()\n{\n\t// Sortable Tasks on filters\n\t$(\".filterlist\").sortable({\n \t\tscroll: \t\tfalse,\n \tdelay:\t\t\t100,\n \tappendTo: \t\t'body',\n \thelper: \t\tfunction(event) {\n \t\t\t\t\treturn $(\"<div class='dragging'></div>\");\n \t\t\t\t\t},\n \tcursorAt: \t\t{ top: 15, left: 15 },\n \tcursor: \t\t'pointer',\n\t\tplaceholder: \t'placeholder'\n });\n}", "filterAndSortDataByYear () {\n }", "function createFilterPairs() {\n//To be created once selection method is designed.\nreturn arrayOfFilterPairs;\n}", "sort() {\n this.filterList.sort( function( a, b ) {\n var alc = a.item.toLowerCase();\n var blc = b.item.toLowerCase();\n if ( alc < blc ) {\n return -1;\n } else if ( alc > blc ) {\n return 1;\n } else {\n return 0;\n }\n });\n }", "function SortFilterGroup() {\n InsertSort(gArrFilterGrpIdSorted);\n}", "withSortPredicate(predicate) {\n this._sortPredicate = predicate;\n }", "filter(predicate){\n if(typeof(predicate) !== \"function\"){\n throw new TypeError(\"Predicate must be a function.\");\n }\n const array = new SortedArray(null, this.comparator);\n array.reversedComparator = this.reversedComparator;\n for(let element of this){\n if(predicate(element)) Array.prototype.push.call(array, element);\n }\n return array;\n }", "createFilters() {\n if (this.fillFilter) {\n this.fillFilter.remove()\n }\n /** This is the filter allowing to only color fill regions greater than the min value and less than the max. Helpful for ascertaining which areas with similar coloration are actually higher or lower values. */\n this.fillFilter = new FillColFilter(this.ctrlDiv, this.paneOb.initialColData, this.eTarget, this.paneOb)\n this.fillFilter.init()\n // set them at default values\n // categorical filters\n if (this.altFilters) {\n this.altFilters.remove()\n }\n /** The alternate column filter. Allows for pairing down which regions are colored based on rules set on */\n this.altFilters = new AltHolder(this.ctrlDiv, this.paneOb)\n this.altFilters.init()\n\n\n }", "function CustomFilter() {}", "function orderAndFilter(data)\n{\n\treturn SORT_BY[$(\"#order-select\").val()](data\n\t\t\t.filter(e => !$(\"#filter-sport\").is(\":checked\")\n\t\t\t\t\t? e.category != $(\"#filter-sport\").val()\n\t\t\t\t\t:true)\n\t\t\t.filter(e => !$(\"#filter-culture\").is(\":checked\")\n\t\t\t\t\t? e.category != $(\"#filter-culture\").val()\n\t\t\t\t\t:true)\n\t\t\t.filter(e => !$(\"#filter-others\").is(\":checked\")\n\t\t\t\t\t? e.category != $(\"#filter-others\").val()\n\t\t\t\t\t:true));\n}", "function createNewFilter() {\n ListFilteringService.createNewFilter($scope.node);\n }", "createFilter (options, config) {\n return new FileFilter({\n converted_prefix: options.prefix,\n exclude_extension: options.exclude_files.by_extension,\n exclude_names: options.exclude_files.by_name\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch to iframe by iframe selector Elements/widgets ( like dialogs, status bars and more) located inside an iframe has to be switch to it
function switchToFrame(iframeSelector) { chillOut(); Reporter_1.Reporter.debug('Switching to an Iframe'); isExist(iframeSelector); Reporter_1.Reporter.debug(`Get iframe element ${iframeSelector}`); const frameId = tryBlock(() => browser.element(iframeSelector).value, `Failed to get iframeId by ${iframeSelector}`); Reporter_1.Reporter.debug(`Switching to Iframe ${iframeSelector}'`); tryBlock(() => browser.frame(frameId), 'Failed to switch frame'); chillOut(); }
[ "function switchToFrame(iFrame) {\n browser.switchToFrame(iFrame)\n }", "function changeIframeToEditor()\n{\n for(var j=0;j<arguments.length;j++)\n {\n var i=0;\n\t while(document.all.tags('iframe')[i])\n\t { \n\t\tif(document.all.tags('iframe')[i].id == arguments[j])\n\t\t { changetoIframeEditor(document.all.tags('iframe')[i]); break; }\n\t i++\n\t }\n }\n}", "function switchToFrame(selector) {\n Reporter_1.Reporter.debug(`Validate iframe with selector ${selector} exist`);\n isExist(selector);\n Reporter_1.Reporter.debug(`Switching to an Iframe by selector '${selector}'`);\n tryBlock(() => browser.switchToFrame($(selector)), 'Failed to switch frame');\n chillOut();\n }", "function yootagSetIframe(){\n\t\tvar iframe;\n\t\t\n\t\tif (navigator.userAgent.indexOf(\"Safari\") != -1) {\n\t\t\tiframe = frames[\"yootagframe\"];\n\t\t}\n\t\telse {\n\t\t\tiframe = document.getElementById(\"yootagframe\").contentWindow;\n\t\t}\n\t\t\n\t\tif (!iframe) \n\t\t\treturn;\n\t\t\n\t\tvar url = 'http://dev.yootag.com/en/tagmarklet/frame.php?add_url=' + window.location.href;\n\t\ttry {\n\t\t\tiframe.location.replace(url);\n\t\t} \n\t\tcatch (e) {\n\t\t\tiframe.location = url; // safari\n\t\t}\n\t}", "function changeAllIframeToEditors()\n{\n var i=0;\n while(document.all.tags('iframe')[i])\n { \n\tif(!changetoIframeEditor(document.all.tags('iframe')[i])) break;\n\ti++\n }\n\n}", "setFrScheduleNavFrame(){\n this.setFrameContentFrame();\n browser.frame(browser.elements(\"div\").value[3].elements(\"iframe\").value[0]);\n }", "function switchFrame(url) {\n\t\tdoc_frame.src = url;\n\t}", "function switchToFrame(msg) {\n let command_id = msg.json.command_id;\n function checkLoad() {\n let errorRegex = /about:.+(error)|(blocked)\\?/;\n if (curFrame.document.readyState == \"complete\") {\n sendOk(command_id);\n return;\n }\n else if (curFrame.document.readyState == \"interactive\" && errorRegex.exec(curFrame.document.baseURI)) {\n sendError(\"Error loading page\", 13, null, command_id);\n return;\n }\n checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);\n }\n let foundFrame = null;\n let frames = []; //curFrame.document.getElementsByTagName(\"iframe\");\n let parWindow = null; //curFrame.QueryInterface(Ci.nsIInterfaceRequestor)\n // Check of the curFrame reference is dead\n try {\n frames = curFrame.document.getElementsByTagName(\"iframe\");\n //Until Bug 761935 lands, we won't have multiple nested OOP iframes. We will only have one.\n //parWindow will refer to the iframe above the nested OOP frame.\n parWindow = curFrame.QueryInterface(Ci.nsIInterfaceRequestor)\n .getInterface(Ci.nsIDOMWindowUtils).outerWindowID;\n } catch (e) {\n // We probably have a dead compartment so accessing it is going to make Firefox\n // very upset. Let's now try redirect everything to the top frame even if the\n // user has given us a frame since search doesnt look up.\n msg.json.id = null;\n msg.json.element = null;\n }\n if ((msg.json.id == null) && (msg.json.element == null)) {\n // returning to root frame\n sendSyncMessage(\"Marionette:switchedToFrame\", { frameValue: null });\n\n curFrame = content;\n if(msg.json.focus == true) {\n curFrame.focus();\n }\n sandbox = null;\n checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);\n return;\n }\n if (msg.json.element != undefined) {\n if (elementManager.seenItems[msg.json.element] != undefined) {\n let wantedFrame;\n try {\n wantedFrame = elementManager.getKnownElement(msg.json.element, curFrame); //HTMLIFrameElement\n }\n catch(e) {\n sendError(e.message, e.code, e.stack, command_id);\n }\n for (let i = 0; i < frames.length; i++) {\n // use XPCNativeWrapper to compare elements; see bug 834266\n if (XPCNativeWrapper(frames[i]) == XPCNativeWrapper(wantedFrame)) {\n curFrame = frames[i];\n foundFrame = i;\n }\n }\n }\n }\n if (foundFrame == null) {\n switch(typeof(msg.json.id)) {\n case \"string\" :\n let foundById = null;\n for (let i = 0; i < frames.length; i++) {\n //give precedence to name\n let frame = frames[i];\n let name = utils.getElementAttribute(frame, 'name');\n let id = utils.getElementAttribute(frame, 'id');\n if (name == msg.json.id) {\n foundFrame = i;\n break;\n } else if ((foundById == null) && (id == msg.json.id)) {\n foundById = i;\n }\n }\n if ((foundFrame == null) && (foundById != null)) {\n foundFrame = foundById;\n curFrame = frames[foundFrame];\n }\n break;\n case \"number\":\n if (frames[msg.json.id] != undefined) {\n foundFrame = msg.json.id;\n curFrame = frames[foundFrame];\n }\n break;\n }\n }\n if (foundFrame == null) {\n sendError(\"Unable to locate frame: \" + msg.json.id, 8, null, command_id);\n return;\n }\n\n sandbox = null;\n\n // send a synchronous message to let the server update the currently active\n // frame element (for getActiveFrame)\n let frameValue = elementManager.wrapValue(curFrame.wrappedJSObject)['ELEMENT'];\n sendSyncMessage(\"Marionette:switchedToFrame\", { frameValue: frameValue });\n\n if (curFrame.contentWindow == null) {\n // The frame we want to switch to is a remote (out-of-process) frame;\n // notify our parent to handle the switch.\n curFrame = content;\n sendToServer('Marionette:switchToFrame', {frame: foundFrame,\n win: parWindow,\n command_id: command_id});\n }\n else {\n curFrame = curFrame.contentWindow;\n if(msg.json.focus == true) {\n curFrame.focus();\n }\n checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);\n }\n}", "function on_iframe_mousedown()\n\t{\n\t}", "function mozSignalIframeChange()\n{\n window.parent.geckoReceiveIframeChange();\n}", "setFrameContentFrame(){\n this.setGlobalWrapperFrame();\n browser.frame(browser.elements(\"frameset\").value[0].elements(\"frame\").value[2]);\n }", "setFrMainFrame(){\n this.setFrameContentFrame();\n browser.frame(browser.elements(\"div\").value[6].elements(\"iframe\").value[0]);\n }", "function setIframeLocationHref(href) {\n var iframeContent = $('iframe[name=\"contentFrame\"]').contents();\n if (iframeContent.attr('location').pathname !== href) {\n iframeContent.attr('location').replace(href);\n }\n // move focus to the content\n $('#config-content').focus();\n}", "showIFrameInParent(data, element) {\n bsw.showIFrame(data.response.sets, element);\n }", "setGlobalWrapperFrame(){\n this.resetFrames();\n browser.frame(browser.element('//iframe[@id=\"GlobalWrapper\"]').value);\n }", "function refreshFrame(frameName, iframeName) {\n window.frames[frameName].location = iframeName;\n }", "function tbelShowDialog(iframeUrl, iframeTitle, iframeHeight, type)\n\t {\n\n\t /* get selected element values to transmit to iframe */\n\n\t var selectedNode = tbelGetSelectedNode();\n\t var nodeAttributes = '';\n\t if(jQuery(selectedNode).hasClass('active')) {\n\t if(jQuery(selectedNode).hasClass('btn')) {\n\t nodeAttributes = tbelGetNodeAttributes(selectedNode, 'bsBtn');\n\t } else if(jQuery(selectedNode).hasClass('label')) {\n\t nodeAttributes = tbelGetNodeAttributes(selectedNode, 'bsLabel');\n\t } else if(jQuery(selectedNode).hasClass('badge')) {\n\t nodeAttributes = tbelGetNodeAttributes(selectedNode, 'bsBadge');\n\t } else if(jQuery(selectedNode).hasClass('alert')) {\n\t nodeAttributes = tbelGetNodeAttributes(selectedNode, 'bsAlert');\n\t }\n\t }\n\t var getTheHtml = function (){\n\t var html = '';\n\t var language = tinymce.activeEditor.getParam('language');\n\t if(!language) {\n\t language = 'en_EN';\n\t }\n\t html += '<input type=\"hidden\" name=\"bs-code\" id=\"bs-code\" />';\n\t var qrySign = '?';\n\t if(iframeUrl.match(/\\?/)) {\n\t qrySign = '&';\n\t }\n\t html += '<iframe src=\"'+ url + '/' + iframeUrl + qrySign + 'language=' + language+ '&css_paths=' + css_paths + '&' + nodeAttributes + '&' + new Date().getTime() + '\"></iframe>';\n\n\t return html;\n\t };\n\n\t var iFrameWidth = iFrameDefaultWidth;\n\n\t if(jQuery(window).width() < 885) {\n\t iFrameWidth = jQuery(window).width()*0.9;\n\t }\n\n\t if(jQuery(window).height() > iframeHeight) {\n\t iframeHeight = (jQuery(window).height()*0.9) - 90;\n\t }\n\n\t var win = editor.windowManager.open({\n\t title: iframeTitle,\n\t width : iFrameWidth,\n\t height : iframeHeight,\n\t html: getTheHtml(),\n\t buttons: [\n\t {\n\t text: 'OK',\n\t subtype: 'primary',\n\t onclick: function(element) {\n\t tbelRenderContent(element, type);\n\t this.parent().parent().close();\n\t }\n\t },\n\t {\n\t text: 'Cancel',\n\t onclick: function() {\n\t this.parent().parent().close();\n\t }\n\t }\n\t ]\n\t },\n {\n jquery: jQuery // PASS JQUERY\n });\n\n\t /* OK / Cancel buttons position for responsive */\n\n\t jQuery('.mce-floatpanel').find('.mce-widget.mce-abs-layout-item.mce-first').css({'left':'auto', 'right':'82px'});\n\t jQuery('.mce-floatpanel').find('.mce-widget.mce-last.mce-abs-layout-item').css({'left':'auto', 'right':'10px'});\n\n\t jQuery(window).on('resize', function() {\n\t tbelResizeDialog();\n\t });\n\t }", "function loadFocusedIframe() {\n var currentReportWin = carousel.find('div[class=\"item active\"]');\n var cIframe = currentReportWin.find('iframe');\n var cActivityInd = currentReportWin\n .find('div[class=\"activity-indicator\"]');\n var cURL = buildIframeUrl(cIframe.data('rooturl'), queryStringObj);\n if (isNewRequest(cURL, cIframe.attr('src'))) {\n clearIframe(cIframe[0]);\n cActivityInd.show();\n if (cIframe.attr('id') !== 'salesIframe') {\n deferred = $.Deferred();\n deferred.done(loadMainSalesReport);\n }\n cIframe.attr('src', cURL);\n return true;\n }\n return false;\n }", "if (iframeEl.contentDocument) {\n setup(iframeEl.contentDocument.body, iframeEl);\n bean.on(iframeEl, 'load', () => {\n if (iframeEl && iframeEl.contentDocument) {\n setup(iframeEl.contentDocument.body, iframeEl);\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get coach timeslot info for a given date
function getTimeslots(date, callback) { const q = ` SELECT user_id, date, time, duration FROM Timeslots WHERE date = ? ;`; const timeslots = {}; db.each(q, [date], (err, row) => { if (err) return callback(err); timeslots[row.user_id] = { starttime: row.time, duration: row.duration, }; return null; }, (err) => { if (err) return callback(err); return callback(err, timeslots); }); }
[ "function getTimeslot(date) {\n const minutes = date.getHours() * 60 + date.getMinutes();\n const timeslot = {\n slot: Math.floor(minutes / TSLength),\n day: getDayEncoding(date)\n };\n return timeslot;\n}", "function getClockings(date) {\n return fetch(getPunchUrl(date))\n .then((response) => {\n if (!response.ok) {\n throw new Error(`Request failed with status ${response.status}`);\n }\n return response.text();\n })\n .then((text) => {\n const parser = new DOMParser();\n const clockingPage = parser.parseFromString(text, 'text/html');\n const clockings = [];\n\n const inputs = clockingPage.querySelectorAll('#punches_collection tr:not(.tr-punch-canceled) input[type=time]');\n\n for (let i = 0; i < inputs.length; i += 2) {\n clockings.push({\n clockIn: stringToMinutes(inputs[i]?.value),\n clockOut: stringToMinutes(inputs[i + 1]?.value),\n });\n }\n\n return clockings;\n });\n }", "function displayTime(date, timeslot) {\n\tdate = new Date(date);\n\ttimeslot = (timeslot + 9) + ':00';\n\n\treturn date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear() +\n\t\t' ' + timeslot;\n}", "function getTimes(date){\n\tvar times = SunCalc.getTimes(date, config.shutters.latitude, config.shutters.longitude);\n\treturn times;\n}", "function getTimeSlots() {\n var start = new Date('2018-01-01T10:00:00+00:00');\n var timeSlots = {};\n \n for (var i = 0; i < NUM_SLOTS; i++) {\n var time = Utilities.formatDate(start, Session.getScriptTimeZone(), 'HH:mm');\n timeSlots[time] = i;\n start.setMinutes(start.getMinutes() + 15);\n }\n return timeSlots;\n}", "function getMeetTimes(sectionHtml) {\n\t\n\tvar times = [];\n\tif (!sectionHtml) {return times;}\n\tvar pos = sectionHtml.search(/Scheduled Meeting Times<\\/caption>\\n/i);\n\tif (pos < 0) {\n\t\treturn times;\n\t}\n\t\n\t// Adjust HTML\n\tsectionHtml = sectionHtml.slice(pos);\n\tsectionHtml = sectionHtml.split(/<\\/TR>\\n<\\/TABLE>/i, 2)[0];\n\t\n\t// Get each meeting time\n\tvar parts = sectionHtml.split(/<\\/TR>\\n/i), n = parts.length;\n\tfor (var i = 1; i < n; i ++) {\n\t\tvar time = {start: 0, end: 0, day: 'X', location: 'TBA',\n\t\t\tstartDate: null, endDate: null, scheduleType: 'Lecture', instructor: 'TBA'};\n\n\t\t// Break it into lines\n\t\tvar lines = parts[i].split('\\n');\n\t\tfor (var j = 1; j < lines.length; j ++) {\n\t\t\tlines[j] = lines[j].split(/<\\/TD>/i, 2)[0].split('>')[1];\n\t\t}\n\t\t\n\t\t// Get the basic info\n\t\ttime.day = lines[3];\n\t\ttime.location = lines[4];\n\t\ttime.scheduleType = lines[6];\n\t\ttime.instructor = lines[7];\n\t\t\n\t\t// Get the date info\n\t\tvar startEnd = lines[5].split(' - ');\n\t\ttime.startDate = new Date(startEnd[0]);\n\t\ttime.endDate = new Date(startEnd[1]);\n\t\tstartEnd = lines[2].split(' - ');\n\t\tfor (var j = 0; j < 2; j ++) {\n\t\t\t\n\t\t\t// Determine morning/afternoon\n\t\t\tvar t = startEnd[j];\n\t\t\tif (!t) {time.end = time.start; break;}\n\t\t\tvar hours = t.search(/pm/i) > 0? 12 : 0;\n\t\t\tt = t.split(' ')[0]; // remove am/pm\n\t\t\t\n\t\t\t// Determine hours and minutes\n\t\t\tvar timeParts = t.split(':');\n\t\t\ttimeParts[0] = parseInt(timeParts[0]) % 12;\n\t\t\ttimeParts[1] = parseInt(timeParts[1]);\n\t\t\tif (!isNaN(timeParts[0]) && !isNaN(timeParts[1])) {\n\t\t\t\thours += timeParts[0];\n\t\t\t\tvar mins = timeParts[1];\n\t\t\t\tvar totalMins = mins + 60 * hours;\n\t\t\t\tif (j == 0) {\n\t\t\t\t\ttime.start = totalMins;\n\t\t\t\t} else {\n\t\t\t\t\ttime.end = totalMins;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttimes.push(time);\n\t}\n\t\n\treturn times;\n}", "function fetchAvailability(availabilities, date, hours) {\n if (availabilities) {\n for (var i = 0; i < availabilities.length; i++) {\n if (availabilities[i].date === date && availabilities[i].hours === hours) {\n return availabilities[i];\n }\n }\n }\n }", "getSchedule(location, date) {\r\n const weekday = this.weekDays[date.getDay()];\r\n return location.openingHours.weekDayOpeningList.find((weekDayOpeningListItem) => weekDayOpeningListItem.weekDay === weekday);\r\n }", "function getInfoMatchday() {\n if ('caches' in window) {\n caches.match(`${url}v2/competitions/SA`).then(response => {\n if (response) {\n response.json().then(data => {\n const currentMatchday = data.currentSeason.currentMatchday;\n // memanggil fungsi getCurrentMatchday untuk mendapatkan data jadwal pertandingan liga serie-A berdasarkan matchday saat ini\n getCurrentMatchday(currentMatchday);\n })\n }\n })\n }\n\n fetch(`${url}v2/competitions/SA`, options)\n .then(status)\n .then(json)\n .then(data => {\n const currentMatchday = data.currentSeason.currentMatchday;\n // memanggil fungsi getCurrentMatchday untuk mendapatkan data jadwal pertandingan liga serie-A berdasarkan matchday saat ini\n getCurrentMatchday(currentMatchday);\n })\n .catch(error);\n}", "function findTimeSlotFromCurrentDateTime(targetDate) {\n \n var currentDateTime = new Date();\n var dateStr = \n currentDateTime.getMonth() + 1 + \"/\" + \n currentDateTime.getDate() + \"/\" + \n currentDateTime.getFullYear();\n \n //console.log(\"DateTime=\", currentHours, currentMins);\n \n // if the timeslot being acquired isn't today,\n // we return the first timeslot of the day, which is 1\n if (targetDate !== dateStr)\n return 1;\n \n // else, we have to calculate\n var currentHours = currentDateTime.getHours();\n var currentMins = currentDateTime.getMinutes();\n \n var timeslot = (currentHours * 2) + 1;\n if (currentMins >= 30)\n timeslot += 1;\n \n return timeslot;\n}", "async function getShiftsOnDate(date) {\n let result = [];\n let shifts = await getShifts();\n for (let i = 0; i < shifts.length; i++) {\n if (shifts[i].start.toDateString() === date.toDateString()) {\n result.push(shifts[i]);\n }\n }\n return result;\n}", "renderTimeSlot(hourOfTheDay) {\n\t\t//get time to show\n\t\tvar timeToShow = hourOfTheDay +\":00\"\n\t\t//get the time instant of this day at this hour (We need to cast it to \"time\" so it is a UTC time)\n\t\tvar timeInstant = new Date(this.props.date + \" \" + timeToShow).getTime(); \n\t\t//check if this time instant is available, plus it has to be bigger than now\n\t\tif (this.props.slots[hourOfTheDay] || this.props.availableTimeSlots.has(timeInstant) && timeInstant > new Date().getTime()) {\n\t\t\treturn (\n\t\t\t\t<TimeSlot ref={\"timeSlot\"+hourOfTheDay} time={timeToShow} date={this.props.date} available={true} onChoose={(datetime) => this.props.onChoosingATimeSlot(hourOfTheDay, datetime)} \n\t\t\t\tonUnChoose={(datetime) =>this.props.onUnChoosingATimeSlot(hourOfTheDay, datetime)} chosen={this.props.slots[hourOfTheDay]}\n\t\t\t\t/>\n\t\t\t);\n\t\t} else {\n\t\t\treturn (\n\t\t\t\t<TimeSlot time={timeToShow} available={false} \n\t\t\t\t/>\n\t\t\t);\n\t\t}\n\t}", "async function getDaySchedule(room, date) {\n const screens = await mongoose.model(\"Screen\").find({ screenRoom: room });\n\n const daySchedule = screens.filter((screen) => {\n let currentScreen = moment(screen.startTime, dateFormat).format(\"MM DD YYYY\");\n const requestedScreen = moment(date.toString(), dateFormat).format(\"MM DD YYYY\");\n\n return currentScreen === requestedScreen;\n });\n\n return daySchedule;\n}", "function Time_Slot(id, time, day, courts) {\n this.id = id;\n this.time = time;\n this.day = day;\n this.courts = courts;\n this.capacity = courts*2+1;\n this.teams = [];\n this.games = []; // all games in this timeslot.\n}", "function getTheatreInfo(date, theatre) {\n //TODO: Access backend to get real data\n return theatreinfo[theatre];\n}", "function getAvailableTimes(hours, appointments, stylist_id, todayIndex){\n\tvar startH = Number(hours[todayIndex].open.hours);\n\tvar startM = Number(hours[todayIndex].open.minutes);\n\tvar closeH = Number(hours[todayIndex].close.hours);\n\tvar closeM = Number(hours[todayIndex].close.minutes);\n\n\tvar unavailable = extractStylistAppointments(appointments, stylist_id);\n\n\tvar unavailableHours = new Array();\n\tfor(var i = 0; i < unavailable.length; i++)\n\t{\n\t\tunavailableHours.push(unavailable[i][0]);\n\t}\n\n\tvar available = new Array();\n\n\t//NOTE: I HAVE NO IDEA WHY TWO LOOPS OF THE SAME THING ARE NEEDED HERE\n\t//BUT FOR SOME REASON WHEN I COMMENT IT OUT IT ONLY SHOWS THE FIRST APPOINTMENT TIME\n\t//I AM SO CONFUSED!?!?!\n\t//I HOPE MY CAPS LOCK IS INDICATING MY CONFUSION\n\tfor(var i = startH; i < closeH; i++)\n\t{\n\n\t\tfor(var i = startH; i < closeH; i++)\n\t\t{\n\t\t\t\tif(unavailableHours.indexOf(i) < 0 && !availableContains(i, available))\n\t\t\t\t{\n\t\t\t\t\tavailable.push([i, startM]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\n\t}\n\tvar formattedTimes = new Array();\n\n\tfor(var i = 0; i < available.length; i++)\n\t{\n\t\tvar time = formatTime(available[i][0], available[i][1]);\n\t\tformattedTimes.push(time);\n\t}\n\n\t// return ['9:00 AM', '10:00 AM', '1:00 PM', '3:00 PM'];\n\treturn formattedTimes;\n}", "function coachCalendarDay(day, month, year) {\r\n\r\n this.coachID;\r\n\r\n this.day = day;\r\n this.month = month;\r\n this.year = year;\r\n this.date = nlapiStringToDate(day+'/'+month+'/'+year);\r\n\r\n this.is_busy = false;\r\n\r\n // Define object method to get all events on this day\r\n this.getEvents = getEvents;\r\n\r\n function getEvents() {\r\n\r\n echoComment('Finding events on ' + this.date.format('d/m/yyyy') + ' for coach ' + this.coachID);\r\n\r\n var events = new Array();\r\n\r\n var filters = new Array();\r\n filters[0] = new nlobjSearchFilter('custrecord_calentry_category', null, 'is', 1);\r\n filters[1] = new nlobjSearchFilter('custrecord_calentry_startdate', null, 'on', this.date.format('d/m/yyyy'));\r\n filters[2] = new nlobjSearchFilter('custrecord_calentry_coach', null, 'is', this.coachID);\r\n\r\n var columns = new Array();\r\n columns[0] = new nlobjSearchColumn('custrecord_calentry_title');\r\n columns[1] = new nlobjSearchColumn('custrecord_calentry_content');\r\n columns[2] = new nlobjSearchColumn('custrecord_calentry_location');\r\n columns[3] = new nlobjSearchColumn('custrecord_calentry_startdate');\r\n columns[4] = new nlobjSearchColumn('custrecord_calentry_starttime');\r\n columns[5] = new nlobjSearchColumn('custrecord_calentry_enddate');\r\n columns[6] = new nlobjSearchColumn('custrecord_calentry_endtime');\r\n columns[7] = new nlobjSearchColumn('custrecord_calentry_timezone');\r\n columns[8] = new nlobjSearchColumn('custrecord_calentry_status');\r\n\r\n // Search for all the coaches calendar bookings\r\n events = nlapiSearchRecord('customrecord_calendarentry', null, filters, columns);\r\n\r\n return events;\r\n\r\n }\r\n\r\n}", "function dateToTourtime(date) {\n var string = \"\";\n \n string =\n (date.getMonth()+1) +\n \"/\" +\n date.getDate() +\n \"/\" +\n date.getFullYear().toString().substring(2) +\n \" \";\n \n var startHour = date.getHours();\n //Convert military-time into 12-hour-time string\n \n //Start time\n var pm = false;\n if(startHour >= AM_HOURS) {\n pm = true;\n if(startHour > AM_HOURS) {\n startHour -= AM_HOURS;\n }\n }\n \n var startMinutes = date.getMinutes().toString();\n if(parseInt(startMinutes) < 10) startMinutes = \"0\" + startMinutes;\n \n string += startHour + \":\" + startMinutes;\n if(pm) {\n string += \"PM\";\n } else string += \"AM\";\n \n string += \" - \";\n \n //End time\n var endHour = date.endHour;\n \n if(endHour) {\n pm = false;\n if(endHour >= AM_HOURS) {\n pm = true;\n if(endHour > AM_HOURS) {\n endHour -= AM_HOURS;\n }\n }\n } else {\n endHour = (startHour + 1);\n if(endHour === 13) {\n pm = !pm;\n endHour = 1;\n }\n }\n \n var endMinute = date.endMinute;\n if(endMinute) {\n if(parseInt(endMinute) < 10) endMinute = \"0\" + endMinute;\n } else {\n endMinute = \"00\";\n }\n \n string += endHour + \":\" + endMinute;\n if(pm) {\n string += \"PM\";\n } else string += \"AM\";\n \n return string;\n}", "function fetchAvailabilities(availabilities, date, hours) {\n var list = [];\n for (var i = 0; i < availabilities.length; i++) {\n if (availabilities[i].date === date && availabilities[i].hours === hours) {\n list.push(availabilities[i]);\n }\n }\n\n return list;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function that set our sticky header width = parent.style.width
function calcWidth() { stickyHeader.style.width = window.getComputedStyle(document.querySelector(mountQuerySelector), null).getPropertyValue('width'); }
[ "function setOuterWidth() {\n outerWidth = wrap.offsetWidth;\n dragBarPos = calcDragBarPosFromCss() || Math.floor(outerWidth / 2) - 5;\n }", "function adjustHeaderWidth() {\n\tvar header = dom.queryOne('#playing-header');\n\tvar left = dom.queryOne('#radio-seed');\n\tvar right = dom.queryOne('#right-header');\n\tleft.style.width = (header.offsetWidth - right.offsetWidth - 34) + \"px\";\n}", "function mfn_header(){\n\t\tvar rightW = $('.top_bar_right').innerWidth();\n\t\tif( rightW && ! $('body').hasClass('header-plain') ){\n\t\t\trightW += 10;\n\t\t}\n\t\tvar parentW = $('#Top_bar .one').innerWidth();\n\t\tvar leftW = parentW - rightW;\n\t\t$('.top_bar_left, .menu > li > ul.mfn-megamenu').css( 'width', leftW );\n\t}", "function setStickyElementWidthAndParentHeight() {\n $('.my-sticky-element').each(function (e) {\n\t var $this = $(this);\n $this.width( $this.parent().width() );\n $this.parent().height( $this.outerHeight() );\n });\n }", "function mfn_header() {\n var rightW = $jq('.top_bar_right').innerWidth();\n if (rightW && !$jq('body').hasClass('header-plain')) {\n rightW += 10;\n }\n var parentW = $jq('#Top_bar .one').innerWidth();\n var leftW = parentW - rightW;\n $jq('.top_bar_left, .menu > li > ul.mfn-megamenu').css('width', leftW);\n }", "function setStickyWidths($tableInstance) {\n\t\t\tvar $stickyWidth = $tableInstance.parent().find('td').first().outerWidth();\n\t\t\tvar test = $tableInstance.parent().siblings('.fixed-column').find('td').first().outerWidth($stickyWidth);\n\t\t}", "_correctRowHeaderWidth(width) {\n let rowHeaderWidth = width;\n\n if (typeof width !== 'number') {\n rowHeaderWidth = this.wot.getSetting('defaultColumnWidth');\n }\n if (this.correctHeaderWidth) {\n rowHeaderWidth += 1;\n }\n\n return rowHeaderWidth;\n }", "function controlTableWidth(obj) {\n var windowWidth = window.parent.innerWidth || window.parent.document.documentElement.clientWidth || window.parent.document.body.clientWidth;\n var tableWidth = windowWidth * 0.96 - 150;\n var fixedColWidth = obj.find('.order-hd').width();\n obj.find('.order-body').css('width',tableWidth - fixedColWidth);\n }", "fixWidths() {\n const me = this,\n {\n element,\n header,\n footer\n } = me;\n\n if (!me.collapsed) {\n if (me.flex) {\n header.flex = me.flex;\n\n if (footer) {\n footer.flex = me.flex;\n }\n\n element.style.flex = me.flex;\n } else {\n // If width is calculated and no column is using flex, check if total width is less than width. If so,\n // recalculate width and bail out of further processing (since setting width will trigger again)\n if (me.hasCalculatedWidth && !me.columns.some(col => !col.hidden && col.flex) && me.totalFixedWidth !== me.width) {\n me.width = me.totalFixedWidth; // Setting width above clears the hasCalculatedWidth flag, but we want to keep it set to react correctly\n // next time\n\n me.hasCalculatedWidth = true;\n return;\n }\n\n let totalWidth = me.width;\n\n if (!totalWidth) {\n totalWidth = 0; // summarize column widths, needed as container width when not using flex widths and for correct\n // overflow check in Edge\n\n for (const col of me.columns) {\n if (!col.flex && !col.hidden) totalWidth += col.width;\n }\n } // rows are absolutely positioned, meaning that their width won't affect container width\n // hence we must set it, if not using flex\n\n element.style.width = `${totalWidth}px`;\n header.width = totalWidth;\n\n if (footer) {\n footer.width = totalWidth;\n }\n }\n\n me.syncScrollingPartners(false);\n }\n }", "respondTo() {\n if (this.isActive || this.isFrozen) {\n let parentComputedStyle = window.getComputedStyle(this.options.respondToParent),\n parentWidth = this.options.respondToParent.getBoundingClientRect().width - parseFloat(parentComputedStyle['padding-left']) - parseFloat(parentComputedStyle['padding-right']);\n\n this.target.style.width = parentWidth + 'px';\n }\n }", "setHeaderWidth() {\n $('.regions-header').width($('.regions-table-first-row').width());\n }", "fixWidths() {\n const\n me = this,\n {\n element,\n header,\n footer\n } = me;\n\n if (!me.collapsed) {\n if (me.flex) {\n header.flex = me.flex;\n if (footer) {\n footer.flex = me.flex;\n }\n element.style.flex = me.flex;\n }\n else {\n // If width is calculated and no column is using flex, check if total width is less than width. If so,\n // recalculate width and bail out of further processing (since setting width will trigger again)\n if (\n me.hasCalculatedWidth &&\n !me.columns.some(col => !col.hidden && col.flex) &&\n me.totalFixedWidth !== me.width\n ) {\n me.width = me.totalFixedWidth;\n // Setting width above clears the hasCalculatedWidth flag, but we want to keep it set to react correctly\n // next time\n me.hasCalculatedWidth = true;\n return;\n }\n\n let totalWidth = me.width;\n\n if (!totalWidth) {\n totalWidth = 0;\n\n // summarize column widths, needed as container width when not using flex widths and for correct\n // overflow check in Edge\n for (const col of me.columns) {\n if (!col.flex && !col.hidden) totalWidth += col.width;\n }\n }\n\n // rows are absolutely positioned, meaning that their width won't affect container width\n // hence we must set it, if not using flex\n element.style.width = `${totalWidth}px`;\n\n header.width = totalWidth;\n if (footer) {\n footer.width = totalWidth;\n }\n }\n\n me.syncScrollingPartners(false);\n }\n }", "function adjustAbstractionHeader() {\n document.getElementById('id-head-abs-name').style.width = \"600px\";\n document.getElementById('id-head-abs-type').style.width = \"10%\";\n document.getElementById('id-head-abs-access').style.width = \"10%\";\n document.getElementById('id-head-abs-content').style.width = \"10%\";\n document.getElementById('id-head-abs-description').style.width = \"40%\";\n}", "function scrolldiv_setWidth(newWidth)\n{\n\tdocument.getElementById('dhtmlgoodies_scrolldiv').style.width = newWidth + 'px';\n\tdocument.getElementById('scrolldiv_parentContainer').style.width = newWidth-30 + 'px';\t\t\n}", "function setParentWrapperWidth(){\n slides.forEach(slide => slide.style.width = slidersParentContainer.clientWidth+'px');\n //slidersWrapper.style.width = (slides.length - 1 * slides[0].clientWidth)+'px';\n }", "get headerWidth() {\n return parseInt(this.width, 10) - 17;\n }", "updateInnerWidthDependingOnChilds(){}", "function setHeaderMinWidth() {\n $(\".dataTables_wrapper\").each(function() {\n var wrapperWidth = $(this).width();\n var tableWidth = $(this).find(\"table.dataTable\").outerWidth();\n if (tableWidth > wrapperWidth) {\n $(this).css(\"min-width\", tableWidth+\"px\");\n }\n });\n}", "function sticky_header() {\n var header_wrap = document.getElementById('header-wrap');\n var description = document.getElementById('description');\n header_wrap.style.position = \"fixed\";\n description.style.paddingTop = header_wrap.offsetHeight;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copyright (c) Microsoft Corporation. A helper to decide if a given argument satisfies the Pipeline contract
function isPipelineLike(pipeline) { if (!pipeline || typeof pipeline !== "object") { return false; } const castPipeline = pipeline; return (Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"); }
[ "function isPipe(){\n\treturn isMatch(pipe, getPipe());\n}", "static pred(arg) {\n let argtype = Argbind.of(arg);\n switch (argtype) {\n // Returns TRUE if value of arg is included in array of acceptable types:\n case \"ARRAY\":\n return x => arg.includes(x);\n // Assumes we are only matching name of type and nothing else:\n default:\n return x => true\n }\n }", "static isPipelineableObject(object) {\n return 'getPipelineEnd' in object;\n }", "_or_(payload) {\n if (!Array.isArray(payload)) throw new Error('Invalid argument. \"_or_\" must be passed an array');\n\n if (payload.length === 0) return true;\n\n let result = false;\n for (const index in payload) {\n const item = payload[index];\n\n if (typeof item !== 'object' || item === null || Array.isArray(item)) {\n result = result || !!item;\n }\n else {\n result = result || !!this.runCommand(item, endpoint);\n }\n\n if (result) break;\n }\n\n return result;\n }", "function isTwoPassed(){\n var args = Array.prototype.slice.call(arguments);\n return args.indexOf(2) != -1;\n}", "checkProcessable(processName, {bitDepth, alpha, colorModel, components, channels} = {}) {\n if (typeof processName !== 'string') {\n throw new TypeError('checkProcessable requires as first parameter the processName (a string)');\n }\n if (bitDepth) {\n if (!Array.isArray(bitDepth)) {\n bitDepth = [bitDepth];\n }\n if (!bitDepth.includes(this.bitDepth)) {\n throw new TypeError('The process: ' + processName + ' can only be applied if bit depth is in: ' + bitDepth);\n }\n }\n if (alpha) {\n if (!Array.isArray(alpha)) {\n alpha = [alpha];\n }\n if (!alpha.includes(this.alpha)) {\n throw new TypeError('The process: ' + processName + ' can only be applied if alpha is in: ' + alpha);\n }\n }\n if (colorModel) {\n if (!Array.isArray(colorModel)) {\n colorModel = [colorModel];\n }\n if (!colorModel.includes(this.colorModel)) {\n throw new TypeError('The process: ' + processName + ' can only be applied if color model is in: ' + colorModel);\n }\n }\n if (components) {\n if (!Array.isArray(components)) {\n components = [components];\n }\n if (!components.includes(this.components)) {\n throw new TypeError('The process: ' + processName + ' can only be applied if the number of channels is in: ' + components);\n }\n }\n if (channels) {\n if (!Array.isArray(channels)) {\n channels = [channels];\n }\n if (!channels.includes(this.channels)) {\n throw new TypeError('The process: ' + processName + ' can only be applied if the number of components is in: ' + channels);\n }\n }\n }", "needsArguments(transforms) {\n\t\treturn transforms.spreadRest && this.params.filter(param => param.type === 'RestElement').length > 0;\n\t}", "needsArguments(transforms) {\n\t\treturn (\n\t\t\ttransforms.spreadRest &&\n\t\t\tthis.params.filter(param => param.type === 'RestElement').length > 0\n\t\t);\n\t}", "checkProcessable(processName, {bitDepth, alpha, colorModel, components} = {}) {\n if (typeof processName !== 'string') {\n throw new TypeError('checkProcessable requires as first parameter the processName (a string)');\n }\n if (bitDepth) {\n if (!Array.isArray(bitDepth)) bitDepth = [bitDepth];\n if (bitDepth.indexOf(this.bitDepth) === -1) {\n throw new TypeError('The process: ' + processName + ' can only be applied if bit depth is in: ' + bitDepth);\n }\n }\n if (alpha) {\n if (!Array.isArray(alpha)) alpha = [alpha];\n if (alpha.indexOf(this.alpha) === -1) {\n throw new TypeError('The process: ' + processName + ' can only be applied if alpha is in: ' + alpha);\n }\n }\n if (colorModel) {\n if (!Array.isArray(colorModel)) colorModel = [colorModel];\n if (colorModel.indexOf(this.colorModel) === -1) {\n throw new TypeError('The process: ' + processName + ' can only be applied if color model is in: ' + colorModel);\n }\n }\n if (components) {\n if (!Array.isArray(components)) components = [components];\n if (components.indexOf(this.components) === -1) {\n throw new TypeError('The process: ' + processName + ' can only be applied if the number of channels is in: ' + components);\n }\n }\n }", "needsArguments(transforms) {\n return transforms.spreadRest && this.params.filter(param => param.type === 'RestElement').length > 0;\n }", "function Prelude__Interfaces__Main___64_Prelude__Interfaces__Eq_36_Filter_58__33__61__61__58_0($_0_arg, $_1_arg){\n \n if(($_1_arg.type === 1)) {\n return (!(!($_0_arg.type === 1)));\n } else if(($_1_arg.type === 0)) {\n return (!(!($_0_arg.type === 0)));\n } else if(($_1_arg.type === 2)) {\n return (!(!($_0_arg.type === 2)));\n } else {\n return false;\n }\n}", "function checkPara() {\n var n = arguments.length;\n if (n < 1) {\n return false;\n } else {\n for (var i = 0; i < n; i++) {\n if (arguments[i] == \"\" || arguments[i] == null)\n return false;\n }\n return true;\n }\n }", "existAnyArguments() {\n const {supportingSituation, supportingActionGoal, notSupportingSituation, notSupportingActionGoal} = this.state;\n return (\n (supportingSituation !== undefined && supportingSituation.length > 0) ||\n (supportingActionGoal !== undefined && supportingActionGoal.length > 0) ||\n (notSupportingSituation !== undefined && notSupportingSituation.length > 0) ||\n (notSupportingActionGoal !== undefined && notSupportingActionGoal.length > 0)\n )\n }", "isArguments (value) {\n\t\treturn typeChecker.getObjectType(value) === '[object Arguments]'\n\t}", "function canArgsBeBatched(args, accumulateBy) {\n return args[accumulateBy] !== undefined && args.offset === undefined && (args.limit === undefined || args.limit === 1);\n}", "has(...args) {\n if (!args.length) { args = ['in']; }\n if (typeof args[args.length - 1] === 'function') {\n let validate = args.pop();\n for (let i = 0; i < args.length; i++) {\n var port = args[i];\n if (!this.ports[port].has(this.scope, validate)) { return false; }\n }\n return true;\n }\n let res = true;\n for (let j = 0; j < args.length; j++) { var port = args[j]; if (res) { res = this.ports[port].ready(this.scope); } }\n return res;\n }", "static isParametered(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Constructor:\r\n case StructureKind_1.StructureKind.ConstructorOverload:\r\n case StructureKind_1.StructureKind.GetAccessor:\r\n case StructureKind_1.StructureKind.Method:\r\n case StructureKind_1.StructureKind.MethodOverload:\r\n case StructureKind_1.StructureKind.SetAccessor:\r\n case StructureKind_1.StructureKind.Function:\r\n case StructureKind_1.StructureKind.FunctionOverload:\r\n case StructureKind_1.StructureKind.CallSignature:\r\n case StructureKind_1.StructureKind.ConstructSignature:\r\n case StructureKind_1.StructureKind.MethodSignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }", "function isAny(param) {\n\treturn true;\n}", "function any(func) {\n return function () {\n var params = getParams(arguments);\n var length = params.length;\n for (var i = 0; i < length; i++) {\n if (func.call(null, params[i])) {\n return true\n }\n }\n return false\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
def generate_cubes_until(modulus): """ Generates the cubes of integers greater than 0 until the next is 0 modulo the provided modulus. >>> list(generate_cubes_until(25)) [1, 8, 27, 64] """ pass
function generateCubesUntil(modules) { if (modules === 0) return null; let total = 1; let range = [1]; let i = 2; while (total % modules !== 0) { let cube = i ** 3; total += cube; range.push(cube); i++; } return range; }
[ "function generateCubes(cubeSize, cubeNum) {\n\n //Offset between cubes\n let xOff = 0;\n let yOff = 0;\n let zOff = 0;\n let init = true;\n\n for (let ix = 0; ix < cubeNum; ix++) {\n //delta = cube-size + distance between cubes\n xOff += delta;\n for (let iy = 0; iy < cubeNum; iy++) {\n yOff += delta;\n for (let iz = 0; iz < cubeNum; iz++) {\n zOff += delta;\n //To leave some empty slots, there is a 15% chance\n //that a cube will not be set\n if (init !== true) {\n cubes.push(new Cube(xOff, yOff, -zOff, cubeSize, false))\n } else {\n cubes.push(new Cube(xOff, yOff, -zOff, cubeSize, true));\n init = false;\n }\n }\n zOff = 0;\n }\n yOff = 0;\n }\n}", "function findBaseCubes(volume){\n let cubeCounter = 0;\n let volumeAcc = 0;\n while (volumeAcc < volume) {\n volumeAcc = volumeAcc + (cubeCounter**3)\n cubeCounter ++;\n }\n if(volumeAcc === volume) return cubeCounter - 1;\n return -1\n}", "function main () {\n var cubes = [];\n\n for (var i = 0; i < 100; i++) {\n cubes.push(\n translate([150 * Math.random() - 75, 150 * Math.random() - 75, 150 * Math.random() - 75],\n cube(5).setColor(hsl2rgb(Math.random() * 0.2 + 0.7, 1, 0.5)))\n );\n }\n return cubes;\n}", "static cube(n) {\n if (typeof n !== 'number' || n < 1) {\n return [];\n }\n let sequence = [];\n for (let i = 1; i < n; i++) {\n sequence.push(i * i * i);\n }\n return sequence;\n }", "addRandomCubes(number) {\n for(let i = 0; i < number; i++) {\n let random = Math.random();\n let width = random * 100;\n let length = random * 100;\n let height = random * 100;\n let size = new THREE.Vector3(width, length, height);\n let coordinates = new THREE.Vector3(Math.random() * MAPWIDTH, Math.random() * MAPLENGTH, random * 50);\n let name = `cube${this.cubes.length}`;\n\n this.addCube(coordinates, size, name);\n }\n }", "function generate(total, minX, minY, minZ, maxX, maxY, maxZ) {\r\n\t\tfor (let i = 0; i < total; i++) {\r\n\t\t\tconst width = (maxX - minX) / 100;\r\n\t\t\tconst height = (maxY - minY) / 200;\r\n\t\t\tconst depth = (maxZ - minZ) / 200;\r\n\t\t\tconst geometry = new THREE.BoxGeometry(width, height, depth);\r\n\t\t\tvar material = new THREE.MeshPhongMaterial({ color: 0xffffff, shading: THREE.FlatShading });\r\n\t\t\tvar cube = new THREE.Mesh(geometry, material);\r\n\t\t\tscene.add(cube);\r\n\t\t\tobjects.push(cube);\r\n\t\t\tconst posX = Math.random() * (maxX - minX) + minX;\r\n\t\t\tconst posY = Math.random() * (maxY - minY) + minY;\r\n\t\t\tconst posZ = Math.random() * (maxZ - minZ) + minZ;\r\n\t\t\tcube.position.set(posX, posY, posZ);\r\n\r\n\t\t}\r\n\t}", "function multiplesOfThree() {\n // for loop to count down from 99 by 3's\n for (i=99; i>=0; i -= 3) {\n console.log(i);\n }\n}", "function createCubesBall(num, scene) {\n const cubes = [];\n for (let i = 0; i < num; i++) {\n if (i === 0) cubes[i] = BABYLON.Mesh.CreateCylinder('b', 0.05, 0.05, 0.01, scene);\n else cubes[i] = cubes[0].createInstance(`b${i}`);\n\n let x = 0;\n let y = 0;\n let z = 0;\n do {\n x = rnd(-5, 5);\n y = rnd(-5, 5);\n z = rnd(-5, 5);\n } while (allWithin(1.5, x, y, z));\n\n cubes[i].scaling = new BABYLON.Vector3(rnd(1.0, 1.5), rnd(1.0, 1.5), rnd(1.0, 10.0));\n\n cubes[i].position = new BABYLON.Vector3(x, y, z);\n\n cubes[i].lookAt(new BABYLON.Vector3(0, 0, 0));\n }\n return cubes;\n}", "function nextCube() {\n num = Number(window.prompt(\"Please enter number you like!\"));\n // Give error if necessary\n if (num <= 0 || !num) {\n alert(\"Please input valid number.\");\n num = 16;\n };\n // Clear the previous cubes\n const blocks = Array.from(document.querySelectorAll(\"#cube\"));\n blocks.forEach(block => {\n container.removeChild(block);\n });\n outputGrid(num);\n}", "function MultiplesOfSix() {\n var i = 6;\n while (i< 60001){\n if (i%6==0){\n console.log(i);\n }\n i++\n } \n}", "function showCubes(amount) {\r\n for(let i = 1; i <= amount; i++) {\r\n let cube = createCube();\r\n showCube(cube);\r\n }\r\n}", "function generate(total, minX, minY, minZ, maxX, maxY, maxZ) {\r\n\t\tfor (let i = 0; i < total; i++) {\r\n\t\t\tconst width = (maxX - minX) / 20;\r\n\t\t\tconst height = (maxY - minY) / 20;\r\n\t\t\tconst depth = (maxZ - minZ) / 20;\r\n\t\t\tconst geometry = new THREE.BoxGeometry(width, height, depth);\r\n\t\t\tvar material = new THREE.MeshNormalMaterial();\r\n\t\t\tvar cube = new THREE.Mesh(geometry, material);\r\n\t\t\tscene.add(cube);\r\n\t\t\tobjects.push(cube);\r\n\t\t\tconst posX = Math.random() * (maxX - minX);\r\n\t\t\tconst posY = Math.random() * (maxY - minY);\r\n\t\t\tconst posZ = Math.random() * (maxZ - minZ);\r\n\t\t\tcube.position.set(posX, posY, posZ);\r\n\r\n\t\t}\r\n\t}", "function sumCubes(num1) {\n var sum = 0;\n\n for (i=1; i <= num1; i++){\n sum = sum + Math.pow(i,3) //increase sum by i to the power of 3\n }\n\n console.log(\"The sum of the cubes from 1 to \" + \"num1\" + \" is: \" + sum)\n}", "function multiplesOf(number){\n let total = 0;\n let n = number - 1;\n while(n > 0) {\n if ((n % 3) === 0 || (n % 5) === 0) {\n total = total + n;\n }\n n--\n }\n return total\n}", "function generatePrimes() {\n primes.push(2);\n let numbers = [];\n let maxNumber = 10000;\n\n for (let i = 3; i < maxNumber; i += 2) {\n numbers.push(i);\n }\n\n while (numbers.length) {\n primes.push(numbers.shift());\n numbers = numbers.filter(function (i) {\n return i % primes[primes.length - 1] !== 0;\n });\n }\n}", "generateRange(floor, ceil) {\n return Array.from({ length: ceil - floor }, (_v, k) => k + floor);\n }", "function multiplesOfNumbers(limit){\r\n for(var i=0;i<=limit;i++){\r\n if(i%3==0 && i%5==0){\r\n console.log(i);\r\n }\r\n }\r\n}", "function sumCubes(n){\nlet sumOfCubes = 0\nfor(let i =1;i<=n; i++){\nsumOfCubes += i * i * i\n}\nreturn sumOfCubes\n}", "function multi3 (){\n for (var i=100; i > 0; i--){\n if (i % 3 == 0){\n console.log(i);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maybe DONT NEED!! Called when a user login Tell frontend the unread message number of this user Use socket.io
UnreadCount (socket, username){ let dboper = new PrivateChatDBOper("", username, url); //emit individual count of unread msg(private) dboper.GetCount_IndividualUnreadMsg(function(statuscode, results){ if(statuscode==success_statuscode) socket.emit("IndividualPrivateUnreadMsgCnt", results); }); }
[ "function update_unread_count() {\n GET(\n\t'/api/user/info/unread',\n\t{},\n\tfunction(xhr) {\n\t var result = JSON.parse(xhr.responseText)\n\t if(result.code == 0) {\n\t\treplyme_link.textContent = printf(\n\t\t '%1(%2)',\n\t\t replyme_link.dataset.content,\n\t\t result.data['reply']\n\t\t);\n\t\tatme_link.textContent = printf(\n\t\t '%1(%2)',\n\t\t atme_link.dataset.content,\n\t\t result.data['at']\n\t\t);\n\t } else {\n\t\tconsole.error(\n\t\t printf('Failed to get unread count: %1', result.msg)\n\t\t);\n\t }\n\t},\n\tfunction(status, text) {\n\t if(status != 0)\n\t\tconsole.error(\n\t\t printf('Failed to get unread count: %1 %2', status, text)\n\t\t);\n\t else\n\t\tconsole.error(\n\t\t 'Failed to get unread count: connection error or timeout'\n\t\t);\n\t}\n )\n}", "function countUnreadMessages () {\n console.log(chalk.yellow(\"countUnreadMessages: {no paramater} \"));\n var sender = CURRENT_ROOM;\n connection.query(\"select sum(m.read) as unread_count from messages m where recipient = ? and read = 0 limit 1\", [sender], function (error, result) {\n if (result == null) {\n console.log(\"countUnreadMessages: 0\");\n socket.emit('showUnreadMessages_' + sender, 0);\n }else{\n console.log(\"countUnreadMessages: \", result[0].unread_count);\n socket.emit('showUnreadMessages_' + sender, result[0].unread_count);\n }\n });\n }", "getCount_IndividualPrivateUnreadMsg (socket){\n return function(username){\n let dboper = new PrivateChatDBOper(\"\", username, url);\n //emit count of all unread msg(public + private)\n dboper.GetCount_IndividualUnreadMsg(function(statuscode, results){\n if(statuscode==success_statuscode) socket.emit(\"IndividualPrivateUnreadMsgCnt\", results);\n });\n };\n }", "refreshUnreadMessageNumber() {\n this.getApi().post('message/unread-number/', {\n infos: this.getJwtValues(),\n token: this.getToken(),\n }).then((data) => {\n this.updateTokenIfExist(data.token);\n if (data.success) {\n this.setUnreadMessageNumber(data.nb_unread);\n }\n });\n }", "function getUnread(req, res){\n var count = 0;\n models.Message.find({to: req.user.getId()}).sort('date', -1).each(function(err,msg,next){\n if(msg){\n if (msg.read == false) count++;\n next();\n }\n else{ res.send(count.toString()) };\n });\n}", "function vivocha_media_unreadCounter() {\r\n if (!vivocha.contact) {\r\n return;\r\n } //prevent badge on first bot message\r\n var t = vivocha.$(\"#vvc_widget_\" + widget.custom.id + \" .unreadCounter\")\r\n , nm = 1;\r\n if (t.is(':visible')) {\r\n nm = parseInt(t.text() ? t.text() : 0, 10);\r\n nm++;\r\n }\r\n if (vivocha.$(\"#vvc_widget_\" + widget.custom.id + \" .vivocha_media_chatMessages:visible\").size() < 1) {\r\n t.show();\r\n }\r\n t.text(nm);\r\n}", "function USERREADMSG(callback) {\n request({\n method: 'GET',\n url: baseurl + '/server/users/' + userdata.id + '/msg/',\n jar: j1,\n }, callback);\n }", "function updateCount(user,roomNo) {\n io.sockets.connected[user].emit(\"roomCount\",{roomNumber: roomNo, count : getRoomCount(roomNo)})\n}", "function updateUnreadCounter() {\n $.ajax({\n url: '/api/dashboard/contacts/unread',\n dataType: 'json',\n success: function (result) {\n // Set to empty string when there are no unread messages to hide the element.\n $('.badge').text(result === 0 ? '' : result);\n },\n complete: function () {\n // Always reschedule a new update every interval\n setTimeout(updateUnreadCounter, interval);\n },\n });\n }", "function updateMessageCounter() {\n $.ajax({\n \"url\": \"/index.php/coms/getCountUnreadMessages\",\n \"method\": \"POST\",\n \"dataType\": \"JSON\",\n success: function(data) {\n notifyMessage(parseInt(data.unread_count));\n },\n error: function() {\n showAlert(\"danger\", \"You have been logout.\");\n }\n });\n}", "function getUnreadMessages(){\n AuthFactory.auth.$onAuthStateChanged(function(currentUser) {\n if(currentUser){\n return currentUser.getToken().then(function(idToken) {\n return $http({\n method: 'GET',\n url: '/message/unread-messages',\n headers: {\n id_token: idToken\n }\n })\n .then(function(response) {\n unreadMessages.unread = response.data.length;\n }),\n function(error) {\n console.log('Error with messages POST request: ', error);\n };\n });\n }\n });\n }", "privateMessageSocket (socket, ConnectedSockets){\n return function(msg) {\n var sender = msg.sender;\n var receiver = msg.receiver;\n var status = msg.emergency_status;\n msg[\"timestamp\"] = Date.now();\n msg[\"EmergencyStatus\"] = status;\n if (ConnectedSockets.hasOwnProperty(receiver)) {\n ConnectedSockets[receiver].emit(\"PrivateChat\", msg);\n //emit update notification of unread\n //emit count of all unread msg(public + private)\n let dboper = new PrivateChatDBOper(sender, receiver, url);\n //emit individual count of unread msg(private)\n dboper.GetCount_IndividualUnreadMsg(function (statuscode, results) {\n if (statuscode == success_statuscode) ConnectedSockets[receiver].emit(\"IndividualPrivateUnreadMsgCnt\", results);\n });\n }\n };\n }", "function increaseUserMessageCounter() {\n recentUserMessages++\n}", "function updateUserCount() {\n io.sockets.emit(chat.PACKETS.USER_COUNT, {count: userCount});\n}", "function get_num_unread_messages(){\n $.post(root + \"php_actions/message_actions/get_unread.php\", function (data) {\n //refresh user list with new data\n $('#user-list').html(data);\n\n //set click function of users list\n set_message_action();\n });\n}", "function logNumUsersOnline() {\n const oneUserOnline = '1 user online';\n const multipleUsersOnline = `${wss.clients.size} users online`;\n const numUsersOnline = {\n type: 'numUsersOnline'\n }\n wss.clients.forEach(client => {\n if (wss.clients.size === 1) {\n numUsersOnline.content = oneUserOnline;\n client.send(JSON.stringify(numUsersOnline));\n } else {\n numUsersOnline.content = multipleUsersOnline;\n client.send(JSON.stringify(numUsersOnline));\n }\n });\n}", "function initUnreadCount() {\n updateUnreadCount(true);\n mobile || setInterval(updateUnreadCount, 60000);\n window.addEventListener('focus', updateUnreadCount, false);\n }", "function OnRead(client,session) { \n var countRead = 0;\n client.onAck(ack => {\n let messageid = ack.id._serialized;\n let msgid = ack.id.id;\n let message = ack.body;\n let ackno = ack.ack;\n let chatid = ack.to;\n var formattedTime = momentTz(new Date().now).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm')\n if(countRead < 1){\n var LogsMesage = '['+formattedTime+' | '+ack.from.replace(\"@c.us\",\" \")+'] => '+ack.body +' <br>'\n fs.appendFile('./logs/storage/message_send_'+session+'.txt', LogsMesage+ \"\\r\\n\" , function (err) {\n if (err) throw err;\n console.log(\"Message : \",message.body);\n });\n }\n \n con.query(\"update chats set ack='\"+ackno+\"',messageid='\"+messageid+\"',msgid='\"+msgid+\"' where chatid='\"+chatid+\"' and message='\"+addslashes(message)+\"'\");\n fs.writeFile('./logs/ack_sent_'+ack.type+'.json',JSON.stringify(ack),'utf8',function(err){\n if(err) console.log(err);\n });\n countRead++;\n });\n}", "componentDidMount() {\n this.socket = new WebSocket('ws://localhost:3001');\n this.socket.onmessage = (event) => {\n const data = JSON.parse(event.data);\n if(data.type === 'userCountChange') {\n this.setState({userCount: data.count});\n } else {\n const messages = this.state.messages.concat(data);\n this.setState({ messages: messages })\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Atualiza a quantidade de visitar no site, utilizando o LocalStorage
function updateVisit() { let div = document.getElementById("count"); if (localStorage === null || typeof (Storage) === 'undefined') { document.write("Sem suporte para Web Storage"); } localStorage.count === undefined ? visitCount(div, true) : visitCount(div, false); }
[ "function updateVisit() {\n if (typeof (Storage) != \"undefined\") {\n if(localStorage.count !== undefined) {\n localStorage.count = parseInt(localStorage.count) + 1;\n document.getElementById(\"count\").innerHTML = localStorage.count;\n } else {\n localStorage.count = 1;\n document.getElementById(\"count\").innerHTML = 1;\n }\n } else {\n document.write(\"Sem suporte para Web Storage\");\n } \n}", "function counter() {\n // debugger;\n var getMeNumber = localStorage.getItem(\"visits\");\n if (getMeNumber == null || isNaN(getMeNumber)) {\n getMeNumber = 0;\n } else {\n getMeNumber = parseInt(getMeNumber);\n }\n getMeNumber++;\n localStorage.setItem(\"visits\", getMeNumber.toString())\n document.querySelector(\"#visited\").innerHTML = localStorage.getItem(\"visits\");\n}", "function khoitao()\n{\n\t//kiem tra kho\n\tvar c=window.localStorage.getItem(\"count\");\n\tif(c==null)\n\t{\n\t\twindow.localStorage.setItem(\"count\",0);\n\t}\n}", "function nombreProduit(){ \n let nombreProduit = localStorage.getItem(\"qté\"); \n nombreProduit = parseInt(nombreProduit);\n \n if (nombreProduit){\n localStorage.setItem(\"qté\", nombreProduit + 1);\n document.querySelector (\".totalQté\").textContent = nombreProduit + 1;\n } else{\n localStorage.setItem(\"qté\", 1);\n document.querySelector (\".totalQté\").textContent = 1;\n };\n }", "function maxnumber(){\n\n//upate the value of max number of clicks & save it after updating in local storage \nmaxNumberofclicks+=25;\nlocalStorage.setItem('maxnumberofclicks',JSON.stringify(maxNumberofclicks))\n\n}", "function saveCountToLS() {\r\n let countData = document.getElementById('nr-of-items');\r\n let itemsCount = countData.innerHTML;\r\n localStorage.setItem('items-count', itemsCount);\r\n}", "function nombreProduit() {\n let nombreProduit = localStorage.getItem('qté');\n nombreProduit = parseInt(nombreProduit);\n\n if (nombreProduit) {\n localStorage.setItem(\"qté\", nombreProduit + 1);\n document.querySelector('.totalQté').textContent = nombreProduit + 1;\n } else {\n localStorage.setItem(\"qté\", 1);\n document.querySelector('.totalQté').textContent = 1;\n }\n }", "function calculateVisitNumber() {\n try {\n var visitElem = document.getElementById(\"visitNumber\");\n var visitNum = localStorage.getItem(\"visitNumber\");\n visitNum = visitNum ? visitNum : 0;\n visitNum++;\n // visitNode = document.createElement(h5);\n visitNode = document.createTextNode(visitNum);\n visitElem.appendChild(visitNode);\n\n localStorage.setItem(\"visitNumber\", visitNum);\n }\n catch (e) {\n\n }\n}", "function getTotalWatched() {\n document.getElementById(\"total\").innerHTML = localStorage ? localStorage.length : 0;\n}", "function saveValueResult(result) {\r\n\r\n var cnt1 = document.getElementById('C');\r\n /*questa variabile tiene conto di quante immagini sono state visualizzate durante\r\n il test in corso in modo da poter associare le valutazioni all'immagine corretta*/\r\n var enter = localStorage.getItem(\"count\");\r\n if (enter == null) { //inizializzazione della variabile al primo ciclo\r\n localStorage.setItem(\"count\", \"1\");\r\n enter = localStorage.getItem(\"count\");\r\n }\r\n enter = Number(enter);\r\n\r\n /*nel localStorage i valori degli smile si chiamano \"Val*\", mentre i valori dell'indice di\r\n gradimento si chiamano \"Valg*\", la riga di codice sotto estrare il valore dello smile alla\r\n corrispondente alla pagina corrente e viene verificato se è stato scelto uno smile\r\n in caso affermativo si procede a salvare l'indice di gradimento selezionato (result)\r\n in caso contrario viene mostrato un alert che invita a scegliere prima lo smile*/\r\n var k = localStorage.getItem(\"Val\" + enter);\r\n if (k == null) {\r\n alert(\"Scegliere prima lo smile e poi scegliere l'indice di gradimento\");\r\n } else {\r\n localStorage.setItem('Valg' + (enter), result); //salvataggio indice di gradimento\r\n enter += 1;\r\n localStorage.setItem('count', enter);\r\n cnt1.innerHTML = '<img src = \"../img/Img_generali/white.png\" class=\"img-responsive\" alt=\"Responsive image\" style=\"width:70%;height:70%\">';\r\n if (enter <= ltest) { //check di fine test\r\n generaImmaginiRandom(enter); //se falso nuova immagine\r\n } else {\r\n localStorage.setItem(\"count\", \"1\"); // se vero reset di count e passaggio a un'altra pagina\r\n location.replace(gotoref1);\r\n }\r\n }\r\n}", "function update_local_storage() {\n\t\tvar space = local_storage_space();\n\t\tvar used = space.used;\n\t\tvar free = space.free;\n\t\tvar width = Math.ceil((used.replace_all(\",\", \"\") / free.replace_all(\",\", \"\")) * 100);\n\t\tdocument.getElementsByClassName(\"settings-wrapper\")[0].getElementsByClassName(\"settings-storage-foreground\")[0].style.width = width + \"%\";\n\t\tdocument.getElementsByClassName(\"settings-wrapper\")[0].getElementsByClassName(\"settings-storage-title\")[0].textContent = used + \" KBs Used | \" + free + \" KBs Free\";\n\t\tif(used > free - 100) {\n\t\t\tnotify(\"Local Storage\", \"The local storage is almost full.\", \"theme\", 4000);\n\t\t}\n\t}", "function loadCountFromLS() {\r\n document.getElementById('nr-of-items').innerHTML = localStorage.getItem('items-count');\r\n}", "function hitCount(){\r\n\tif (localStorage.pagecount){\r\n\t\tlocalStorage.pagecount=Number(localStorage.pagecount) +1;\r\n\t}\r\n\telse{\r\n\t\tlocalStorage.pagecount=1;\r\n\t}\r\n\tdocument.getElementById(\"hits\").innerHTML=localStorage.pagecount;\r\n}", "function Save(){\n localStorage.setItem(\"monsterrawrs\",monstercount)\n}", "function pageVisitedCounter(){\n //check if type writer exists on the current page\n var text = document.getElementById('text');\n if (text)\n var word = text.getElementsByTagName('span');\n if (word)\n StartType();\n\n //check if user has visited this website before, if no, set the default value to 0\n if (localStorage.getItem(\"VISITED\") === null)\n localStorage.setItem(\"VISITED\", 0);\n\n //increase and update the page visited count\n let pageVisitCount = +localStorage.getItem(\"VISITED\") + 1;\n localStorage.setItem(\"VISITED\", pageVisitCount);\n\n let updatePageText = document.getElementById(\"pageVisited\");\n updatePageText.append(\"You've visited this website \" + pageVisitCount + \" times\");\n}", "function prixTotal(){\n let price = parseInt(reflex.price);\n let prixDuPanier = JSON.parse(localStorage.getItem(\"prixTotal\"));\n \n if(prixDuPanier != null){\n localStorage.setItem(\"prixTotal\", prixDuPanier + price);\n } else {\n localStorage.setItem(\"prixTotal\", price);\n };\n }", "function linksUpdate(num) {\n localStorage[\"numLinks\"] = num;\n}", "function aumentarCantidad(item){\n\n let cantidadItems = localStorage.getItem('cantidad');\n cantidadItems = parseInt(cantidadItems);\n if(cantidadItems)\n {\n localStorage.setItem('cantidad', cantidadItems + 1);\n } else{\n localStorage.setItem('cantidad', 1);\n }\n registrarItems(item);\n itemsDesplegados = JSON.parse(localStorage.getItem('seleccion'));\n suma();\n}", "function addValue(){\r\n var sum = parseInt( localStorage.getItem(\"M+ Values\"));\r\n var a = parseInt(document.getElementById(\"calc\").value); \r\n sum = sum + a;\r\n localStorage.setItem(\"M+ Values\",sum);\r\n // console.log(\"sum : \" + sum);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function that returns a data object used in vis.Network(container, data, options). The object consists of nodes and edges, where there are n nodes, and a random amount of edges
function getRandomNetwork(numberNodes) { nodesArray = new vis.DataSet([]); edgesArray = new vis.DataSet([]); let probability = 0.13; // make n nodes for (let i = 0; i < numberNodes; i++) { nodesArray.add({id: i, label: "Node " + i}); } // populate edges for (let i = 0; i < numberNodes; i++) { for (let j = 0; j < numberNodes; j++) { if (Math.random() < probability) { if (i !== j && i < j && edgesArray.get(i + "-" + j) === null) { edgesArray.add({id: i + "-" + j, from: i, to: j, label: "" + Math.ceil(Math.random() * numberNodes),}); } else if (i !== j && j < i && edgesArray.get(j + "-" + i) === null) { edgesArray.add({id: j + "-" + i, from: j, to: i, label: "" + Math.ceil(Math.random() * numberNodes),}); } } } } nodes = nodesArray; edges = edgesArray; return { edges: edgesArray, nodes, nodesArray }; }
[ "function generateNewData() {\n // Reset the data object back to its empty state.\n data.nodes = [];\n data.links = [];\n\n // Create nodes.\n for (let i = 0; i < NUMBER_OF_NODES; i++) {\n let node = {\n index: i,\n color: d3.interpolateRainbow(i / NUMBER_OF_NODES),\n size: Math.floor(randBetween(MIN_NODE_SIZE, MAX_NODE_SIZE))\n }\n data.nodes.push(node);\n }\n\n // Create links.\n for (let i = 0; i < NUMBER_OF_NODES; i++) {\n for (let j = i + 1; j < NUMBER_OF_NODES; j++) {\n if (Math.random() < PROBABILITY_OF_LINK) {\n let minSize = Math.min(data.nodes[i].size, data.nodes[j].size);\n let link = {\n source: data.nodes[i],\n target: data.nodes[j],\n weight: Math.floor(randBetween(1, minSize))\n }\n data.links.push(link);\n }\n }\n }\n\n return data;\n }", "function createGraph()\r\n\t\t\t{\r\n\t\t\t\t\tlet edges = [];\r\n\t\t\t\t\tlet nodes = [];\r\n\r\n\t\t\t\t\tlet V = Math.floor(Math.random()*10);\r\n\r\n\t\t\t\t\tfor(let i = 1; i <= V ; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnodes.push({id : i,label : \"person\"+i});\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor(let i = 1; i <= V ; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor(let j = i + 1; j <= V ; j++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tlet isEdge = Math.random();\r\n\r\n\t\t\t\t\t\t\t\t\tif(isEdge > 0.5)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tlet Dir = Math.random();\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tif(Dir > 0.5)\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tedges.push({from : i , to : j , label : String(Math.floor(Math.random()*100))});\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tedges.push({from : j , to : i , label : String(Math.floor(Math.random()*100))});\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tdata = {\r\n\r\n\t\t\t\t\t\tnodes : nodes,\r\n\t\t\t\t\t\tedges : edges,\r\n\t\t\t\t\t};\r\n\r\n\r\n\t\t\t\t\treturn data;\r\n\t\t\t}", "function generate_graph_data(num_nodes, type)\n{\n\n var i, j, dataset = {\n nodes :[],\n edges :[]\n }\n\n if(type == \"Line\")\n {\n for(i = 0; i < num_nodes; i++)\n {\n dataset.nodes.push({name: \"node \" + i, system_type: \"W32\"\n , social_eng: \"false\"\n , intrusion_detect: \" false\"\n , honeypot: \" false\"\n , software_uptodate: \" false\"\n , infected_with: \"none\"\n , adjacent_to: []});\n if(i == 0)\n dataset.nodes[i].adjacent_to.push(i+1);\n else if(i == num_nodes - 1)\n dataset.nodes[i].adjacent_to.push(i-1);\n else\n dataset.nodes[i].adjacent_to.push(i-1, i+1);\n }\n \n for(j = 0; j < num_nodes - 1; j++)\n dataset.edges.push({ source: j, target: j + 1 });\n }\n else if(type == \"Star\")\n {\n dataset.nodes.push({name: \"Central Hub\", system_type: \"NA\"\n , social_eng: \"false\"\n , intrusion_detect: \" false\"\n , honeypot: \" false\"\n , software_uptodate: \" false\"\n , status: \"active\"\n , infected_with: \"none\"\n , adjacent_to: []});\n \n for(i = 0 ; i < num_nodes; i++)\n {\n dataset.nodes.push({name: \"node \" + i, system_type: \"W32\"\n , social_eng: \"false\"\n , intrusion_detect: \" false\"\n , honeypot: \" false\"\n , software_uptodate: \" false\"\n , status: \"active\"\n , infected_with: \"none\"\n , adjacent_to: []});\n }\n for(i = 1; i < num_nodes + 1; i++)\n dataset.nodes[0].adjacent_to.push(i);\n for(j = 1; j < num_nodes + 1; j++)\n {\n dataset.nodes[j].adjacent_to.push(0);\n dataset.edges.push({ source: j, target: 0 });\n }\n //console.log(\"gen_graph_data(): dataset \", dataset);\n }\n else if(type == \"Mesh\")\n {\n var randLength;\n var randNode;\n \n for(i = 0 ; i < num_nodes; i++)\n {\n dataset.nodes.push({name: \"node \" + i, system_type: \"W32\"\n , social_eng: \"false\"\n , intrusion_detect: \" false\"\n , honeypot: \" false\"\n , software_uptodate: \" false\"\n , status: \"active\"\n , infected_with: \"none\"\n , adjacent_to: []});\n }\n for(j = 0; j < num_nodes; j++)\n {\n /* Making number of adjacent nodes proportional to the square root of the number\n of nodes seems to scale well */\n randLength = Math.floor((Math.random() \n * (Math.sqrt(num_nodes))) + 1); //cant be 0\n for(var k = 0; k < randLength; k++)\n {\n randNode = Math.floor((Math.random() \n * (num_nodes)));\n // console.log(\"Node:\", randNode);\n dataset.nodes[j].adjacent_to.push(randNode);\n dataset.nodes[randNode].adjacent_to.push(j);\n\n dataset.edges.push({ source: randNode, target: j });\n dataset.edges.push({ source: j, target: randNode });\n }\n \n }\n console.log(dataset);\n }\n else if(type == \"Ring\")\n {\n for(i = 0; i < num_nodes; i++)\n {\n dataset.nodes.push({name: \"node \" + i, system_type: \"W32\"\n , social_eng: \"false\"\n , intrusion_detect: \" false\"\n , honeypot: \" false\"\n , software_uptodate: \" false\"\n , status: \"active\"\n , infected_with: \"none\"\n , adjacent_to: []});\n if(i == 0)\n dataset.nodes[i].adjacent_to.push(i+1, num_nodes - 1);\n else if(i == num_nodes - 1)\n dataset.nodes[i].adjacent_to.push(i-1, 0);\n else\n dataset.nodes[i].adjacent_to.push(i-1, i+1);\n }\n \n for(j = 0; j < num_nodes - 1; j++)\n dataset.edges.push({ source: j, target: j + 1 });\n dataset.edges.push({ source: j, target: 0 });\n }\n else if(type == \"Complete\")\n {\n for(i = 0; i < num_nodes; i++)\n {\n dataset.nodes.push({name: \"node \" + i, system_type: \"W32\"\n , social_eng: \"false\"\n , intrusion_detect: \" false\"\n , honeypot: \" false\"\n , software_uptodate: \" false\"\n , status: \"active\"\n , infected_with: \"none\"\n , adjacent_to: []}); \n }\n //n(n-1)/2 nodes in complete graph\n for(j = 0; j < num_nodes; j++)\n {\n for(i = 0; i < num_nodes; i++)\n {\n if(i != j)\n {\n dataset.nodes[j].adjacent_to.push(i);\n dataset.edges.push({source: j, target: i});\n }\n }\n }\n } \n return dataset;\n}", "function createNodes(rawData) {\n // Use the max total_amount in the data as the max in the scale's domain\n // note we have to ensure the total_amount is a number.\n var maxAmount = d3.max(rawData, function (d) { return +d.Emissions; });\n\n // Sizes bubbles based on area.\n // @v4: new flattened scale names.\n var radiusScale = d3.scalePow()\n .exponent(0.5)\n .range([2, 85])\n .domain([0, maxAmount]);\n\n // Use map() to convert raw data into node data.\n // Checkout http://learnjsdata.com/ for more on\n // working with data.\n\n var myNodes = rawData.map(function (d, i) {\n\n return {\n id: i,\n radius: 1.3 * radiusScale(+d.Emissions),\n emissions: +d.Emissions,\n food: d.Food,\n group: d.Group,\n x: Math.random() * 900,\n y: Math.random() * 800,\n img: d.Image\n };\n });\n\n // sort them to prevent occlusion of smaller nodes.\n myNodes.sort(function (a, b) { return b.emissions - a.emissions; });\n\n return myNodes;\n }", "function genNetworkStats(){\n\n //Get the counts of unique domains\n data.domains = _.reduce(_.groupBy(data.networks, function(n){\n return n._source.networkDomain;\n }), function(toRet, val, key){\n toRet.labels.push(key);\n toRet.data[0].push(val.length);\n return toRet;\n }, data.domains);\n\n //Get the counts of unique graph properties (Stored as a string of comma separated\n //properties\n data.properties = _.reduce(_.groupBy(_.reduce(data.networks, function(arr, n){\n return arr.concat(_.map(n._source.graphProperties.split(','), function(nTrim){\n return nTrim.trim();\n }));\n },[]), function(n){\n return n;\n }), function(toRet, val, key){\n toRet.labels.push(key);\n toRet.data[0].push(val.length);\n return toRet;\n }, data.properties);\n\n var nearestPower = function(n){\n return Math.pow(10, n.toString().length - 1);\n };\n\n var individualGraphs = _.flatten(_.reduce(data.networks, function(toRet, n){\n toRet.push(n._source.graphs);\n return toRet;\n },[]));\n\n data.numEntries = individualGraphs.length;\n\n //Get range of graph sizes for the current data\n var nodes = _.map(individualGraphs, function(n){ return n.nodes });\n var edges = _.map(individualGraphs, function(n){ return n.edges});\n var sizeDistNodes = _.reduce(_.groupBy(nodes , nearestPower), function(iter, arr, key){\n iter.labels.push(key);\n iter.data.push(arr.length);\n return iter;\n },{labels:[], data:[]});\n\n var sizeDistEdges = _.reduce(_.groupBy(edges, nearestPower), function(iter, arr, key){\n iter.labels.push(key);\n iter.data.push(arr.length);\n return iter;\n },{labels:[], data:[]});\n\n data.sizeDist = {\n data: [sizeDistNodes.data, sizeDistEdges.data],\n labels: sizeDistNodes.labels,\n series: ['Nodes', 'Edges']\n };\n\n }", "function createRandomDataArray() {\n var randomStructureArray = [];\n var amountOfFriends = Math.floor(( Math.random() * dataSetCreatorRandomAmount) + 2);\n \n for ( var i = 0; i < amountOfFriends; i++ ) {\n // 25% chance to create a deeper level array, 75% chance to just create friends\n var randomAmount = Math.floor( Math.random() * 4 );\n \n if ( randomAmount == 3 ) {\n // I am so GDLK with recursion\n randomStructureArray.push( createRandomDataArray() );\n \n } else {\n randomStructureArray.push( randomAmount );\n }\n }\n \n // Eventually reduce this number so it HAS to end at some point :D\n dataSetCreatorRandomAmount--;\n \n return randomStructureArray;\n}", "function init_nodes(nodes, edges){\r\n var links = data.links; // {target: n1, source: n2}\r\n // process nodes\r\n for(var i=0; i<NUM_NODES; i++) {\r\n var node = {\r\n val: i, \r\n vx: 0,\r\n vy: 0,\r\n x: Math.random() * 400,\r\n y: Math.random() * 400,\r\n force_x: 0,\r\n force_y: 0\r\n };\r\n nodes.push(node);\r\n edges.push([]);\r\n }\r\n // process edges\r\n for(var i=0; i<links.length; i++) {\r\n var source = links[i].source,\r\n target = links[i].target;\r\n edges[target].push(source);\r\n edges[source].push(target);\r\n }\r\n}", "function createNodes(rawData) {\n\t\t// Use the max total_amount in the data as the max in the scale's domain\n\t\t// note we have to ensure the total_amount is a number.\n\t\tvar maxAmount = d3.max(rawData, function (d) { return +d.value; });\n\n\t\t// Sizes bubbles based on area.\n\t\t// @v4: new flattened scale names.\n\t\tvar radiusScale = d3.scalePow()\n\t\t.exponent(0.5)\n\t\t.range([1, 20])\n\t\t.domain([0, maxAmount]);\n\n\t\t// Use map() to convert raw data into node data.\n\t\t// Checkout http://learnjsdata.com/ for more on\n\t\t// working with data.\n\t\tvar myNodes = rawData.map(function (d) {\n\t\t\treturn {\n\t\t\t\tradius: radiusScale(+d.value) * (width/1366),\n\t\t\t\tvalue: +d.value,\n\t\t\t\tname: d.tech,\n\t\t\t\tcountry: d.country,\n\t\t\t\tx: Math.random() * 900,\n\t\t\t\ty: Math.random() * 800\n\t\t\t};\n\t\t});\n\n\t\t// sort them to prevent occlusion of smaller nodes.\n\t\tmyNodes.sort(function (a, b) { return b.value - a.value; });\n\n\t\treturn myNodes;\n\t}", "function createNodes(rawData) {\n // Use the max amount in the data as the max in the scale's domain\n // note we have to ensure the amount is a number. \n var maxAmount = d3.max(rawData, function (d) { return +d.amount; });\n\n // Sizes bubbles based on area.\n // @v4: new flattened scale names.\n var radiusScale = d3.scalePow()\n .exponent(0.5)\n .range([2, 85])\n .domain([0, maxAmount]);\n // .domain([0, 10]);\n\n // Use map() to convert raw data into node data.\n // Checkout http://learnjsdata.com/ for more on\n // working with data.\n var myNodes = rawData.map(function (d) {\n return {\n id: d.id,\n term: d.term,\n alt: d.alt,\n descr: d.descr,\n egs: d.egs,\n cat: d.cat,\n radius: radiusScale(+d.amount),\n value: +d.amount,\n catdescr: d.catdescr,\n dup: d.dup,\n x: initialX(d.dup),\n y: initialY(d.dup)\n };\n });\n\n // sort them to prevent occlusion of smaller nodes.\n //myNodes.sort(function (a, b) { return b.value - a.value; });\n\n return myNodes;\n }", "generateEdges(){\n let keys = Object.keys(this.storage);\n //Randomly select toNode and fromNode\n for (let i= 0; i < 50; i++) {\n let nodes = _.sample(keys, 2);\n let toNode = _.sample(Object.keys(this.storage[nodes[0]]));\n let fromNode = _.sample(Object.keys(this.storage[nodes[1]]));\n this.addEdge(fromNode, toNode);\n }\n }", "function createNetwork(options) {\n const [network] = createSampleNetwork(options);\n\n return network;\n }", "function createCustomData() {\n return {\n dict: {},\n nextNodeId: 1,\n };\n}", "function buildNetwork(data) {\n\n data = filterDataByYear(data, networkChart['selectedYear']);\n\n networkChart.nodes = data['nodes']\n networkChart.links = data['links']\n\n}", "function randomNetwork() {\n let traps = randomTraps();\n let target = randomTarget();\n let walls = randomWalls();\n\n while (\n // prevent target from appearing on traps\n traps.trapsXY.some((xy) => xy.join() === target.join()) ||\n // and make sure it appears in a dead end\n walls.connections[target[0]][target[1]] !== 1\n ) {\n traps = randomTraps();\n target = randomTarget();\n }\n\n return {\n colors: randomColors(),\n traps: traps,\n target: target,\n walls: walls\n };\n}", "function DataNode(data, meta){\n var _obj = {};\n var _data = d3.set(data);\n var _meta = meta || {};\n _meta.count = _data.values().length;\n \n /**\n #### .meta([key], [value])\n Gets or sets metadata for this data set. If no arguments are given, the\n entire metadata object is returned. A 'count' metadata value is always\n made available with the number of items in the data set.\n **/\n _obj.meta = function(k,v){\n if(!arguments.length){ return _meta; }\n if(arguments.length == 1){ return _meta[k]; }\n _meta[k] = v;\n return _obj;\n };\n \n /**\n #### .data([array])\n Gets or sets the data associated with this node. It is coerced into a set.\n **/\n _obj.data = function(a){\n if(!arguments.length){ return _data; }\n _data = d3.set(a);\n _meta.count = _data.values().length;\n return _obj;\n };\n \n /**\n #### .accept(visitor)\n Implements the visitor pattern to allow various operations on this node.\n **/\n _obj.accept = function(v){\n v.visitPre(_obj);\n v.visitPost(_obj);\n };\n \n return _obj;\n}", "function createDataset () {\n var set = []\n var numPoints = Math.random() * 100\n var maxX = Math.random() * 1000\n var maxY = Math.random() * 500\n var maxR = Math.random() * 25\n\n for (var i = 0; i < numPoints; i++) {\n set.push({\n x: Math.floor(Math.random() * maxX),\n y: Math.floor(Math.random() * maxY),\n r: Math.floor(Math.random() * maxR) + 1\n })\n }\n\n return set\n }", "function randomGraph(numNodes, numLinks, maxLinksEach){\n\n// initialize graph to return\n var graph = {\"nodes\":[], \"links\":[]};\n \n // initialize nodes who have reached maximum number of links and those with no links\n var fullNodes = [];\n var idWithoutLinks = [];\n\n // create all vertexes in the graph and append them to the graph array\n for(var i = 0; i<numNodes; i++){\n graph.nodes.push({\"id\":i, \"connections\":[], \"links\": []});\n }\n\n// create links until the desired amount is obtained\n for (var i = 0; i<numLinks; i++){ \n\n// get two nodes from the graph to consider for creating an edge\n node1 = graph.nodes.popRandomNode();\n \n// if the nodes have already reached their edge limit don't consider them and continue\n if(node1 == null){\n continue;\n }\n node2 = graph.nodes.popRandomNode();\n if(node2 == null){\n graph.nodes.push(node1);\n continue;\n }\n\n// if the edge hasn't already been added add it to the nodes adjacency list and the link list\n if(node1.connections.indexOf(node2) == -1 && node2.connections.indexOf(node1)== -1){\n // add nodes to the adjacency list for each node\n node1.connections.push(node2);\n node2.connections.push(node1);\n\n// create a link add add it to the link list\n tempLink = {\"source\":node1.id, \"target\":node2.id, \"weight\":Math.floor(Math.random()*30)};\n graph.links.push(tempLink);\n node1.links.push(tempLink);\n node2.links.push(tempLink);\n }\n// if the nodes now have reached the max number of links allowed push them into a separate list so they are no longer considered\n (node1.connections.length < maxLinksEach) ? graph.nodes.push(node1) : fullNodes.push(node1);\n (node2.connections.length < maxLinksEach) ? graph.nodes.push(node2) : fullNodes.push(node2);\n\n }\n // combine the full nodes and graph nodes (those with 1 less than the maximum allowed links) and return the result\n graph.nodes.push.apply(graph.nodes, fullNodes);\n return graph;\n}", "function drawNetwork({nodes: nodesDataset, edges: edgesDataset}) {\n network = new vis.Network(container, {nodes: nodesDataset, edges: edgesDataset} , options);\n }", "createRandomNetwork(){\n const maxDegree = this.settings.numV - 1\n var maxEdges = Math.floor(maxDegree*this.settings.numV/2)\n const vertices = []\n let availableVertices = [] //used for determining edge assignment\n //create random points from 0 to 1\n for(let i = 0; i < this.settings.numV; i++){\n if (this.isThreeDimensional){\n vertices.push(new Vertex(Math.random(), Math.random(), Math.random()))\n } else{\n vertices.push(new Vertex(Math.random(), Math.random()))\n }\n availableVertices.push(i)\n }\n\n\n const edges = []\n if (!this.settings.properties.Cycle){\n let already_connected = new Map();\n let remainingEdges = this.settings.numE;\n\n if (this.settings.properties.Connected){\n //connect the network before assigning remaining edges\n let unvisited = []\n for(let i = 0; i < this.settings.numV; i++){\n unvisited.push(i)\n }\n let visited = []\n var vIndex1 = pickRandomVertex(unvisited)\n var v1 = unvisited[vIndex1]\n visited.push(v1)\n unvisited = removeFromArray(unvisited, vIndex1)\n var visitedNum = 1;\n while(visitedNum < this.settings.numV) {\n var vIndex2 = pickRandomVertex(unvisited)\n var v2 = unvisited[vIndex2]\n visited.push(v2)\n edges.push(new Edge(v1, v2))\n if (this.isThreeDimensional) edges[edges.length - 1].color = this.edgeInitialColor\n vertices[v1].increment_degree()\n vertices[v2].increment_degree()\n remainingEdges--;\n maxEdges--;\n const indexTo = v1 + 1000 * v2 //works as long as numV < 1000\n const indexFrom = v2 + 1000 * v1;\n already_connected.set(indexTo, true)\n already_connected.set(indexFrom, true)\n unvisited = removeFromArray(unvisited, vIndex2)\n vIndex1 = pickRandomVertex(visited)\n v1 = visited[vIndex1]\n visitedNum++\n }\n }\n\n // assign remaining edges to network\n while(remainingEdges > 0 && maxEdges > 0 && availableVertices.length > 1){\n const [random1, random2] = connectRandomVertices(availableVertices.slice())\n if(random1 === random2) throw new Error(\"Randomly selected values in network generation were the same\")\n if(random1 === undefined) throw new Error(\"Randomly selected value 1 in network generation was undefined \")\n if(random2 === undefined) throw new Error(\"Randomly selected value 2 in network generation was undefined \")\n const indexTo = random1+1000*random2; // as long as numV < 1000 this works\n const indexFrom = random2+1000*random1;\n if(already_connected.get(indexTo) === undefined ){\n edges.push(new Edge(random1, random2));\n if (this.isThreeDimensional){\n edges[edges.length-1].color = this.edgeInitialColor\n }\n vertices[random1].increment_degree();\n vertices[random2].increment_degree();\n if(vertices[random1].degree > maxDegree) availableVertices.splice(random1, 1);\n if(vertices[random2].degree > maxDegree) availableVertices.splice(random2, 1);\n already_connected.set(indexTo, true);\n already_connected.set(indexFrom, true);\n remainingEdges --;\n maxEdges --;\n }\n }\n }\n else{\n var [path, root] = initialRandomCycle(vertices);\n for(let i = 0; i < path.length -1; i++){\n const e = new Edge(path[i], path[i+1])\n if (this.isThreeDimensional) e.color = this.edgeInitialColor\n edges.push(e)\n }\n\n for(let i = 0; i < vertices.length; i++){\n vertices[i].degree = 2\n }\n }\n\n this.settings.shouldReset = false\n this.vertices = vertices\n this.edges = edges\n this.findExtremeDegrees()\n this.applyVertexSize()\n this.applyColorGradient()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a highlight halo to a specified map item(s). svg Root svg element to find things in selector An svg selector for items. filter A predicate run on selected items
function highlightMapLocations(svg, selector, filter, retries) { if (filter === undefined) {filter = function(d,i) {return true;}} var items = svg.selectAll(selector).filter(filter) if (items.empty()) { if (retries === undefined) {retries = 20;} if (retries > 0) { console.error("Retry highlight") setTimeout(function() {highlightMapLocations(svg, selector, filter, retries-1)}, 1000) } return; } items.each( function(d, i) { var id = "highlight" + this.id d3.select(this.parentNode).append("circle") .attr("id", id) .attr("r", 20) .attr('stroke-width', 0) .attr("stroke", "#76231F") .attr("fill", "none") .each(__pulse) function __pulse() { var circle = svg.select("#" + id); (function repeat() { circle = circle.transition() .duration(2000) .attr("stroke-width", 2) .attr("r", 1) .transition() .duration(10) .attr('stroke-width', 0) .attr("r", 20) .ease('sine') .each("end", repeat); })(); } }); }
[ "function identifyHighlights(itemList, filter) {\n if (!Array.isArray(itemList)) {\n return itemList;\n }\n if (!Array.isArray(filter)) {\n if (filter === true || filter === \"all\") {\n filter = [\"all\"]\n } else if (typeof filter === \"object\") {\n filter = Object.keys(filter);\n } else {\n filter = [];\n }\n }\n return itemList.map(function(item) {\n if ((filter.includes(\"all\")\n && !filter.includes(\"-\" + item.id))\n || filter.includes(item.id)) {\n return inheritAndAdd(item, {highlight: true});\n } else {\n return inheritAndAdd(item, {highlight: false});\n }\n });\n }", "function highlightExtractor(elem, isExtractorHighlighted, svgLeafNodes) {\n\t\n\tvar ellipse = elem.find(\"ellipse\");\n\tvar extractorOpacity = ellipse.css('opacity');\n\t\n\tvar dependencyId = ellipse.attr(\"dependency-id\");\n\t\n\t//if an extractor is highlighted and user clicks it again\n\t// we remove the highlight\n\tif (isExtractorHighlighted && extractorOpacity == 1) {\n\t\t$(\"svg\").find(\"*\").fadeTo(\"fast\", 1);\n\t}\n\t\n\t//else either user highlights a first extractor\n\t//or wants to change the highlight to another extractor\n\telse {\n\t\t\n\t\tvar desiredNodes = svgLeafNodes\n\t\t\t\t\t\t\t\t .filter(function(index) {\n\t\t\t\t\t\t\t\t\t \tvar dependencies = $(this).attr(\"dependencies\");\n\t\t\t\t\t\t\t\t\t \tdependencies = extractValues(dependencies);\n\t\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t\t \treturn $.inArray(dependencyId, dependencies) != -1;\n\t\t\t\t\t\t\t\t\t});\n\t\t\n\t\t//highlight the desired nodes\n\t\thighlightDesired(desiredNodes);\n\t}\n}", "highlightData() {\n let _this = this;\n _this.svg.selectAll('.entry')\n .filter(function(d) {\n return Object.keys(_this.options.data)\n .indexOf(d.parentElement.attributes.name.value.split(':')[1]) >=0;\n })\n .attr('data-html', function(d) {\n if(_this.options.tooltip)\n return _this.options\n .tooltip(_this.options\n .data[d.parentElement.attributes.name.value.split(':')[1]]);\n return;\n })\n // .style('fill', '#efefef')\n .style('fill', function(d) {\n if(_this.options.color)\n return _this.options\n .color(_this.options\n .data[d.parentElement.attributes.name.value.split(':')[1]]);\n return;\n });\n }", "highlightFeatures(filter, on) {\n this.dispatch(setHotFilter(filter));\n }", "function highlightItems(){\n\titems.forEach(elem =>{\n\t\t//If the item is checked, toggle its light property\n\t\tif(elem.checked){\n\t\t\telem.light = !elem.light;\n\t\t}\n\t});\n\trenderList();\n}", "function highlightMarkersearch(e){\n var layer = e.feature;\n var iconElem = L.DomUtil.get(e._icon);\n iconElem.style.border=\"4px #00ffff solid\";\n iconElem.style.height=\"38px\";\n iconElem.style.width=\"38px\";\n iconElem.style.marginTop=\"-19px\";\n iconElem.style.marginLeft=\"-19px\";\n iconElem.id=\"selectedIcon\";\n }", "function highlight(country) {\n\t//change stroke\n\tvar selected = d3.selectAll(\"#country\"+country.brk_a3)\n\t\t.style(\"stroke\",\"rgba(217,72,1,0.5)\")\n\t\t.style(\"stroke-width\",\"10\")\n\t\t;\n\t//change stroke\n\tvar selected = d3.selectAll(\"#circle\"+country.brk_a3)\n\t\t.style(\"stroke\",\"#444\")\n\t\t.style(\"stroke-width\",\"4\")\n\t\t;\n\tsetLabel(country); //call popup label\n}", "function updateFilterAppearance() {\n\n map.selectAll(\"circle\")\n .attr(\"opacity\", d => (evalFilters(d)) ? 0.7 : 0.1)\n .attr(\"stroke\", d => (evalFilters(d)) ? \"black\" : \"none\")\n\n }", "function highlightInput(elem, isInputHighlighted, svgLeafNodes) {\n\t//get extractor information\n\tvar ellipse = elem.find(\"ellipse\");\n\tvar extractorOpacity = ellipse.css(\"opacity\");\n\t\n\tvar extractorName = ellipse.attr(\"extractor-id\");\n\t\n\tvar inputThemes = ellipse.attr(\"input-themes\");\n\tinputThemes = extractValues(inputThemes);\n\t\n\t//if an extractor is highlighted and user clicks it again\n\t// we remove the highlight\n\tif (isInputHighlighted && extractorOpacity == 1) {\n\t\t$(\"svg\").find(\"*\").fadeTo(\"fast\", 1);\n\t}\n\t//else either user highlights a first extractor\n\t//or wants to change the highlight to another extractor\n\telse {\n\t\tvar desiredNodes = svgLeafNodes\n\t\t\t\t\t\t\t\t .filter(function(index) {\n\t\t\t\t\t\t\t\t \tvar themeName = $(this).attr(\"theme-name\");\n\t\t\t\t\t\t\t\t \tvar extrName = $(this).attr(\"extractor-id\");\n\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t \t//Do not highlight data files\n\t\t\t\t\t\t\t\t \tif ($(this).attr(\"data-file\") == \"true\") {\n\t\t\t\t\t\t\t\t \t\treturn false;\n\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t \t//all nodes related to the extractor input themes\n\t\t\t\t\t\t\t\t\tif ($.inArray(themeName, inputThemes) != -1) {\n\t\t\t\t\t\t\t\t\t\tvar nodeName = $(this).prop(\"nodeName\");\n\t\t\t\t\t\t\t\t\t\t//we choose a node if: \n\t\t\t\t\t\t\t\t\t\t//- it is not a line\n\t\t\t\t\t\t\t\t\t\t//- it is a line and the line leads to the chosen extractor\n\t\t\t\t\t\t\t\t\t\tif (nodeName != 'line' || nodeName == 'line' && extrName == extractorName) {\n\t\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t//all nodes related to the chosen extractor\n\t\t\t\t\t\t\t\t\tif (extrName == extractorName) {\n\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t});\n\t\t//highlight the desired nodes\n\t\thighlightDesired(desiredNodes);\n\t}\n}", "function addHighlight(project, item) {\r\n\tproject.activate();\r\n\t// highlight layer\r\n\tproject.layers[2].activate();\r\n\t\r\n\t// special case clipped link to frame\r\n\tif (item instanceof paper.Group && item.sketchFrameFlag) {\r\n\t\tfor (var ci=0; ci<item.children.length; ci++) {\r\n\t\t\tvar c = item.children[ci];\r\n\t\t\tif (c.clipped && c.children.length>0) {\r\n\t\t\t\titem = c.children[0];\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t// temporary hack to show red box at bounds as highlight\r\n\tvar topLeft = item.bounds.topLeft;\r\n\tvar bottomRight = item.bounds.bottomRight;\r\n\tvar parent = item.parent;\r\n\twhile(parent instanceof paper.Group && parent.matrix) {\r\n\t\ttopLeft = parent.matrix.transform(topLeft);\r\n\t\tbottomRight = parent.matrix.transform(bottomRight);\r\n\t\tparent = parent.parent;\r\n\t}\r\n\tvar highlightItem = new paper.Path.Rectangle(topLeft, bottomRight);\r\n\thighlightItem.strokeWidth = 1;\r\n\tproject.layers[1].activate();\r\n\thighlightItem.strokeColor = 'red';\r\n\treturn highlightItem;\r\n}", "activate(value) {\n const itemsGroup = this.get('itemsGroup');\n const children = itemsGroup.get('children');\n let markerItem = void 0;\n children.forEach(child => {\n markerItem = findShapeByName(child, 'legend-marker');\n if (!markerItem) return;\n const checked = child.get('checked');\n if (this.get('highlight')) {\n // change stroke color\n if (child.get('value') === value && checked) {\n markerItem.attr('stroke', '#333');\n return;\n }\n } else {\n // change opacity\n if (child.get('value') === value) {\n markerItem.attr('fillOpacity', 1);\n } else {\n checked && markerItem.attr('fillOpacity', 0.5);\n }\n }\n });\n this.get('canvas').draw();\n return;\n }", "function highlightElements(event) {\n if (event.selection != null) {\n\n let circles = d3.select('#pressure-ensemble')\n .select('#pressure-violin')\n .selectAll('circle');\n\n // Unhighlight all circles\n circles.attr(\"class\", \"non_brushed\");\n\n // Highlight brushed circles\n circles.filter(function (){\n var cx = d3.select(this).attr(\"cx\"),\n cy = d3.select(this).attr(\"cy\");\n return isBrushed(event.selection, cx, cy);\n })\n .attr(\"class\", \"brushed\");\n\n var d_brushed = d3.selectAll(\".brushed\").data();\n if (d_brushed.length > 0) {\n for (let c of d_brushed) {\n let test = c;\n let test2 = 0;\n }\n } \n }\n}", "function highlightMarkers(e){\n var layer = e.target;\n var iconElem = L.DomUtil.get(layer._icon);\n iconElem.style.border=\"4px #00ffff solid\";\n iconElem.style.height=\"38px\";\n iconElem.style.width=\"38px\";\n iconElem.style.marginTop=\"-19px\";\n iconElem.style.marginLeft=\"-19px\";\n iconElem.id=\"selectedIcon\";\n }", "function category_highlight(color_id) {\n current_category_highlight = color_id;\n reset_category_highlight();\n //fully opaque on selected item\n d3.selectAll(\"line[stroke='\" + color_id + \"']\")\n .style(\"opacity\", 1.0);\n d3.selectAll(\"circle[fill='\" + color_id + \"']\")\n .style(\"opacity\", 1.0);\n //move to forground\n $(\"line[strok='\" + color_id + \"']\")\n .appendTo(\"#plot-svg\");\n $(\"circle[fill='\" + color_id + \"']\")\n .appendTo(\"#plot-svg\");\n}", "function togglehlt(selectorAndResultArray) {\n var selector = selectorAndResultArray.selector;\n var theMap = $(\"g.svg-pan-zoom_viewport\")[0];\n\n // Add the dimming layer (if it's not already there) - first, so the highlighted UNO will come after / on-top\n createDimming();\n TweenLite.to(\"#dimmingLayer\", idiagramSvg.hltDuration, {\n opacity: idiagramSvg.hltOpacity\n });\n\n // Toggle a highlight for a single selector (UNO)\n\n var unoID = selector;\n\n // If the UNO is already highlighted - because there's a placeholder for this UNO\n var unoCopy = document.getElementById(unoID + \"placeholder\");\n if (unoCopy != null) {\n unhlt(selectorAndResultArray);\n $.address.parameter(\"togglehlt\", \"\"); //remove all these commands from url\n return;\n }\n\n // Create the placeholder\n var uno1 = document.getElementById(unoID);\n if (uno1 != null) {\n var pNode = uno1.parentElement;\n var placeHolder = document.createElement(\"div\");\n var insertedNode = pNode.insertBefore(placeHolder, uno1);\n insertedNode.id = unoID + \"placeholder\";\n\n // If this is the first UNO to be highlighted, else just bring it to the front without fading,\n var highlighted = theMap.querySelectorAll(\".highlighted\");\n if (highlighted.length == 0) {\n $(\"#\" + unoID).appendTo(theMap);\n uno1.classList.add(\"highlighted\");\n } else {\n // fade on the highlighted UNO nicely\n var start = 1.0 - idiagramSvg.hltOpacity;\n TweenLite.to(\"#\" + unoID, 0, {\n opacity: start\n });\n $(\"#\" + unoID).appendTo(theMap);\n uno1.classList.add(\"highlighted\");\n TweenLite.to(\"#\" + unoID, idiagramSvg.hltDuration, {\n opacity: 1.0\n });\n }\n }\n\n $.address.parameter(\"togglehlt\", \"\"); //remove all these commands from url\n}", "function highlightPathsOnMap() {\n clearMapHighlights();\n d3.select('#tbodyForSelected').selectAll('tr').select(function (d) {\n highlightPaths(d);\n });\n}", "highlightDistrict(geoid) {\n let filterSettings;\n // Filter for which district has been selected.\n if (typeof geoid === 'object') {\n filterSettings = ['any'];\n\n geoid.forEach((i) => {\n filterSettings.push(['==', 'GEOID', i]);\n });\n } else {\n filterSettings = ['all', ['==', 'GEOID', geoid]];\n }\n // Set that layer filter to the selected\n this.toggleFilters('selected-fill', filterSettings);\n this.toggleFilters('selected-border', filterSettings);\n }", "function highlightIsolines(e) {\n // NOTE: as shown in the examples on the Leaflet website, e.target = the layer the user is interacting with\n var layer = e.target;\n layer.setStyle({\n fillColor: '#ffea00',\n dashArray: '1,13',\n weight: 4,\n fillOpacity: '0.5',\n opacity: '1'\n });\n}", "highlightDistrict(geoid) {\n let filterSettings;\n // Filter for which district has been selected.\n if (typeof geoid === 'object') {\n filterSettings = ['any'];\n\n geoid.forEach((i) => {\n filterSettings.push(['==', 'GEOID', i]);\n });\n } else {\n if (geoid.substring(0, 2) === '42') {\n filterSettings = ['all', ['==', 'DISTRICT', geoid.substring(2)]];\n this.toggleFilters('selected-border-pa', filterSettings);\n return;\n }\n filterSettings = ['all', ['==', 'GEOID', geoid]];\n }\n // Set that layer filter to the selected\n this.toggleFilters('selected-fill', filterSettings);\n this.toggleFilters('selected-border', filterSettings);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get assigned doctors of current user Will be replaced by user.getAssignedDoctors() eventually when server functionality is added
function getAssignedDoctors() { // Make fake doctors for now createDoctor(0, 'password', 'doctor1@gmail.com', '(123) 456 - 7890', 'Doc', 'Tor', 'Cardiology', '123 Fake Street'); createDoctor(1, 'password', 'doctor2@gmail.com', '(123) 456 - 7890', 'Some', 'Doctor', 'Neurology', '123 Fake Avenue'); createDoctor(2, 'password', 'doctor3@gmail.com', '(123) 456 - 7890', 'Test', 'Name', 'ENT', '123 Fake Crecent'); createDoctor(3, 'password', 'doctor4@gmail.com', '(123) 456 - 7890', 'Test', 'Name 2', 'General Surgeon' , '123 Fake Crecent'); // Hard-code assign them to current user // Note: Assigning patients is done from doctor's side doctorList[0].assignPatient(user); doctorList[1].assignPatient(user); doctorList[2].assignPatient(user); doctorList[3].assignPatient(user); return user.getDoctors(); }
[ "function getCompDoctors(compID) {\n var docList = []\n var companion = getCompanion(compID)\n\n if (companion.doctors){\n // loop through each doctor\n for (var docID of companion.doctors) {\n let doc = getDoctor(docID)\n docList.push(doc)\n }\n }\n\n return docList\n}", "async get_assignees() {\n let collaborators;\n let retval = [];\n let page_number = 1;\n do {\n collaborators = await this.repo.collaborators.fetch({ per_page: 100, page: page_number });\n page_number += 1;\n retval = [...retval, ...collaborators.items];\n } while (collaborators.nextPageUrl);\n return retval.map((person) => person.login);\n }", "function fetchDoctorsByUserId(user_id) {\n return axiosInstance({\n method: \"get\",\n url: `api/doctors/VMsupervisors/:${user_id}`,\n data: null,\n });\n}", "function populate_assignedDoctors() {\n // Will be replaced by user.getAssignedDoctors() eventually when server functionality is added\n const doctors = getAssignedDoctors(); \n\n const assignedDoctorSection = document.querySelector('#assigned-doctors');\n\n for (let i = 0; i < doctors.length; i++) {\n // Create doctor container element\n const mainContainer = document.createElement('div');\n mainContainer.setAttribute('class', 'doctor-container');\n\n // Create doctor picture element\n const pictureContainer = document.createElement('div');\n pictureContainer.setAttribute('class', 'doctor-picture-container');\n const picture = document.createElement('img');\n picture.setAttribute('class', 'doctor-picture');\n picture.setAttribute('src', './resources/images/icons/stockdoctor-icon.png');\n pictureContainer.append(picture);\n\n // Create doctor name / specialty element\n const nameContainer = document.createElement('div');\n nameContainer.setAttribute('class', 'doctor-name-container card-subsection-notes');\n const nameNode = document.createTextNode(\"Dr. \" + doctors[i].getFName() + \" \" + doctors[i].getLName());\n const nameElement = document.createElement('strong');\n nameElement.appendChild(nameNode);\n nameElement.appendChild(document.createElement('br'));\n const specialtyNode = document.createTextNode(doctors[i].getSpecialty());\n const specialtyElement = document.createElement('span');\n specialtyElement.setAttribute('class', 'font-12');\n specialtyElement.appendChild(specialtyNode);\n nameContainer.appendChild(nameElement);\n nameContainer.appendChild(specialtyElement);\n\n // Add both to doctor container\n mainContainer.appendChild(pictureContainer);\n mainContainer.appendChild(nameContainer);\n\n // Add to assigned doctor section\n assignedDoctorSection.appendChild(mainContainer);\n }\n}", "get_dashboard_doctors(id) {\n return http.get(`doctors/${id}/statistic`)\n .then(res => res.data)\n .catch(err=> err.response.data)\n }", "getDoctor(id) {\n return axios.get('/api/doctors/' + id);\n }", "async function getDoctorCompanions(doctor) {\n // Get id of Doctor\n const id = doctor._id\n // Fetch companions from REST API\n let response = await fetch(`${baseURL}/doctors/${id}/companions/`);\n // Return JSON\n return response.json();\n}", "function fetchDoctors (knex, req, res)\n{\n knex\n .select()\n .from('faculty')\n .where(function() {\n this.where('accType', 'doctor').orWhere('accType', 'adminDoctor')\n })\n .then(function (results) {\n util.respond(res, 200, JSON.stringify(results));\n });\n}", "function randomDoctor() {\n\t\treturn doctors[Math.floor(Math.random() * doctors.length)];\n\t}", "function getUserPatients() {\n return user.getPatients();\n}", "function getAutoAssignReviewers(capID,disciplineList)\r{\r\tvar result = aa.people.autoAssignReviewers(capID, disciplineList, limit, degreeValue);\r\tif(result.getSuccess())\r\t{\r\t\tvar autoAssignReviewerMap = result.getOutput();\r\t\treturn autoAssignReviewerMap;\r\t}\r\telse\r\t{\r\t\taa.print(\"ERROR: Failed to get auto reviewers: \" + result.getErrorMessage());\r\t\treturn null;\r\t}\r}", "function getDoctorsById(clinicId,specialityId){\n\t \tvar deferred = $q.defer();\n\n\t \tvar serviceCall\t =\tcommonService.GetAll(url+'doctors/getDoctorsById?clinicId='+clinicId+'&specialityId='+specialityId);\n\n\t\t\tserviceCall\n\t\t\t\t.success(function(data) {\n\t\t\t\t\tdeferred.resolve(data);\n\t\t\t\t}).\n\t\t\t\terror(function(response){\n\t\t\t\t\tdeferred.reject(response.data);\n\t\t\t\t});\n\n\t\t\treturn deferred.promise;\n\t }", "async getAllDctors(req, res) {\n const doctors = await DoctorModel.find();\n res.send(doctors);\n }", "function fetchDoctors (knex, req, res)\r\n{\r\n knex\r\n .select()\r\n .from('faculty')\r\n .where(function() {\r\n this.where('accType', 'doctor').orWhere('accType', 'adminDoctor')\r\n })\r\n .then(function (results) {\r\n util.respond(res, 200, JSON.stringify(results));\r\n });\r\n}", "function getCohortsForUser (req, res, nextFn) {\n // grab cohorts if the user is logged in\n if (isFn(req.isAuthenticated) && req.isAuthenticated() && req.user && req.user.id) {\n UserCohort.getCohortsForUser(req.user.id)\n .then(function (cohorts) {\n req.cohorts = cohorts\n nextFn()\n })\n .catch(nextFn)\n } else {\n // do nothing if they are not logged in\n req.cohortSlugs = null\n nextFn()\n }\n}", "getAssignedTrainers(trainers, courseId){\r\n var course = this.getCourse(courseId)\r\n var assigned = []\r\n course.trainers.forEach(id => {\r\n for(var i=0; i< trainers.length; i++){\r\n if (trainers[i].id === id){assigned.push(trainers[i])}\r\n }\r\n });\r\n return assigned\r\n }", "function getUserAppointments() {\n // Hard-code in appointments for now\n const appt1 = new Appointment(0, \"Regular Checkup\", new dateTime(\"2019\", \"Feb\",\"28\",1100), new dateTime(\"2019\", \"Feb\",\"28\",1200), doctorList[1]);\n\n // Note: Adding appointments is done from doctor's side\n // Rescheduling appointments is a different functionality and may be initiated by either patients or doctors\n doctorList[1].addAppointment(user, appt1);\n \n return user.getAppointments();\n}", "static async getAllDoctors(req,res){\n const doctor = await Collections.Doctor.find().select('-_id -__v') //to find all doctors data\n res.send(doctor)\n }", "getAssigneeName(value){\n // const { people } = this.props.match.params.people;\n // console.log('from people: ', people);\n return value\n //return people.filter((person) => person._id === value)\n //get the name from the users collection\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
objDim This function is shorthand for new Dim(objW(o, w), objH(o, h)) Specifying w as 1 is equivalent to o.style.width = o.offsetWidth Specifying h as 1 is equivalent to o.style.height = o.offsetHeight Prototype: Dim objDim(Object o[,[Dim d][int w, int h]]) Arguments: o ... An HTML Element object d ... An optional Dim object representing w and h w ... An optional width h ... An optional height Results: A Dim object representing object o's rendering width and height. An adjustment is made for Geckobased browsers because they do not include borders and padding when reporting width and height. This adjustment may not be correctly applied if object o has not been prepped by initXuaObj().
function objDim(o) { var w, h; if (arguments.length == 3) { w = arguments[1]; h = arguments[2]; } else if (arguments.length == 2) { w = arguments[1].w; h = arguments[1].h; } var d = new Dim(objW(o, w), objH(o, h)); return d; }
[ "function Dim(a,c){this.w=a;this.h=c;return true}", "function dim( w, h ) {\n return { w: w, h: h };\n}", "function Dim(w, h) {\r\n this.w = w;\r\n this.h = h;\r\n\r\n this.toString = function() {\r\n return this.w + 'x' + this.h;\r\n };\r\n}", "function dim() {\r\n var d = _dfa(arguments);\r\n\r\n if (d) {\r\n if (ie) {\r\n // The resizeBy can throw an exception if the user clicks too fast (PR39015);\r\n // catch and do nothing since the window is ultimately resized correctly anyway.\r\n try {\r\n var ow = document.body.clientWidth;\r\n var oh = document.body.clientHeight;\r\n self.resizeBy(d.w - ow, d.h - oh);\r\n } catch (e) {\r\n ;\r\n }\r\n } else {\r\n self.innerWidth = d.w;\r\n self.innerHeight = d.h;\r\n }\r\n }\r\n\r\n return new Dim(ie ? document.body.clientWidth : self.innerWidth,\r\n ie ? document.body.clientHeight : self.innerHeight);\r\n}", "function Dim(a, c) {\n\tthis.w = a;\n\tthis.h = c;\n\treturn true\n}", "function _dim() {\r\n var d = _dfa(arguments);\r\n if (d) {\r\n this.d = objDim(this, d);\r\n }\r\n return objCss(this, \"position\") == \"absolute\" ? this.d : objDim(this);\r\n}", "function Dimension( width, height )\n{\n this.width = ( width ? width : 0 );\n this.height = ( height ? height : 0 );\n this.getWidth = new Function( \"\", \"return this.width\" );\n this.getHeight = new Function( \"\", \"return this.height\" );\n this.toString = new Function( '', 'return (\"[width=\"+this.width+\",height=\"+this.height+\"]\")' );\n}", "function Dimension(width, height) {\n this.w = width;\n this.h = height;\n}", "function getDim(vidEl) {\n var style = vidEl.style || {};\n if (vidEl.videoWidth && vidEl.videoHeight) {\n return {w: vidEl.videoWidth, h: vidEl.videoHeight };\n }\n if (vidEl.offsetWidth && vidEl.offsetHeight) {\n return {w: vidEl.offsetWidth, h: vidEl.offsetHeight};\n }\n if (style.width && style.height) {\n return {w: parseInt(style.width.replace(/\\D+/, \"\")), h: parseInt(style.height.replace(/\\D+/, \"\"))};\n }\n return {w: 640, h: 360};\n }", "function getElementUNPOSDimension(Element, dim) {\n\toElement = createReference(Element)\n if (isIE && !isMac) {\t\n\t\tif (dim == \"width\") {\n\t\t\tdim = \"scrollWidth\"\n\t\t} else {\n\t\t\tdim = \"scrollHeight\"\n\t\t}\t\t\t\t\t\t\n\t\telementDim = eval('document.all.' + Element + '.' + dim);\n\t} else {\n\t\tif (dim == \"width\") {\n\t\t\tdim = \"offsetWidth\"\n\t\t} else {\n\t\t\tdim = \"offsetHeight\"\n\t\t}\t\n\t\telementDim = eval('document.getElementById(\"' + Element + '\").' + dim);\t\n }\n return elementDim\n}", "function getElementDimension(Element, dim) {\n oElement = createReference(Element)\n if (isIE) {\t\t\t\t\t\t\t\t\t\t\t\t//String manip: Make sure side is Left or Top...IE doesn't understand all lower case.\n\t\telementDim = eval('oElement.pixel' + (dim.toUpperCase()).substring(0,1) + (dim.toLowerCase()).substring(1,dim.length))\n\t} else if (isDOM) {\n elementDim = parseInt(eval('oElement.' + dim.toLowerCase()))\n } else {\n\t\telementDim = eval('oElement.document.' + dim.toLowerCase())\n\t}\n return elementDim\n}", "function setObjectSize(element, width ,height, unitW, unitH){\r\n \r\n // we take 5000 to see whats going on\r\n if(width == undefined)\r\n \twidth = 5000;\r\n if(height == undefined)\r\n \theight = 5000;\r\n \r\n if(unitW == \"\")\r\n untiW = globals.stdUnit;\r\n if(unitH == \"\")\r\n unitH = globals.stdUnit;\r\n \r\n var v1 = getValueWithUnits(width, unitW);\r\n element.style.width = v1;\r\n \r\n var v2 = getValueWithUnits(height, unitH);\r\n element.style.height = v2;\r\n}", "function Dimension(width, height) {\n this.width = width || 0;\n this.height = height || 0;\n}", "function SMR_resize(obj, SMR_confMaxDim) {\n\n thisWidth = obj.width;\n thisHeight = obj.height;\n \n if(thisWidth > thisHeight) thisMaxDim = thisWidth;\n else thisMaxDim = thisHeight;\n \n if(thisMaxDim > SMR_confMaxDim) {\n thisMinDim = Math.round((((thisWidth > thisHeight)?thisHeight:thisWidth) * SMR_confMaxDim) / thisMaxDim); \n \n if(thisWidth > thisHeight) {\n thisWidth = SMR_confMaxDim;\n thisHeight = thisMinDim;\n } else {\n thisHeight = SMR_confMaxDim;\n thisWidth = thisMinDim;\n }\n } // if(thisMaxDim > SMR_confMaxDim)\n\n obj.height = thisHeight;\n obj.width = thisWidth;\n}", "function dynObj(id,x,y,w,h) {\n\tthis.el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? getLyrRef(id,document): null;\n\tif (!this.el) return null;\n\tthis.doc = (document.layers)? this.el.document: this.el;\n\tthis.css = (this.el.style)? this.el.style: this.el;\n\tvar px = (document.layers||window.opera)? \"\": \"px\";\n\tthis.x = x || 0;\tif (x) this.css.left = this.x+px;\n\tthis.y = y || 0;\tif (y) this.css.top = this.y+px;\n\tthis.width = w? w: (this.el.offsetWidth)? this.el.offsetWidth: (this.css.clip.width)? this.css.clip.width: 0;\n\tthis.height = h? h: (this.el.offsetHeight)? this.el.offsetHeight: (this.css.clip.height)? this.css.clip.height: 0;\n\t// if w/h passed, set style width/height\n\tif (w){ (document.layers)? this.css.clip.width=w+px: this.css.width=w+px;}\n\tif (h){ (document.layers)? this.css.clip.height=h+px: this.css.height=h+px;}\n\tthis.obj = id + \"_dynObj\"; \teval(this.obj + \"=this\");\n}", "function PageDim(){\n//Get the page width and height\n\tthis.W = 600;\n\tthis.H = 400;\n\tthis.W = document.getElementsByTagName('body')[0].offsetWidth;\n\tthis.H = document.getElementsByTagName('body')[0].offsetHeight;\n}", "function Legato_Structure_Dimensions()\r\n{\r\n\t\r\n\t// What type of arguments passed in?\r\n\tif ( arguments.length == 2 )\r\n\t{\r\n\r\n\t\t// Store the passed in parameters.\r\n\t\tthis.width = arguments[0];\r\n\t\tthis.height = arguments[1];\r\n\t\t\r\n\t} // End if a width and height.\r\n\telse if ( arguments.length == 1 )\r\n\t{\r\n\t\t\r\n\t\tvar element = $( arguments[0] );\r\n\r\n\t\t// Get the element's dimensions.\r\n\t\tvar dimensions = element.dimensions();\r\n\t\tthis.width = dimensions[0];\r\n\t\tthis.height = dimensions[1];\r\n\t\t\r\n\t} // End if element passed in.\r\n\r\n}", "getDim() {\n var width, height;\n\n // If the particle only has a set size (not width/height)\n if (this.size) {\n width = this.size;\n height = this.size;\n } else {\n width = this.width;\n height = this.height;\n }\n\n return {\n width: width,\n height: height\n };\n }", "function PageDim(){\n//Get the page width and height\n\tthis.W = 600;\n\tthis.H = 400;\n\tthis.W = document.getElementsByTagName('body')[0].clientWidth;\n\tthis.H = document.getElementsByTagName('body')[0].clientHeight;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a filename into a uid, by splitting on '.'.
function fileUid(filename) { var tokens = filename.split('.'); if ( tokens.length === 0 ) return tokens[0]; return tokens.slice(0, tokens.length-1).join('.'); }
[ "function generate_file_user_ids() {\n let cur_file_id = 0;\n for (let f in path_to_file) {\n filepath_to_id[f] = cur_file_id;\n id_to_filepath[cur_file_id] = f;\n cur_file_id += 1;\n }\n\n let cur_user_id = 0;\n for (let u in all_users) {\n username_to_id[u] = cur_user_id;\n id_to_username[cur_user_id] = u;\n cur_user_id += 1;\n }\n}", "toCloudinaryId(filename) {\n var parsed = path.parse(this.toCloudinaryFile(filename));\n return path.join(parsed.dir, parsed.name);\n }", "function getUserNameFromRawFileName(fileName) {\r\n return fileName.substr(0, fileName.length - 5 - 3);\r\n}", "function fileUID(owner) {\n var filename = crypto.pseudoRandomBytes(10).toString('hex');\n if (owner) filename += '-' + owner;\n filename += '-' + moment().format('YYYYMMDDhhmmss');\n return filename;\n}", "_extractUserIdentifier(path) {\n\n\t\tlet extractor = (path.startsWith('/profile.php?') ? /(?:\\?id=[0-9]+)/ : /\\/([^\\/?]+)[\\/?]?/);\n\t\tlet parts = path.match(extractor);\n\n\t\tif (parts && parts.length > 1) {\n\t\t\treturn parts[1]\n\t\t}\n\t\treturn path;\n\t}", "function getFileId(filename) {\n return new Buffer(filename).toString('base64').replace(/=/g, '');\n}", "function filenameToMigration(filename) {\n var splitFile = filename.split('_')\n\n return { path: filename, version: parseInt(splitFile[0]) }\n}", "function getIdPrefix(filename, dirPath) {\n if (filename && dirPath) {\n // if the file is within the dir path, use the structure\n // of the directory tree to create the id\n if (filename.indexOf(dirPath) !== -1) {\n var subpath = _.replace(filename, dirPath, '');\n var prefix = _.replace(subpath, /\\.(csv|geojson)/, '');\n return _.trim(prefix, '/');\n }\n }\n\n // if the dirPath doesn't contain this file, return the basename without extension\n return path.basename(path.basename(filename, '.csv'), '.geojson');\n}", "function encodeUid(uid) {\n return uid.split('').reduce((prev, curr) => {\n const encodedCurr = curr.charCodeAt(0);\n return `${prev}${encodedCurr}`;\n }, '');\n}", "function getUID(asset) {\n\tvar uid;\n\tvar classes = $(asset).parents(\".asset\").attr(\"class\").split(\" \");\n\n\t$(classes).each(function(index,value) {\n\t\tif (value.indexOf(\"uid_\")!==-1) {\n\t\t\tuid = value.split(\"_\");\n\t\t\tuid = uid[1];\n\t\t}\n\t});\n\n\treturn uid;\n}", "function unix_getuid() { unix_ll(\"unix_getuid\", arguments); }", "function beautifyFilename(filename) {\n\tvar tokens = filename.split('.');\n\tvar tripped = tokens[0];\n\tvar ext = tokens[tokens.length - 1].toLowerCase();\n\ttokens = tripped.split('-');\n\ttokens.splice(1, 0, ext);\n\tvar newFilename = tokens.join('-');\n\treturn newFilename;\n}", "getFileName(filename) {\n const name = filename.slice(0, filename.lastIndexOf('.'));\n if (this.isContactUs && name.length > 17) {\n const extension = filename.substr(filename.lastIndexOf('.'), filename.length);\n const truncatedName = name.slice(0, 17);\n const newFileName = truncatedName + extension;\n return newFileName;\n }\n return filename;\n }", "file_name(fnam) {\r\n let ss = fnam.split(\".\");\r\n let n = ss.length;\r\n if (n > 1) {\r\n return ss[n - 2];\r\n } else {\r\n return \"\";\r\n }\r\n }", "function GetUserIDFromDFDE(content) {\r\n if (content.indexOf('user.getname.xml') != -1)\r\n return content.split(TOWN_URL+'dev/api/user.getname.xml?name=')[1].split('\" target')[0];\r\n return content.split(TOWN_URL+'dev/api/user.')[1].split('.xml\"')[0];\r\n }", "function getUID(id_div) {\n\tvar uid = id_div.split('user_')[1];\n\tif (! /\\d+/.test(uid))\n\t\tuid = '+' + uid;\n\treturn uid;\n}", "function ip_to_id(ip) {\n return ip.replace(/[.\\s]+/g, '_');\n}", "function getLocalIdent(filePath, localName) {\n const content = `${path.relative(root, filePath).replace(/\\\\/g, \"/\")}+${localName}`;\n const hash = crypto.createHash(\"md5\")\n .update(content)\n .digest(\"base64\")\n .replace(/[^a-z0-9]/gi, \"\")\n .substr(0, 5);\n return `${localName}--${hash}`;\n}", "function createUID(text){\n // Create a directory \n var folderName = '';\n var suffix = '';\n \n // Etract first 23 characters\n if(text){\n folderName += text.substr(0, maxLength-(UIDblock.length + 1));\n suffix += '-' + UIDblock;\n }else{\n suffix += UIDblock + '-' + UIDblock; \n }\n \n folderName += suffix.replace(/[xy]/g, function(c) {\n var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);\n return v.toString(16);\n });\n \n return folderName;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dequeue the next key and set its bit. Return whether a key was processed.
processKeyQueue() { const keyActivity = this.keyQueue.shift(); if (keyActivity === undefined) { return false; } this.shiftForce = keyActivity.keyInfo.shiftForce; const bit = 1 << keyActivity.keyInfo.bitNumber; if (keyActivity.isPressed) { this.keys[keyActivity.keyInfo.byteIndex] |= bit; } else { this.keys[keyActivity.keyInfo.byteIndex] &= ~bit; } return true; }
[ "function runKeyQueue() {\n if( keyQueue.length > 0 ) {\n const key = keyQueue.shift();\n keypress.send({ keyCode: key.charCodeAt(0), force: true });\n return false;\n }\n\n return true;\n}", "canDequeue() {\n return Object.keys(this.queue).length && (Object.keys(this.running).length < this.concurrencyCount);\n }", "keysSorted() {\n const offset = this.bb.__offset(this.bb_pos, 4);\n return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;\n }", "wasReleased(key) {\n return this._keysUp.indexOf(key) > -1;\n }", "hasThisKey(key) {\n let testNode = this.head;\n while (testNode !== null) {\n if (testNode.data.key === key) return true;\n testNode = testNode.next;\n }\n return false;\n }", "keysSorted() {\n let offset = this.bb.__offset(this.bb_pos, 4);\n return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;\n }", "function processNext() {\n if (!ready || waitingForData || queue.length == 0) return;\n\n const entry = queue[0];\n\n if (entry.waitForInput) {\n waitingForData = true;\n port.write(entry.command);\n } else {\n port.write(entry.command);\n queue.shift(); // Remove processed entry\n entry.resolve();\n processNext();\n }\n}", "function checkQueue() {\n if(queued.length === 0) return false;\n\n var nextClient = bs.clients[queued.splice(0,1)]\n\n console.log('getting next client', nextClient);\n\n if (!nextClient) return;\n\t\n nextClient.streams[nextClient.messageStreamId].write({data: 'isNext'});\n\tnextClient.isTransmitting = true;\n\tlocked = true;\n}", "function is_unlocked() { return back_key !== null; }", "delete(key)\n\t{\n\t\tif (!this.contains(key))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tthis.records.delete(key);\n\t\tprocess.nextTick(() => this.purge());\n\t\treturn true;\n\t}", "async _next () {\n if (!this._pendingCount) return (this._idle = true) // Finished processing\n console.log(this._queue, this._processing, this._pendingCount)\n this._idle = false\n this._pendingCount--\n if (this._processing > 0) {\n const { removeWhenDone } = this._queue[this._processing]\n if (removeWhenDone) this._remove(this._processing)\n }\n // Run task\n this._queue[++this._processing].run()\n }", "dequeueToNextConditionally(sendToNextCallback, nextQ = this.nextQueue) {\n if (this.isEmpty()) {\n return \"Underflow\";\n }\n \n const dequeued = this.dequeue();\n this.dequeueCount++;\n \n if (sendToNextCallback.call(this, dequeued) === true) {\n nextQ.enqueue(dequeued);\n }\n return dequeued;\n }", "function isPending(key) {\r\n\t\treturn pending.hasOwnProperty(key);\r\n\t}", "check_key() {\n var ref;\n if (this.flow_level !== 0) {\n // KEY (flow context)\n return true;\n }\n // KEY (block context)\n return ref = this.peek(1), indexOf.call(C_LB + C_WS + '\\x00', ref) >= 0;\n }", "contains(key) {\n let current = this.head;\n while(current.object != key) {\n current = current.next;\n if(current == null)\n return false;\n }\n return true;\n }", "function popIfKey(key) {\n if (peekKey() == key) {\n return popValue();\n } else {\n return undefined;\n }\n }", "remove(element){\n if(element === null) return false;\n if(!this.queue.includes(element)) return false;\n var index = this.queue.indexOf(element);\n this.queue.splice(index,1);\n if(index === this.queue.length-1){\n this.back = this.queue[this.queue.length-1];\n } else if(index === 0){\n this.front = this.queue[0];\n }\n return true;\n }", "moveNext() {\n const _ = this;\n _._assertBadState();\n try {\n switch (_._state) {\n case 0 /* Before */:\n _._yielder = _._yielder || yielder();\n _._state = 1 /* Active */;\n const initializer = _._initializer;\n if (initializer)\n initializer();\n // fall through\n case 1 /* Active */:\n if (_._tryGetNext(_._yielder)) {\n return true;\n }\n else {\n this.dispose();\n _._state = 2 /* Completed */;\n return false;\n }\n default:\n return false;\n }\n }\n catch (e) {\n this.dispose();\n _._state = 3 /* Faulted */;\n throw e;\n }\n }", "isDecrypted() {\n return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }