query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
invoke selectvalue function, for popup grid, generate custom restriction if exist regreq_type two case: if it is 'Permit and License' View. call method 'selectRequirementCommon' with a parameter 'extraRes' of sql condition regreq_type in ('License', 'Permit'); verse call original common method 'selectRequirementCommon' directly. | function customSelectRequirementCommon(){
var extraRes = " and regrequirement.regreq_type in ('License', 'Permit') ";
if(abCompSelectRequirementController.isPermitsAndLicenses){
selectRequirementCommon('abCompSelectRequirementConsole', 'regrequirement','multiple',extraRes);
}else{
selectRequirementCommon('abCompSelectRequirementConsole', 'regrequirement','multiple');
}
} | [
"function customSelectRequirementCommon(){\n\t\n\tvar extraRes = \" and regrequirement.regreq_type in ('License', 'Permit') \";\n\t\n\tif(typeof(permitController)!='undefined'&&permitController.isPermit){\n\t\tselectRequirementCommon('abCompDrilldownConsole', 'regrequirement','multiple',extraRes);\n\t\t\n\t}else{\n\t\tselectRequirementCommon('abCompDrilldownConsole', 'regrequirement','multiple');\n\t}\n\n\tif(typeof(abCompSelectRequirementController)!='undefined'&&abCompSelectRequirementController.isPermitsAndLicenses){\n\t\tselectRequirementCommon('abCompSelectRequirementConsole', 'regrequirement','multiple',extraRes);\n\t\t\n\t}else{\n\t\tselectRequirementCommon('abCompSelectRequirementConsole', 'regrequirement','multiple');\n\t}\n}",
"function selectRequirementCommon(formId, tableName,isMultiple,extraRes){\n\tvar form = View.panels.get(formId);\n\t\n\tif(typeof(form)=='undefined')\n\t\treturn;\n\t//Construct restriction from value of regulation and program\n\tvar res = \" 1=1 \";\n\tvar regulation = form.getFieldValue(tableName+\".regulation\");\n\tif(regulation){\n\t\tres+= \" AND regrequirement.regulation='\"+regulation+\"' \";\n\t}\n\tvar program = form.getFieldValue(tableName+\".reg_program\");\n\tif(program){\n\t\tres+=\" and regrequirement.reg_program='\"+program+\"' \";\n\t}\n\tif(extraRes){\n\t\tres+=extraRes;\n\t}\n\n\t// ordered by regulation ascending\n\tvar sortValues = [];\n\tsortValues.push( {\n\t\tfieldName : 'regrequirement.regulation',\n\t\tsortOrder : 1\n\t});\n\tsortValues.push( {\n\t\tfieldName : 'regrequirement.reg_program',\n\t\tsortOrder : 1\n\t});\n\tsortValues.push( {\n\t\tfieldName : 'regrequirement.reg_requirement',\n\t\tsortOrder : 1\n\t});\n\n\tView.selectValue({\n\t\tformId: formId,\n\t\ttitle:getMessage(\"selReq\"),\n\t\trestriction: res,\n\t\tselectValueType: isMultiple?\"multiple\":null,\n\t\tactionListener: isMultiple?null:\"afterSelectRequirement\",\n\t\tfieldNames: [tableName+'.regulation', tableName+'.reg_program', tableName+'.reg_requirement'],\n\t\tselectTableName : 'regrequirement',\n\t\tselectFieldNames: ['regrequirement.regulation', 'regrequirement.reg_program', 'regrequirement.reg_requirement'],\n\t\tsortValues: toJSON(sortValues),\n\t\tvisibleFields: [\n\t\t\t{fieldName: 'regrequirement.regulation'},\n\t\t\t{fieldName: 'regrequirement.reg_requirement'},\n\t\t\t{fieldName: 'regrequirement.reg_program'},\n\t\t\t{fieldName: 'regrequirement.regreq_type'},\n\t\t\t{fieldName: 'regrequirement.regreq_cat'},\n\t\t\t{fieldName: 'regrequirement.summary'}\n\t\t]\n\t});\n\n}",
"function selectProgramCommon(formId, tableName,isMultiple, afterSelectLisenter){\n\tvar form = View.panels.get(formId);\n\n\t//Construct restriction from value of regulation\n\tvar res = \" 1=1 \";\n\tvar regulation = form.getFieldValue(tableName+\".regulation\");\n\tif(regulation){\n\t\tvar fieldName = tableName+\".regulation\";\n if (form.hasFieldMultipleValues(fieldName)) {\n var values = form.getFieldMultipleValues(fieldName);\n res = \" regprogram.regulation IN ('\" + values.join(\"','\") + \"')\";\n } else {\n\t\t\tres= \" regprogram.regulation='\"+regulation+\"' \";\n }\n\t}\n\n\t// ordered by regulation ascending\n\tvar sortValues = [];\n\tsortValues.push( {\n\t\tfieldName : 'regprogram.regulation',\n\t\tsortOrder : 1\n\t});\n\tsortValues.push( {\n\t\tfieldName : 'regprogram.reg_program',\n\t\tsortOrder : 1\n\t});\n\n\tView.selectValue({\n\t\ttitle:getMessage(\"selProg\"),\n\t\tformId: formId,\n\t\trestriction: res,\n\t\tselectValueType: isMultiple?\"multiple\":null,\n\t\tfieldNames: [tableName+'.regulation', tableName+'.reg_program'],\n\t\tselectTableName : 'regprogram',\n\t\tselectFieldNames: ['regprogram.regulation', 'regprogram.reg_program'],\n\t\tactionListener: afterSelectLisenter?afterSelectLisenter:null,\n\t\tsortValues: toJSON(sortValues),\n\t\tvisibleFields: [\n\t\t\t{fieldName: 'regprogram.regulation'},\n\t\t\t{fieldName: 'regprogram.reg_program'},\n\t\t\t{fieldName: 'regprogram.regprog_type'},\n\t\t\t{fieldName: 'regprogram.regprog_cat'},\n\t\t\t{fieldName: 'regprogram.summary'}\n\t\t]\n\t});\n}",
"function selectRegulationCommon(formId, tableName,isMultiple){\n\tvar form = View.panels.get(formId);\n\n\t// ordered by regulation ascending\n\tvar sortValues = [];\n\tsortValues.push( {\n\t\tfieldName : 'regulation.regulation',\n\t\tsortOrder : 1\n\t});\n\n\tView.selectValue({\n\t\ttitle:getMessage(\"selReg\"),\n\t\trestriction: ' 1=1 ',\n\t\tselectValueType: isMultiple?\"multiple\":null,\n\t\tformId: formId,\n\t\tfieldNames: [tableName+'.regulation'],\n\t\tselectTableName : 'regulation',\n\t\tselectFieldNames: ['regulation.regulation'],\n\t\tsortValues: toJSON(sortValues),\n\t\tapplyFilter: false,\n\t\tvisibleFields: [\n\t\t\t{fieldName: 'regulation.regulation'},\n\t\t\t{fieldName: 'regulation.reg_rank'},\n\t\t\t{fieldName: 'regulation.authority'},\n\t\t\t{fieldName: 'regulation.reg_class'},\n\t\t\t{fieldName: 'regulation.reg_type'},\n\t\t\t{fieldName: 'regulation.reg_cat'}\n\t\t]\n\t});\n}",
"function selectYear(){\n var restriction = \"1=1\";\n if (valueExistsNotEmpty(getFieldRes('bl.site_id'))) {\n restriction += \" and exists(select 1 from bl where gb_fp_setup.bl_id = bl.bl_id and \" + getFieldRes('bl.site_id') + \")\";\n }\n \n if (valueExistsNotEmpty(getFieldRes('gb_fp_setup.scenario_id'))) {\n restriction += \" and \" + getFieldRes('gb_fp_setup.scenario_id');\n }\n View.selectValue(\"abGbFpEsExpConsole\", '', [\"gb_fp_setup.calc_year\"], \"gb_fp_setup\", [\"gb_fp_setup.calc_year\"], [\"gb_fp_setup.calc_year\"], restriction, null, null, null, null, null, null, 'multiple');\n \n}",
"function selectSite(){\n var restriction = \"site.site_id IN (select bl.site_id from bl where exists(select 1 from gb_fp_setup where gb_fp_setup.bl_id = bl.bl_id\";\n if (valueExistsNotEmpty(getFieldRes('gb_fp_setup.calc_year'), true)) {\n restriction += \" and \" + getFieldRes('gb_fp_setup.calc_year', true);\n }\n \n if (valueExistsNotEmpty(getFieldRes('gb_fp_setup.scenario_id'))) {\n restriction += \" and \" + getFieldRes('gb_fp_setup.scenario_id');\n }\n \n restriction += \"))\";\n\t\n View.selectValue(\"abGbFpEsExpConsole\", '', [\"bl.site_id\"], \"site\", [\"site.site_id\"], [\"site.name\", \"site.site_id\"], restriction, null, null, null, null, null, null, 'multiple');\n \n}",
"function onSelectVRestrict(strSerialized, strField, formName, getRestriction, strRestriction)\n{\n\tvar strXMLData = \"\";\n\tvar objForm = document.forms[formName];\n\tvar selectedFieldObj = objForm.elements[strField];\n\tif(selectedFieldObj != null)\n\t{\n\t\t//setSerializedInsertingDataVariables() in common.js\n\t\tsetSerializedInsertingDataVariables(strSerialized);\n\t\tvar typeUpperCase = arrFieldsInformation[strField][\"type\"];\n\t\ttypeUpperCase = typeUpperCase.toUpperCase();\n\t\tvar formatUpperCase = arrFieldsInformation[strField][\"format\"];\n\t\tformatUpperCase = formatUpperCase.toUpperCase();\n\t\tvar strValue = selectedFieldObj.value;\n\t\t//removing money sign and grouping separator and changing date into ISO format\n\t\tstrValue = convertFieldValueIntoValidFormat(typeUpperCase, formatUpperCase, strValue);\n\t\t//trim strValue\n\t\tstrValue = trim(strValue);\n\t\t//changing some special characters into valid characters in xml\n\t\t//convert2validXMLValue() in common.js\n\t\tstrValue = convert2validXMLValue(strValue);\n\t\tvar strData = \"\";\n\t\tvar strXMLValue = \"\";\n\t\tif(strSerialized != \"\")\n\t\t{\n\t\t\tvar temp_table = \"\";\n\t\t\tvar temp_field = \"\";\n\t\t\tvar temp_array = new Array();\n\t\t\ttemp_array = strField.split(\".\");\n\t\t\tif(temp_array[0] != null)\n\t\t\t\ttemp_table = temp_array[0];\n\t\t\tif(temp_array[1] != null)\n\t\t\t\ttemp_field = temp_array[1];\n\t\t\tstrData = '<fields><field ';\n\t\t\tstrData = strData + 'table=\"'+temp_table+'\" name=\"'+temp_field+'\"/></fields>';\n\t\t\t//getting all records\n\t\t\tstrData += '<userInputRecordsFlag>';\n\t\t\tstrData += gettingRecordsData(objForm);\n\n\t\t\tif (typeof getRestriction == \"function\")\n\t\t\t{\n\t\t\t\tstrData += getRestriction(strField, formName);\n\t\t\t}\n\t\t\tif (typeof strRestriction == \"string\")\n\t\t\t{\n\t\t\t\tstrData += strRestriction;\n\t\t\t}\n\n\t\t\tstrData += '</userInputRecordsFlag>';\n\n\t\t\tstrXMLValue = strSerializedInsertingDataFirstPart + strData + strSerializedInsertingDataRestPart;\n\t\t\t//calling OpenSelectVWindow() to open a new window for server\n\t\t\t//to show available values for specified field\n\t\t\tOpenSelectVWindow(strXMLValue);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(Debug)\n\t\t\t{\n\t\t\t\talert(\"The attribute serialized of afmAction is empty.\");\n\t\t\t}\n\t\t}\n\t}\n\n}",
"function selectDistanceTypeValue(){\n\n var seatClassRestr = \" 1=1 \"\n\tvar seatClass = View.panels.get('abGbFpDataS3EmpTransAir_form').getFieldValue('gb_fp_s3_em_air.seating_type');\n\tif(seatClass){\n\t\tseatClassRestr = \" gb_fp_comm_airc_data.seating_type ='\" + seatClass + \"'\";\n\t}\n\t\n\tAb.view.View.selectValue('abGbFpDataS3EmpTransAir_form', \n\t\t\t\tgetMessage('selectDistance'), \n\t\t\t\t['gb_fp_s3_em_air.seating_type', 'gb_fp_s3_em_air.distance_type'], \n\t\t\t\t'gb_fp_comm_airc_data', \n\t\t\t\t['gb_fp_comm_airc_data.seating_type', 'gb_fp_comm_airc_data.distance_type'], \n\t\t\t\t['gb_fp_comm_airc_data.version_name', 'gb_fp_comm_airc_data.seating_type', 'gb_fp_comm_airc_data.distance_type '], \n\t\t\t\t\" gb_fp_comm_airc_data.version_name = '\" + abGbFpDataS3EmpTransAir_ctrl.version_name \n\t\t\t\t+ \"' and gb_fp_comm_airc_data.version_type = '\" + abGbFpDataS3EmpTransAir_ctrl.version_type \n\t\t\t\t+ \"' and \" + seatClassRestr, \n\t\t\t\tnull, false, false , null, null, null, 'grid', 0, \n\t\t\t\t\"[{'fieldName': 'gb_fp_comm_airc_data.version_name', 'sortOrder': 1},{'fieldName': 'gb_fp_comm_airc_data.seating_type', 'sortOrder': 1},{'fieldName': 'gb_fp_comm_airc_data.distance_type', 'sortOrder': 1}]\");\n\n}",
"function selectCraftsperson(){\n var workTeamId = ondemandPanel.getFieldValue(\"helpdesk_sla_response.work_team_id\");\n var supervisor = ondemandPanel.getFieldValue(\"helpdesk_sla_response.supervisor\");\n var sql = \"cf.assign_work = 1\";\n if (workTeamId) {\n sql += \" AND cf.work_team_id='\" + workTeamId + \"'\";\n }\n else \n if (supervisor) {\n sql += \" AND cf.work_team_id = (SELECT work_team_id FROM cf WHERE email = (SELECT email FROM em WHERE em_id = '\" + supervisor + \"'))\";\n }\n View.selectValue('panel_ondemand_response', getMessage('craftsperson'), ['helpdesk_sla_response.cf_id'], 'cf', ['cf.cf_id'], ['cf.cf_id', 'cf.name', 'cf.tr_id', 'cf.work_team_id'], sql);\n}",
"function exWorkRequestDynamicTabs_wrConsole_applyRestriction() {\n var console = Ab.view.View.getControl('', 'exWorkRequestDynamicTabs_wrConsole');\n var restriction = console.getFieldRestriction();\n \n // remove the default = clause on date_requested - we will add custom clauses for this field\n restriction.removeClause('wr.date_requested');\n \n // map Urgency list selection to the wr.priority value range\n var urgency = $('exWorkRequestDynamicTabs_urgency').value;\n if (urgency == 'emergency') {\n restriction.addClause('wr.priority', '75', '>');\n } else if (urgency == 'oneDay') {\n restriction.addClause('wr.priority', '75', '<=');\n restriction.addClause('wr.priority', '50', '>');\n } else if (urgency == 'oneWeek') {\n restriction.addClause('wr.priority', '50', '<=');\n restriction.addClause('wr.priority', '25', '>');\n } else if (urgency == 'oneMonth') {\n restriction.addClause('wr.priority', '25', '<=');\n restriction.addClause('wr.priority', '0', '>');\n } else if (urgency == 'eventually') {\n restriction.addClause('wr.priority', '0')\n }\n \n // map Requested list selection to the wr.date_requested value range\n\tvar today = new Date();\n\tvar day\t = today.getDate();\n\tvar month = today.getMonth()+ 1;\n\tvar year = today.getFullYear();\n \n var requested = $('exWorkRequestDynamicTabs_requested').value;\n if (requested == 'Date Range') {\n var dateRequestedFrom = console.getFieldValue('wr.date_requested.from');\n if (dateRequestedFrom != '') {\n restriction.addClause('wr.date_requested', dateRequestedFrom, '>=');\n }\n var dateRequestedTo = console.getFieldValue('wr.date_requested.to');\n if (dateRequestedTo != '') {\n restriction.addClause('wr.date_requested', dateRequestedTo, '<=');\n }\n \n } else if (requested =='Today') {\n restriction.addClause('wr.date_requested', console.formatDate(day, month, year));\n \n } else if (requested =='This Week') {\n\t\tvar thisWeekStartDate = new Date(today.getTime() - 24*60*60*1000 * today.getDay());\n\t\tvar thisWeekEndDate = new Date(today.getTime() + 24*60*60*1000 * (6 - today.getDay()));\n restriction.addClause('wr.date_requested', console.formatDate(thisWeekStartDate.getDate(), thisWeekStartDate.getMonth()+1, thisWeekStartDate.getFullYear()), '>=');\n restriction.addClause('wr.date_requested', console.formatDate(thisWeekEndDate.getDate(), thisWeekEndDate.getMonth()+1, thisWeekEndDate.getFullYear()), '<=');\n \n } else if (requested =='This Month') {\n var daysInThisMonth = GetMonthMaxDays(month, year);\n restriction.addClause('wr.date_requested', console.formatDate(1, month, year), '>=');\n restriction.addClause('wr.date_requested', console.formatDate(daysInThisMonth, month, year), '<=');\n \n } else if (requested =='This Year') {\n restriction.addClause('wr.date_requested', console.formatDate(1, 1, year), '>=');\n restriction.addClause('wr.date_requested', console.formatDate(31, 12, year), '<=');\n }\n \n // apply restriction to the report\n var report = Ab.view.View.getControl('', 'exWorkRequestDynamicTabs_wrReport');\n report.refresh(restriction);\n \n // show the report\n report.show(true);\n}",
"function selectDrugAllergy(allergen,type,code,args){\n\tif(code.indexOf('_') >0){\n\t\tvar codeAndType = code.split('_');\n\t\tif(codeAndType.length != 2){\n\t\t\talert('invalid allergy details');\n\t\t}\n\t\tcode = codeAndType[0];\n\t\ttype = codeAndType[1];\n\t\t\n\t}\n\tvar params = args.split('|');\n\tvar formId = params[0];\n\tvar rootForm = $(params[0]);\n\t$(formId + \":fdbDrugAllergyName\").value = allergen;\n\t$(formId + \":fdbDrugAllergyType\").value = type;\n\t$(formId + \":fdbDrugAllergyCode\").value = code;\n\t$(formId + \":computeEnable\").value = \"true\";\n\t$(formId + \":computeAction\").value = 'selectDrugAllergy';\n\tvar wipNode = rootForm.parentNode;\n\tvar currentStep = 1 * rootForm.getAttribute('currentStep');\n\tajaxSubmit4(rootForm, wipNode.id,currentStep);\n\t$(formId + \":computeEnable\").value = \"false\";\n }",
"function roomReportOnClick(){\n\n var grid = View.panels.get('roomsGrid');\n var selectedRow = grid.rows[grid.selectedRowIndex];\n \n var rmStd = selectedRow[\"rm.rm_std\"];\n var restriction = new Ab.view.Restriction();\n restriction.addClause('rmstd.rm_std', rmStd, '=');\n var roomStdForm = View.panels.get('roomStdForm');\n roomStdForm.refresh(restriction);\n \n}",
"function selectLocationId(form, tableName, title){\n\tvar restriction = \" 1=1 \";\n\tvar regulation = form.getFieldValue(tableName+\".regulation\");\n\tif(regulation){\n\t\trestriction = restriction+\" and regulation='\"+regulation+\"' \";\n\t}\n\tvar program = form.getFieldValue(tableName+\".reg_program\");\n\tif(program){\n\t\trestriction = restriction+\" and reg_program='\"+program+\"' \";\n\t}\n\tvar requirement = form.getFieldValue(tableName+\".reg_requirement\");\n\tif(requirement){\n\t\trestriction = restriction+\" and (reg_requirement IS NULL OR reg_requirement='\"+requirement+\"') \";\n\t}\n\n View.selectValue(form.id, title, \n\t\t\t[tableName+'.regulation',tableName+'.reg_program', \n\t\t\ttableName+'.reg_requirement',tableName+'.location_id'], \n\t\t\t'regloc', \n\t\t\t['regloc.regulation', 'regloc.reg_program', 'regloc.reg_requirement', 'regloc.location_id'], \n\t\t\t['regloc.regulation', 'regloc.reg_program', 'regloc.reg_requirement', 'compliance_locations.site_id', \n\t\t\t\t'compliance_locations.pr_id', 'compliance_locations.bl_id', 'compliance_locations.fl_id', \n\t\t\t\t'compliance_locations.rm_id', 'compliance_locations.eq_std', 'compliance_locations.eq_id', \n\t\t\t\t'compliance_locations.em_id', 'compliance_locations.city_id', 'compliance_locations.county_id', \n\t\t\t\t'compliance_locations.state_id', 'compliance_locations.regn_id', 'compliance_locations.ctry_id', \n\t\t\t\t'compliance_locations.geo_region_id', 'compliance_locations.location_id'],\n\t\t\trestriction, afterSelectLocationID, false\n\t) ;\n}",
"function setRestriction(){\n // get reference to the console form\n var console = View.getControl('', 'request_console');\n \n // get the date range values in ISO format\n var dateRequestedFrom = console.getFieldValue('wr.date_requested.from');\n var dateRequestedTo = console.getFieldValue('wr.date_requested.to');\n \n // validate the date range \n if (dateRequestedFrom!='' && dateRequestedTo!='') {\n // the compareLocalizedDates() function expects formatted (displayed) date values\n if (compareLocalizedDates(\n $('wr.date_requested.to').value, \n $('wr.date_requested.from').value)) {\n // display the error message defined in AXVW as message element\n alert(getMessage('error_date_range'));\n return;\n }\n }\t\n \n // prepare the grid report restriction from the console values\n var restriction = new Ab.view.Restriction(console.getFieldValues());\n\t\trestriction.removeClause('wr.date_requested.from');\n\t\trestriction.removeClause('wr.date_requested.to');\n try {\n\t var status = console.getFieldValue('wr.status');\n\t\t\tif (status != undefined){\n\t\t if (status == '--NULL--') {\t\n\t\t restriction.removeClause('wr.status');\n\t\t }\n\t\t\t}\n\t\t} catch(err){}\n if (dateRequestedFrom != '') {\n restriction.addClause('wr.date_requested', dateRequestedFrom, '>=');\n }\n if (dateRequestedTo != '') {\n restriction.addClause('wr.date_requested', dateRequestedTo, '<=');\n }\n\t\twindow.selectRestriction = restriction;\n // refresh the grid report\n var report = View.getControl('', 'wr_report');\n report.refresh(restriction)\n\t\t\n}",
"function selectBl(){\n var restriction = \"bl.bl_id IN (select gb_fp_setup.bl_id from gb_fp_setup where gb_fp_setup.bl_id = bl.bl_id\";\n if (valueExistsNotEmpty(getFieldRes('gb_fp_setup.calc_year', true))) {\n restriction += \" and \" + getFieldRes('gb_fp_setup.calc_year', true);\n }\n \n if (valueExistsNotEmpty(getFieldRes('gb_fp_setup.scenario_id'))) {\n restriction += \" and \" + getFieldRes('gb_fp_setup.scenario_id');\n }\n \n restriction += \")\";\n \n if (valueExistsNotEmpty(getFieldRes('bl.site_id'))) {\n restriction += \" and \" + getFieldRes('bl.site_id');\n }\n\t\n View.selectValue(\"abGbFpEsExpConsole\", '', [\"gb_fp_setup.bl_id\"], \"bl\", [\"bl.bl_id\"], [\"bl.site_id\", \"bl.bl_id\"], restriction, null, null, null, null, null, null, 'multiple');\n}",
"function selectValue() {\n\t\n\tvar restriction = \"1=1\";\n\tvar projectId = View.panels.get('abCbRptAssessLoc_filter').getFieldMultipleValues('activity_log.project_id');\n\tif (projectId.length>0 && projectId[0] != undefined && projectId[0] != \"\") {\n\t\trestriction = \"(EXISTS (select 1 from activity_log where activity_log.fl_id = fl.fl_id and activity_log.bl_id = fl.bl_id and activity_log.project_id in ('\"\n\t\t\t\t+ projectId.join(\"','\") + \"')))\";\n\t}\n\n\tView.selectValue('abCbRptAssessLoc_filter', \n\t\t\t\t\tgetMessage('floor'), \n\t\t\t\t\t['activity_log.bl_id','activity_log.fl_id'],\n\t\t\t\t\t'fl', \n\t\t\t\t\t['fl.bl_id','fl.fl_id'], \n\t\t\t\t\t['fl.bl_id','fl.fl_id','fl.name'], \n\t\t\t\t\trestriction,\n\t\t\t\t\tnull, null, null, null, null, null, \n\t\t\t\t\t'multiple');\n\t\n}",
"function setRestriction(){\n var console = View.getControl('', \"wr_upd_sel_wr_console\");\n \n // get the date range values in ISO format\n var dateRequestedFrom = console.getFieldValue('wr.date_requested.from');\n var dateRequestedTo = console.getFieldValue('wr.date_requested.to');\n \n // validate the date range \n if (dateRequestedFrom != '' && dateRequestedTo != '') {\n // the compareLocalizedDates() function expects formatted (displayed) date values\n if (compareLocalizedDates($('wr.date_requested.to').value, $('wr.date_requested.from').value)) {\n // display the error message defined in AXVW as message element\n View.showMessage(getMessage('errorDateRange'));\n return;\n }\n }\n \n var wrFrom = console.getFieldValue('wr.wr_id.from');\n var wrTo = console.getFieldValue('wr.wr_id.to');\n \n // prepare the grid report restriction from the console values\n var restriction = new Ab.view.Restriction(console.getFieldValues());\n \n if ($(\"wr_upd_sel_wr_console_wr.prob_type\").value == \"--NULL--\") {\n restriction.removeClause('wr.prob_type');\n }\n \n \n if (dateRequestedFrom != '') {\n restriction.removeClause('wr.date_requested.from');\n restriction.addClause('wr.date_requested', dateRequestedFrom, '>=');\n }\n if (dateRequestedTo != '') {\n restriction.removeClause('wr.date_requested.to');\n restriction.addClause('wr.date_requested', dateRequestedTo, '<=');\n }\n if (wrFrom != '') {\n restriction.removeClause('wr.wr_id.from');\n restriction.addClause('wr.wr_id', wrFrom, '>=');\n }\n if (wrTo != '') {\n restriction.removeClause('wr.wr_id.to');\n restriction.addClause('wr.wr_id', wrTo, '<=');\n }\n var panel = View.getControl('', 'wr_upd_sel_wr_report');\n panel.refresh(restriction);\n}",
"function onEquipmentGridRowClick(){\n\n //get the selected eq_id\n var grid = abBldgOpsReportWrSameEqLocController.abBldgOpsReportWrSameEqLocEquipmentGrid;\n var selectedRow = grid.rows[grid.selectedRowIndex];\n var eqId = selectedRow[\"wr.eq_id\"];\n \n //create restriction\n var restriction = new Ab.view.Restriction();\n restriction.addClause(\"wr.eq_id\", eqId, \"=\");\n \n //refresh and show details panel as pop-up\n var detailsGrid = abBldgOpsReportWrSameEqLocController.abBldgOpsReportWrSameEqLocDetailsGrid;\n detailsGrid.refresh(restriction);\n detailsGrid.showInWindow({\n width: 1200,\n height: 400\n });\n \n}",
"function radioClick(){\n\tvar resultDate = getDateValue();\n\tvar date_start = resultDate[0];\n\tvar date_end = resultDate[1];\n\tvar selectLocation = document.getElementsByName(\"selectLocation\");\n\tvar popupPanel = View.panels.get('abSpAsgnEmFromRm_popup');\n//\tvar restriction = new Ab.view.Restriction();\n\t//KB3036965 - support em_id with single quotes\n var emId = row_em_id.replace(/\\'/g, \"''\");\n\tvar restriction = \" em_id = '\"+emId+\"' AND status = 1 \" +\n\t\"AND (date_start IS NULL or date_start <= ${sql.date('\"+ dateFormat(date_end) +\"')})\" +\n\t\" AND (date_end is null or date_end >=${sql.date('\"+ dateFormat(date_end) +\"')}) \";\n\tif (selectLocation[0].checked) {\n\t popupPanel.refresh(restriction+ \"AND rm.hotelable = 0\");\n\t}else{//another Location\n\t\tvar restrictionOthers =\"rmpct.pct_id not in (SELECT rmpct.pct_id FROM rmpct,(select bl_id,fl_id,rm_id from rmpct \" +\n\t\t\t\t\"where\"+restriction+\") ${sql.as} rmpctExist \" +\n\t\t\t\t\"WHERE rmpct.bl_id= rmpctExist.bl_id and rmpct.fl_id= rmpctExist.fl_id and rmpct.rm_id= rmpctExist.rm_id) \" +\n\t\t\t\t\" AND rm.hotelable = 0\";\n\t\tpopupPanel.refresh(restrictionOthers);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interprets using the `lli` executable the VSL code. Resolves when execution is finished | async interpret() {
const byteCode = await this.emitRawStream();
await new Promise((resolve, reject) => {
let lli = spawn('lli', [], {
stdio: ['pipe', 'inherit', 'inherit']
});
byteCode.pipe(lli.stdin);
lli.on('error', reject);
lli.on('exit', resolve);
});
} | [
"function executeVLT(i) {\n const vs = cop2VS(i);\n const vt = cop2VT(i);\n\n const vco = rsp.VCO;\n let vccLo = 0;\n let vccHi = 0;\n for (let el = 0, select = rsp.vecSelectU32[cop2E(i)]; el < 8; el++, select >>= 4) {\n const s = rsp.getVecS16(vs, el);\n const t = rsp.getVecS16(vt, select & 0x7);\n\n const elBit = 1 << el;\n const vcoLo = (vco & elBit) != 0;\n const vcoHi = (vco & (elBit << 8)) != 0;\n const onEqual = vcoLo && vcoHi;\n\n const cond = s < t || ((s == t) && onEqual);\n const result = cond ? s : t;\n vccLo |= cond ? elBit : 0;\n\n rsp.setAccLow(el, result);\n }\n rsp.setVecFromAccLow(cop2VD(i));\n rsp.setVCCHiLo(vccHi, vccLo);\n rsp.VCO = 0;\n}",
"async function ireeLoadProgram(vmfbPathOrBuffer) {\n return _ireeLoadProgram(vmfbPathOrBuffer);\n}",
"function trans_program(rest_ast){\n\tvar js_codes = \"OO.initializeCT();\\n\"; // initialize first\n\tvar i=0;\n\tfor(; i<rest_ast.length; i++){\n\t\tjs_codes += trans(rest_ast[i]) +\";\\n\"; // translate each piece of code \n\t}\n\treturn js_codes;\n\t\n}",
"function liriInstruction(){\n console.log(\"To run Liri: \");\n console.log(\"node liri concert-this '<artist/band name here>'\");\n console.log(\"node liri spotify-this-song '<song name here>'\");\n console.log(\"node liri movie-this '<movie name here>'\");\n console.log(\"node liri do-what-it-says\");\n}",
"function liner(lzv,ip){ip*=12; k=lzv[ip]; acti=k/4; c=137/ftw[9];\n line=labs[lzv[ip+1]]+\" \"+verb4.substring(k,k+4); jj=ip+3;\n // For each of the 3 addresses. Get name, offset, and register. Use the Actions types. \n for(i=0;i<3;i++){px=lzv[jj+1];py=lzv[jj+2]%128; \n if(types[k+i]!=0&&types[k+i]!=4){ line+=\" \"; \n if(lzv[jj]>0){\n if(lzv[jj]>=217&&lzv[jj]<300){s1=nvar[lzv[jj]];line+=s1;b=0;\n }else{ s1=nvar[lzv[jj]]+\" \";\n if(lzv[jj]>368){v9=px+(lzv[jj]-368)*4096;\n v10=ftmswap.indexOf(v9);if(v10>=0){s1=ftmswap[200+v10]+\" \";px=0;}; };\n a=s1.indexOf(\" \");line+=s1.substring(0,a);b=0;\n if(px>0){b=1;line+=\"+\"+px.toString(); };\n if(py>0){ if(b<1){line+=\"+\";};line+=nvar[py]; }; }; // end of varb 217 else\n }else{s5=px.toString();a=s5.length;if(a>8){line+=s5;}else{line+=blanks.substring(0,8-a)+s5;};\n if(py>0){line+=\"+\"+nvar[py]; }; }; }; \n a=i*c+25-line.length;if(a>0){line+=blanks.substring(0,a);}else{line+=\" \";}; jj+=3;}; \n // Add the To-Label to the line. The zero indexed label is blank.\n line+=\" \"+labs[lzv[ip+2]];\n\nif(acti==79){a=nadd[lzv[ip+6]]+lzv[ip+7];line=line.substring(0,40)+ps.substring(a,a+27);}; // TEXT\n\nif(acti==41){s8=comment[subi*257+lzv[ip+1]]+blanks.substring(0,56);\n line=line.substring(0,18)+s8.substring(0,48);}; // TAB\n\nif(acti==64){s8=comment[subi*257+lzv[ip+2]]+blanks.substring(0,56); // GOTO\n line=line.substring(0,12)+s8.substring(0,51)+line.substring(63,line.length);};\n\nif(acti==49&&lzv[ip+3]==0&&lzv[ip+4]>99&&lzv[ip+5]==0){px=a=lzv[ip+4]; b=a%100;a=Math.floor(a/100); // CALL \n tabzv=12000*a+taboff[px]; line=line.substring(0,9)+px.toString(); py=zv[tabzv+1];\n if(py>0){line+=\" \"+comment[py+257*a];};};\n \nline=line+blanks.substring(line.length,66);\n }",
"function decode2UExecution() {}",
"function executeVMULU(i) {\n vectorMulFractions(cop2VS(i), cop2VT(i), cop2E(i), false, 0x8000n);\n rsp.setVecFromAccUnsignedMid(cop2VD(i));\n}",
"function run(code, scenario) {\n var trans = new Function(\"data\", code.partialSource.transitionFunction);\n var init = new Function(\"data\", code.partialSource.initializationFunction);\n\n var trace = [init()];\n\n // Execute LIDL system step by step\n var i;\n for (i = 0; i < scenario.length; i++) {\n trace[i].inter = scenario[i].inter;\n trace[i].args = scenario[i].args;\n trace[i] = trans(trace[i]);\n if (i < scenario.length - 1) {\n trace[i + 1] = {};\n trace[i + 1].state = trace[i].state;\n trace[i + 1].memo = trace[i].memo;\n }\n }\n return trace;\n}",
"function runit(cm) {\n currentcm = cm;\n var code = cm.getValue();\n var output = document.getElementById(\"codeout\"+cm.idnum);\n output.innerHTML = '';\n Sk.configure({output:outf});\n try {\n eval(Sk.importMainWithBody(\"<stdin>\", false, code));\n } catch (e) {\n output.innerHTML = e;\n }\n}",
"_runInterpreter() { \n this._parser.program.interpret();\n let result = '<h2>Program output</h2><pre>' + this._parser.program.output + '</pre>';\n document.getElementById('result').innerHTML = result;\n this._formButton.innerHTML = 'Run compiler';\n this._formButton.onclick = () => { this._runCompiler(); };\n }",
"_runCompiler() {\n this._parser.program.compile();\n let result = '<h2>Program translation</h2><pre>' + this._parser.program.translation + ' </pre>';\n document.getElementById('result').innerHTML = result;\n this.startOver();\n }",
"function LScript()\n{\n\tthis.code = \"function update(dt) {\\n\\n}\";\n\tthis.exported_callbacks = [\"start\",\"update\"]; //detects if there is a function with this name and exports it as a property\n\tthis.extracode = \"\";\n\tthis.catch_exceptions = true;\n}",
"function _LCSEOptimizeCommand() {\n}",
"function ireeLoadProgram(vmfbPathOrBuffer) {\n return _callIntoWorker({\n 'messageType': 'loadProgram',\n 'payload': vmfbPathOrBuffer,\n });\n}",
"function runit() { \n var prog = editor.getValue();\n var mypre = document.getElementById(\"output\"); \n mypre.innerHTML = ''; \n Sk.pre = \"output\";\n Sk.configure({output:outf, read:builtinRead}); \n var myPromise = Sk.misceval.asyncToPromise(function() {\n return Sk.importMainWithBody(\"<stdin>\", false, prog, true);\n });\n myPromise.then(function(mod) {\n console.log('success');\n },\n \n function(err) {\n console.log(err.toString());\n mypre.innerHTML = mypre.innerHTML + err.toString(); \n });\n}",
"function disas_neon_ls_insn(/* CPUARMState * */ env, /* DisasContext * */ s, /* uint32_t */ insn)\n{\n var rd, rn, rm;\n var op;\n var nregs;\n var interleave;\n var stride;\n var size;\n var reg;\n var pass;\n var load;\n var shift;\n var /* uint32_t */ mask;\n var n;\n\n if (!vfp_enabled(env))\n return 1;\n do { if (arm_feature(env, ARM_FEATURE_VFP3)) { rd = (((insn) >> (12)) & 0x0f) | (((insn) >> ((22) - 4)) & 0x10); } else { if (insn & (1 << (22))) return 1; rd = ((insn) >> (12)) & 0x0f; }} while (0);\n rn = (insn >> 16) & 0xf;\n rm = insn & 0xf;\n load = (insn & (1 << 21)) != 0;\n if ((insn & (1 << 23)) == 0) {\n /* Load store all elements. */\n op = (insn >> 8) & 0xf;\n size = (insn >> 6) & 3;\n if (op > 10 || size == 3)\n return 1;\n nregs = neon_ls_element_type[op].nregs;\n interleave = neon_ls_element_type[op].interleave;\n gen_movl_T1_reg(s, rn);\n stride = (1 << size) * interleave;\n for (reg = 0; reg < nregs; reg++) {\n if (interleave > 2 || (interleave == 2 && nregs == 2)) {\n gen_movl_T1_reg(s, rn);\n gen_op_addl_T1_im((1 << size) * reg);\n } else if (interleave == 2 && nregs == 4 && reg == 2) {\n gen_movl_T1_reg(s, rn);\n gen_op_addl_T1_im(1 << size);\n }\n for (pass = 0; pass < 2; pass++) {\n if (size == 2) {\n if (load) {\n do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0);\n gen_op_neon_setreg_T0(neon_reg_offset(rd, pass));\n } else {\n gen_op_neon_getreg_T0(neon_reg_offset(rd, pass));\n do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0);\n }\n gen_op_addl_T1_im(stride);\n } else if (size == 1) {\n if (load) {\n do { s.is_mem = 1; if ((s.user)) gen_op_lduw_user(); else gen_op_lduw_kernel(); } while (0);\n gen_op_addl_T1_im(stride);\n gen_op_movl_T2_T0();\n do { s.is_mem = 1; if ((s.user)) gen_op_lduw_user(); else gen_op_lduw_kernel(); } while (0);\n gen_op_addl_T1_im(stride);\n gen_op_neon_insert_elt(16, 0xffff);\n gen_op_neon_setreg_T2(neon_reg_offset(rd, pass));\n } else {\n gen_op_neon_getreg_T2(neon_reg_offset(rd, pass));\n gen_op_movl_T0_T2();\n do { s.is_mem = 1; if ((s.user)) gen_op_stw_user(); else gen_op_stw_kernel(); } while (0);\n gen_op_addl_T1_im(stride);\n gen_op_neon_extract_elt(16, 0xffff0000);\n do { s.is_mem = 1; if ((s.user)) gen_op_stw_user(); else gen_op_stw_kernel(); } while (0);\n gen_op_addl_T1_im(stride);\n }\n } else /* size == 0 */ {\n if (load) {\n mask = 0xff;\n for (n = 0; n < 4; n++) {\n do { s.is_mem = 1; if ((s.user)) gen_op_ldub_user(); else gen_op_ldub_kernel(); } while (0);\n gen_op_addl_T1_im(stride);\n if (n == 0) {\n gen_op_movl_T2_T0();\n } else {\n gen_op_neon_insert_elt(n * 8, ~mask);\n }\n mask <<= 8;\n }\n gen_op_neon_setreg_T2(neon_reg_offset(rd, pass));\n } else {\n gen_op_neon_getreg_T2(neon_reg_offset(rd, pass));\n mask = 0xff;\n for (n = 0; n < 4; n++) {\n if (n == 0) {\n gen_op_movl_T0_T2();\n } else {\n gen_op_neon_extract_elt(n * 8, mask);\n }\n do { s.is_mem = 1; if ((s.user)) gen_op_stb_user(); else gen_op_stb_kernel(); } while (0);\n gen_op_addl_T1_im(stride);\n mask <<= 8;\n }\n }\n }\n }\n rd += neon_ls_element_type[op].spacing;\n }\n stride = nregs * 8;\n } else {\n size = (insn >> 10) & 3;\n if (size == 3) {\n /* Load single element to all lanes. */\n if (!load)\n return 1;\n size = (insn >> 6) & 3;\n nregs = ((insn >> 8) & 3) + 1;\n stride = (insn & (1 << 5)) ? 2 : 1;\n gen_movl_T1_reg(s, rn);\n for (reg = 0; reg < nregs; reg++) {\n switch (size) {\n case 0:\n do { s.is_mem = 1; if ((s.user)) gen_op_ldub_user(); else gen_op_ldub_kernel(); } while (0);\n gen_op_neon_dup_u8(0);\n break;\n case 1:\n do { s.is_mem = 1; if ((s.user)) gen_op_lduw_user(); else gen_op_lduw_kernel(); } while (0);\n gen_op_neon_dup_low16();\n break;\n case 2:\n do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0);\n break;\n case 3:\n return 1;\n }\n gen_op_addl_T1_im(1 << size);\n gen_op_neon_setreg_T0(neon_reg_offset(rd, 0));\n gen_op_neon_setreg_T0(neon_reg_offset(rd, 1));\n rd += stride;\n }\n stride = (1 << size) * nregs;\n } else {\n /* Single element. */\n pass = (insn >> 7) & 1;\n switch (size) {\n case 0:\n shift = ((insn >> 5) & 3) * 8;\n mask = 0xff << shift;\n stride = 1;\n break;\n case 1:\n shift = ((insn >> 6) & 1) * 16;\n mask = shift ? 0xffff0000 : 0xffff;\n stride = (insn & (1 << 5)) ? 2 : 1;\n break;\n case 2:\n shift = 0;\n mask = 0xffffffff;\n stride = (insn & (1 << 6)) ? 2 : 1;\n break;\n default:\n abort();\n }\n nregs = ((insn >> 8) & 3) + 1;\n gen_movl_T1_reg(s, rn);\n for (reg = 0; reg < nregs; reg++) {\n if (load) {\n if (size != 2) {\n gen_op_neon_getreg_T2(neon_reg_offset(rd, pass));\n }\n switch (size) {\n case 0:\n do { s.is_mem = 1; if ((s.user)) gen_op_ldub_user(); else gen_op_ldub_kernel(); } while (0);\n break;\n case 1:\n do { s.is_mem = 1; if ((s.user)) gen_op_lduw_user(); else gen_op_lduw_kernel(); } while (0);\n break;\n case 2:\n do { s.is_mem = 1; if ((s.user)) gen_op_ldl_user(); else gen_op_ldl_kernel(); } while (0);\n gen_op_neon_setreg_T0(neon_reg_offset(rd, pass));\n break;\n }\n if (size != 2) {\n gen_op_neon_insert_elt(shift, ~mask);\n gen_op_neon_setreg_T0(neon_reg_offset(rd, pass));\n }\n } else { /* Store */\n if (size == 2) {\n gen_op_neon_getreg_T0(neon_reg_offset(rd, pass));\n } else {\n gen_op_neon_getreg_T2(neon_reg_offset(rd, pass));\n gen_op_neon_extract_elt(shift, mask);\n }\n switch (size) {\n case 0:\n do { s.is_mem = 1; if ((s.user)) gen_op_stb_user(); else gen_op_stb_kernel(); } while (0);\n break;\n case 1:\n do { s.is_mem = 1; if ((s.user)) gen_op_stw_user(); else gen_op_stw_kernel(); } while (0);\n break;\n case 2:\n do { s.is_mem = 1; if ((s.user)) gen_op_stl_user(); else gen_op_stl_kernel(); } while (0);\n break;\n }\n }\n rd += stride;\n gen_op_addl_T1_im(1 << size);\n }\n stride = nregs * (1 << size);\n }\n }\n if (rm != 15) {\n gen_movl_T1_reg(s, rn);\n if (rm == 13) {\n gen_op_addl_T1_im(stride);\n } else {\n gen_movl_T2_reg(s, rm);\n gen_op_addl_T1_T2();\n }\n gen_movl_reg_T1(s, rn);\n }\n return 0;\n}",
"function InterpreterCompileAndRun( program_text )\n{\n\t// Clear contents.\n\tinterpreter_stdout = '';\n\tinterpreter_stderr = '';\n\n\tvar file_name = 'test.u';\n\tFS.writeFile( file_name, program_text );\n\tvar call_result = callMain( [file_name, '--entry', 'main'] );\n\n\treturn [ call_result, interpreter_stdout, interpreter_stderr ];\n}",
"compileScript( script ) {\n\n\t\tlet { NodeVM, VMScript } = require( 'vm2' );\n\n\t\tthis.resetSandbox();\n\t\tthis.runningCode = script;\n\t\tthis.vm = new NodeVM( {\n\t\t\t'console': 'inherit',\n\t\t\t'sandbox': this.sandbox\n\t\t} );\n\n\t\tthis.runningVmScript = new VMScript( this.runningCode );\n\n\t}",
"function testLiriCommand() {\n // console.log(\"This worked!\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Partitions the section of the given array between the given left and right indices to be properly partitioned. An initial pivot value is chosen based on the pivotFunction passed in. | function partition(pivotFunction, array, left, right) {
let originalLeft = left;
// get pivot based on the user's pivot-selection choice
let pivot = pivotFunction(array, originalLeft, right);
// get the value at the pivot from the array
let pivotValue = array[pivot];
// swap the elements at pivot and original left, then increment left
swap(array, pivot, originalLeft);
left++;
// iterate so long as the left index is less than or equal to the right index
while (left <= right) {
// increment the left index until we find an element less than the pivot value
while (array[left] < pivotValue) {
left++;
}
// increment the right index until we find an element greater than the pivot value
while (array[right] > pivotValue) {
right--;
}
// swap the elements at the left and right index if left hasn't crossed over right
if (left <= right) {
swap(array, left, right);
left++;
right--;
}
}
// swap the original left value with the value at the final left index
swap(array, originalLeft, left - 1);
// return the left index (one past the "middle")
return left;
} | [
"function partition(arr, pivot, left, right){\n var pivotValue = arr[pivot],\n partitionIndex = left;\n \n for(var i = left; i < right; i++){\n if(arr[i] < pivotValue){\n swap(arr, i, partitionIndex);\n partitionIndex++;\n }\n }\n swap(arr, right, partitionIndex);\n return partitionIndex;\n }",
"function partition (array, start, end){\r\n // choose pivot\r\n var pivot = array[end]\r\n // \"lastOfSmallerIndex\" variable points to the last (most right) index of the subarray for elements that are smaller than or equal to pivot\r\n // \"lastOfSmallerIndex\" is initialized to (startingSubarrayIndex - 1) since at first the number of smaller element is 0\r\n var lastOfSmallerIndex = start - 1\r\n // loop through the originalArray from startingSubarrayIndex to (and including) endingSubarrayIndex - 1 (the pivot is in endingSubarrayIndex)\r\n for(var i = start; i <= end - 1; i++){\r\n // if the current checked element is less than or equal to pivot\r\n if(array[i] <= pivot){\r\n // increment the \"lastOfSmallerIndex\" index so that it points to an element not yet checked or an element greater than pivot (breaking the loop invariant)\r\n lastOfSmallerIndex++\r\n // swap the currently checked element with the element in the \"lastOfSmallerIndex\" (restoring the loop invariant)\r\n array.swap(i, lastOfSmallerIndex)\r\n }\r\n }\r\n // increment the \"lastOfSmallerIndex\" index so that it points to an element not yet checked or an element greater than pivot (breaking the loop invariant)\r\n lastOfSmallerIndex++\r\n // and swap the pivot element at endingSubarrayIndex with the element in the \"lastOfSmallerIndex\" (restoring the loop invariant)\r\n array.swap(end, lastOfSmallerIndex)\r\n // return lastOfSmallerIndex (which now points to the pivot) to be used for the next iteration of QUICK-SORT as the new partitionIndex\r\n return lastOfSmallerIndex\r\n}",
"partition(unsorted, left, right, pivot){\n while(left <= right){\n //while value at left is less than pivot move left\n while(unsorted[left][sortBy] < pivot){\n left++;\n }\n //while value at right is greater than pivot move right\n while(unsorted[right][sortBy] > pivot){\n right--;\n }\n if(left <= right){\n //if sub-arrays do no match swap left and right\n [unsorted[left], unsorted[right]] = [unsorted[right], unsorted[left]];\n\n left++;\n right--;\n }\n }\n return left;\n }",
"function partition(pivot, left, right) {\n var pivotValue = keyColumn[pivot];\n\n // At the end of each iteration, the following is true:\n // All elements at k for left <= k < partitionIndex are < pivotValue.\n // All elements at k for partitionIndex <= k <= i are >= pivotValue.\n // Specifically, the element at partitionIndex is the first one in the\n // range left <= k <= right which is potentially >= pivotValue, and which\n // will need to be moved out of the way when encountering an element\n // that's < pivotValue.\n var partitionIndex = left;\n var pivotIndex = pivot;\n for (var i = left; i <= right; i++) {\n if (comparator(keyColumn[i], pivotValue) < 0) {\n swap(i, partitionIndex);\n if (partitionIndex === pivotIndex) {\n // We just swapped our pivot away. Update pivotIndex to keep track\n // of it.\n pivotIndex = i;\n }\n partitionIndex++;\n }\n }\n // Swap the pivot back into the position at partitionIndex.\n swap(partitionIndex, pivotIndex);\n return partitionIndex;\n }",
"function partition(array, p, r) {\n // Initialize the pivot (q) and j to the first element of the array\n let q = p\n\n // Loop through the subarray until we reach the pivot\n for (let j = p; j < r; j++) {\n // Compare the left most element arr[j] with the pivot arr[q]\n if (array[j] <= array[r]) {\n // Swap the element in the current index arr[j] with the element in\n // the pivot arr[q]\n swap(array, j, q)\n // Shift the pivot to the right\n q++\n }\n }\n\n // Swap the pivot, arr[q], with the leftmost element arr[r]\n swap(array, r, q)\n\n // Return the calculated pivot\n return q\n}",
"function arragePivotPartition (A, start, end){\n var pivot = A[end];\n var indexPartition = start;\n for(var i=start; i<=end;i++){\n if(A[i] < pivot){\n var temp = A[indexPartition];\n A[indexPartition] = A[i];\n A[i] = temp;\n indexPartition++;\n }\n }\n A[end] = A[indexPartition];\n A[indexPartition] = pivot;\n \n return indexPartition;\n}",
"function quickSort(array, left, right){ // takes in an array, a left index, and right index value\n var index; // initialize an index variable where we will store the partitioning index\n if(array.length > 1){ // base case for quickSort recursion, this will stop when the array length is down to 0\n index = partition(array, left, right); // the index will store the value we will use for further sorting\n \n if(left < index - 1){\n quickSort(array, left, index - 1); // continue to sort if there are still values to the left\n }\n \n if(index < right){\n quickSort(array, index, right); // continue to sort if there are still values to the right\n }\n }\n return array; // return the sorted array\n}",
"function partitionHoare(arr, left, right) {\n const pivot = arr[Math.floor((left + right) / 2)];\n console.log(\"partitionHoare is running\")\n while (left <= right) {\n while (arr[left] < pivot && left <= right) {\n left++;\n }\n while (arr[right] > pivot) {\n right--;\n }\n if (left <= right) {\n [arr[left], arr[right]] = [arr[right], arr[left]];\n left++;\n right--;\n }\n }\n\n return left;\n}",
"function partition(items, left, right) {\n\n var pivot = items[Math.floor((right + left) / 2)],\n i = left,\n j = right;\n\n\n while (i <= j) {\n\n while (items[i].startPoint < pivot.startPoint) {\n i++;\n }\n\n while (items[j].startPoint > pivot.startPoint) {\n j--;\n }\n\n if (i <= j) {\n swap(items, i, j);\n i++;\n j--;\n }\n\n }\n\n return i;\n }",
"function partitionHelper(array, start, end, animationsArray) {\n let i = start-1;\n // Here we use the final entry as the pivot - but using any entry would be valid.\n // Other implementations use the start, middle, or even randomized entries.\n const pivotElement = array[end];\n animationsArray.push([\"pivot_highlight\", end, end])\n for (let j = start; j < end; j+=1) {\n // If an element is less than the pivot, we place it at the leftmost available\n // spot in the array. We don't care if the entries are in order right now,\n // we only examine if they are less/greater than the pivot value.\n if (array[j] < pivotElement) {\n i += 1;\n animationsArray.push([\"swap_compared\", i, j]);\n animationsArray.push([\"swap_elements\", array[i], array[j]]);\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n }\n animationsArray.push([\"pivot_unhighlight\", end, end]);\n animationsArray.push([\"swap_compared\", end, i + 1]);\n animationsArray.push([\"swap_elements\", array[end], array[i + 1]]);\n // We finish by swapping the final entry in the array with the our recorded\n // \"ith\" value - this is because the final entry is the pivot, so this swap ensures\n // that everything to the left is smaller than the pivot and everything to the\n // right is larger!\n const newTemp = array[end];\n array[end] = array[i+1];\n array[i+1] = newTemp;\n return (i+1);\n}",
"function generateRandomPivot(array, left, right) {\n const randomPivotIndex = getRandomInt(left, right - 1)\n swapValuesAtIndices(randomPivotIndex, right - 1)\n return partition(array, left, right)\n}",
"function quickSortHelper(array, leftStart, rightEnd, animations) {\n //check if left index is equal to the right index then we have nothing to compare!\n if (leftStart <= rightEnd) {\n return;\n }\n //get the pivot the point at which we will compare the values\n const pivot = startPartition(array, leftStart, rightEnd, animations);\n //sort the first half of the array to the pivot\n quickSortHelper(array, leftStart, pivot, animations);\n //sort the second half of the array from the pivot to the end of the array\n quickSortHelper(array, pivot + 1, rightEnd, animations);\n}",
"function partition(array, start, end) {\n const pivotValue = array[end];\n let pivotIndex = start;\n for (let i = start; i < end; i++) {\n animations.push([i, pivotIndex, end, false]);\n if (array[i] < pivotValue) {\n animations.push([i, pivotIndex, end, true]);\n array = swapFunction(array, pivotIndex, i);\n animations.push([i, pivotIndex, end, false]);\n pivotIndex++;\n } else {\n animations.push([i, pivotIndex, end, false]);\n animations.push([i, pivotIndex, end, false]);\n }\n }\n\n animations.push([end, pivotIndex, end, true]);\n animations.push([end, pivotIndex, end, true]);\n animations.push([end, pivotIndex, end, true]);\n\n array = swapFunction(array, pivotIndex, end);\n return pivotIndex;\n}",
"function partition(array, lo, hi) {\n var i = lo;\n var j = hi;\n var pivot = array[lo];\n var leftSwapReady = false;\n var rightSwapReady = false;\n while(i <= j) {\n if(array[i] > pivot) {\n leftSwapReady = true;\n } else {\n i++\n }\n if(array[j] < pivot) {\n rightSwapReady = true;\n } else {\n j--\n }\n if(leftSwapReady && rightSwapReady) {\n swapArr(array, i, j)\n leftSwapReady = false;\n rightSwapReady = false;\n }\n }\n swapArr(array, lo, i-1);\n return i-1;\n}",
"function findPivot(array) {\n let left = 0,\n right = array.length - 1;\n \n \n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n if (array[right] > array[mid]) {\n right = mid - 1;\n } else if (array[right] < array[mid]) {\n left = mid + 1;\n } else {\n return mid;\n }\n }\n }",
"function sortUniqueShared(array, left, right) { \n\n var i = left;\n var j = right;\n var tmp;\n var pivotidx = (left + right) / 2; \n \n var pivot = parseInt(array[pivotidx.toFixed()]); \n \n // partition \n\n while (i <= j) {\n \n while (parseInt(array[i][0]) < pivot)\n\n i++;\n\n while (parseInt(array[j][0]) > pivot)\n\n j--;\n \n if (i <= j) {\n \n tmp = array[i];\n array[i] = array[j];\n array[j] = tmp;\n i++;\n j--;\n }\n }\n\n // recursion \n\n if (left < j){\n\n sortUniqueShared(array, left, j);\n }\n \n if (i < right) {\n\n sortUniqueShared(array, i, right);\n }\n \n return array;\n}",
"function partition(array, p, r) {\n // Get a pivot. It's easiest to take the last element of the array.\n let pivot = array[r - 1];\n let i = p - 1;\n // Iterate through the entries starting at p (our base index) to find ones smaller. If an entry is smaller, swap it\n // with a larger value (or with the beginning of the list, if not smaller value has been found yet).\n // In this way build out the smaller larger lists. Place the pivot in the proper position last.\n for(let j = p; j < r; j++) {\n if (array[j] <= pivot) {\n i++;\n [array[i], array[j]] = [array[j], array[i]];\n }\n }\n [array[i + 1], array[r - 1]] = [array[r - 1], array[i + 1]];\n array = array.filter(function(d) { return typeof d != \"undefined\"; });\n return [array, i + 1];\n}",
"function partition(p, r) {\n let x = arr[r]; //pivot\n let i = p - 1; //counter\n\n for (let j = p; j <= r - 1; j++) {\n if (arr[j] <= x) {\n i += 1;\n let temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n let temp = arr[r];\n arr[r] = arr[i + 1];\n arr[i + 1] = temp;\n return i + 1;\n}",
"_partition(a, lo, hi) {\n let i = lo;\n let j = hi + 1;\n\n const pivot = a[lo];\n\n while (true) {\n // find item on lo to swap\n while (this.comparator.lessThan(a[++i], pivot)) {\n if (i == hi) {\n break;\n }\n }\n\n // find item on hi to swap\n while (this.comparator.lessThan(pivot, a[--j])) {\n if (j == lo) {\n break; // redundant since a[lo] acts as sentinel\n }\n }\n\n // check if pointers cross\n if (i >= j) {\n break;\n }\n\n this._exch(a, i, j);\n }\n\n // put partitioning item pivot at a[j]\n this._exch(a, lo, j);\n\n // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]\n return j;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to setup all public and private events for bot. | setupEvents() {
this.eventEmitter
.on('close', () => {
this.botInterface.emit('close');
})
.on('connect', () => {
this.loadSavedEvents();
})
.on('reconnect', () => {
this.reconnect();
})
.on('shutdown', () => {
this.botInterface.emit('shutdown');
})
.on('start', () => {
this.botInterface.emit('start');
})
.on('ping', (args) => {
this.dispatchMessage(...args);
})
.on('message', (args) => {
this.handleMessage(...args);
})
.on('channel', (args) => {
this.handleChannelEvents(...args);
})
.on('user', (args) => {
this.handleUserEvents(...args);
})
.on('team', (args) => {
this.handleTeamEvents(...args);
})
.on('presence', (args) => {
this.handlePresenceEvents(...args);
});
} | [
"function initEvents(client, bot) {\n\tclient.on(\"message\", (message) => {\n\t\tif (!message.guild) return;\n\t\ttry {\n\t\t\tclient.events.get(\"message\").func(bot, message);\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n });\n client.on(\"ready\", ()=>{\n try {\n\t\t\tclient.events.get(\"ready\").func(bot);\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t})\n\t// client.on(\"channelCreate\", (channel)=>{\n\t// \ttry {\n\t// \t\tclient.events.get(\"channelCreate\").func(bot, channel);\n\t// \t} catch (err) {\n\t// \t\tconsole.error(err);\n\t// \t}\n\t// });\n\t// client.on(\"channelDelete\", (channel)=>{\n\t// \ttry {\n\t// \t\tclient.events.get(\"channelDelete\").func(bot, channel);\n\t// \t} catch (err) {\n\t// \t\tconsole.error(err);\n\t// \t}\n\t// });\n\t// client.on(\"guildCreate\", (guild)=>{\n\t// \ttry{\n\t// \t\tclient.events.get(\"guildCreate\").func(bot, guild);\n\t// \t} catch (err){\n\t// \t\tconsole.log(err)\n\t// \t}\n\t// })\n\t// client.on(\"guildDelete\", (guild)=>{\n\t// \ttry{\n\t// \t\tclient.events.get(\"guildDelete\").func(bot, guild);\n\t// \t} catch (err){\n\t// \t\tconsole.log(err)\n\t// \t}\n\t// })\n}",
"function _assignEvents() {\n\n if (config.controller === 'site')\n _homeEvents();\n if (config.controller === 'orders')\n _ordersEvents();\n }",
"__initEvents() {\n if (this.__hasInitEvents) {\n return;\n }\n\n this.__hasInitEvents = true;\n this.$eventHub = eventCenter;\n let events = this.$rawBroadcastEvents;\n if (typeof events === 'function') {\n events = this.$rawBroadcastEvents = events();\n }\n this.__bindBroadcastEvents(events);\n }",
"function setEvents () {\n\t\t\n\t\t\t// Start link event\n\t\t\t$(o.startLink).click(function(){\n\t\t\t\tuser.showForm();\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t});\n\t\t\t\n\t\t\t// Start popin form event\n\t\t\t$(o.form).submit(function(){\n\t\t\t\tuser.hideForm();\n\t\t\t\treturn api.send($(this));\t\t\t\n\t\t\t});\n\t\t\t\n\t\t\t// Set release and records link event\n\t\t\t$(o.releaseLink+', '+o.recordsLink).click(function(){\n\t\t\t\tapi.send($(this));\n\t\t\t\treturn false;\n\t\t\t});\t\t\t\n\t\t}",
"function setupHandlers () {\n\n \"use strict\";\n var self = this;\n var worker = self.worker;\n\n // History (group / channel / history)\n worker.on('history', handleHistory.bind(self));\n\n // Error from worker\n worker.on('error', handleError.bind(self));\n\n // New location (group / channel)\n worker.on('location', handleLocation.bind(self));\n\n // Away (for keeping the bot active)\n worker.on('away', handleKeepActive);\n\n // Mark (for marking a private messagae read)\n worker.on('mark', handleMarkMessage);\n\n // Handle Stats\n worker.on('stats', handleStats.bind(self));\n\n // Handle Plugin\n worker.on('other', handleOther);\n\n // Handle My User\n worker.on('myUser', handleMyUser)\n\n}",
"_setupInternalEventBindings() {\n\t this.on(Settings.Events.CREATE, this._onCreate);\n\t this.on(Settings.Events.CHANGE, this._onChange);\n\t this.on(Settings.Events.SAVE, this._onSave);\n\t this.on(Settings.Events.ERROR, this._onError);\n\t }",
"setupListeners() {\n this.setupLeagues();\n this.setupDrivers();\n }",
"async init(){\n //Variable for reading files from handlers directory.\n const fileNames = readdirSync('./src/handlers/events');\n //Getting each file and importing the files.\n for(const name of fileNames){\n //Import starts from where the event handler is.\n const { default: Event } = await import(`./events/${name}`);\n const event = new Event();\n if(!event.on) continue;\n\n bot.on(event.on, event.invoke.bind(event));\n }\n\n console.log(`${fileNames.length - 1} events were loaded.`);\n }",
"function setupChatEventHandlers(){\n//\treadKeys();\n\n\teventBus.on('headless_wallet_ready', function(){\n\t\tconsole.log('headless_wallet_ready');\n\t\tinitRPC();\n\t});\n\n\teventBus.on('paired', function(from_address){\n\t\tconsole.log('paired '+from_address);\n\t\tif (!isControlAddress(from_address))\n\t\t\treturn console.log('ignoring pairing from non-control address');\n\t\thandlePairing(from_address);\n\t});\n\n\teventBus.on('text', function(from_address, text){\n\t\tconsole.log('text from '+from_address+': '+text);\n\t\tif (!isControlAddress(from_address))\n\t\t\treturn console.log('ignoring text from non-control address');\n\t\thandleText(from_address, text);\n\t});\n}",
"setup() {\n this.setupHandlers();\n this.setupPeer();\n }",
"function _assignEvents() {\n _generalEvents();\n _mediaEvents();\n _userEvents();\n }",
"_initEvents()\n {\n if (this.config.responsive)\n {\n this._onResize();\n }\n\n if (this.config.mouseOverEvents)\n {\n this._onMouseMove();\n this._onMouseLeave();\n }\n\n if (this.config.mouseClickEvents)\n {\n this._onMouseClick();\n }\n\n if (this.config.audio)\n {\n this._onTimeUpdate();\n this._onCanPlay();\n }\n }",
"function setupLifecycleEvents () {\n // Go through all Sails models lifecycles\n _.each(lifecycles, function (lifecycleName) {\n \n // Setup the lifecycle callabck as a function that will be \n // responsible for triggering the event handlers\n workingModel[lifecycleName] = function (instance, cb) {\n // If nobody has subscribed to this lifecycle, run callback immediately\n if (!eventManager.any(lifecycleName)) {\n cb();\n return;\n }\n \n // `orphanCallback` will allow us to know if any of the handlers called the cb() callback\n // of the lifecycle\n var orphanCallback = true;\n \n // the `adopt` callback lets us know that the user assumed responsibility of running the callback\n var adopt = function () {\n orphanCallback = false;\n };\n \n // Wrap sails callback in order to know if any handlers ran or plan to run the callback manually\n var wrappedCb = _.wrap(cb, function (fx, message) {\n // This callback is not an orphan anymore\n adopt();\n \n // Run the sails lifecycle cb()\n fx(message);\n });\n \n // Trigger all event handlers of this lifecycle\n eventManager.trigger(lifecycleName, [instance, wrappedCb, adopt]);\n \n // If the lifecycle cb() did not run, let's run it to get the response out of limbo\n if (orphanCallback) {\n cb();\n }\n };\n });\n }",
"function setupListeners() {\n setupAppHomeOpenedListener();\n setupClearGoalsButtonListener();\n}",
"setupEventListener() {\n const instance = this;\n Event.defineEvent('socketserver:syncclients')\n .defaultFn(instance.updateAllClients.bind(instance));\n }",
"function registerEvents() {\n // TODO: Handle error and reaction\n\n discordClient.on(\"ready\", () => {\n Logger.info(\"Logged into Discord as **\" + discordClient.user.tag + \"**\");\n discotron.updateGuilds();\n discotron.getBotSettings().setBotPresence();\n });\n\n discordClient.on(\"message\", discotron.onMessage);\n discordClient.on(\"messageReactionAdd\", discotron.onReaction);\n discordClient.on(\"guildCreate\", discotron.onJoinGuild);\n discordClient.on(\"guildDelete\", discotron.onLeaveGuild);\n discordClient.on(\"error\", () => {\n // TODO: Handle reconnection and bot status update\n });\n\n // Handle disconnecting the bot gracefully\n process.stdin.resume();\n\n process.on(\"exit\", exitHandler.bind(null, {\n cleanup: true\n }));\n process.on(\"SIGINT\", exitHandler.bind(null, {\n exit: true\n }));\n process.on(\"SIGUSR1\", exitHandler.bind(null, {\n exit: true\n }));\n process.on(\"SIGUSR2\", exitHandler.bind(null, {\n exit: true\n }));\n }",
"bindEvents() {\n this.bot.start((ctx) => ctx.reply(this.reply_messages.start));\n this.bot.help((ctx) => ctx.reply(this.reply_messages.help));\n this.bot.mention(this.bot_name, (ctx) => ctx.reply(this.reply_messages.mention));\n this.available_commands.forEach((command) => {\n this.bot.command(command, (ctx) => this.commandHandler(ctx, command));\n });\n // this.bot.action(this.processAction);\n }",
"function registerEvents() {\n // TODO: Handle error and reaction\n\n discordClient.on(\"ready\", () => {\n Logger.log(\"Logged into Discord as **\" + discordClient.user.tag + \"**\", \"info\");\n discotron.updateGuilds();\n discotron.getBotSettings().setBotPresence();\n });\n\n discordClient.on(\"message\", discotron.onMessage);\n discordClient.on(\"messageReactionAdd\", discotron.onReaction);\n discordClient.on(\"guildCreate\", discotron.onJoinGuild);\n discordClient.on(\"guildDelete\", discotron.onLeaveGuild);\n discordClient.on(\"error\", () => {\n // TODO: Handle reconnection and bot status update\n });\n\n // Handle disconnecting the bot gracefully\n process.stdin.resume();\n\n process.on(\"exit\", exitHandler.bind(null, {\n cleanup: true\n }));\n process.on(\"SIGINT\", exitHandler.bind(null, {\n exit: true\n }));\n process.on(\"SIGUSR1\", exitHandler.bind(null, {\n exit: true\n }));\n process.on(\"SIGUSR2\", exitHandler.bind(null, {\n exit: true\n }));\n}",
"function setupInternalEventOnlyModule() {\n\t\tvar dispatcher = new Dispatcher();\n\n\t\treturn {\n\t\t\tDispatcher: dispatcher,\n\t\t\tCommander: new Commander(dispatcher),\n\t\t\tFacade: new Facade()\n\t\t};\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Appends arguments passed in to the base document url and returns the same. | function AppendArgumentsToBaseUrl() {
var url = GetBaseUrlPath();
for (arg_index = 0; arg_index < arguments.length; arg_index++) {
url += arguments[arg_index];
}
return url;
} | [
"function addUrlArgs (url, args){\r\n if (!args)\r\n return url;\r\n if (url.indexOf('?') < 0)\r\n url += '?';\r\n else if (url.substr(url.length-1) != '&')\r\n url += '&'; \r\n if (matTypeof(args == 'object'))\r\n return url + implodeUrlArgs (args); \r\n return url + args;\r\n}",
"function addUrlArgs (url, args){\n if (!args)\n return url;\n if (url.indexOf('?') < 0)\n url += '?';\n else if (url.substr(url.length-1) != '&')\n url += '&'; \n if (matTypeof(args == 'object'))\n return url + implodeUrlArgs (args); \n return url + args;\n}",
"function buildUrl(base, args) {\n 'use strict';\n var s = base + '?'\n for (var arg in args) {\n s += encodeURIComponent(arg) + '=' + encodeURIComponent(args[arg]) + '&'\n }\n return s.slice(0, s.length - 1)\n}",
"function gscAppendParameter(baseUrl, append) {\n //Nothing to append? return the base\n if (gscIsEmptyString(append)) {\n return baseUrl;\n }\n\n if (gscIsEmptyString(baseUrl))\n {\n return append;\n }\n\n //Otherwise, append\n return baseUrl + \"&\" + append;\n}",
"function url(baseUrl, args) {\n return `${baseUrl}?${args.join(\"&\")}`;\n}",
"function appendUrl(base, url) {\n if (typeof base === \"undefined\" || base === null || base === \"\") {\n return url;\n }\n var baseSlash = base.slice(-1) === \"/\";\n var urlSlash = url.charAt(0) === \"/\";\n if (baseSlash && urlSlash) {\n return base.slice(0, base.length-1) + url;\n } else if (!baseSlash && !urlSlash) {\n return base + \"/\" + url;\n } else {\n return base + url;\n }\n}",
"function appendReferalURL(url){\n var hashStart = (url.indexOf('#') === -1) ? url.length : url.indexOf('#');\n var querySymbol = (url.indexOf('?') === -1) ? '?' : '&';\n var newUrl = url.substring(0, hashStart) + querySymbol + customParam +\n url.substring(hashStart);\n return newUrl;\n}",
"function dust_url(opts, chunk, ctx, bodies, params) {\n\tvar url = dust.helpers.tap(params.url, chunk, ctx);\n\n\t// Only prepend our base url if we're looking for something relative to it\n\tif (url[0] == '/')\n\t\treturn chunk.write(opts.base_url + url);\n\telse\n\t\treturn chunk.write(url);\n}",
"function buildDocURL(base, docId/*, ..args */) {\n // return Cell with to-be-built URL when any of arguments is a cell\n var args = _.toArray(arguments);\n if ((base instanceof Cell) || (docId instanceof Cell)) {\n return Cell.applyFunctionWithResolvedValues(buildDocURL, this, args);\n }\n\n if (base.charAt(base.length-1) !== '/') {\n args[0] += '/'; // NOTE: this is base but it's used as part of\n // args\n }\n\n if (docId.slice(0, \"_design/\".length) === \"_design/\") {\n args.splice(1, 1, \"_design\", docId.slice(\"_design/\".length));\n } else if (docId.slice(0, \"_local/\".length) === \"_local/\") {\n args.splice(1, 1, \"_local\", docId.slice(\"_local/\".length));\n }\n return buildURL.apply(null, args);\n}",
"function buildNewUrl(base) {\n \"use strict\";\n\n var qs = buildNewQueryString();\n\n if (null === base) {\n base = $.GLOBALS.currentPageBase;\n }\n \n if (base.indexOf('?') !== -1) {\n return base + '&' + qs;\n } else {\n return base + '?' + qs;\n }\n}",
"function _MSRS_buildURL(url,method,args)\r\n\t{\r\n\t\tif (url == '') url = window.location.pathname;\r\n\t\tif (typeof(method) == 'string')\r\n\t\t{\r\n\t\t\turl += '?_method=' + method;\r\n\t\t\turl += '&_mtype=execute';\r\n\t\t\tvar params = '&pcount=0';\r\n\t\t\tif (typeof(args) != 'undefined' && args.length)\r\n\t\t\t{\t// add parameters\r\n\t\t\t\tparams = '&pcount=' + args.length \r\n\t\t\t\tfor (var i = 0; i < args.length; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tvar arg = args[i];\r\n\t\t\t\t\tparams += '&p' + i + '=' + escape(arg).replace(/\\+/g,\"%2b\"); \r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\turl += params;\r\n\t\t}\r\n\t\treturn url;\r\n\t}",
"get url() {\n\t\tif (this.path != '')\n\t\t\treturn `${this.host}/${this.path}/${this.document}`;\n\t\telse\n\t\t\treturn `${this.host}/${this.document}`;\n\t}",
"function updateUrl(argDict) {\n var url = window.location.origin + window.location.pathname + '?';\n\n for (var key in argDict) {\n var values = argDict[key];\n for (var i in values) {\n url += '&' + key + '=' + values[i];\n }\n }\n window.location.href = url;\n}",
"#buildUrl() {\n let { url } = this.#request;\n let { prefix, suffix } = this.#configs;\n\n url = trim(url, '/');\n prefix = trim(prefix, '/');\n suffix = trim(suffix, '/');\n\n this.#request.url =\n (prefix && !startsWith(url, prefix, 0) ? `${prefix}/` : '') +\n url +\n (suffix && !endsWith(url, suffix, url.length) ? `/${suffix}` : '');\n }",
"function urlBuilder(base) {\n return function() {\n let path = base;\n for (let i = 0; i < arguments.length; i++) {\n if (arguments[i] !== undefined) {\n path = url.resolve(path, arguments[i]) + '/';\n }\n }\n return path;\n };\n}",
"function _createURL()\n { var arr\n\n if(arguments.length === 1) arr=arguments[0]\n else arr = arguments\n\n var url = _transaction.server.location\n\n // arr:['route', 'article', 54 ] => str:\"/route/article/54\"\n for (var i=0; i<arr.length; i++){\n url += '/';\n if (arr[i] in _transaction.server)\n url += _transaction.server[arr[i]];\n else if (arr[i]+'Path' in _transaction.server)\n url += _transaction.server[arr[i]+'Path'];\n else\n url += arr[i]\n }\n\n return url;\n }",
"function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {\n global $_links_add_base;\n $_links_add_base = $base;\n $attrs = implode('|', (array)$attrs);\n return preg_replace_callback( \"!($attrs)=(['\\\"])(.+?)\\\\2!i\", '_links_add_base', $content );\n }",
"function gscAppendQueryString(baseUrl, append) {\n localAssert(!gscIsNullOrUndefined(baseUrl), \"missing base\");\n\n //Nothing to append? return the base\n if (gscIsEmptyString(append))\n {\n return baseUrl;\n }\n\n //If it has no query string yet, start one\n var idxQuestion = baseUrl.indexOf(\"?\");\n if(idxQuestion == -1)\n {\n return baseUrl + \"?\" + append;\n }\n\n //Otherwise, append\n return baseUrl + \"&\" + append;\n}",
"function resourceUrl (args, parents, base, resource) {\n var argIndex = 0\n , nodes = []\n , params = args[args.length.toString()]\n ;\n\n if (parents && parents.length > 0) {\n parents.forEach(function (parent, i) {\n nodes.push(parent, args[i.toString()])\n argIndex += 1;\n });\n } \n\n nodes.push(resource);\n if (['string', 'number'].indexOf(typeof args[argIndex.toString()]) !== -1) {\n nodes.push(args[argIndex.toString()]);\n }\n\n return base += nodes.join('/');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes number and rounding level start value n>=s | function roundTo(n, r, s){
return (Math.floor((n-s)/r)*r)+s
} | [
"function roundTo(n, increment = 1) {\n return Math.round(n / increment) * increment;\n }",
"function maximizeNumberRoundness(n) {\n\n}",
"function round(a){return Math.floor(a);}",
"function roundN(num,n){\n return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);\n }",
"function roundX(x,n)\r\n{\r\n return Math.round(x/n)*n;\r\n}",
"function formatter(n) {return util.round(n,6);}",
"function round(x, n) {\n\tif (n >= 0) {\n\t\treturn Math.round(x * ( 10 ** n ) ) / ( 10 ** n );\n\t}\n\n\treturn x\n}",
"function roundTo(n, digits) \r\n{\r\n\tif (digits === undefined) {\r\n\t\tdigits = 0;\r\n\t}\r\n\r\n\tvar multiplicator = Math.pow(10, digits);\r\n\tn = parseFloat((n * multiplicator).toFixed(11));\r\n\treturn Math.round(n) / multiplicator;\r\n}",
"function roundNumber(n, precision)\n{\n\treturn Math.round(n*Math.pow(10,precision))/Math.pow(10,precision);\t\n}",
"function roundTiny(n){\n if(Math.abs(n) < Number.EPSILON)\n return 0;\n return n;\n}",
"function roundNumber(value) {\r\n 'use strict';\r\n console.log(Math.floor(value));\r\n console.log(Math.round(value));\r\n}",
"function nice_round(num, digits){\n if(num == 0){ return 0;}\n //add_note(num + \" \" + digits);\n var num_digits = 1+Math.floor(Math.log(num) / Math.log(10) + .000001);\n var digger = Math.pow(10,num_digits - digits);\n return round_to((Math.floor(num /digger) * digger),digits); //also round to clean up rounding errors\n}",
"function round(valueToRound) {\n\t\tvar lastDigith = valueToRound % 10;\n\n\t\tif (lastDigith > 4) {\n\t\t\treturn valueToRound - lastDigith + 10;\n\t\t} else {\n\t\t\treturn valueToRound - lastDigith;\n\t\t}\n\t}",
"function iround(n) {\n return round(n);\n}",
"function int_round5(no) {\n\n no % 5 === 0 ? console.log(no) : console.log((Math.floor(no / 5) + 1) * 5);\n\n}",
"function increaseNumberRoundness(n) {\n let consecutiveNonZeroes = /^[1-9]+0*$/;\n \n return !consecutiveNonZeroes.test(n);\n}",
"function roundDown(n, down)\n{\n return (n - (n % down));\n}",
"function round(number) {\n return (number + .5) >> 0;\n}",
"function roundOff(num, precision) {\r\n\tx = (num * precision * 10) % 10;\r\n\tif (x >= 5)\r\n\t\treturn ((parseInt(num * precision)) + 1) / precision;\r\n\telse\r\n\t\treturn (parseInt(num * precision)) / precision;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle super page functionality popup products | function _handleSuperPage() {
// Attach XHR handler to send product data
easy.events.on(easy.EVENT_JQUERY_READY, function ($) {
$(document).ajaxSuccess(function (event, jqxhr, settings) {
easy.addExceptionHandling(function () {
if (settings.url.match(/^\/Variant\/GetProductAsync/)) {
var productId = settings.url.match(/\?code\=(\d{7})\_/).pop();
_parseProduct(productId, document.querySelector('#quickShopModal'));
}
}, {
code: easy.ERROR_SITE_PRODUCT_ATTRIBUTE
})();
});
});
} | [
"function _handleProductPage() {\n var productId = scopeWindow.location.pathname.split('/').pop();\n _parseProduct(productId, document.querySelector('article.product'));\n }",
"function notAProductPage () {\n alert(\"Sorry, WishThis only works on product pages.\");\n }",
"function openProductHelper() {\n if(currentUser.roles[0] === 'designer') {\n openImageEdit();\n } else if(currentUser.roles[0] === 'applier') {\n openQrScanner();\n } else if(currentUser.roles[0] === 'reviewer') {\n openApprovalPage();\n }\n}",
"function ActivePopupInPage() {\n$( document ).on( 's123.page.ready', function( event ) {\nActivePopupActionButtonsInPage();\n});\n}",
"function openProducts() {\n\t\t$ocModal.open({\n\t\t\turl: 'partials/products.html',\n\t\t init: {\n\t\t products: app.products,\n\t\t buyProduct: buyProduct\n\t\t }\n\t\t});\n\t}",
"function sidebarProductPreviewLinkHandler()\n\t{\n\t\t$('.sidebar-product-img__link').on('click', function(e){\n\t\t\te.preventDefault();\n\t\t\t$('.product-image__link.more-views__fancy-item').click();\n\t\t});\n\t}",
"function displayProducts(products, page, pageTitle,dataObj) {\n if (typeof products === 'object' && products.length > 0) {\n var productsHTML = getProductHTMLCode(products, page, dataObj);\n // MARK: - if page is not 'home', then we should open channel view\n if (page !== '') {\n var channelHTML = channelPageTemplate\n .replace('[channelContent]', productsHTML)\n .replace('[channelTitle]', pageTitle);\n var channelView = $('#channelview');\n channelView.html(channelHTML);\n document.getElementById('header-title').innerHTML = pageTitle;\n closeOverlay();\n document.body.className = 'channelview channel-iap';\n gNowView = 'channelview';\n if (useFTScroller === 0) {\n window.scrollTo(0, 0);\n }\n // MARK: - Send Traffic Data so that this can be tracked\n var url = gDeviceType + '/channelpage/iap/' + page;\n httpspv(url);\n // MARK: 记录频道页浏览历史\n if (hist && ((hist[0] && hist[0].url != url) || hist.length == 0)) {\n hist.unshift({ 'url': '/channelpage/iap/' + page, 'title': pageTitle });\n }\n }\n\n $('.policy').unbind().bind('click', function() {\n var url = $(this).attr('url');\n window.open(url);\n });\n }\n}",
"function go2ProductPersonalisation(){\n\tsessionStorage.productID = $(this).closest(\".product-cover-block\").data(\"id\");\n\twindow.location = \"/personalize/\";\n}",
"static clickProduct() {\n // declare slides\n const slides = document.querySelectorAll(\n // eslint-disable-next-line comma-dangle\n '#featured-product-slider .splide__slide'\n );\n // declare cards\n const cards = document.querySelectorAll('.product-card');\n\n // click event for each slide\n slides.forEach((slide) => {\n slide.addEventListener('click', () => {\n ProductView.viewProductModal();\n ProductView.viewProduct(slide);\n });\n });\n\n // click event for each product card\n cards.forEach((card) => {\n card.addEventListener('click', () => {\n ProductView.viewProductModal();\n ProductView.viewProduct(card);\n });\n });\n\n // click event for close btn\n productViewCloseBtn.addEventListener('click', () => {\n ProductView.viewProductModal();\n });\n\n // click event for overlay\n productViewOverlay.addEventListener('click', () => {\n ProductView.viewProductModal();\n });\n }",
"OnClick(products){\n console.log(\"product selected\")\n BuySdkManager.presentProductwithId(String(products.product_id));\n console.log(\"product view displayed succesfully\");\n }",
"hideQuickShop(e) {\r\n this.props.updateProductListPage(e.target.getAttribute('data-product-id'), 'remove-qs-open');\r\n }",
"OpenProductsBrowser() {\r\n this.AppHelper.openDialog({\r\n component: 'products-browser-modal'\r\n });\r\n }",
"function mybExtrasPage() {\n}",
"function openModal() {\n $(\".basket-items table:first tr td img\").closest(\"a\").click(function(e) {\n e.preventDefault();\n\n // Get product code\n var productUrl = $(this).attr(\"href\");\n var productCode = productUrl.substr(productUrl.lastIndexOf('/') + 1);\n \n\n if (basketProductData[productCode]) {\n exp.log(\"Product found!\");\n exp.log(basketProductData[productCode]);\n\n // Show modal\n $('#AWA-popup').show();\n $('#__msg_overlay').show();\n\n\n // Extra Bullets\n $(\"#AWA-new-image\").after(exp.vars.extraBullets);\n\n if (basketProductData[productCode][\"ideal_for\"]) {\n $(\"#AWA-ideal-for\").text(basketProductData[productCode][\"ideal_for\"].split(',').join(', '));\n } else {\n $(\"#AWA-ideal-for\").text(\"N/A\");\n }\n if (basketProductData[productCode][\"flowering_months\"]) {\n $(\"#AWA-flowering-period\").text(basketProductData[productCode][\"flowering_months\"].split(',').join(', '));\n } else {\n $(\"#AWA-flowering-period\").text(\"N/A\");\n }\n if (basketProductData[productCode][\"sun_shade\"]) {\n $(\"#AWA-position\").text(basketProductData[productCode][\"sun_shade\"].split(',').join(', '));\n } else {\n $(\"#AWA-position\").text(\"N/A\");\n }\n if (basketProductData[productCode][\"height\"]) {\n $(\"#AWA-height\").text(basketProductData[productCode][\"height\"]);\n } else {\n $(\"#AWA-height\").text(\"N/A\");\n }\n if (basketProductData[productCode][\"spread\"]) {\n $(\"#AWA-spread\").text(basketProductData[productCode][\"spread\"]);\n } else {\n $(\"#AWA-spread\").text(\"N/A\");\n }\n \n\n // Get product title\n if (basketProductData[productCode][\"product_name_common\"]) {\n $(\"#AWA-title\").html(basketProductData[productCode][\"product_name_common\"]);\n }\n\n // Get latin name\n if (basketProductData[productCode][\"product_name_latin\"]) {\n $(\"#AWA-latin\").text(basketProductData[productCode][\"product_name_latin\"]);\n } else {\n $(\"#AWA-latin\").text(\"\");\n }\n\n // Move bullets into proper location\n $(\"#AWA-category\").after($(\"#AWA-extra-bullets\"));\n\n // Decrease modal size since bullets contain a lot of whitespace - change in CSS\n\n $(\"#AWA-link a\").attr(\"href\", $(this).attr(\"href\"));\n } else {\n exp.log(\"Product not found - not opening modal\");\n }\n\n });\n }",
"function layPopup_fancy(){\r\n\t\r\n\t//EC-OP-0101_Cart–General Delivery Overview\r\n\t$(\".link_type1\").click(function(){\r\n\t\t$.fancybox($('#FO-OP-MART'));\r\n\t});\r\n\r\n\t//EC-MA-0113_Social Wish List Main\r\n\t$(\".link_type2\").click(function(){\r\n\t\t$.fancybox($('#EC-MA-0114_POP'));\r\n\t});\r\n\r\n\t//EC_PR_v0.7.0_product_detail_EC-PR-0101\r\n\t$(\".btn_size\").click(function(){\r\n\t\t$.fancybox($('#EC-PR-0101_brandsize'));\r\n\t});\r\n}",
"function goToProducts() {\n\tif (screen.width <= 1000) {\n\t\twindow.location.replace(\"http://www.slave-angelovski.com/furniture_site/products.html\");\n\t}\n}",
"function look_ruby_single_page_featured_popup() {\r\n $('.page-template-default .post-thumb.is-image-single a').magnificPopup({\r\n type: 'image',\r\n removalDelay: 500,\r\n mainClass: 'mfp-fade',\r\n closeOnContentClick: true,\r\n closeBtnInside: true\r\n });\r\n }",
"function changeProducts() {\n showProducts(cacheHandler.getPageFromProductCache());\n updatePageVisuals();\n}",
"function prodDoPreview(mode) {\n common.setButtonState('otherButton', 'createStoreViewProductsButton', 'Disabled');\n common.replaceElemClassFromTo('createStorePageDiv', 'visibleT', 'hidden', null);\n //\n const createStoreEditProdTlcSel = document.getElementById('createStore' + mode + 'ProdTlcSel');\n const createStoreEditProdLlcBitsSel = document.getElementById('createStore' + mode + 'ProdLlcBitsSel');\n const categoryBN = common.numberToBN(createStoreEditProdTlcSel.value).iushln(248);\n for (let i = 0; i < createStoreEditProdLlcBitsSel.selectedOptions.length; ++i) {\n\tconst llcBitsBn = common.numberToBN(createStoreEditProdLlcBitsSel.selectedOptions[i].value);\n\tcategoryBN.iuor(llcBitsBn);\n }\n const priceBN = meEther.usdStrToDaiBN(document.getElementById('createStore' + mode + 'ProdPriceArea').value);\n const regionBN = createStore.defaultRegionBN;\n const quantity = document.getElementById('createStore' + mode + 'ProdQuantityArea').value;\n const name = document.getElementById('createStore' + mode + 'ProdNameArea').value;\n const desc = document.getElementById('createStore' + mode + 'ProdDescArea').value;\n const image = document.getElementById('createStore' + mode + 'ProdImg').src;\n const product = new meUtil.Product(new BN('0', 16), name, desc, image);\n const vendorAddr = common.web3.eth.accounts[0];\n const productInfo = new meUtil.ProductInfo(common.BNToHex256(priceBN), quantity, common.BNToHex256(categoryBN), common.BNToHex256(regionBN), vendorAddr);\n product.setProductInfo(productInfo);\n meUtil.showProductDetail(product, 'view', 'extend', () => (mode == 'Add') ? addProductEditProduct(product) : viewProdsEditProduct(product));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
code TODO: ptdhCtrl | controller_by_user controller by user | function controller_by_user(){
try {
} catch(e){
console.log("%cerror: %cPage: `ptdh` and field: `Custom Controller`","color:blue;font-size:18px","color:red;font-size:18px");
console.dir(e);
}
} | [
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page index => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page storie_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page winner_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page faq_singles => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page faqs => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `index` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `hierbas_tes_yuyos` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `aceites` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page about_us => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `confites` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `prod_aptos_para_celacos` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `publicar` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page side_menus => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `slide_tab_menu` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `granos_y_semillas` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `menu` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `congelados` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page winner => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"%cerror: %cPage: `profile` and field: `Custom Controller`\",\"color:blue;font-size:18px\",\"color:red;font-size:18px\");\n\t\t\tconsole.dir(e);\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggles the container. / / The identifier. / The sender identifier. / The show text. / The hide text. | function toggleContainer(id,senderId,showText,hideText){var el=jQuery('#' + id);var sender=jQuery('#' + senderId);el.toggle(function(){sender.attr("title",hideText);sender.html(hideText);sender.addClass('hide');},function(){sender.attr("title",showText);sender.html(showText);sender.addClass('show');});} | [
"function showHide(elementId, containerId) {\r\n $(elementId).on('click', function(e) {\r\n e.preventDefault();\r\n $(containerId).toggleClass('is-hidden');\r\n });\r\n}",
"function toggleVisibility(idButton, idTarget, toggleContentName) {\n\tvar targetEle = document.getElementById(idTarget);\n\tvar buttonEle = document.getElementById(idButton); \n \n if (targetEle.style.display == \"block\" ){\n targetEle.style.display = \"none\";\n\t\tbuttonEle.value = \"Show \"+toggleContentName;\n } else {\n targetEle.style.display = \"block\";\n\t\tbuttonEle.value = \"Hide \"+toggleContentName;\n }\n}",
"function toggle(e) {\r\nvar node=(typeof e=='string')?document.getElementById(e):((typeof e=='object')?e:false);\r\nnode.style.display=(node.style.display!='none')?'none':'';\r\n}",
"function toggleInfo() {\n var state = document.getElementById('description').className;\n if (state == 'hide') {\n // Info anzeigen\n document.getElementById('description').className = '';\n document.getElementById('descriptionToggle').innerHTML = text[1];\n }\n else {\n // Info verstecken\n document.getElementById('description').className = 'hide';\n document.getElementById('descriptionToggle').innerHTML = text[0];\n }\n}",
"toggle() {\n if (this.isShown)\n this.hide();\n else\n this.show();\n }",
"function toggle_handler() {\n toggle($(this.id.substr(7)));\n }",
"function toggleContainer() {\n\t\t\tvm.isContainerVisible = ! vm.isContainerVisible;\n\t\t}",
"function toggle_displays() {\r\n console.log('--')\r\n\r\n // Toggle title containers\r\n document.getElementById(\"current_title_container\").hidden = !document.getElementById(\"current_title_checkbox\").checked\r\n\r\n // Toggle keywords containers\r\n document.getElementById(\"current_keywords_container\").hidden = !document.getElementById(\"current_keywords_checkbox\").checked\r\n\r\n // Toggle descriptions containers\r\n document.getElementById(\"current_descriptions_container\").hidden = !document.getElementById(\"current_descriptions_checkbox\").checked\r\n}",
"toggleBubble() {\n if (this.showingBubble) {\n this.hideBubble();\n } else {\n this.showBubble(this.createDomTree(this.getBubbleText()));\n }\n }",
"function toggleSpanVisibility() {\r\n $(\"#message\").toggle(300);\r\n if($(this).text() == \"Hide\") {\r\n $(this).text(\"Show\");\r\n } else {\r\n $(this).text(\"Hide\");\r\n }\r\n}",
"function toggle() {\n const desc = document.getElementById(\"show-hide\");\n if (desc.innerHTML === \"Show description\") {\n desc.innerHTML = \"Hide description\";\n } else {\n desc.innerHTML = \"Show description\";\n }\n}",
"toggle() {\n const { tooltip: e, container: n, offsetParent: s } = this;\n e && !St(e, n === s ? n : s) ? this.show() : this.hide();\n }",
"function toggleTeamDisplay(event){\n document.getElementById(\"kim-content\").style.display = \"none\";\n document.getElementById(\"aaron-content\").style.display = \"none\";\n document.getElementById(\"melissa-content\").style.display = \"none\";\n document.getElementById(\"ozlem-content\").style.display = \"none\";\n document.getElementById(\"redacted-content\").style.display = \"none\";\n document.getElementById(event.target.id + \"-content\").style.display = \"block\";\n}",
"function toggle(id, msgOff, msgOn) {\n var L = document.getElementById(\"L\"+id);\n var I = document.getElementById(\"I\"+id);\n if (L.style.display == \"\" || L.style.display == \"none\") {\n L.style.display = \"block\";\n I.src = \"http://www.columbia.edu/cu/lweb/images/icons/left-on.gif\";\n document.getElementById(\"spanblurb\"+id).innerHTML = msgOn;\n } // end IF\n else {\n L.style.display = \"none\";\n I.src = \"http://www.columbia.edu/cu/lweb/images/icons/left-off.gif\";\n document.getElementById(\"spanblurb\"+id).innerHTML = msgOff;\n } // end ELSE\n} // end FUNCTION toggle(id)",
"function trackDescToggle(){\n if(ui_state.track_desc_visible) trackDescCollapse();\n else trackDescExpand();\n}",
"function collapse(button, container, id) {\n\t// toggle button format\n\tvar btnType = button.className;\n\tvar dlID = \"dummy-line-\" + id;\n\tvar dcID = \"dummy-cont-\" + id; \n\tif(btnType == \"toggle-open\") {\n\t\tbutton.className = \"toggle-closed\";\n\t\t// replace with dummy line\n\t\tvar dLine = document.createElement(\"span\");\n\t\tvar dContent = document.createElement(\"span\");\n\t\tdLine.id = dlID;\n\t\tdLine.className = \"line\";\n\t\tdContent.id = dcID; \n\t\tdContent.className = \"comment-line toggle-section\"; // selection included since mouse will be over\n\t\tdContent.innerHTML = \"// \" + id + \"... \";\n\t\tcontainer.parentNode.insertBefore(dLine, container);\n\t\tcontainer.parentNode.insertBefore(dContent, container);\n\t} else{\n\t\tbutton.className = \"toggle-open\";\n\t\t// remove dummy items\n\t\tdocument.getElementById(dlID).outerHTML = \"\";\n\t\tdocument.getElementById(dcID).outerHTML = \"\";\n\t}\n\t// toggle visibility of container\n\tif (container.style.display === \"none\") {\n\t\tcontainer.style.display = \"inline\";\n\t} else {\n\t\tcontainer.style.display = \"none\";\n\t}\n}",
"didToggle() {}",
"handleToggleClick() {\n // retrieve the classList from the specific element\n const contentBlockClasslist = this.template.querySelector(\n \".lgc-id_content-toggle\"\n ).classList;\n // toggle the hidden class\n contentBlockClasslist.toggle(\"slds-hidden\");\n\n // if the current icon-name is `utility:preview` then change it to `utility:hide`\n if (this.toggleIconName === \"utility:preview\") {\n this.toggleIconName = \"utility:hide\";\n this.toggleButtonLabel = \"Reveal content\";\n } else {\n this.toggleIconName = \"utility:preview\";\n this.toggleButtonLabel = \"Hide content\";\n }\n }",
"function toggleVisibility() {\n toggle(this);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert articles into Article collection | function addArticles(articles) {
console.log(`Adding ${articles.length} articles`);
articles.forEach(item => {
db.Article.findOneAndUpdate({
link: item.link
},
item, {
upsert: true,
returnNewDocument: true
})
.then(doc => {
;
})
.catch(err => console.log(err));
});
} | [
"function addArticles(articles) {\n console.log(`Adding ${articles.length} articles`);\n \n articles.forEach(item => {\n // const article = new db.Article(item);\n \n // \"unique\" constraint doesn't seem to work sometimes(?)\n // somehow allowing to insert duplicates\n // article\n // .save()\n // .then(dbArticle => console.log(dbArticle))\n // .catch(err => console.log(err));\n \n // console.log(`Adding ${item}`);\n db.Article.findOneAndUpdate({\n link: item.link\n }, \n item, {\n upsert: true,\n returnNewDocument: true\n })\n .then(doc => {\n // console.log(`Added ${doc}`);\n ;\n })\n .catch(err => console.log(err));\n });\n}",
"async function insertNewsArticles(country) {\n\tgetNewsArticles(country)\n\t\t.then((res) => {\n\t\t\tfor (var i = 0; i < res.data.articles.length; i++) {\n\t\t\t\taddArticle(country, res.data.articles[i]);\n\t\t\t}\n\t\t})\n\t\t.catch((err) => {\n\t\t\tconsole.log(\"Failed to insert article into DB...\\n\", err);\n\t\t});\n}",
"function insertArticle(article) {\n\n console.log('Inserting new Article...');\n \n db.query(properties.get('queries.articles.insert'), [article.title, article.author, article.body], (err, results, fields) => {\n if (err) {\n return console.error(err.message);\n }\n // log result\n //console.log('Rows inserted [' + results.affectedRows + ']');\n if (results.affectedRows==1) {\n article.id = results.insertId;\n console.log('Article inserted with id: ' + article.id);\n } else {\n console.log('Unable to insert Article');\n }\n });\n}",
"async function createArticles() {\n const types = ['a', 'a','a', 'a', 'a','b', 'b', 'b', 'b', 'b', 'c', 'c','c', 'c', 'c',]\n const articles = types.map(d => ({type: d})).map(mapArticle)\n try {\n const {result} = await articleCollection.insertMany(articles)\n console.log(`Added ${result.n} articles`)\n } catch (err) {\n console.error(err)\n }\n}",
"async function example5() {\n try {\n const types = ['a', 'b', 'c'].map(type => Array(5).fill(type)).flat();\n const articles = types.map(d => ({type: d})).map(mapArticle);\n try {\n const {result} = await articleCollection.insertMany(articles);\n console.log(`Added ${result.n} articles`);\n } catch (err) {\n console.error(err);\n }\n } catch (err) {\n console.error(err);\n }\n}",
"async function articlesTask1 () {\n try {\n const types = ['a', 'b', 'c']\n const articles = types.map(type=>type.repeat(5).split('')).flat().map(el=>mapArticle({type:el}))\n await articleCollection.insertMany(articles)\n } catch (error) {\n console.log(error);\n }\n}",
"function saveArticles(articles) {\n async.each(articles, (article, callback) => {\n Article.findOneAndUpdate({\n url: article.url\n }, {\n author: article.author,\n title: article.title,\n description: article.description,\n urlToImage: article.urlToImage,\n content: article.content,\n publishedAt: article.publishedAt\n }, {\n upsert: true\n }, (err, article) => {\n callback();\n }); \n }, (err) => { \n if( err ) {\n console.log('Unable to save some article ');\n } else {\n console.log('All articles are saved');\n }\n });\n}",
"function addArticles() {\n\tsortResults('publishedAt');\n\tfor(var i = 0; i < (articleList.length < 20 ? articleList.length : 20); i++) {\n\t\taddArticle(articleList[i].title, articleList[i].description, articleList[i].url, articleList[i].publishedAt, articleList[i].source, articleList[i].color);\n\t}\n\tif(articleList.length==0)\n\t\taddArticle(\"Désolé\", \"Nous n'avons pas d'article à vous proposer pour cette localisation dans les catégories sélectionnées.\", \"\", \"undefined\", \"undefined\", \"#454545\");\n}",
"'entries.insert'(doc){\n\t\t\tEntries.insert(doc);\n\t\t}",
"function updateArticles(items, callback) {\n var cb = callback ? callback : function(err, feeds){};\n\n\tconnect(function() {\n\t\tvar articles = _db.collection('articles');\n\t\tarticles.insertMany(items, {ordered : false}, cb);\n\t});\n}",
"function handleArticlePublish({ connection, article, callback }) {\n r.db(config.DB_NAME).table('articles')\n .insert(Object.assign(article, { timestamp: new Date() }))\n .run(connection)\n .then(callback)\n}",
"function saveArticle(title, subtitles, tags, text, img, author, date) {\n let newArticleRef = articlesRef.push();\n newArticleRef.set({\n title: title,\n description: subtitles,\n subtitles: subtitles,\n tags: tags,\n text: text,\n img: img,\n author: author,\n date: date\n })\n }",
"function insertArticle(newArticle)\r\n{\r\n\tlow = 0;\r\n\thigh = articles.length - 1;\r\n\tdone = false;\r\n\twhile(high !== low)\r\n\t{\r\n\t\tmid = Math.floor((low + high)/2);\r\n\t\tif(articles[mid][0].toLowerCase().localeCompare(newArticle.toLowerCase()) >= 0)\r\n\t\t\thigh = mid;\r\n\t\telse\r\n\t\t\tlow = mid + 1;\r\n\t}\r\n\tlet articleDOM = document.querySelector(\"#articles\");\r\n\tarticleDOM.innerHTML = articleDOM.innerHTML.replace(articles[low][0], newArticle + \"^^\" + articles[low][0]);\r\n\r\n\t// Update articles datastructure\r\n\tinitArticles();\r\n} // articlesUpdate()",
"insertMany() {\n errors.throwNotImplemented(\"inserting multiple docs into a collection\");\n }",
"function insertMany(err) {\n\t\t\tif (err){\n\t\t\t\thandleError(err, res, db);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcommands.push(\"#1.2 Insert documents into a collection\");\n\t\t\tcollection.insert([{name : \"test1\", value : 11}, {name : \"test2\", value : 2}, {name : \"test3\", value : 3}], findOne);\n\t\t\tcommands.push(\"Inserted \\n{name : \\\"test1\\\", value : 1}\\n{name : \\\"test2\\\", value : 2}\\n{name : \\\"test3\\\", value : 3}\");\n\t\t}",
"function loadArticles() {\n client.query('SELECT COUNT(*) FROM articles')\n .then(result => {\n if(!parseInt(result.rows[0].count)) {\n fs.readFile('./public/data/hackerIpsum.json', (err, fd) => {\n JSON.parse(fd.toString()).forEach(ele => {\n client.query(`\n INSERT INTO\n articles(title, author, \"authorUrl\", category, \"publishedOn\", body)\n VALUES ($1, $2, $3, $4, $5, $6);\n `,\n [ele.title, ele.author, ele.authorUrl, ele.category, ele.publishedOn, ele.body]\n )\n })\n })\n }\n })\n}",
"function createArticles(articles){\n return db.Article.create(articles)\n .then(function (dbArticle) {\n // console.log(dbArticle.length)\n return dbArticle\n })\n .catch(function (err) {\n return false\n });\n}",
"function createArticles(articles, user) {\n return new Promise((resolve, reject) => {\n Article.create(articles, (err, newArticles) => {\n if (err) {\n console.log(\"Error in creating new articles\");\n console.log(err);\n }\n newArticles.forEach((article) => {\n user.articles.push(article);\n });\n user.save((err, updatedUser) => {\n if (err) {\n console.log(\"Error in saving articles to user\");\n console.log(err);\n }\n console.log(\"News articles successfully saved\");\n resolve();\n });\n });\n });\n}",
"async function task5() {\n try {\n \n const types = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c']\n const articles = types.map(type => ({\n name: 'Mongodb - introduction',\n description: 'Mongodb - text',\n type: type,\n tags: []\n }))\n\n const { result } = await userCollection.insertMany(articles)\n console.log(`added ${result.n} articles`)\n } catch (err) {\n console.log(err)\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates new Room instance from arguments DB: register new room register room.users in roomUsers add roomId to each list of user rooms in userRooms return room | create(userIdList, props, callback) {
(props = props || {}).uid = firebase.auth().currentUser.uid;
let room = new Room(this._chatPath, props);
room.createdAt = room.updatedAt = new Date();
room.creatorId = firebase.auth().currentUser.uid;
room.users = uniqueKeys((userIdList || []).concat([room.creatorId]));
room.id = firebase.database().ref(this.path(['rooms'])).push(room.toJson()).key;
room._dbMessagesRef = firebase.database().ref(this.path(['messages', room.id]));
room._dbMessagesRef.off();
room._dbRoomUsersRef = firebase.database().ref(this.path(['roomUsers', room.id]));
room._dbRoomUsersRef.off();
room._dbRoomRef = firebase.database().ref(this.path(['rooms', room.id]));
room._dbRoomRef.off();
room._dbRoomRef.once('value', snapshot => {
room.onUpdated(snapshot);
if (callback) callback(room);
});
return room;
} | [
"createRoom() {\n check(arguments, Match.OneOf({}, undefined, null));\n\n this.unblock();\n\n let id = Rooms.insert({\n owner: this.userId,\n connected: [],\n });\n\n Roles.addUsersToRoles(this.userId, id, Roles.GLOBAL_GROUP);\n\n return id;\n }",
"function createRooms(room) {\n var room_data = {\n _id: new Date().toISOString(),\n room: room\n };\n db.put(room_data, function callback(err, result) {\n if (!err) {\n console.log(\"Successfully added a room!\");\n }\n });\n}",
"async function createNewRoom(username, roomName, id) {\n console.log(\"CREATING A NEW ROOM\");\n const newUser = new User(username, roomName, id);\n\n const newRoom = new Room({\n hostId: id,\n roomName: roomName,\n })\n\n newRoom.addUser(newUser)\n\n return Room.create(newRoom).then(data => {\n return data\n }).catch(err => {\n console.error(err);\n process.exit(1)\n })\n}",
"function createNewRoom() {\r\n // Generate room id.\r\n const newID = uuidv4().substring(0, 8);\r\n\r\n // Join room\r\n socket.join(newID);\r\n\r\n // Update corressponding object in usersArray\r\n updateUserRoom(socket, newID);\r\n\r\n // Send room data to socket\r\n io.to(socket.id).emit(\"roomData\", {\r\n roomId: newID,\r\n });\r\n }",
"addRoom(room) {\n room.users = []\n rooms.set(room.id, room);\n }",
"createRoom(userIdList, props, callback) {\n let room = this.roomFactory.create(userIdList, props, callback);\n this.rooms[room.id] = room;\n return room;\n }",
"createRoom() {\n this.addRoom();\n var uid = firebase.auth().currentUser.uid;\n var name = firebase.auth().currentUser.displayName;\n var database = firebase.database();\n var roomName = document.getElementById(\"roomname\").value;\n var privacy = document.getElementById(\"privacy\").checked;\n var roomPush = database.ref().push();\n var roomKey = roomPush.key;\n database.ref('rooms/' + roomKey).set({\n roomname: roomName,\n downvoters: '',\n songs: '',\n chats: '',\n privacy: privacy,\n admin: uid,\n users: '',\n downvotes: 0,\n numberOfUsers: 1\n });\n database.ref('rooms/' + roomKey +'/users').push(uid);\n var userID = firebase.auth().currentUser.uid;\n database.ref('users/' + userID ).push();\n database.ref('users/' + userID ).set({\n name: name\n });\n database.ref('users/' + userID + \"/roomKeys\").push();\n database.ref('users/' + userID + \"/roomKeys\").set({\n currentRoom: roomKey\n });\n }",
"function createChatRoom(title, name, maxNumUsers=10, chatRoomId, lat, lng, password=\"password\"){\n firebase.database().ref('chat_rooms/' +chatRoomId).set({\n lat:lat,\n lng:lng,\n guest_ids:[name],\n maximum_number_users: maxNumUsers,\n messages:[],\n owner_id:name,\n maxNumUsers:maxNumUsers,\n password:password,\n title:title\n });\n}",
"function createNewRoom() {\n console.log(nextRoomId);\n createRoomDOM(nextRoomId);\n signalRoomCreated(nextRoomId);\n\n nextRoomId++;\n}",
"addRoom(){\n\t\tvar newRoom = new Room(this);\n\t\tthis.rooms.push(newRoom);\n\t}",
"async function newRoom() {\n let room;\n try {\n room = await rest.post(`${url}/rooms`, {});\n if (room.error) throw new Error(room.message);\n } catch (error) {\n showModalOnScreen(true, error.message);\n return;\n }\n setShowRoom(true);\n setRoomID(room.idRoom);\n setHash(room.hashP1);\n }",
"addRooms(state, rooms) {\n for (let r of rooms) {\n if (state.rooms.hasOwnProperty(r.id)) { continue; }\n Vue.set(state.rooms, r.id, new Room(r.id, r.name, r.users, r.picture_url));\n }\n }",
"function createRoom() {\n const args = Array.prototype.slice.call(arguments);\n const name = args.shift();\n args.unshift(DEFAULT_ROOM);\n return createObject(name, args);\n}",
"async function addUser(username, roomName, id) {\n console.log(\"ADDING A NEW USER\");\n const existingRoom = await checkRoomNameExist(roomName);\n if (existingRoom) {\n const existingUser = checkUsedUsername(existingRoom.users, username)\n if (existingUser) {\n return {\n error: 'Username is taken.'\n }\n } else {\n const newUser = new User(username, roomName, id);\n return await Room.findOneAndUpdate({\n roomName: roomName\n }, {\n $push: {\n users: newUser\n }\n }, {\n new: true\n }).then(data => {\n const Room = data\n return {\n Room\n }\n }).catch(err => {\n throw err\n })\n }\n // else create a new room since that room doesnt already exist\n } else {\n const Room = await createNewRoom(username, roomName, id)\n console.log(\"New Room created\", Room);\n return {\n Room\n }\n }\n}",
"function addRoom() {\n\tvar roomName = $('#add-room-name').val();\n\tvar posting = $.post(roomsAddURI, {\n\t\tname : roomName\n\t});\n\tposting.done(function(data) {\n\t\t//Add room via rest api then join it\n\t\tvar room = JSON.parse(JSON.stringify(data));\n\t\tjoinRoom(room.roomId, true);\n\t});\n}",
"function createRoom(x, y, z, user) {\n // Return 0 by defualt, if any coord is passed without value.\n ( x ? parseInt(x) : 0 );\n ( y ? parseInt(y) : 0 );\n ( z ? parseInt(z) : 0 );\n\n // Make sure they all parsed well. NaN means Not a Number.\n if (isNaN(x) || isNaN(y) || isNaN(z)) {\n console.log('Position did not pass parsing to int: ' + x + ', ' + y + ', ' + z + '.');\n return;\n }\n\n // Just for shorthand.\n var strPos = x + ', ' + y + ', ' + z;\n var strCoord = x + 'x' + y + 'y' + z + 'z'; // This is how room names (as objects) look like.\n var roomPos = { 'x': x, 'y': y, 'z': z } // Mimic how the DB object looks.\n \n // Create room object for insert.\n var roomObj = constructor.room(user.player.map, roomPos);\n \n var strObj = {};\n strObj[strCoord] = { '$exists': true }; // DB query for existing field.\n\n // Make sure the room does not already exist.\n // I prefer checking here than having the DB handle duplicates.\n mapsdb.findOne(strObj, function (err, room) {\n if (room) {\n console.log('Room at ' + strPos + ' already exists!'); \n return;\n }\n \n // Otherwise, insert the new room normally.\n // Insert room to world.map object with property name '#x#y#z' from coords.\n world.maps[roomObj.map].rooms[strCoord] = roomObj;\n \n // Add to changed objects for next DB update.\n world.changed.rooms.push(roomObj);\n \n // Inform the user of success.\n if (x == 0 && y == 0 && z == 0 && user.player.map == 0) {\n user.socket.emit('info', '<i><b>The first room in this world' +\n ' has been created successfully!</b></i>');\n } else if (x == 0 && y == 0 && z == 0) {\n user.socket.emit('info', '<i><b>The first room in the map' +\n ' has been created successfully.</b></i>');\n } else {\n user.socket.emit('info', '<i><b>Room at ' + strPos +\n ' has been created successfully.</b></i>');\n }\n \n processRoom(user, 'new'); // Apply room data.\n });\n}",
"function createRoom() {\n const msgCreateRoom = {\n method: 'createRoom'\n };\n sendMsg(msgCreateRoom);\n}",
"function addRoom(room,pwd,game){\n rooms.push({room,pwd,game});\n}",
"add(room) {\n\tthis._rooms[room.identifier] = room;\n\treturn room;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigate to the tickets page of a current training room | function navigateToTickets(roomId){
window.location.href = "tickets.html?roomId=" + roomId;
} | [
"function navigate(num) {\n console.log(\"Navigating to \" + num);\n if (typeof num !== \"undefined\" && num != \"home\") {\n window.location.href = \"https://ithelp.uoregon.edu/Ticket/Display.html?id=\" + num;\n } else {\n window.location.href = \"https://ithelp.uoregon.edu\";\n }\n}",
"function workoutPage() {\n window.location.href = `/#/workout?access_token=${TOKEN}`;\n }",
"function viewItineraries(){\n\tlet event_id = parseInt($(\".js-next\").attr(\"data-id\"));\n\twindow.location.href = `/events/${event_id}/itineraries`;\n}",
"function goToWorkout() {\n if (contextObject.workoutStarted === false) {\n navigation.navigate('StartWorkout')\n } else {\n navigation.navigate('Workout')\n }\n }",
"function navigate()\n{\n var testCase = $(this).find(\"td.tcName\").text();\n testCase += \"_details.html\";\n window.open(testCase);\n}",
"function ksGotoCoursePage(id){\n window.location = \"/course/course/id/\" + id;\n}",
"function goToRoom(e) {\n\te.preventDefault();\n\n\tvar roomName = $.trim($('#roomName').val());\n\n\tif(!roomName){ return; } \n\n window.location.href = '/covert/room/' + roomName;\n}",
"function GoTeamPage()\n{\n if( ! LocationTest(\"/bvs/team.html\") )\n {\n\tvar menucell = document.evaluate('//a[text()=\"Team\"]', document, null,\n\t\t\t\t\t XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;\t\t\t\t \n\teval(\"unsafeWindow.\" + menucell.href.split(\":\")[1]);\n\tthrow new Error(\"Moving to team page\");\t\n }\n}",
"navigateConferenceResearchPage(e, researchId) {\n window.location = `/conferenceResearch/${researchId}`;\n }",
"function jumpToTimeTable() {\n window.location.href = \"../TimeTable/TimeTable.html\";\n}",
"navigateConferenceWorkshopPage(e, workshopId){\n window.location = `/conferenceWorkshop/${workshopId}`\n }",
"function getTourUrl() {\n self.location = \"/promos/dc/take_tour.html\";\n}",
"function buyTickets() {\n let event = events[eventsIndex];\n window.open(event.ticketURL, '_blank');\n }",
"function GuestList(){\r\n \r\n window.location.pathname = 'GuestList.html'\r\n \r\n }",
"navigateConferenceWorkshopPage(e, workshopId) {\n window.location = `/conferenceWorkshop/${workshopId}`;\n }",
"function toScheduledTripsPage() {\n window.location = \"scheduledTripsPage.html\";\n}",
"function assignTicketId(id){\n\tconsole.log(\"Ticket assi...\")\n location.replace(`update.html?id=${id}`);\n\n}",
"function getPastOrders(){\n window.location.assign(\"previousorders.html\");\n}",
"function ViewItineraryPage() { }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function update the .cdmarker position on hover | function updateHoverNav() {
var hoverItem = $('.cd-hover'),
hoverItemPosition = hoverItem.index() + 1,
leftPosition = hoverItem.offset().left,
backgroundColor = hoverItem.data('color'),
marker = $('.cd-marker');
marker.removeClassPrefix('color').addClass('color-'+ hoverItemPosition).css({
'left': leftPosition,
});
} | [
"function handleHover(centered, d){\n mediumlightBar(mapObj[d.properties.ID].realname);\n}",
"function markerHover() {\n\n\t\tthis.setIcon(highlightedIcon);\n }",
"getMarkersHoverOn(marker) {\n marker.on('mouseover', function(e) {\n marker.openPopup();\n });\n }",
"function moveTooltip() {\n\t tooltippy.style(\"top\",(d3.event.pageY+tooltipOffset.y)+\"px\")\n\t .style(\"left\",(d3.event.pageX+tooltipOffset.x)+\"px\");\n\t}",
"function moveTooltip() {\n tooltip.style(\"top\",(d3.event.pageY+tooltipOffset.y)+\"px\")\n .style(\"left\",(d3.event.pageX+tooltipOffset.x)+\"px\");\n }",
"updateMarkerDistance(distance) {\n this.laserMarker.position.z = distance;\n }",
"function moveTooltip() {\n tooltip.style(\"top\",(d3.event.pageY+tooltipOffset.y)+\"px\")\n .style(\"left\",(d3.event.pageX+tooltipOffset.x)+\"px\");\n }",
"function mousemove(d){\n tooltip.style(\"position\", \"absolute\").style(\"left\", (d3.event.pageX) + \"px\").style(\"top\", (d3.event.pageY) + \"px\");\n }",
"function moveTooltip() {\n tooltip.style(\"top\",(d3.event.pageY+tooltipOffset.y)+\"px\")\n .style(\"left\",(d3.event.pageX+tooltipOffset.x)+\"px\");\n}",
"function moveTooltip() {\n\t tooltip.style(\"top\",(d3.event.pageY+tooltipOffset.y)+\"px\")\n\t .style(\"left\",(d3.event.pageX+tooltipOffset.x)+\"px\");\n\t}",
"function markerMouseoverCallback(event) {\n document.getElementById(\"bottom-left-coordinates-lat\").innerHTML = $.i18n('coordinates-hover-container-latitude') + \": \" + parseFloat(event.feature.getProperty(\"Latitud\").toFixed(4)) + \"°\";\n document.getElementById(\"bottom-left-coordinates-lng\").innerHTML = $.i18n('coordinates-hover-container-longitude') + \": \" + parseFloat(event.feature.getProperty(\"Longitud\").toFixed(4)) + \"°\";\n fadeInElements([\"map-bottom-left-container\"], 350);\n}",
"function cordMark()\n{\n\tmap.removeLayer(marker);\n\tmarker = L.marker(cord);\n\tmap.addLayer(marker);\n\tmarker.bindPopup(\"Cordinatote - \"+\" Latitude: \"+cord[0]+\" Longitude: \"+cord[1]).openPopup();\n}",
"function markHover() {\n atomicText.addClass('hover-mark');\n ionicText.addClass('hover-mark');\n}",
"function updateToolTipPosition(x, y){\n powerTooltip.style.top = (y + 20) + 'px';\n powerTooltip.style.left = (x - 60) + 'px';\n }",
"function HM_UpdateTooltip(x, y, value) {\n // + 15 for distance to cursor\n var translation = 'translate(' + (x + 100) + 'px, ' + (y + 100) + 'px)';\n hm_tooltip.style.webkitTransform = translation;\n hm_tooltip.innerHTML = value;\n}",
"function handleMouseOver(d, ii){\n d3.select('#scat-marks')\n .append('text')\n .text(ii.StateAbbr)\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"font-weight\", \"100\")\n .attr(\"x\", 5)\n .attr(\"y\", 15);\n}",
"function link_onMouseOver(e,d,i) {\n\n // find the associated candidate and get values for the datatip\n var cand=viz.selection().selectAll(\".vz-halo-node.node-key_\" + viz.nodeKey()(d.data));\n var datum=cand.datum();\n var total = \"$\" + d3.format(\",.0f\")(viz.value()(d.data));\n var date = d.data.Month + \"/\" + d.data.Day + \"/\" + d.data.Year;\n\n //Create and position the datatip\n var rect = d3.selectAll(\".vz-halo-arc-plot\")[0][0].getBoundingClientRect();\n createDataTip(datum.x + rect.left + datum.r, datum.y + datum.r + 25 + rect.top, date, d.data.CAND_NAME,\"Received: \" + total);\n\n //find the pac and create a label for it.\n var pac=viz.selection().selectAll(\".vz-halo-arc.halo-key_\" + viz.haloKey()(d.data));\n datum=pac.datum();\n createPacLabel(datum.x, datum.y,datum.data.values[0].CMTE_NM);\n}",
"updateMarkers() {\n if (this.workspace_.keyboardAccessibilityMode && this.cursorSvg_) {\n this.workspace_.getCursor().draw();\n }\n }",
"function changeShipHoverPos(event) {\r\n if (state.phase !== 'setup') {\r\n return;\r\n }\r\n shipHoverEl.style.left = `calc(${event.pageX}px - 2vw)`;\r\n shipHoverEl.style.top = `calc(${event.pageY}px - 2vw)`;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Concatenates a list of `tf.Tensor3D`s along an axis. See `concat` for details. For example, if: A: shape(2, 1, 3) = | r1, g1, b1 | | r2, g2, b2 | B: shape(2, 1, 3) = | r3, g3, b3 | | r4, g4, b4 | C = tf.concat3d([A, B], axis) if axis = 0: C: shape(4, 1, 3) = | r1, g1, b1 | | r2, g2, b2 | | r3, g3, b3 | | r4, g4, b4 | if axis = 1: C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 | | r2, g2, b2, r4, g4, b4 | if axis = 2: C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 | | r2, g2, b2, r4, g4, b4 | | function concat3d_(tensors, axis) {
return exports.concat(tensors, axis);
} | [
"function concat3d_(tensors, axis) {\n return _concat.concat(tensors, axis);\n}",
"function concat3d_(tensors, axis) {\n return concat(tensors, axis);\n}",
"function concat3d_(tensors, axis) {\n return concat(tensors, axis);\n}",
"function concat3d_(tensors, axis) {\n return (0, _concat.concat)(tensors, axis);\n}",
"function concatenate(tensors, axis = -1) {\n let rank;\n if (axis < 0) {\n rank = tensors[0].rank;\n if (rank !== 0) {\n axis = rank;\n }\n else {\n axis = 0;\n }\n }\n if (axis === tensors[0].rank) {\n // Porting Note: This is necessary because tfc.concat() requires axis to be\n // in the interval [-rank, rank).\n axis = -1;\n }\n // Porting Note: Sparse concat is not supported yet.\n return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.concat(tensors, axis);\n}",
"function concatenate(tensors, axis) {\n if (axis === void 0) { axis = -1; }\n var rank;\n if (axis < 0) {\n rank = tensors[0].rank;\n if (rank !== 0) {\n axis = rank;\n }\n else {\n axis = 0;\n }\n }\n if (axis === tensors[0].rank) {\n // Porting Note: This is necessary because tfc.concat() requires axis to be\n // in the interval [-rank, rank).\n axis = -1;\n }\n // Porting Note: Sparse concat is not supported yet.\n return tfc.concat(tensors, axis);\n}",
"function concatenate(tensors, axis) {\n if (axis === void 0) {\n axis = -1;\n }\n var rank;\n if (axis < 0) {\n rank = tensors[0].rank;\n if (rank !== 0) {\n axis = rank;\n } else {\n axis = 0;\n }\n }\n if (axis === tensors[0].rank) {\n // Porting Note: This is necessary because tfc.concat() requires axis to be\n // in the interval [-rank, rank).\n axis = -1;\n }\n // Porting Note: Sparse concat is not supported yet.\n return tfc.concat(tensors, axis);\n}",
"function concat4d_(tensors, axis) {\n return concat(tensors, axis);\n}",
"function concat4d_(tensors, axis) {\n return concat(tensors, axis);\n}",
"function concat4d_(tensors, axis) {\n return exports.concat(tensors, axis);\n}",
"function concat4d_(tensors, axis) {\n return (0, _concat.concat)(tensors, axis);\n}",
"function concat2d_(tensors, axis) {\n return _concat.concat(tensors, axis);\n}",
"function concat4d_(tensors, axis) {\n return (0,_concat__WEBPACK_IMPORTED_MODULE_0__.concat)(tensors, axis);\n}",
"function concat2d_(tensors, axis) {\n return concat(tensors, axis);\n}",
"function concat2d_(tensors, axis) {\n return concat(tensors, axis);\n}",
"function batchConcat(arrays) {\n if (arrays.length === 0) {\n // We can't return an empty Tensor because we don't know the element shape.\n throw new Error('Can\\'t make a batch of zero elements.');\n }\n if (arrays[0] instanceof tf.Tensor) {\n // Input is an array of Tensors\n return tf.stack(arrays);\n }\n else {\n // Input is a possibly-nested array of numbers.\n return tf.tensor(arrays);\n }\n}",
"function batchConcat(arrays) {\n if (arrays.length === 0) {\n // We can't return an empty Tensor because we don't know the element shape.\n throw new Error('Can\\'t make a batch of zero elements.');\n }\n if (arrays[0] instanceof tf.Tensor) {\n // Input is an array of Tensors\n return tf.stack(arrays);\n } else {\n // Input is a possibly-nested array of numbers.\n return tf.tensor(arrays);\n }\n}",
"function concat2d_(tensors, axis) {\n return exports.concat(tensors, axis);\n}",
"function concat2d_(tensors, axis) {\n return (0, _concat.concat)(tensors, axis);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change textField's value to upperCase | function changeToUpperCase(field) {
var valueStr = new String(field.value);
field.value = valueStr.toUpperCase();
} | [
"function textToUpperCase(field)\n{\n field.value = field.value.toUpperCase();\n return true;\n}",
"function _Field_toUpperCase(){\n\tthis.setValue(this.getValue().toUpperCase(), null, false);\n\treturn true;\n}",
"function setFieldsToUpperCase(){\r\n\tfor(var i=0;i<arguments.length;i++) {\r\n\t\targuments[i].value = arguments[i].value.toUpperCase();\r\n\t\t}\r\n\t}",
"function setFieldsToUpperCase(){\n\tfor(var i=0;i<arguments.length;i++) {\n\t\targuments[i].value = arguments[i].value.toUpperCase();\n\t\t}\n\t}",
"function UpperCaseName(field)\n{\n function capitalizeOnBlur(field) {\n if (field.length > 0) {\n field.on('blur', function () {\n var name = field.val();\n E.$(this).val(titleCase(name));\n });\n }\n }\n\n function titleCase(value) {\n value = value ? value : '';\n var result = [],\n separators = [' ', '-', '–', '_', '.'],\n upperCase = true;\n\n for(var i = 0; i < value.length; i++)\n {\n result.push(upperCase ? value[i].toUpperCase() : value[i]);\n upperCase = false;\n if(separators.indexOf(value[i]) >= 0)\n upperCase = true;\n }\n\n result = result.join('');\n return result.replace(/\\s{2,}/g, ' ').trim();\n }\n\n if(typeof field == \"string\") field = E.$(field);\n else if(typeof field != \"object\" || typeof field.val != \"function\" || typeof field.val() != \"string\")\n {\n E.log.error('UpperCaseName: The field for uppercase must be a input text field as either a css selector or a jQuery object.');\n return;\n }\n capitalizeOnBlur(field);\n}",
"function setFieldsToUpperCase() {\r\n for (var i=0; i<arguments.length; i++) {\r\n var obj = arguments[i];\r\n obj.value = obj.value.toUpperCase();\r\n }\r\n }",
"function capitalizeOnBlur () {\r\n var id= event.currentTarget.id;\r\n if((id.split(\"_\"))[4]==\"null\"){ \r\n var text=$('#'+id+'').val();\r\n var textlength=$('#'+id+'').length;\r\n if(event.keyCode==32)\r\n {\r\n if(textlength>0)\r\n $('#'+id+'').val(text.charAt(0).toUpperCase() + text.slice(1));\r\n }\r\n }\r\n}",
"function makeAllInputFieldsUpperCase() {\n\t$$(\"input[type='text'], textarea\").each(function (e) {\n\t\tif (e.id != \"email\"){\t//added by angelo 01.20.11 to avoid automatic capitalization of email\n\t\t\te.observe(\"keyup\", function () {\n\t\t\t\te.value = e.value.toUpperCase();\n\t\t\t});\n\t\t}\n\t});\n}",
"function setUpperCaseValue(){\n\t$(document).delegate(\"[data-uppercase = true]\", \"change\", function() {\n\t\tvar inputValue = $(this).val().toUpperCase();\n\t\t$(this).val(inputValue);\n\t});\n}",
"function capitalizeText() {\n var inputCapitalize = document.getElementById(\"inputCapitalize\");\n inputCapitalize.value = inputCapitalize.value.toUpperCase();\n}",
"function up_cas(lwc) {\n\n lwc.keyup(function() {\n\n lwc.val($(this).val().toUpperCase());\n\n });\n\n}",
"function letterCaseToggle(){\r\n if(magicTxt.value != magicTxt.value.toUpperCase()){\r\n magicTxt.value = magicTxt.value.toUpperCase();\r\n magicTxt.focus();\r\n }else{\r\n magicTxt.value = magicTxt.value.toLowerCase();\r\n magicTxt.focus();\r\n }\r\n}",
"function caseEHandler(event, _this, toLowerCase) {\n var editor = atom.workspace.getActiveTextEditor();\n var originalText = document.getElementById(\"originalText\").getModel().getText();\n\n editor.insertText((toLowerCase ? originalText.toLowerCase() : originalText.toUpperCase()));\n}",
"function uppercase(input) {}",
"function uppercaseValue(controlId) {\r\n jQuery(\"#\" + controlId).css('text-transform', 'uppercase');\r\n jQuery(\"#\" + controlId).change(function () {\r\n this.value = this.value.toUpperCase();\r\n });\r\n}",
"function toUpperCase() {\n applySelectionStringChange((text) => { return text.toUpperCase(); });\n}",
"function countryCodeChgCase()\n{\n document.popperform.countryCode.value = (document.popperform.countryCode.value).toUpperCase(); \n}",
"function firstLetterUpperCase(nameField){\n return nameField.charAt(0).toUpperCase()+nameField.slice(1);\n }",
"function capitalize()\n{\n\t//As such, we only select these two fields.\n\tvar selections = \"input[id=fname], input[id=lname]\";\n\tvar fields = document.querySelectorAll(selections);\n\t//If not empty, we cycle through the fields array.\n\tif(fields != null)\n\t{\n\t\t//The full array is cycled through.\n\t\tfor(var i = 0; i <fields.length; i++)\n\t\t{\n\t\t\t//The var string is set to the basic value for some input adjustment. If not empty, only the first character is capitalized, with the rest staying lowercase. Then, the adjusted value is set as the new text box value.\n\t\t\tvar string = fields[i].value;\n\t\t\tif(string != \"\")\n\t\t\t{\n\t\t\t\tstring = string[0].toUpperCase() + string.slice(1).toLowerCase(); \n\t\t\t\tfields[i].value = string;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change values determined by product family (when choosing product) | function changeProductValues() {
showHideProductValues();
enableDisableCreditFields();
} | [
"function changeMprod() {\n spec.miningProd = getMprod()\n itemUpdate()\n}",
"function setClassification() {\n var classification = document.getElementById('classification');\n var product = document.getElementById('product');\n var selected_product = product.value; \n var select_classification = all_classifications[selected_product];\n classification.value = select_classification;\n bz_fireEvent(classification, 'change');\n}",
"function changePrices(affiliation, id, num)\n{\n\n if (affiliation == \"UC\") {\n switch (id) {\n case 'ST_VM':\n price_vm = PRICE_ST_VM_UC;\n break;\n case 'HS_VM':\n price_vm = PRICE_HS_VM_UC;\n break;\n case 'CL_STR':\n price_cl_str = PRICE_CLOUD_STORAGE_UC;\n original = PRICE_CLOUD_STORAGE_UC;\n dual = PRICE_DUAL_SITE_CLOUD_STORAGE_UC;\n break;\n case 'PR_STR':\n price_pr_str = PRICE_PROJECT_STORAGE_UC;\n break;\n case 'PR_CON':\n price_pr_con = PRICE_PROJECT_CONDO_UC;\n break;\n case 'RECUR_DESK':\n case 'DESK':\n price_consult = PRICE_DESKTOP_SERVICES_UC;\n break;\n case 'RECUR_SYSTEMS':\n case 'SYSTEMS':\n price_consult = PRICE_SYSTEMS_SERVICES_UC;\n break;\n case 'RECUR_STORAGE':\n case 'STORAGE':\n price_consult = PRICE_STORAGE_SERVICES_UC;\n break;\n case 'SITE':\n price_share = [PRICE_SHAREPOINT_SITES_UC, PRICE_ADD_DA_STORAGE_UC, PRICE_CONSULTATION_SUPPORT_UC];\n break;\n case 'SUPPORT':\n case 'SYS_MAN':\n price_sys_man = PRICE_SYSTEM_MANAGEMENT_UC;\n break;\n case 'COMMVAULT':\n price_comm = [PRICE_RAW_BACKUP_DATA_UC, PRICE_FULL_BACKUP_UC, PRICE_DIFFERENTIAL_INCREMENTAL_UC];\n break;\n case 'RAW':\n case 'CL_COMPUTE':\n price = PRICE_CL_COMPUTE_UC;\n break;\n }\n }\n else {\n switch (id) {\n case 'ST_VM':\n price_vm = PRICE_ST_VM_EXT;\n break;\n case 'HS_VM':\n price_vm = PRICE_HS_VM_EXT;\n break;\n case 'CL_STR':\n price_cl_str = PRICE_CLOUD_STORAGE_EXT;\n original = PRICE_CLOUD_STORAGE_EXT;\n dual = PRICE_DUAL_SITE_CLOUD_STORAGE_EXT;\n break;\n case 'PR_STR':\n price_pr_str = PRICE_PROJECT_STORAGE_EXT;\n break;\n case 'PR_CON':\n price_pr_con = PRICE_PROJECT_CONDO_EXT;\n break;\n case 'DESK':\n case 'RECUR_DESK':\n price_consult = PRICE_DESKTOP_SERVICES_EXT;\n break;\n case 'SYSTEMS':\n case 'RECUR_SYSTEMS':\n price_consult = PRICE_SYSTEMS_SERVICES_EXT;\n break;\n case 'STORAGE':\n case 'RECUR_STORAGE':\n price_consult = PRICE_STORAGE_SERVICES_EXT;\n break;\n case 'SITE':\n price_share = [PRICE_SHAREPOINT_SITES_EXT, PRICE_ADD_DA_STORAGE_EXT, PRICE_CONSULTATION_SUPPORT_EXT];\n break;\n case 'SUPPORT':\n case 'SYS_MAN':\n price_sys_man = PRICE_SYSTEM_MANAGEMENT_EXT;\n break;\n case 'COMMVAULT':\n price_comm = [PRICE_RAW_BACKUP_DATA_EXT, PRICE_FULL_BACKUP_EXT, PRICE_DIFFERENTIAL_INCREMENTAL_EXT];\n break;\n case 'RAW':\n case 'CL_COMPUTE':\n price = PRICE_CL_COMPUTE_EXT;\n break;\n }\n }\n switch (id) {\n case 'ST_VM':\n for (n=0, item_num=1; n < price_vm.length; n++, item_num++) {\n document.getElementById(\"st-vm-price\" + num + item_num).setAttribute(\"st-vm-price\" + num + item_num, parseFloat(price_vm[n]).toFixed(2));\n if (item_num!=6)document.getElementById(\"st-vm-qty\" + num + item_num).setAttribute(\"st-vm-price\" + num + item_num, parseFloat(price_vm[n]).toFixed(2));\n switch (n) {\n case 0:\n document.getElementById(\"st-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/CPU\";\n document.getElementById(\"st-vm-sub\" + num + item_num).value = \"$\" + parseFloat(price_vm[n]).toFixed(2);\n getEstimate('cpu', \"st-vm-qty\" + num + item_num, price_vm[n], \"st-vm-sub\" + num + item_num, num, 'ST_VM');\n break;\n case 1:\n document.getElementById(\"st-vm-qty\" + num + item_num).setAttribute(\"price\", parseFloat(price_vm[n]).toFixed(2));\n document.getElementById(\"st-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/CPU\";\n getEstimate('cpu', \"st-vm-qty\" + num + item_num, price_vm[n], \"st-vm-sub\" + num + item_num, num, 'ST_VM');\n break;\n case 2:\n document.getElementById(\"st-vm-qty\" + num + item_num).setAttribute(\"price\", parseFloat(price_vm[n]).toFixed(2));\n document.getElementById(\"st-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/GB\";\n getEstimate('mem', \"st-vm-qty\" + num + item_num, price_vm[n], \"st-vm-sub\" + num + item_num, num, 'ST_VM');\n break;\n case 3:\n document.getElementById(\"st-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/TB\";\n document.getElementById(\"st-vm-qty\" + num + item_num).setAttribute(\"price\",price_vm[n]);\n getEstimate('silver', \"st-vm-qty\" + num + item_num, price_vm[n], \"st-vm-sub\" + num + item_num, num, 'ST_VM');\n document.getElementById(\"units\" + num + item_num).setAttribute(\"value\", \"TB\");\n document.getElementById(\"GB\" + num + item_num).removeAttribute(\"selected\");\n document.getElementById(\"TB\" + num + item_num).setAttribute(\"selected\", \"selected\");\n break;\n case 4:\n document.getElementById(\"st-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/TB\";\n document.getElementById(\"st-vm-qty\" + num + item_num).setAttribute(\"price\",price_vm[n]);\n getEstimate('gold', \"st-vm-qty\" + num + item_num, price_vm[n], \"st-vm-sub\" + num + item_num, num, 'ST_VM');\n document.getElementById(\"units\" + num + item_num).setAttribute(\"value\", \"TB\");\n document.getElementById(\"GB\" + num + item_num).removeAttribute(\"selected\");\n document.getElementById(\"TB\" + num + item_num).setAttribute(\"selected\", \"selected\");\n break;\n case 5:\n document.getElementById(\"st-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2);\n if (document.getElementById(\"st-vm-qty\"+num+item_num).value == \"Yes\") extraSnaps(num, item_num, \"st-vm\");\n break;\n }\n }\n sub('vm-sub');\n break;\n case 'HS_VM':\n for (n=0, item_num=1; n < price_vm.length; n++, item_num++) {\n document.getElementById(\"hs-vm-price\" + num + item_num).setAttribute(\"hs-vm-price\"+item_num, parseFloat(price_vm[n]).toFixed(2));\n if (item_num!=5)document.getElementById(\"hs-vm-qty\" + num + item_num).setAttribute(\"hs-vm-price\" + num + item_num, parseFloat(price_vm[n]).toFixed(2));\n switch (n) {\n case 0:\n document.getElementById(\"hs-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/CPU\";\n document.getElementById(\"hs-vm-sub\" + num + item_num).value = \"$\" + parseFloat(price_vm[n]).toFixed(2);\n getEstimate('cpu', \"hs-vm-qty\" + num + item_num, price_vm[n], \"hs-vm-sub\" + num + item_num, num, 'HS_VM');\n break;\n case 1:\n document.getElementById(\"hs-vm-qty\" + num + item_num).setAttribute(\"cpu-price\", parseFloat(price_vm[n]).toFixed(2));\n document.getElementById(\"hs-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/CPU\";\n getEstimate('cpu', \"hs-vm-qty\" + num + item_num, price_vm[n], \"hs-vm-sub\" + num + item_num, num, 'HS_VM');\n break;\n case 2:\n document.getElementById(\"hs-vm-qty\" + num + item_num).setAttribute(\"mem-price\", parseFloat(price_vm[n]).toFixed(2));\n document.getElementById(\"hs-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/GB\";\n getEstimate('mem', \"hs-vm-qty\" + num + item_num, price_vm[n], \"hs-vm-sub\" + num + item_num, num, 'HS_VM');\n break;\n case 3:\n item_num--;\n break;\n case 4:\n document.getElementById(\"hs-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2) + \"/TB\";\n document.getElementById(\"hs-vm-qty\" + num + item_num).setAttribute(\"san-price\",price_vm[n]);\n getEstimate('gold', \"hs-vm-qty\" + num + item_num, price_vm[n], \"hs-vm-sub\" + num + item_num, num, 'HS_VM');\n document.getElementById(\"units\" + num + item_num).setAttribute(\"value\", \"TB\");\n document.getElementById(\"GB\" + num + item_num).removeAttribute(\"selected\");\n document.getElementById(\"TB\" + num + item_num).setAttribute(\"selected\", \"selected\");\n break;\n case 5:\n document.getElementById(\"hs-vm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_vm[n]).toFixed(2);\n if (document.getElementById(\"hs-vm\").value == \"Yes\") extraSnaps(num, item_num, \"hs-vm\");\n break;\n }\n }\n break;\n case 'CL_STR':\n item_num = 1;\n document.getElementById(\"str-price\" + num + item_num).value = parseFloat(price_cl_str).toFixed(2);\n document.getElementById(\"str-qty\" + num + item_num).setAttribute(\"str-price\", price_cl_str);\n document.getElementById(\"str-qty\" + num + item_num).setAttribute(\"price\",price_cl_str);\n document.getElementById(\"str-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_cl_str).toFixed(2) + \"/TB\";\n document.getElementById(\"units\" + num + item_num).setAttribute(\"value\", \"TB\");\n document.getElementById(\"GB\" + num + item_num).removeAttribute(\"selected\");\n document.getElementById(\"TB\" + num + item_num).setAttribute(\"selected\", \"selected\");\n document.getElementById(\"dualoptions\" + num).setAttribute(\"original\", original);\n document.getElementById(\"dualoptions\" + num).setAttribute(\"double\", dual);\n document.getElementById(\"onchange\", \"changePrice(num, document.getElementById('dualoptions' + num).getAttribute('original'), document.getElementById('dualoptions' + num).getAttribute('double'))\");\n if (document.getElementById(\"dualoptions\" + num).value == \"Yes\") changePrice(num, document.getElementById('dualoptions' + num).getAttribute('original'), document.getElementById('dualoptions' + num).getAttribute('double'));\n getEstimate(\"str\", \"str-qty\" + num + item_num, document.getElementById(\"str-price\" + num + item_num).value, \"str-sub\" + num + item_num, num, \"CL_STR\");\n break;\n case 'PR_STR':\n item_num = 1;\n document.getElementById(\"str-price\" + num + item_num).value = parseFloat(price_pr_str).toFixed(2);\n document.getElementById(\"str-qty\" + num + item_num).setAttribute(\"str-price\", price_pr_str);\n document.getElementById(\"str-qty\" + num + item_num).setAttribute(\"price\",price_pr_str);\n document.getElementById(\"str-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_pr_str).toFixed(2) + \"/TB\";\n document.getElementById(\"units\" + num + item_num).setAttribute(\"value\", \"TB\");\n document.getElementById(\"GB\" + num + item_num).removeAttribute(\"selected\");\n document.getElementById(\"TB\" + num + item_num).setAttribute(\"selected\", \"selected\");\n getEstimate('pr-str', 'str-qty' + num + item_num, price_pr_str, 'str-sub' + num + item_num, num, 'CL_STR');\n break;\n case 'PR_CON':\n item_num = 1;\n document.getElementById(\"str-price\" + num + item_num).value = parseFloat(price_pr_con).toFixed(2);\n document.getElementById(\"str-qty\" + num + item_num).setAttribute(\"str-price\", price_pr_con);\n document.getElementById(\"str-qty\" + num + item_num).setAttribute(\"price\",price_pr_con);\n document.getElementById(\"str-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_pr_con).toFixed(2) + \"/unit\";\n getEstimate('pr-str', 'str-qty' + num + item_num, price_pr_con, 'str-sub' + num + item_num, num, 'CL_STR');\n break;\n case 'DESK':\n case 'SYSTEMS':\n case 'STORAGE':\n case 'RECUR_DESK':\n case 'RECUR_SYSTEMS':\n case 'RECUR_STORAGE':\n item_num = 1;\n document.getElementById(\"consult-price\" + num + item_num).value = parseFloat(price_consult).toFixed(2);\n document.getElementById(\"consult-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_consult).toFixed(2) + \"/hr\";\n document.getElementById(\"consult-qty\" + num + item_num).setAttribute(\"price\", price_consult);\n getEstimate('consult', \"consult-qty\" + num + item_num, price_consult, \"consult-sub\" + num + item_num, num, 'DESK');\n break;\n case 'SITE':\n for (item_num = 1, n = 0; item_num < 3; n++, item_num++) {\n document.getElementById(\"share-price\" + num + item_num).value = parseFloat(price_share[n]).toFixed(2);\n if (i<2)document.getElementById(\"share-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_share[n]).toFixed(2) + \"/month\";\n else document.getElementById(\"share-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_share[n]).toFixed(2);\n document.getElementById(\"share-qty\" + num + item_num).setAttribute(\"share_price\", price_share[n]);\n switch (item_num) {\n case (1):\n getEstimate('sp', \"share-qty\" + num + item_num, price_share[n], \"share-sub\" + num + item_num, num, 'SITE');\n break;\n case (2):\n getEstimate('additional-sp', \"share-qty\" + num + item_num, price_share[n], \"share-sub\" + num + item_num, num, 'SITE');\n break;\n case(3):\n getEstimate('sp-consult', \"share-qty\" + num + item_num, price_share[n], \"share-sub\" + num + item_num, num, 'SITE');\n break;\n }\n }\n break;\n case 'SUPPORT':\n case 'SYS_MAN':\n // set up loop to go through each line item\n for (i = 0, item_num = 1; item_num < 8; item_num++, i++){\n document.getElementById(\"pa-price\" + num + item_num).value = \"$\" + parseFloat(price_sys_man[i]).toFixed(2);\n document.getElementById(\"pa-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_sys_man[i]).toFixed(2);\n document.getElementById(\"pa-qty\" + num + item_num).setAttribute(\"price\", price_sys_man[i]);\n getEstimate('pa-sub', \"pa-qty\" + num + item_num, price_sys_man[i], \"pa-sub\" + num + item_num, num, 'SYS_MAN');\n }\n break;\n case 'COMMVAULT':\n for (i = 0, item_num = 1; item_num < 4; item_num++, i++){\n document.getElementById(\"comm-price\" + num + item_num).setAttribute(\"value\", price_comm[i]);\n document.getElementById(\"comm-price\" + num + item_num).innerHTML = \"$\" + parseFloat(price_comm[i]).toFixed(2) + '/TB';\n document.getElementById(\"comm-qty\" + num + item_num).setAttribute(\"comm-price\", price_comm[i]);\n }\n if(toggle == true) {\n\n if (document.getElementById(\"raw-units\" + num + \"1\").getAttribute(\"value\") == 'TB') {\n currentprice = price_comm[0];\n currentprice *= 1000;\n document.getElementById(\"comm-qty\" + num + \"1\").setAttribute(\"comm-price\", currentprice);\n } else {\n currentprice = price_comm[0];\n currentprice /= 1000;\n document.getElementById(\"comm-qty\" + num + \"1\").setAttribute(\"comm-price\", currentprice);\n }\n }\n var element = document.getElementById(\"comm-qty\" + num + \"1\")\n getEstimate('raw', \"comm-qty\" + num + \"1\", element.getAttribute(\"comm-price\"), \"comm-sub\" + num + \"1\", num, 'RAW');\n break;\n case 'RAW':\n case 'CL_COMPUTE':\n for (n=0, item_num=1; n < price.length; n++, item_num++) {\n if (n<10){\n document.getElementById(\"cl-compute-price\" + num + item_num).innerHTML = \"$\" + price[n] + \"/hr/instance\";\n }\n else {\n document.getElementById(\"cl-compute-price\" + num + item_num).innerHTML = \"$\" + price[n] + \"/GB/instance\";\n }\n document.getElementById(\"cl-compute-instances\" + num + item_num).setAttribute(\"cl-compute-price\", price[n]);\n document.getElementById(\"cl-compute-hours\" + num + item_num).setAttribute(\"cl-compute-price\", price[n]);\n getEstimate('cl-compute', 'cl-compute-hours' + num + item_num, price[n], document.getElementById(\"cl-compute-hours\" + num + item_num).getAttribute('dest'), item_num,'CL_COMPUTE');\n }\n break;\n\n }\n document.getElementById(\"affiliation\" + num).setAttribute(\"value\", affiliation);\n}",
"function changePriceInProduct() {\n productList.forEach(pr => {\n if (valuta === 'eur') {\n pr.price = (pr.price / EUR_RSD).toFixed(2);\n } else {\n pr.price = (pr.price * EUR_RSD).toFixed(0);\n }\n });\n updatePricesTextOnCurrencyChange();\n}",
"function updateProductBySKU(sku,newProduct){\n for (var i = 0; i < products.length; i++) {\n if (products[i].SKU.toUpperCase() == sku.toUpperCase()){\n products[i].QTY=newProduct.QTY;\n }\n }\n}",
"function setProd(prod){\n\t\t\t\t\n\t\t\t\tvar prodId = parseInt(prod.value);\n\t\t\t\tvar productName = prodList[prodId];\n\t\t var productPrice = prodPrice[prodId];\n\t\t\t\t\n\t\t\t\tprodQty[prodId] += 1;\n\t\t\t\t\n\t\t\t\tvar tempQty = prodQty[prodId];\n\t\t\t\tvar eleQtyName = \"qty_\"+prodId;\n\t\t\t\t_(eleQtyName).innerHTML = tempQty;\n\t\t\t\tvar total = calculateCost(productPrice,tempQty);\n\t\t\t\t\n\t\t\t//\ttotalAmt +=parseFloat(total);\n\t\t\t\tvar eleCostName = \"cost_\"+prodId;\n\t\t\t\t_(eleCostName).innerHTML = \"$ \"+total;\n\t\t}",
"set_plant_distribution(store, sell) { // producing over market demand\n this.store = store;\n this.sell = sell;\n }",
"function setProductPerVersion(product) {\r\n\tlogger.entry(\"setProductPerVersion\", product);\r\n\r\n\tproductPerVersion = product;\r\n\r\n\tlogger.exit(\"setProductPerVersion\");\r\n}",
"function change_product_supplier_settings(product_id)\n{\n\t//get information from checkmark and supplier id and premium values from HTML\n\t$.each(suppliers_list, function (supplier_id, supplier_details)\n\t{\n\t\tvar supplier_checkbox = \"supsettings_\"+supplier_id+\"_\"+product_id;\n\t\tvar premium_input_name = \"supsetting_premium_\"+supplier_id+\"_\"+product_id;\n\t\tif ($(\"#\"+supplier_checkbox).prop(\"checked\"))\n\t\t{\n\t\t\torder_list[product_id].supplier_settings[supplier_id].name = suppliers_list[supplier_id].name;\n\t\t\torder_list[product_id].supplier_settings[supplier_id].premium = $(\"#\"+premium_input_name).val();\n\t\t}\n\t});\t\n}",
"function updateProductQuantitiesOnInvoice(){\n const { faste, wifi } = readUserSelectedQuantities();\n $$.invoice.products.faste.quantity.text(faste);\n $$.invoice.products.wifi.quantity.text(wifi);\n }",
"function updateProductId() {\n productId4 = 12;\n}",
"function switch_recommended_products() {\n if (is_using_setA == true) {\n recommended_index_array_setB.forEach(insert_recommended_product);\n } else {\n recommended_index_array_setA.forEach(insert_recommended_product);\n }\n is_using_setA = !is_using_setA;\n}",
"function updateProduct(quantity) {\n}",
"changeProduct(v){\r\n\t\tvar rowObj = v, unitPrice = 0;\t\t\r\n\t\tlet vv = +rowObj['options'][v['selectedIndex']].value; //the ProductID value in the products array.\r\n\t\t\t\t\r\n\t\t//Find the original 'UnitPrice' from the products table of the product item the user selected from the dropdown list.\r\n\t\t//and set that unit price in the 'Unit Price' cell of the row that the user is on. Comma format it.\r\n\t\tfor(let i = 0; i < this.ProductsData['products'].length; i += 1){\r\n\t\t\tlet pId = +this.ProductsData['products'][i]['ProductID'];\r\n\t\t\tif( pId == vv ){\r\n\t\t\t\tunitPrice = +this.ParseFloat(''+this.ProductsData['products'][i]['UnitPrice']);\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\trowObj = document.getElementById(v['id']);\t\t\r\n\t\trowObj['cells'][1]['children'][0]['value'] = this.commaFormatted(''+ (unitPrice).toFixed(2));\r\n\t\t\r\n\t\treturn this.updateTotals();\t\t\r\n\t}",
"function qty_change_input_product(e) {\n\t\tsumtotal = 0;\n\t\ttotal_product(e, type);\n\t\tsumtotal += sumtotal_product(e);\n\t\t$('.price_all_product').text('IDR '+number_format(sumtotal))\n\t\te.attr('data-oldValue', e.val());\n\t}",
"function changeProduct(){\r\n\r\n toolbox.product_selected = true;\r\n \t\r\n\t\t$('#pi_product_name').html(\r\n\t\t\ttoolbox.selected_client_name + ' - ' +\r\n\t\t\ttoolbox.selected_manufacturer_name + ' - ' +\r\n\t\t\ttoolbox.selected_product_name\r\n\t\t);\r\n\r\n\t\tif (toolbox.selected_language_id) {\r\n \t\tloadProductImages();\r\n \t}\r\n \t\r\n }",
"updatePerishableProducts()\n {\n this.items = this.items.filter(\n function (product) {\n if (typeof product === \"undefined\") {\n return false;\n }\n\n const initPerishable = GAME.model.base.products\n .filter((prod) => prod.name == product.name)\n .shift().values.perishable - 1;\n\n product.values.perishable = product.values.perishable - 1;\n product.values.percentage = 100 * product.values.perishable / initPerishable;\n\n // empty container does not have defined products. Else: product needs to be perishable,\n // and needs to have perished.\n return !(product.values.isPerishable && product.values.perishable <= 0)\n }\n );\n }",
"function _setfenixvariant(){\n let productvars = JSON.parse(fenixcommerceGlobal.variations);\n let currentvariant = jQuery(\"input[name='variant_id']\").val(); \n jQuery.each(productvars, function( index, value ) {\n if( currentvariant == value.variant_id ){\n fenixcommerceGlobal.pdpsku = value.sku;\n }\n });\n}",
"function updateVariantPrice(product) {\n let variant = product.selectedVariant;\n\n $(`#product-${product.id} .product-price`).text('$' + variant.price);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mediator es una clase generica que puede ser utilizada para interactuar con servicios de datos de manera asincrona | function Mediator()
{
// Super
psd.framework.EventDispatcher.call(this);
// Id de la peticion actual
var _id = "0";
// Url de la peticion actual
var _url = "";
// Parser de la peticion actual
var _parser = null;
//Indica si se utilizará XDomainRequest en navegadores Explorer <= 9 para la carga Ajaz con CORS
//Por defecto está inhabilidado debido a los problemas que ocasiona esta clase
var _corsIE = false;
// Tipo de respuesta de la peticion actual
var _type = Mediator.RESPONSE_XML;
// Referencia dinamica a la instancia para no perder el contexto dentro
// de las respuestas asincronas del XMLHttpRequest
var _mediatorInstance = this;
//Nombre de la función que se llama en JSONP
var _customJSONPCallback = null;
//Parámetro que se pasará a la url para solicitar JSONP
var _customCallbackParam = null;
var _deferredJSONP = (function(mediator) {return function(data) {_jsonp.apply(mediator,[data]);}})(this);
var _jsonp = function(responseData)
{
var parserResult = responseData,
mediatorResult = new psd.framework.MediatorResult( psd.framework.MediatorResult.MEDIATOR_SUCCESS_CODE
, psd.framework.MediatorResult.MEDIATOR_SUCCESS
, parserResult );
_mediatorInstance.dispatchEvent(new psd.framework.MediatorEvent(psd.framework.MediatorEvent.MEDIATE_COMPLETE, _id, mediatorResult));
};
this.corsIE = function(value){
if(value && value!=_corsIE) {_corsIE = value;}
return _corsIE;
};
this.setCustomCallback = function(customCallback){
_customJSONPCallback = customCallback;
};
/**
* Inicia la mediacion solicitada
* @param url La url de los datos
* @param parser El parser que se utiliza para analizar la respuesta
* @param type El tipo de respuesta (TEXT, XML, JSON)
*/
this.mediate = function(url, parser, type)
{
var xmlhttp, script,src, separator
responseData = "",
mediationID = Mediator.getNextKey();
_id = "mediate_" + mediationID;
_url = url;
_parser = parser;
if (type && (type == Mediator.RESPONSE_TEXT ||
type == Mediator.RESPONSE_XML ||
type == Mediator.RESPONSE_JSON ||
type == Mediator.RESPONSE_JSONP))
{
_type = type;
}
if(_type == Mediator.RESPONSE_JSONP)
{
script = document.createElement('script');
script.setAttribute("type", "text/javascript");
if (_customJSONPCallback){
script.setAttribute("src", url);
window[_customJSONPCallback] = _deferredJSONP;
}else{
separator = (url.indexOf("?")>-1)? "&":"?";
script.setAttribute("src", url + separator + "jsonp=psd.framework.mediator.jsonp." + _id);
psd.framework.mediator.jsonp[_id] = _deferredJSONP;
}
document.getElementsByTagName("head")[0].appendChild(script);
} else {
if ((window.XDomainRequest) && _corsIE){ //IE 8, modo no estándar de realizar peticiones Ajax que soporten CORS
xmlhttp = new XDomainRequest();
xmlhttp.onerror = function(){
mediatorResult = new psd.framework.MediatorResult( psd.framework.MediatorResult.MEDIATOR_ERROR_CODE
, psd.framework.MediatorResult.MEDIATOR_ERROR
, null
);
_mediatorInstance.dispatchEvent(new psd.framework.MediatorEvent(psd.framework.MediatorEvent.MEDIATE_ERROR
, _id
, mediatorResult));
};
xmlhttp.onload = function(){
//creación del xml a partir del string
switch (_type) {
case Mediator.RESPONSE_TEXT:
responseData = xmlhttp.responseText;
break;
case Mediator.RESPONSE_XML:
responseData = new ActiveXObject('Microsoft.XMLDOM');
responseData.async='false';
responseData.loadXML(xmlhttp.responseText);
break;
case Mediator.RESPONSE_JSON:
responseData = xmlhttp.responseText;
break;
}
var parserResult = _parser.parse(responseData);
mediatorResult = new psd.framework.MediatorResult( psd.framework.MediatorResult.MEDIATOR_SUCCESS_CODE
, psd.framework.MediatorResult.MEDIATOR_SUCCESS
, parserResult
);
_mediatorInstance.dispatchEvent(new psd.framework.MediatorEvent(psd.framework.MediatorEvent.MEDIATE_COMPLETE
, _id
, mediatorResult));
}
}else{
// Code for Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else { // code IE6 (no soporta CORS)
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
switch (xmlhttp.readyState) {
case Mediator._STATE_REQUEST_NOT_INITIALIZED_CODE:
break;
case Mediator._STATE_SERVER_CONECTION_STABLISHED_CODE:
break;
case Mediator._STATE_REQUEST_RECEIVED_CODE:
break;
case Mediator._STATE_REQUEST_PROCESSING_CODE:
break;
case Mediator._STATE_REQUEST_FINISHED_CODE:
var mediatorResult;
if (xmlhttp.status == Mediator._REQUEST_OK_CODE) {
switch (_type) {
case Mediator.RESPONSE_TEXT:
responseData = xmlhttp.responseText;
break;
case Mediator.RESPONSE_XML:
responseData = xmlhttp.responseXML;
break;
case Mediator.RESPONSE_JSON:
responseData = xmlhttp.responseText;
break;
}
var parserResult = _parser.parse(responseData);
mediatorResult = new psd.framework.MediatorResult( psd.framework.MediatorResult.MEDIATOR_SUCCESS_CODE
, psd.framework.MediatorResult.MEDIATOR_SUCCESS
, parserResult
);
_mediatorInstance.dispatchEvent(new psd.framework.MediatorEvent(psd.framework.MediatorEvent.MEDIATE_COMPLETE
, _id
, mediatorResult));
}
else {
mediatorResult = new psd.framework.MediatorResult( psd.framework.MediatorResult.MEDIATOR_ERROR_CODE
, psd.framework.MediatorResult.MEDIATOR_ERROR
, null
);
_mediatorInstance.dispatchEvent(new psd.framework.MediatorEvent(psd.framework.MediatorEvent.MEDIATE_ERROR
, _id
, mediatorResult));
}
break;
};
};
};
xmlhttp.open(Mediator.REQUEST_GET, _url, true);
xmlhttp.send();
}
};
return _id;
} | [
"function Mediator() {\n\n \tthis._events = {};\n\n }",
"function Mediator() {\n this.events = {};\n}",
"function serviceActuators(method, query, data, resp) {\n\twriteHeaders(resp);\n\t\n\t// Parse the json DATA request\n\trequest = JSON.parse(data);\n\tif(!request) {\n\t\terror(0, resp);\n\t\treturn;\n\t}\n\t\n\t// Get the response from the modeladmin layer :\n\tmodeladmin.setActuator(request, function(response) {\n\t\t// Send the stringified json to client :\n\t\tvar strResponse = JSON.stringify(response);\n\t\tresp.end(strResponse);\n\t});\n}",
"getMediatorName() {\n return this.mediatorName;\n }",
"function MediatorEvent(type, id, mediatorResult) \n {\n // Super\n psd.framework.Event.call(this, type);\n\n this.id = id;\n this.result = mediatorResult;\n }",
"mock() {\n this.mediator.mock();\n }",
"retrieveMediator(mediatorName) {\n return this.view.retrieveMediator(mediatorName);\n }",
"_add(mediator) {\n this.memory.set(mediator._id, mediator);\n this.items.push(mediator._id);\n this.emit('add', mediator);\n }",
"call(someData, to) {\n this.mediator.send(someData, this, to);\n }",
"registerMediator(mediator) {\n if (this.view != null) {\n this.view.registerMediator(mediator);\n }\n }",
"function serviceBondsActuators(method, query, data, resp) {\n\twriteHeaders(resp);\n\n\t// Parse the json DATA request\n\trequest = JSON.parse(data);\n\tif(!request) {\n\t\terror(0, resp);\n\t\treturn;\n\t}\n\t\n\tmodelbondsActuators.getBondsActuators(request, function(result) {\n\t\t\tvar strResult = JSON.stringify(result);\n\t\t\tresp.end(strResult);\n\t});\n}",
"function init() {\n _subMediator();\n }",
"function mockSyncDataservice() {\n return {getCustomers: mockData.getMockCustomers};\n }",
"function DataEmitter() {\n}",
"function AbstractMediatorTemplate() {\n if (!(this instanceof AbstractMediatorTemplate)) {\n console.log(\"WARNING: AbstractMediatorTemplate created without New operator\");\n return new AbstractMediatorTemplate();\n }\n \n /**\n * Andmete töötlejad registreeritakse sellesse massiivi, näiteks:\n * ```mediator['processors'].push(proc1);```\n * \n * @property {Array} processors\n */\n this.processors = [];\n this.id = null;\n this.name = null;\n this.abbr = null;\n this.data = {};\n this.details = {};\n}",
"function mockSyncDataservice() {\n return {getAvengers: mockData.getMockAvengers};\n }",
"onPedidoPagado() {\n return new rxjs_internal_Observable__WEBPACK_IMPORTED_MODULE_7__.Observable(observer => {\n this.socket.on('pedido-pagado-cliente', res => {\n observer.next(res);\n });\n });\n }",
"function serviceMurs(method, query, data, resp) {\n\twriteHeaders(resp);\n\n\t// Parse the json DATA request\n\trequest = JSON.parse(data);\n\tif(!request) {\n\t\terror(0, resp);\n\t\treturn;\n\t}\t\n\t\n\tmodelmurs.getMurs(request, function(result) {\n\t\t\tvar strResult = JSON.stringify(result);\n\t\t\tresp.end(strResult);\n\t});\n}",
"function MediatorResult(code, msg, parserResult) \n {\n this.code = code;\n this.msg = msg;\n this.parserResult = parserResult;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert array to Map using number indexes as keys | function arrayToMap (arr) {
const result = new Map()
arr.forEach((value, index) => result.set(index, value))
return result
} | [
"function arrayToIndexMap (arr) {\n const result = new Map()\n arr.forEach((value, index) => result.set(value, index))\n return result\n}",
"function indexMap (arr){\n var newArray = arr.map(function(val, idx){\n return val * idx\n })\n return newArray\n}",
"mapArray(array = [], key) {\n const map = {}\n array.forEach((item, index) => {\n map[item[key]] = item\n })\n return map\n }",
"static mapCnlNums(cnlNums) {\n let map = new Map();\n\n if (Array.isArray(cnlNums)) {\n let idx = 0;\n\n for (let cnlNum of cnlNums) {\n map.set(cnlNum, idx);\n idx++;\n }\n }\n\n return map;\n }",
"function indexMap (arr) {\n\n var indexArr = [];\n\n for(var i = 0; i < arr.length; i++) {\n indexArr.push(arr[i] * arr.indexOf(arr[i]))\n }\n\n return indexArr;\n\n}",
"function get_map(arr){\t\t\t\t\t\t\t\t\r\n\tlet map = new Map();\r\n\tvar thisKey;\r\n\tfor (var i=0;i< arr.length;i++){\r\n\t\tvar thisKey = \"\";\r\n\t\tvar thisArrLength = arr[i].length;\r\n\t\tfor (var j = 0; j< thisArrLength - 1; j++)\r\n\t\tthisKey += arr[i][j];\t\t\t\t\t\t// map key is the combination of element of array 'values', except the last element\r\n\t\tmap.set(thisKey, arr[i][thisArrLength - 1]); // map value is the last element of array 'values'\r\n\t}\r\n\treturn map;\r\n}",
"function makeMap (array, key, val) {\n const r = {}\n array.forEach(item => {\n r[item[key]] = item[val]\n })\n return r\n}",
"function createKeyToIndexMap(items, start, end) {\n const map = new Map();\n for (let i = start; i <= end; i++) {\n const item = items[i];\n if (item !== null) {\n map.set(item.key, i);\n }\n }\n return map;\n}",
"__arr_to_obj(arr) {\n let arr_map = {}\n arr.forEach((ele, i) => {\n arr_map[ele] = i\n })\n return arr_map\n }",
"function h$decodeMapping(arr) {\n var r = [];\n for(var i=0;i<arr.length;i+=2) {\n var from = arr[i];\n var to = arr[i+1];\n r[from] = to;\n }\n return r;\n}",
"function arrToMap(arr){\n\t\tvar ret = {};\n\t\tfor(i in arr){\n\t\t\tret[arr[i]]=true;\n\t\t}\n\t\treturn ret;\n\t}",
"function arrayToObject(arr, keyfn) {\n var map = {};\n arr.forEach(function (o) {\n var key = keyfn(o);\n map[key] = o;\n });\n return map;\n }",
"static asMap(...keyValues) {\n\t\tkeyValues = ArrayUtils.checkArray(keyValues);\n\t\tconst map = new Map();\n\t\tfor (let i = 0; i < keyValues.length; i += 2) {\n\t\t\tmap.put(keyValues[i], keyValues[i + 1]);\n\t\t}\n\t\treturn map;\n\t}",
"function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index};}",
"function createFrequencyCounter(array) {\n let freqs = new Map();\n \n for (let val of array) {\n let valCount = freqs.get(val) || 0;\n freqs.set(val, valCount + 1);\n }\n \n return freqs;\n }",
"function buildMapIndex() {\n // mapIndex[typename] will be [[x,y],[x,y],...]\n var mapIndex = {};\n\n for (var y = 0; y < map.length; y++) {\n for (var x = 0; x < map[y].length; x++) {\n var typeName = tileTypes[map[y][x].type][0];\n if (!mapIndex[typeName]) { mapIndex[typeName] = []; }\n mapIndex[typeName].push([x, y]);\n }\n }\n\n return mapIndex;\n}",
"function generateIndexMap(allUniqueColIndex, startDim, dimNum)\r\n {\r\n var map = {};\r\n for(var i = 0; i < allUniqueColIndex.length; ++i)\r\n {\r\n map[buildOneHeader(allUniqueColIndex[i], startDim, dimNum)] = i;\r\n }\r\n return map;\r\n }",
"function getFrequencyDict(arr) {\r\n var dictionary = {};\r\n arr.forEach((item) => {\r\n if (dictionary[item] === undefined) {\r\n dictionary[item] = 1;\r\n } else {\r\n dictionary[item] = dictionary[item] + 1;\r\n }\r\n });\r\n\r\n return dictionary;\r\n}",
"function aggregate(array) {\n const aggregationMap = new Map();\n array.forEach(([item, key]) => {\n const existingItems = aggregationMap.get(key) || [];\n existingItems.push(item);\n\n if (!aggregationMap.has(key)) {\n aggregationMap.set(key, existingItems);\n }\n });\n return aggregationMap;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efetua a alteracao do gerente da unidade | function alterarGerenteUnidade(){
var tecnico = DWRUtil.getValue("comboTecnicoHelpDesk");
var unidade = DWRUtil.getValue("comboUnidade");
if((tecnico==null ||tecnico=='')){
alert("Selecione um tecnico do HelpDesk para alterar o gerente.");
}else{
if (confirm("Você tem certeza que deseja alterar o gerente da unidade?")) {
FacadeAjax.setarGerente(unidade, tecnico);
}
}
mostrarGerenteUnidade();
} | [
"function alterarTipoGerencia(){\n\tvar unidade = DWRUtil.getValue(\"comboUnidade\"); \n\tvar tipoGerencia = DWRUtil.getValue(\"comboGerencia\"); \n\tFacadeAjax.alterarGerencia(unidade,tipoGerencia);\n}",
"function mostrarGerenteUnidade(){\n\tvar unidade = DWRUtil.getValue(\"comboUnidade\"); \n\tFacadeAjax.getGerenteUnidade(unidade, function(tecnico){\n\t\t\tDWRUtil.setValue(\"nomeGerenteUnidade\",tecnico.nome);\n\t});\n}",
"function AtualizaGeral() {\n // Apenas le as gEntradas para a estrutura de gEntradas.\n LeEntradas();\n // converte a estrutura de gEntradas para a de personagem.\n ConverteEntradasParaPersonagem();\n PersonagemLimpaPericias();\n DependenciasGerais();\n _AtualizaGeral();\n gEstado.Salva(JSON.stringify(gEntradas));\n}",
"function ChangeEscolaProibida(chave_classe, indice, dom) {\n AtualizaGeral();\n}",
"UPDATE_UNIDADES (state, unidad) {\n // Actualiza la data del array 'Unidades' en base al trabajador\n for (var i = 0; i < state.unidades.length; i++) {\n // console.log('Contador:' + i)\n if (state.unidades[i].idUnidad === unidad.idUnidad) {\n state.unidades.splice(i, 1, unidad)\n break\n }\n }\n }",
"function cadastrarUmaUnidade(){\n\tvar unidadeSelecionadaBDTRE = DWRUtil.getValue(\"comboUnidadeTRE\"); \n\tif(unidadeSelecionadaBDTRE==null || unidadeSelecionadaBDTRE==''){\n\t\talert(\"Selecione uma unidade a ser cadastrada.\");\n\t}else{\n\t\tvar loginGerente = DWRUtil.getValue(\"loginGerenteUnidade\");\n\t\tvar matriculaGerente = DWRUtil.getValue(\"matriculaGerente\"); \n\t\tFacadeAjax.cadastrarUnidadeSuporte(unidadeSelecionadaBDTRE,loginGerente,matriculaGerente);\n\t\tcarregarCamposUnidades();\n\t}\n}",
"function carregaOpcoesUnidadeSuporte(){\n\tcarregaTipoGerencia();\t\n\tcarregaTecnicos();\n\tcarregaUnidadesSolicitantes();\t\n\tcarregaEdicaoTipos();//no arquivo tipoSubtipo.js\n\tcarregaComboTipo();//no arquivo tipoSubtipo.js\n}",
"updateMinerWithUnspentChange(minerId){\n //Assignining Unspent Change to the Miner\n this.on(UNSPENT_CHANGE, (o) =>{\n if(this.utxo[minerId]){\n this.utxo[minerId] += o;\n return;\n }\n });\n }",
"createUnidad ({\n commit\n }, unidad) {\n ApiService.postUnidad(unidad).then((response) => {\n unidad.idUnidad = response.data.idUnidad // retorna el nuevo identificador creado por el servidor\n\n commit('ADD_UNIDAD', unidad)\n }).catch(error => {\n console.log('ERROR:', error.message)\n })\n }",
"async restaruarDireccionEntrega() {\n addStep('Vuelve a editar a la direccion original');\n await super.clickearElemento(await this.botonUpdate);\n await super.clickearElemento(this.address); \n await super.vaciarCampoYEnviarTexto(await this.address, datos.direccion);\n await super.clickearElemento(this.botonSave);\n }",
"updateUidIfAlguienAbandona(){\n\t\tthis.Uids--;\n\t\tif(this.Uids < 0)\n\t\t\tthis.Uids = 0; //evitar -1 si owner quita\n\n\t\tthis.usuarios.forEach((usuario,index) => usuario.setId(index));\n\t}",
"function realizarTransfencia() {\n\n}",
"function alterarAgendamento() {\n //fecha modal visualizar\n $uibModalInstance.close();\n\n //abre modal alterar evento\n vm.alterarEvento(vm.agendamento.idAgendamento);\n }",
"function dibujarRecorrido(datos_unidad){\n vectorSourceDibujo.clear();\n agregarRecorridos(datos_unidad, vectorSourceDibujo);\n agregarIniFinRecorrido(datos_unidad, vectorSourceDibujo);\n }",
"alterRenteninfo (person) {\n const geburtsjahr = person.geburtstag.getFullYear()\n return person.jahrRenteninfo - 1 - geburtsjahr\n }",
"function Unidade() {\n\tthis.unidades = {}\n}",
"function _AtualizaImunidades() {\n var dom_imunidades = Dom('imunidades');\n RemoveFilhos(dom_imunidades);\n gPersonagem.imunidades.forEach(function(imunidade) {\n AdicionaImunidade(imunidade, dom_imunidades);\n });\n}",
"function modificaRiga() {\r\n }",
"passendeUtstyr() {\n // Bruker typen til å hente ut utstyrstypene som passer med sykkeltypen\n s_restriksjon.HentPassendeUtstyr(this.type, minusUtstyr => {\n this.minusUtstyr = minusUtstyr;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
RETURN CURRENT CENTER COORDINATES amSetCenterCoords(map_id, long, lat, zoom) This function is called by the chart when you request this information by calling getCenterCoords() function | function amSetCenterCoords(map_id, long, lat, zoom) {
Ammap.publish('amsetcentercoords', map_id, long, lat, zoom);
} | [
"mapCenter(lat, lng){\n this.map.setCenter({lat: lat, lng: lng});\n }",
"function getMapCenter() {\n \n var mapCenterCoords = [30, 0];\n\n return mapCenterCoords;\n \n}",
"function calculateCenter() {\n center = map.getCenter();\n }",
"function calculateCenter(){\n center = map.getCenter();\n }",
"centerMap() {\n map.setCenter([31.900092, 27.318739])\n map.setZoom(4.5)\n }",
"function setCenter() {\n\t\t// Google.v3 uses EPSG:900913 as projection, so we have to\n\t\t// transform our coordinates\n\t\tmap.setCenter( getTransform(longitude, latitude), zoomLevel);\t\t\n\t\treturn;\n\t}",
"function getCenter(){\n var center = my.map.getCenter();\n return [center.lng, center.lat];\n }",
"function calculateCenter(){\n center = map.getCenter();\n}",
"function centerMap() {\n \tmap.setCenter({\n \t\tlat: lat,\n \t\tlng: lng\n \t});\n \tmap.setZoom(17);\n }",
"function centerMap() {\r\n\t\tvar sets = $['mapsettings'];\r\n\t\tvar $this = sets.element;\r\n\t\tvar location = new Point(($this.innerWidth()/2)-(sets.resolutions[sets.zoom-1].width/2),($this.innerHeight()/2)-(sets.resolutions[sets.zoom-1].height/2));\r\n\t\tsetInnerDimentions(location);\r\n\t}",
"function centerMap() {\n getLocation()\n }",
"function _map_setCenterAndZoom(map,center,nZoom){\r\n\tif (map){\r\n\t\tmap.setCenter(center,nZoom);\r\n\t}\r\n}",
"onCenterChanged() {\n const lat = this.state.mapRef.getCenter().lat();\n const lng = this.state.mapRef.getCenter().lng();\n const zoom = this.state.mapRef.getZoom();\n this.props.updateMapCenter({\n lat,\n lng,\n zoom,\n fetch: this.props.shouldFetch,\n });\n }",
"function centreMap(lat, lng) {\n myMap.setView([lat, lng], 16);\n}",
"function centerMap(map) {\n // Create map boundaries from all map markers.\n var bounds = new google.maps.LatLngBounds();\n map.markers.forEach(function (marker) {\n bounds.extend({\n lat: marker.position.lat(),\n lng: marker.position.lng()\n });\n }); // Case: Single marker.\n\n if (map.markers.length == 1) {\n map.setCenter(bounds.getCenter()); // Case: Multiple markers.\n } else {\n map.fitBounds(bounds);\n }\n } // Render maps on page load.",
"function center_map(map) {\n\n\t\t// vars\n\t\tvar bounds = new google.maps.LatLngBounds();\n\n\t\t// loop through all markers and create bounds\n\t\t$.each(map.markers, function (i, marker) {\n\n\t\t\tvar latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());\n\n\t\t\tbounds.extend(latlng);\n\n\t\t});\n\n\t\t// only 1 marker?\n\t\tif (map.markers.length == 1) {\n\t\t\t// set center of map\n\t\t\tmap.setCenter(bounds.getCenter());\n\t\t\tmap.setZoom(16);\n\t\t} else {\n\t\t\t// fit to bounds\n\t\t\tmap.fitBounds(bounds);\n\t\t}\n\n\t}",
"function centerMap(){\n\tvar point = map.getCenter();\n\n\t$('#aside__detail').hide();\n\teasingAnimator.easeProp({\n\t\tlat: point.lat(),\n\t\tlng: point.lng()\n\t}, center);\n\tmap.setZoom(NORMAL_ZOOM_DISTANCE);\n}",
"function centerMap() {\n\tvar point = map.getCenter();\n\n\t$('#aside__detail').hide();\n\teasingAnimator.easeProp({\n\t\tlat: point.lat(),\n\t\tlng: point.lng()\n\t}, center);\n\tmap.setZoom(NORMAL_ZOOM_DISTANCE);\n}",
"centerMap() {\n if(map) {\n map.setCenter({lat: 27.318739, lng: 31.900092})\n map.setZoom(4.5)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fires when a pokemon is clicked, grabs info about it and populates info box with info about the pokemon by calling the relevant function | function onPokeClick(pokemon){
let pokeInfo = $.get("http://pokeapi.co/api/v1/pokemon/" + pokemon.attr("id"), function(data){
console.log(data);
populatePokemanInfo(data);
}, "json");
} | [
"function addEventListener(button, pokemon) {\n button.addEventListener('click', function() {\n showDetails(pokemon);\n });\n }",
"function addListener(button, pokemon) {\n button.click(function() {\n showDetails(pokemon);\n });\n }",
"function playerSelect() {\n $(\".pokemon .poke-container\").click(function () {\n // get the name of the clicked pokemon and compare it to the name in pokemonList array\n let name = $(this).children(\"h2\").text();\n for (let i in pokemonList) {\n if (pokemonList[i].name === name) {\n // find and save the chosen pokemon as the player's choice\n player.choice = pokemonList[i];\n //hide the pokemon list\n pokemon.style.display = \"none\";\n //after selecting pokemon, generate the pokemon in the battle arena, along with the user attacks\n createPoke($(\".arena .player\"), player.choice);\n createPoke($(\".arena .computer\"), computer.choice);\n attackList();\n }\n }\n });\n}",
"function baseStage() {\n for(var i = 0; i < foundPokemon.length; i++) {\n $(foundPokemon[i]).addEventListener(\"click\", getInfo);\n }\n }",
"function showDetails(pokemon) {\n console.log(pokemon)\n}",
"function displayYourPokemon(pokemon) {\n scrollUp();\n $('.pokemon-selector-grid').html(\"\")\n $(\"#your-pokemon\").html(`<h1>You picked <font color=\"#0000e5\">${pokemon.species.name}</font>!</h1>\n <p><center><img src=\"${pokemon.sprites.front_default}\"></center></p>\n <p><h2>Choose 4 Moves for Your Pokemon!</h2></p>`)\n }",
"function displayPokemon() \n{\n\n $(\".pokemonName\").text(pokedex.pokemon.name);\n $(\".pokemonId\").text(`No. ` + pokedex.pokemon.id);\n\n $(\".sprite-box\").attr(\"src\", pokedex.pokemon.sprites.normal);\n $(\".item-description-box\").text(pokedex.pokemon.description[0]);\n\n var weight = pokedex.pokemon.weight ? pokedex.pokemon.weight : 0;\n var height = pokedex.pokemon.height ? pokedex.pokemon.height : 0;\n $(\".weight\").text(\"Weight\" + weight.toString().padStart(9, '.') + \"Lbs\");\n $(\".height\").text(\"Height\" + height.toString().padStart(9, '.') + \"'\");\n\n var hp = pokedex.pokemon.baseStats.hp ? pokedex.pokemon.baseStats.hp : 0;\n var attack = pokedex.pokemon.baseStats.attack ? pokedex.pokemon.baseStats.attack : 0;\n var defense = pokedex.pokemon.baseStats.defense ? pokedex.pokemon.baseStats.defense : 0;\n var special_attack = pokedex.pokemon.baseStats.specialAtk ? pokedex.pokemon.baseStats.specialAtk : 0;\n var special_defense = pokedex.pokemon.baseStats.specialDefense ? pokedex.pokemon.baseStats.specialDefense : 0;\n var speed = pokedex.pokemon.baseStats.speed ? pokedex.pokemon.baseStats.speed : 0;\n $(\".hp\").text(\"Hp\" + hp.toString().padStart(21, '.'));\n $(\".attack\").text(\"Attack\" + attack.toString().padStart(17, '.'));\n $(\".defense\").text(\"Defense\" + defense.toString().padStart(16, '.'));\n $(\".special_attack\").text(\"Special Attack\" + special_attack.toString().padStart(9, '.'));\n $(\".special_defense\").text(\"Special Defense\" + special_defense.toString().padStart(8, '.'));\n $(\".speed\").text(\"Speed\" + speed.toString().padStart(18, '.'));\n \n //Loops and displays pokemon type \n var pokemonType = \"\";\n $.each(pokedex.pokemon.type, function (key, value) {\n pokemonType += `<div class=\"stats-box-left-item2 ${pokedex.pokemon.type[key]}\">${pokedex.pokemon.type[key]}</div>`;\n });\n\n $(\".stats-box-left-item2\").html(pokemonType);\n\n\n //Loops evolution chain and displays species evolution\n var spritePath = \"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/\";\n var noDataSprite = \"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png\";\n\n for(var i=1; i<=3; i++){\n $(\"#stage\" + i).text(\"\");\n $(\"#stage\" + i +\"-sprite\").attr('src', noDataSprite);\n }\n\n var evolveChain = pokedex.pokemon.evolutions;\n var evolution = evolveChain[0]\n var i = 1;\n do{\n $(\"#stage\" + i).text(evolution.species.name);\n var species_url = evolution.species.url.split(\"/\");\n $(\"#stage\" + i +\"-sprite\").attr('src', spritePath + species_url[6] + \".png\"); \n evolution = evolution.evolves_to.length > 0 ? evolution.evolves_to[0] : null;\n i++;\n }while(evolution != null);\n\n //RIGHT PANEL - 3rd Row move details\n $(\".ability-name\").text(pokedex.pokemon.moves[0].name);\n\n var accuracy = pokedex.pokemon.moves[0].accuracy ? pokedex.pokemon.moves[0].accuracy : 0;\n var power = pokedex.pokemon.moves[0].power ? pokedex.pokemon.moves[0].power : 0;\n var pp = pokedex.pokemon.moves[0].pp ? pokedex.pokemon.moves[0].pp : 0;\n $(\".accuracy\").text(\"Accuracy\" + accuracy.toString().padStart(10, '.'));\n $(\".power\").text(\"Power\" + power.toString().padStart(10, '.'));;\n $(\".pp\").text(\"pp\" + pp.toString().padStart(10, '.'));\n\n $(\"#ability-type\").text(pokedex.pokemon.moves[0].type);\n $(\"#ability-type\").addClass(pokedex.pokemon.moves[0].type);\n\n //RIGHT PANEL - 4th ROW - prev and next pokemon\n $(\".prev\").attr(\"data-value\", pokedex.pokemon.id - 1);\n $(\".next\").attr(\"data-value\", pokedex.pokemon.id + 1);\n\n //RIGHT PANEL - Pokemon ID input\n $(\".pokemon-id-input\").attr(\"value\", pokedex.pokemon.id);\n\n var ability_class = pokedex.pokemon.moves[0].ability_class;\n var level_learned_at = pokedex.pokemon.moves[0].level_learned_at;\n var method = pokedex.pokemon.moves[0].method;\n\n $(\".ability_class\").text(\"Class\" + ability_class.toString().padStart(15, '.'));\n $(\".learned_at\").text(\"Learned At\" + level_learned_at.toString().padStart(10, '.'));;\n $(\".method\").text(\"Method\" + method.toString().padStart(14, '.'));\n\n $(\"#short-desc\").text(pokedex.pokemon.moves[0].description);\n $(\"#effect\").text(pokedex.pokemon.moves[0].move_effect);\n}",
"function showInfosPokemon(pokemon) {\n pokemonSelected = {\n ...pokemon\n };\n console.log(pokemon)\n let infos = `<h2>${pokemonSelected.name}</h2>`;\n infos += `<img src=${pokemonSelected.sprites.front_default} alt=\"${pokemonSelected.name} sprite\" class=\"sprite\">`\n infos += `<div class=\"pokedatas\">`;\n infos += `<div class=\"data\"><span>National N°</span> <strong>${pokemonSelected.id}</strong></div>`;\n infos += `<div class=\"data\"><span>Type</span> <strong>`;\n let type = pokemonSelected.types.reverse();\n type.forEach(e => {\n infos += `<img src=\"assets/types/${e.type.name}.gif\" alt=\"${e.type.name}\"> `;\n });\n infos += `</strong></div>`;\n infos += `<div class=\"data\"><span>Height</span> <strong>${calculData(pokemonSelected.height)}m</strong></div>`;\n infos += `<div class=\"data\"><span>Weight</span> <strong>${calculData(pokemonSelected.weight)}kg</strong></div>`;\n let abilities = pokemonSelected.abilities;\n abilities.sort((a, b) => {\n return a.slot - b.slot;\n })\n infos += `<div class=\"data\"><span>Abilities</span> <ol>`;\n abilities.forEach(e => {\n let hidden = e.is_hidden ? \"(hidden)\" : \"\";\n infos += `<li><strong>${e.ability.name}</strong> ${hidden}</li>`;\n });\n infos += `</ol></div>`;\n infos += `</div>`;\n\n infos += `<table class=\"statbloc\">`;\n infos += `<thead>`;\n infos += `<tr>`;\n infos += `<th colspan=\"4\">Stat bloc</th>`;\n infos += `</tr>`;\n infos += `</thead>`;\n infos += `<tr>`;\n infos += `<td>HP</td>`;\n infos += `<td>${pokemonSelected.stats[5].base_stat}</td>`;\n infos += `<td>Speed</td>`;\n infos += `<td>${pokemonSelected.stats[0].base_stat}</td>`;\n infos += `</tr>`;\n infos += `<tr>`;\n infos += `<td>Attack</td>`;\n infos += `<td>${pokemonSelected.stats[4].base_stat}</td>`;\n infos += `<td>Defense</td>`;\n infos += `<td>${pokemonSelected.stats[3].base_stat}</td>`;\n infos += `</tr>`;\n infos += `<tr>`;\n infos += `<td>Sp. Attack</td>`;\n infos += `<td>${pokemonSelected.stats[2].base_stat}</td>`;\n infos += `<td>Sp. Defense</td>`;\n infos += `<td>${pokemonSelected.stats[1].base_stat}</td>`;\n infos += `</tr>`;\n infos += `</table>`;\n mainContent.innerHTML = infos;\n}",
"function newButtonListener (button, pokemon) {\n button.addEventListener(\"click\", function() {\n showDetails(pokemon)\n } );\n }",
"function interacciones(){\n\n\t// 1.-Hace el pokedex visible, 3.-Crea la imagen del pokemon en la pokedex\n $(document).on('click', '#libro img', function(){ \n if ($(this).attr('pokenumero') !== undefined){\n var numeroPokemon = $(this).attr('pokenumero');\n console.log (numeroPokemon);\n var urlImgPokemon = \"http://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/\" + numeroPokemon; \n $(\"#pokedex\").after(\"<img class='pokedex pokeenpokedex sound' src='\" + urlImgPokemon + \".png' pokenumero='\" + (numeroPokemon) + \"'>\");\n $(\".pokedex\").css('visibility', 'visible');\n const infoPokemon = document.getElementById(\"infopokemon\");\n var output = \"\";\n $.ajax({\n method: \"GET\",\n url: \"https://pokeapi.co/api/v2/pokemon/\" + (numeroPokemon) +\"/\",\n dataType: 'json',\n async: false\n })\n .done(function(dataPoke) {\n output += \"<h3>\" + dataPoke.name[0].toUpperCase() + dataPoke.name.slice(1) + \"</h3>\";\n output += \"<h4>Number: <span>\" + dataPoke.id + \"</span></h4>\";\n output += \"<h4>Types: <span>\";\n for (let h=0; h<dataPoke.types.length; h++){\n if (h !== dataPoke.types.length-1){\n output += dataPoke.types[h].type.name + \", \";\n }\n else{\n output += dataPoke.types[h].type.name;\n }\n }\n output += \"</span></h4>\";\n output += \"<h4>Height: <span>\" + dataPoke.height + \"</span></h4>\";\n output += \"<h4>Abilities: <span>\";\n for (let j=0; j<dataPoke.abilities.length; j++){\n if (j !== dataPoke.abilities.length-1){\n output += dataPoke.abilities[j].ability.name + \", \";\n }\n else{\n output += dataPoke.abilities[j].ability.name;\n }\n }\n output += \"</span></h4>\";\n output += \"<h4>Description:</h4>\";\n output += descriptionPokemon(numeroPokemon);\n\n output += \"<h4>Evolutions:</h4>\";\n output += evolutionsPokemon(numeroPokemon);\n\n infoPokemon.innerHTML = output;\n });\n \n }\n });\n\n // 1.-Activa la reproduccion del sonido del pokemon dentro y fuera de la pokedex\n $(document).on('click', '.container .sound', function(){ // \n if ($(this).attr('pokenumero') !== undefined && $(this).attr('pokenumero') < 152){\n pokemonSound($(this).attr('pokenumero'));\n }\n });\n\n // Muestra los siguientes o anteriores 20 pokemones de la lista\n $(document).on('click', '.pokeballs', function(){ \n if ($(this).attr(\"id\") === \"pokeballBack\"){\n console.log(\"BACK\");\n if (PrevList !== null){\n $(\".pokemon\").remove();\n MostrarPokemones(ListaPokemones(PrevList));\n }\n else{\n console.log(\"no existe pagina anterior\");\n }\n }\n else{\n console.log(\"NEXT\");\n if (NextList !== null){\n $(\".pokemon\").remove();\n MostrarPokemones(ListaPokemones(NextList));\n }\n else{\n console.log(\"no existe pagina posterior\");\n }\n }\n });\n\n // Borra la imagen del pokemon en la pokedex y los datos del pokkemon, ademas esconde la imagen del pokedex\n $(document).on('click', '#exit', function(){ \n $(\".pokeenpokedex\").remove();\n $(\".pokedex\").css('visibility', 'hidden');\n });\n\n}",
"function addPokeInfo() {\n let pokeId = parseInt(this.innerText);\n let pokeInfo = allPokemon[pokeId - 1];\n changeSprite(pokeInfo);\n changeStats(pokeInfo);\n }",
"function handlePokeListItemClick(e) {\n getPokemon(e.target.dataset.url);\n}",
"function showDetails(button, pokemon) {\n\t\t\tloadDetails(pokemon).then(function () {\n\t\t\t\tshowModal(pokemon.name, pokemon.height,\n\t\t\t\t\tpokemon.imageUrl);\t// jl: imported from modal demo\n\t\t\t})\n\t\t}",
"function pokedex(){\n \n // id or attack of the pokemon stronger\n let array = highestPokemons();\n // let arrayPokHighest = array[0];\n let arrayIdHighest = array[1];\n let arrayStats = array[2];\n \n $('#pokedexInfo').on('click',()=>{\n\n $('#modalPokedex').fadeIn(1, ()=>{\n\n //Transition from pokedex modal\n $('#modalPokedex').attr('transition-duration','2s');\n $('#modalPokedex').css('transform','translate(650px, -100px)'); \n \n });\n\n addSixHighestPoks(arrayIdHighest);\n somaCharacPoks(arrayIdHighest);\n pokemonHover(arrayStats);\n\n closeModalPokedex();\n\n return false;\n });\n }",
"function showDetails(pokemon) {\n // Call the loadDetails function to load Pokemon details from the API, and add this information to the Modal\n loadDetails(pokemon).then(function () {\n let modalTitle = $('#pokemon-modal-header');\n let modalBody = $('#pokemon-modal-body');\n\n // Empty existing modal content\n modalBody.empty();\n modalTitle.empty();\n\n // Show the loading spinner for the modal\n showLoadingModalSpinner();\n\n // Add the Pokemon's name as an h1 element\n let modalName = $(`<h1 class=\"w-100 text-center\">${pokemon.name}</h1>`);\n\n // Add the Pokemon's height as a p element\n let modalHeight = $(`<p class=\"text-center\">Height: ${(pokemon.height) / 10}m</p>`);\n\n // Add the Pokemon's types as a p element\n let modalTypes = $(`<p class=\"text-center\">Types: </p>`);\n\n // Loop through the pokemon.types array, then get type.name for the display name of the type\n pokemon.types.forEach(function (individualType) {\n // Adding a span here will allow us to change the colour of this type section depending on what type it is\n let typesSpan = $(`<span class=\"${individualType.type.name} pokemon-type text-center\"></span>`);\n // Capitalize the type name\n let capitalType = individualType.type.name.charAt(0).toUpperCase() + individualType.type.name.slice(1);\n // Add the type text to the <span>\n typesSpan.text(`${capitalType} `);\n // Add the <span> to the <p> element above\n modalTypes.append(typesSpan);\n });\n\n // Add the sprite image of this Pokemon in an img tag\n let modalImage = $(`<img class=\"img-fluid\" src=\"${pokemon.imageUrl}\">`);\n\n // Add close button for the modal\n let closeButton = $('<button type=\"button\" class=\"btn-close\" data-dismiss=\"modal\" aria-label=\"close\">X</button>');\n\n // Hide the loading modal spinner\n hideLoadingModalSpinner();\n\n // Append each element to the appropriate part of the modal\n modalTitle.append(modalName);\n modalTitle.append(closeButton);\n modalBody.append(modalHeight);\n modalBody.append(modalTypes);\n modalBody.append(modalImage);\n });\n }",
"function drawPokemonInfo(pokemon) {\n //clearing all the previous data that was inside #info tag\n $('#info').empty();\n\n let pokeString = \"<div>\"\n\n pokeString += \"<h2 class='pokemon-info-heading'>\" + pokemon.name + \"</h2>\"\n pokeString += \"<img src=\" + pokemon.sprite + \" alt='image of \" + pokemon.name + \"'>\"\n pokeString += \"<dl class='info-item'>\"\n pokeString += \"<dt>\" + pokemon.types.heading + \":</dt>\"\n\n for (let i = 0; i < pokemon.types.types.length; i++) {\n pokeString += \"<dd>\" + pokemon.types.types[i].type.name + \"</dd>\"\n }\n\n pokeString += \"<dt>Weight:</dt>\"\n pokeString += \"<dd>\" + pokemon.weight + \"</dd>\"\n pokeString += \"<dt>Height:</dt>\"\n pokeString += \"<dd>\" + pokemon.height + \"</dd>\"\n pokeString += \"</dl>\"\n pokeString += \"</div>\"\n\n $('#info').append(pokeString);\n }",
"function createPokeInfo(pokemon, element) {\n //Grab pokemon ID and pad it with leading 0s\n var displayID = JSON.stringify(pokemon.id).padStart(3, '0');\n //Grab pokemon name and capitalize\n var pokeName = pokemon.name[0].toUpperCase() + pokemon.name.slice(1);\n //Grab pokemon type\n var typeArray = [];\n if (Object.keys(pokemon.types).length === 1) {\n typeArray.push(pokemon.types[0].type.name);\n } else {\n pokemon.types.forEach(function(res) {\n typeArray.push(res.type.name);\n })\n }\n var pokeTypes = typeArray.join(\", \");\n //Grab pokemon picture\n var pokePic = pokemon.sprites.front_default;\n //Grab pokemon height\n var pokeHeight = pokemon.height * 10;\n //Grab pokemon weight\n var pokeWeight = pokemon.weight / 10;\n //Put API info into DOM\n var pokeElement = `<div class='infoTile' id='${pokemon.name}Info' data-id='tile-${pokemon.id}'>\n <p class='back'>Go Back</p>\n <h3 class='pokemonTitle'>#${displayID} ${pokeName}</h3>\n <div class=\"pokemonInfo\" data-id='info-${pokemon.id}'>\n <img class='pokemonPic' data-id='picture-${pokemon.id}' src='${pokePic}'>\n <div class=\"pokemonInner\" data-id='inner-${pokemon.id}'>\n <span class='pokemonType' data-id='type-${pokemon.id}'><b>Type:</b> ${pokeTypes}</span></br>\n <span class='pokemonHeight' data-id='height-${pokemon.id}'><b>Height:</b> ${pokeHeight}cm</span></br>\n <span class='pokemonWeight' data-id='weight-${pokemon.id}'><b>Weight:</b> ${pokeWeight}kg</span>\n </div>\n </div>\n <div class=\"poke-btn-container\">\n <button class=\"choose-btn\" value=\"${pokeName}\" >I choose you!</button>\n </div>\n</div>`;\n element.insertAdjacentHTML('afterend',pokeElement);\n pendo.track(\"Poke Info Viewed\", {\n PokemonName: `${pokeName}`\n });\n }",
"function addPokemonToPage(pokemonName, pokemonImageUrl, abilities){\n\n}",
"function showDetails(pokemon) {\n // pokemonRepository.loadDetails(item).then(function() {\n loadDetails(pokemon).then(function() {\n showModal(pokemon);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fills in missing fields in certificate extensions. | function _fillMissingExtensionFields(e, options) {
options = options || {};
// populate missing name
if(typeof e.name === 'undefined') {
if(e.id && e.id in pki.oids) {
e.name = pki.oids[e.id];
}
}
// populate missing id
if(typeof e.id === 'undefined') {
if(e.name && e.name in pki.oids) {
e.id = pki.oids[e.name];
} else {
var error = new Error('Extension ID not specified.');
error.extension = e;
throw error;
}
}
if(typeof e.value !== 'undefined') {
return;
}
// handle missing value:
// value is a BIT STRING
if(e.name === 'keyUsage') {
// build flags
var unused = 0;
var b2 = 0x00;
var b3 = 0x00;
if(e.digitalSignature) {
b2 |= 0x80;
unused = 7;
}
if(e.nonRepudiation) {
b2 |= 0x40;
unused = 6;
}
if(e.keyEncipherment) {
b2 |= 0x20;
unused = 5;
}
if(e.dataEncipherment) {
b2 |= 0x10;
unused = 4;
}
if(e.keyAgreement) {
b2 |= 0x08;
unused = 3;
}
if(e.keyCertSign) {
b2 |= 0x04;
unused = 2;
}
if(e.cRLSign) {
b2 |= 0x02;
unused = 1;
}
if(e.encipherOnly) {
b2 |= 0x01;
unused = 0;
}
if(e.decipherOnly) {
b3 |= 0x80;
unused = 7;
}
// create bit string
var value = String.fromCharCode(unused);
if(b3 !== 0) {
value += String.fromCharCode(b2) + String.fromCharCode(b3);
} else if(b2 !== 0) {
value += String.fromCharCode(b2);
}
e.value = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
} else if(e.name === 'basicConstraints') {
// basicConstraints is a SEQUENCE
e.value = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
// cA BOOLEAN flag defaults to false
if(e.cA) {
e.value.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
String.fromCharCode(0xFF)));
}
if('pathLenConstraint' in e) {
e.value.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
asn1.integerToDer(e.pathLenConstraint).getBytes()));
}
} else if(e.name === 'extKeyUsage') {
// extKeyUsage is a SEQUENCE of OIDs
e.value = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
var seq = e.value.value;
for(var key in e) {
if(e[key] !== true) {
continue;
}
// key is name in OID map
if(key in oids) {
seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,
false, asn1.oidToDer(oids[key]).getBytes()));
} else if(key.indexOf('.') !== -1) {
// assume key is an OID
seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,
false, asn1.oidToDer(key).getBytes()));
}
}
} else if(e.name === 'nsCertType') {
// nsCertType is a BIT STRING
// build flags
var unused = 0;
var b2 = 0x00;
if(e.client) {
b2 |= 0x80;
unused = 7;
}
if(e.server) {
b2 |= 0x40;
unused = 6;
}
if(e.email) {
b2 |= 0x20;
unused = 5;
}
if(e.objsign) {
b2 |= 0x10;
unused = 4;
}
if(e.reserved) {
b2 |= 0x08;
unused = 3;
}
if(e.sslCA) {
b2 |= 0x04;
unused = 2;
}
if(e.emailCA) {
b2 |= 0x02;
unused = 1;
}
if(e.objCA) {
b2 |= 0x01;
unused = 0;
}
// create bit string
var value = String.fromCharCode(unused);
if(b2 !== 0) {
value += String.fromCharCode(b2);
}
e.value = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
} else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {
// SYNTAX SEQUENCE
e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
var altName;
for(var n = 0; n < e.altNames.length; ++n) {
altName = e.altNames[n];
var value = altName.value;
// handle IP
if(altName.type === 7 && altName.ip) {
value = forge.util.bytesFromIP(altName.ip);
if(value === null) {
var error = new Error(
'Extension "ip" value is not a valid IPv4 or IPv6 address.');
error.extension = e;
throw error;
}
} else if(altName.type === 8) {
// handle OID
if(altName.oid) {
value = asn1.oidToDer(asn1.oidToDer(altName.oid));
} else {
// deprecated ... convert value to OID
value = asn1.oidToDer(value);
}
}
e.value.value.push(asn1.create(
asn1.Class.CONTEXT_SPECIFIC, altName.type, false,
value));
}
} else if(e.name === 'subjectKeyIdentifier' && options.cert) {
var ski = options.cert.generateSubjectKeyIdentifier();
e.subjectKeyIdentifier = ski.toHex();
// OCTETSTRING w/digest
e.value = asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());
}
// ensure value has been defined by now
if(typeof e.value === 'undefined') {
var error = new Error('Extension value not specified.');
error.extension = e;
throw error;
}
return e;
} | [
"function _fillMissingExtensionFields(e,options){options=options||{};// populate missing name\nif(typeof e.name==='undefined'){if(e.id&&e.id in pki.oids){e.name=pki.oids[e.id];}}// populate missing id\nif(typeof e.id==='undefined'){if(e.name&&e.name in pki.oids){e.id=pki.oids[e.name];}else{var error=new Error('Extension ID not specified.');error.extension=e;throw error;}}if(typeof e.value!=='undefined'){return e;}// handle missing value:\n// value is a BIT STRING\nif(e.name==='keyUsage'){// build flags\nvar unused=0;var b2=0x00;var b3=0x00;if(e.digitalSignature){b2|=0x80;unused=7;}if(e.nonRepudiation){b2|=0x40;unused=6;}if(e.keyEncipherment){b2|=0x20;unused=5;}if(e.dataEncipherment){b2|=0x10;unused=4;}if(e.keyAgreement){b2|=0x08;unused=3;}if(e.keyCertSign){b2|=0x04;unused=2;}if(e.cRLSign){b2|=0x02;unused=1;}if(e.encipherOnly){b2|=0x01;unused=0;}if(e.decipherOnly){b3|=0x80;unused=7;}// create bit string\nvar value=String.fromCharCode(unused);if(b3!==0){value+=String.fromCharCode(b2)+String.fromCharCode(b3);}else if(b2!==0){value+=String.fromCharCode(b2);}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,value);}else if(e.name==='basicConstraints'){// basicConstraints is a SEQUENCE\ne.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);// cA BOOLEAN flag defaults to false\nif(e.cA){e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,false,String.fromCharCode(0xFF)));}if('pathLenConstraint'in e){e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(e.pathLenConstraint).getBytes()));}}else if(e.name==='extKeyUsage'){// extKeyUsage is a SEQUENCE of OIDs\ne.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;for(var key in e){if(e[key]!==true){continue;}// key is name in OID map\nif(key in oids){seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids[key]).getBytes()));}else if(key.indexOf('.')!==-1){// assume key is an OID\nseq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(key).getBytes()));}}}else if(e.name==='nsCertType'){// nsCertType is a BIT STRING\n// build flags\nvar unused=0;var b2=0x00;if(e.client){b2|=0x80;unused=7;}if(e.server){b2|=0x40;unused=6;}if(e.email){b2|=0x20;unused=5;}if(e.objsign){b2|=0x10;unused=4;}if(e.reserved){b2|=0x08;unused=3;}if(e.sslCA){b2|=0x04;unused=2;}if(e.emailCA){b2|=0x02;unused=1;}if(e.objCA){b2|=0x01;unused=0;}// create bit string\nvar value=String.fromCharCode(unused);if(b2!==0){value+=String.fromCharCode(b2);}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,value);}else if(e.name==='subjectAltName'||e.name==='issuerAltName'){// SYNTAX SEQUENCE\ne.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var altName;for(var n=0;n<e.altNames.length;++n){altName=e.altNames[n];var value=altName.value;// handle IP\nif(altName.type===7&&altName.ip){value=forge.util.bytesFromIP(altName.ip);if(value===null){var error=new Error('Extension \"ip\" value is not a valid IPv4 or IPv6 address.');error.extension=e;throw error;}}else if(altName.type===8){// handle OID\nif(altName.oid){value=asn1.oidToDer(asn1.oidToDer(altName.oid));}else{// deprecated ... convert value to OID\nvalue=asn1.oidToDer(value);}}e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,false,value));}}else if(e.name==='subjectKeyIdentifier'&&options.cert){var ski=options.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=ski.toHex();// OCTETSTRING w/digest\ne.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ski.getBytes());}else if(e.name==='authorityKeyIdentifier'&&options.cert){// SYNTAX SEQUENCE\ne.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;if(e.keyIdentifier){var keyIdentifier=e.keyIdentifier===true?options.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,false,keyIdentifier));}if(e.authorityCertIssuer){var authorityCertIssuer=[asn1.create(asn1.Class.CONTEXT_SPECIFIC,4,true,[_dnToAsn1(e.authorityCertIssuer===true?options.cert.issuer:e.authorityCertIssuer)])];seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,authorityCertIssuer));}if(e.serialNumber){var serialNumber=forge.util.hexToBytes(e.serialNumber===true?options.cert.serialNumber:e.serialNumber);seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,false,serialNumber));}}else if(e.name==='cRLDistributionPoints'){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;// Create sub SEQUENCE of DistributionPointName\nvar subSeq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);// Create fullName CHOICE\nvar fullNameGeneralNames=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);var altName;for(var n=0;n<e.altNames.length;++n){altName=e.altNames[n];var value=altName.value;// handle IP\nif(altName.type===7&&altName.ip){value=forge.util.bytesFromIP(altName.ip);if(value===null){var error=new Error('Extension \"ip\" value is not a valid IPv4 or IPv6 address.');error.extension=e;throw error;}}else if(altName.type===8){// handle OID\nif(altName.oid){value=asn1.oidToDer(asn1.oidToDer(altName.oid));}else{// deprecated ... convert value to OID\nvalue=asn1.oidToDer(value);}}fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,false,value));}// Add to the parent SEQUENCE\nsubSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[fullNameGeneralNames]));seq.push(subSeq);}// ensure value has been defined by now\nif(typeof e.value==='undefined'){var error=new Error('Extension value not specified.');error.extension=e;throw error;}return e;}",
"function _fillMissingExtensionFields(e, options) {\n options = options || {}; // populate missing name\n\n if (typeof e.name === 'undefined') {\n if (e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n } // populate missing id\n\n\n if (typeof e.id === 'undefined') {\n if (e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if (typeof e.value !== 'undefined') {\n return e;\n } // handle missing value:\n // value is a BIT STRING\n\n\n if (e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n\n if (e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n\n if (e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n\n if (e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n\n if (e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n\n if (e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n\n if (e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n\n if (e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n\n if (e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n\n if (e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n } // create bit string\n\n\n var value = String.fromCharCode(unused);\n\n if (b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if (b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if (e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); // cA BOOLEAN flag defaults to false\n\n if (e.cA) {\n e.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(0xFF)));\n }\n\n if ('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if (e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n for (var key in e) {\n if (e[key] !== true) {\n continue;\n } // key is name in OID map\n\n\n if (key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids[key]).getBytes()));\n } else if (key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if (e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if (e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n\n if (e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n\n if (e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n\n if (e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n\n if (e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n\n if (e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n\n if (e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n\n if (e.objCA) {\n b2 |= 0x01;\n unused = 0;\n } // create bit string\n\n\n var value = String.fromCharCode(unused);\n\n if (b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if (e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var altName;\n\n for (var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value; // handle IP\n\n if (altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n\n if (value === null) {\n var error = new Error('Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if (altName.type === 8) {\n // handle OID\n if (altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n\n e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value));\n }\n } else if (e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex(); // OCTETSTRING w/digest\n\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if (e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if (e.keyIdentifier) {\n var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier;\n seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if (e.authorityCertIssuer) {\n var authorityCertIssuer = [asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [_dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer)])];\n seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if (e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber);\n seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if (e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value; // Create sub SEQUENCE of DistributionPointName\n\n var subSeq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); // Create fullName CHOICE\n\n var fullNameGeneralNames = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n\n for (var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value; // handle IP\n\n if (altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n\n if (value === null) {\n var error = new Error('Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if (altName.type === 8) {\n // handle OID\n if (altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n\n fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value));\n } // Add to the parent SEQUENCE\n\n\n subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n } // ensure value has been defined by now\n\n\n if (typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}",
"function _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}",
"function _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if (e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}",
"function _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}",
"SetCertificateExtension(string, int, int, Variant) {\n\n }",
"checkRecognizedExtensions() {\n // The extension list is the first (and only) element of the extensions\n // context specific tag\n const extSeq = this.extensionsObj?.subs[0];\n const exts = extSeq?.subs.map((ext) => new ext_1.x509Extension(ext));\n // Check for unrecognized critical extensions\n return (!exts ||\n exts.every((ext) => !ext.critical || RECOGNIZED_EXTENSIONS.includes(ext.oid)));\n }",
"addAllowedExtensions(extensions) {\n for(let extension of extensions) {\n this.addAllowedExtension(extension);\n }\n }",
"initExtensions(){\n let exts = this.extensions;\n\n for(let i=0, len=exts.length; i<len; i++){\n let ext = exts[i];\n if(!this.ExtRegistry[ext.name]){\n this.loadExtension(ext);\n }\n }\n }",
"function formatExtensions() {\n\n if (opt.properties.validExtensions != \"\") {\n var extensionList = opt.properties.validExtensions.replaceAll(\"*\", \"\");\n extensionList = extensionList.replaceAll(\";\", \",\");\n\n opt.properties.processedFileExtension = extensionList;\n }\n }",
"function _prepareExtension(extension) {\n var ext = {};\n\n try {\n if (({}).toString.call(extension) === '[object Object]') {\n ext.userInfo = extension;\n ext = JSON.parse(JSON.stringify(ext).replace(/null/g, \"\\\"\\\"\"));\n } else {\n throw new Error('Invalid type of \"extension\" object.');\n }\n } catch (err) {\n Helpers.traceWarning(err.message);\n }\n\n return ext;\n}",
"GetCertificateExtension(string, int) {\n\n }",
"setSignedExtensions(signedExtensions = fallbackExtensions, userExtensions) {\n _classPrivateFieldBase(this, _signedExtensions)[_signedExtensions] = signedExtensions;\n _classPrivateFieldBase(this, _userExtensions)[_userExtensions] = userExtensions;\n const unknown = findUnknownExtensions(_classPrivateFieldBase(this, _signedExtensions)[_signedExtensions], _classPrivateFieldBase(this, _userExtensions)[_userExtensions]);\n\n if (unknown.length) {\n registry_l.warn(`Unknown signed extensions ${unknown.join(', ')} found, treating them as no-effect`);\n }\n }",
"function _prepareExtension(extension) {\n var ext = {};\n\n try {\n if ( ({}).toString.call(extension) === '[object Object]' ) {\n ext.userInfo = extension;\n ext = JSON.parse( JSON.stringify(ext).replace(/null/g, \"\\\"\\\"\") );\n } else {\n throw new Error('Invalid type of \"extension\" object.');\n }\n } catch (err) {\n Helpers.traceWarning(err.message);\n }\n\n return ext;\n}",
"function prepareExtensions(options) {\n var _this = this;\n var _a;\n var extensions = (_a = options === null || options === void 0 ? void 0 : options.extensions) !== null && _a !== void 0 ? _a : [];\n var extConfig = {};\n var incompatibleExtensions = [];\n if (Array.isArray(extensions)) {\n extensions.forEach(function (ext) {\n if (checkExtensionCompat(ext)) {\n ext.init(_this);\n _this[ext.name] = ext;\n if (ext instanceof base_extension_1.Extension.Internal) {\n if (!type_guards_1.isEmpty(ext.config))\n extConfig[ext.name] = ext.config;\n }\n }\n else {\n incompatibleExtensions.push(ext);\n }\n });\n }\n else {\n Object.keys(extensions).forEach(function (name) {\n if (checkExtensionCompat(extensions[name])) {\n extensions[name].init(_this);\n var ext = extensions[name];\n _this[name] = ext;\n if (ext instanceof base_extension_1.Extension.Internal) {\n if (!type_guards_1.isEmpty(ext.config))\n extConfig[extensions[name].name] = ext.config;\n }\n }\n else {\n incompatibleExtensions.push(extensions[name]);\n }\n });\n }\n if (incompatibleExtensions.length) {\n throw sdk_exceptions_1.createIncompatibleExtensionsError(incompatibleExtensions);\n }\n return extConfig;\n}",
"function fixcerts() {\n var tmpcerts = { 'trusted_pubkeys': [] };\n for (var key in certs) {\n var certpem = certs[key];\n var certder = pem2der(certpem);\n //getfield(certder);\n var subj = getSubjectString(certder, 'own');\n if (tmpcerts.hasOwnProperty(subj)) {\n //Duplicate found. Rename the existing entry and the duplicate\n //with extended subject\n //console.log('adding duplicate:', subj);\n var pem_one = tmpcerts[subj];\n var der_one = pem2der(pem_one);\n var subj_one = getSubjectString(der_one, 'own', true);\n tmpcerts[subj_one] = pem_one;\n delete tmpcerts[subj];\n var subj_two = getSubjectString(certder, 'own', true);\n subj = subj_two;\n }\n tmpcerts[subj] = certpem;\n var pk = getPubkey(certder);\n tmpcerts['trusted_pubkeys'].push(tlsn_utils.b64encode(tlsn_utils.ua2ba(pk)));\n }\n certs = tmpcerts;\n}",
"function assignAllowedExtensions() {\n let elements = document.querySelector('#allowed-extensions').children;\n\n // if elements present\n if (elements.length > 0) {\n for (let i = 0; i < elements.length; i++) {\n allowedExtensions.push(elements[i].value.toLowerCase());\n }\n\n } else {\n // assign default values if no values found\n allowedExtensions = ['jpg', 'jpeg', 'png', 'svg', 'gif'];\n }\n }",
"function cfnCertificateExtensionsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnCertificate_ExtensionsPropertyValidator(properties).assertSuccess();\n return {\n CertificatePolicies: cdk.listMapper(cfnCertificatePolicyInformationPropertyToCloudFormation)(properties.certificatePolicies),\n CustomExtensions: cdk.listMapper(cfnCertificateCustomExtensionPropertyToCloudFormation)(properties.customExtensions),\n ExtendedKeyUsage: cdk.listMapper(cfnCertificateExtendedKeyUsagePropertyToCloudFormation)(properties.extendedKeyUsage),\n KeyUsage: cfnCertificateKeyUsagePropertyToCloudFormation(properties.keyUsage),\n SubjectAlternativeNames: cdk.listMapper(cfnCertificateGeneralNamePropertyToCloudFormation)(properties.subjectAlternativeNames),\n };\n}",
"function prepareExtensions(options) {\n var _this = this;\n var _a;\n var extensions = (_a = options === null || options === void 0 ? void 0 : options.extensions) !== null && _a !== void 0 ? _a : [];\n var extConfig = {};\n var incompatibleExtensions = [];\n if (Array.isArray(extensions)) {\n extensions.forEach(function (ext) {\n if (checkExtensionCompat(ext)) {\n ext.init(_this);\n _this[ext.name] = ext;\n if (ext instanceof _modules_base_extension__WEBPACK_IMPORTED_MODULE_7__.Extension.Internal) {\n if (!(0,_util_type_guards__WEBPACK_IMPORTED_MODULE_8__.isEmpty)(ext.config))\n extConfig[ext.name] = ext.config;\n }\n }\n else {\n incompatibleExtensions.push(ext);\n }\n });\n }\n else {\n Object.keys(extensions).forEach(function (name) {\n if (checkExtensionCompat(extensions[name])) {\n extensions[name].init(_this);\n var ext = extensions[name];\n _this[name] = ext;\n if (ext instanceof _modules_base_extension__WEBPACK_IMPORTED_MODULE_7__.Extension.Internal) {\n if (!(0,_util_type_guards__WEBPACK_IMPORTED_MODULE_8__.isEmpty)(ext.config))\n extConfig[extensions[name].name] = ext.config;\n }\n }\n else {\n incompatibleExtensions.push(extensions[name]);\n }\n });\n }\n if (incompatibleExtensions.length) {\n throw (0,_sdk_exceptions__WEBPACK_IMPORTED_MODULE_2__.createIncompatibleExtensionsError)(incompatibleExtensions);\n }\n return extConfig;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts new chat into the HTML | function insertNewChat(val) {
// Create the div element to contain the chat message
var div = document.createElement("div");
div.setAttribute("class", "chat-item");
// Create the p element to hold the text
var para = document.createElement("p");
para.setAttribute("class", "chat-text");
var message = document.createTextNode(val.message);
// Create the span that will hold the handle
var span = document.createElement("span");
span.setAttribute("class", "chat-name");
// Set the handle
var handle = getUserHandle(val.player_Id);
var handleEl = document.createTextNode(handle + ": ");
span.appendChild(handleEl);
// Append all of the elments
para.appendChild(span);
para.appendChild(message);
div.appendChild(para);
$("#chat-container").append(div);
$("#last-chat-id").val(val.chat_Id);
} | [
"function insertChatMessage(msg) {\n var formattedDate = moment(msg.timeStamp).format(\"LT\");\n var fromPlayer = playersById[msg.userId];\n insert(\"chat\", \"<div style='border-left-color: \" + fromPlayer.color\n + \"'><article><b>\" + msg.sender + \":</b><p class='msg-content'>\" \n + \"</p><span class='timestamp'>\" + formattedDate + \"</span></article></div>\");\n $(\".msg-content\").text(msg.content);\n $(\".msg-content\").removeClass(\"msg-content\");\n $(\"#chat\").scrollTop($(\"#chat\")[0].scrollHeight);\n}",
"function chat_add_html(html) {\n $(\"#chat_log\").append(html);\n chat_scrolldown();\n}",
"function chat_add_html(html) {\n $(\"#chat_log\").append(html);\n chat_scrolldown();\n }",
"function chat_add_html(html) {\r\n $(\"#chat_log\").append(html);\r\n chat_scrolldown();\r\n }",
"function newChatLine(message){\n\n\t $(\".chat\").append($('#chatRow').html()); \n\t $(\".chat .username\").last().append(message.user.name);\n\t $(\".chat .messageDate\").last().append(message.created_at);\n\t $(\".chat .messageDate .msg-id\").last().val(message.id); \n\t $(\".chat .messageDate\").last().append(' <i class=\"fa fa-trash delete-msg\" aria-hidden=\"true\"></i>');\n\t $(\".chat .message\").last().append(message.message); \n\t}",
"function insertMessageToChat(str) {\t\n\tif (messages_container.children().length == max_chat_messages)\n\t\tmessages_container.children(':first').remove();\n\t\n\tmessages_container.append(`<div class=\"chat_message\">${str}</div>`);\n\n\tlet height = messages_container[0].scrollHeight;\n\tif (height > messages_container.height())\n\t\tmessages_container.scrollTop(height);\n}",
"function pupulateChatContent() {\n var $nameMarkup = '<div><label for=\"name\">Your name:</label><input type=\"text\" name=\"name\" value=\"\" id=\"name\" class=\"span5\"></div>';\n var $messageMarkup = '<div><label for=\"message\">Message:</label><textarea name=\"message\" value=\"\" id=\"message\" class=\"span5\">' + $defaultTextAreaMessage + '</textarea></div>';\n var $buttonMarkup = '<div><div class=\"buttons\"><button class=\"btn primary\" class=\"span5\">Submit</button></div>';\n $('#uwc-chat-window').append($nameMarkup + $messageMarkup + $buttonMarkup)\n .prepend('<div id=\"message-area\"><ul></ul></div>');\n }",
"function appendChat(msg){\n\tvar chatmsgSpan = document.createElement(\"SPAN\");\n\tchatmsgSpan.innerHTML = \"<b>Server: </b>\" + msg.toString() + \"<br/>\";\n\tchatWindow.appendChild(chatmsgSpan);\n\tchatmsgSpan.focus();\n}",
"function updateMyChat(newChatRow) {\n let myRowTemplate = `\n <div class=\"chat__row --self\">\n <div class=\"chat__row__msg\">${newChatRow}</div>\n <div class=\"chat__row__img\">\n <img src=\"images/self_avatar.jpg\" alt=\"Fran\">\n </div>\n </div>\n `;\n chat.insertAdjacentHTML('beforeend', myRowTemplate);\n }",
"function addNewMessage(data){\n\t\t$chat.append(createMessage(data));\n\t\t$chat.scrollTop($chat[0].scrollHeight);\n\t}",
"function appendNewChat(chat){\n let div = document.createElement('div');\n let name = chat.chatMembers.filter((member) => {\n return member._id != userinfo.id;\n });\n\n $(`<div class=\"dp\"> <img src=\"/download.png\" /> </div>\n <div> ${!chat.chatType ? name[0].firstName + ' ' + name[0].lastName : chat.chatName} </div>`)\n .appendTo(div);\n\n div.onclick = async function(){ \n // console.log(chat._id, activeChat);\n if(activeChat._id !== chat._id){\n\n // uppdate chat info\n activeChat = chat;\n activeChat.receiver = name;\n page=0;\n // update chatscreen header\n $('.chatOwner').html(!chat.chatType ? name[0].firstName + ' ' + name[0].lastName : chat.chatName);\n $('.show').removeClass('show');\n name.length === 1 && name[0].status === 1 && $('.online').addClass('show');\n\n // animation\n $('.selectedChat').removeClass('selectedChat');\n $(div).addClass('selectedChat');\n\n // empty message box\n $('.messageHistory').empty();\n\n //get messages\n await getMessages(chat._id);\n $('.messageHistory').scrollTop($('.messageHistory')[0].scrollHeight);\n }\n }\n\n return $('.ongoingchats').append(div);\n }",
"function appendChat(name, data) {\n\tvar $chatLink = $(lpMTagConfig.dynButton0[data.buttonState + \"HTML\"]);\n\t$chatLink.empty();\n\t$('.trigger-chat').each(function(index){\n\t\t$(this).wrapInner($chatLink);\n\t});\n}",
"function insContent(senderClass, chatInput){\r\n var chatbody = document.getElementById(\"chatbody\");\r\n var content = document.getElementById(\"chat_content\");\r\n var str = \"<div class = \"+senderClass+\"><span>\"+chatInput+\"</span></div>\";\r\n content.innerHTML = content.innerHTML + str;\r\n chatbody.scrollTop = chatbody.scrollHeight; //scroll down to the latest content automatically\r\n}",
"function appendChat(name, text)\n{\n\tconst chatLine = document.createElement(\"div\");\n\tchatLine.className = \"chatLine\";\n\t\n\tconst playerName = document.createElement(\"span\");\n\tplayerName.className = \"playerName\";\n\tplayerName.innerHTML = name + \":\";\n\t\n\tchatLine.appendChild(playerName);\n\tchatLine.innerHTML += text;\n\t\n\tdocument.getElementById(\"chatLines\").appendChild(chatLine);\n\tdocument.getElementById(\"chatHistory\").scrollTop = document.getElementById(\"chatHistory\").scrollHeight;\n}",
"function saveUserChat(input){\n\n\t$(\".chat-area\").append(`<div class=\"chat-text-container\"><div class=\"user-chat bg-info text-white\">${input}</div></div><br/>`)\n\n}",
"function chatAdd(newChatText) {\n var $chatBox = $(\"#chat-box\");\n $chatBox.append(newChatText);\n if ($chatBox.length) {\n $chatBox.scrollTop($chatBox[0].scrollHeight - $chatBox.height());\n }\n}",
"appendHTML() {\n\t\t\n\t\tthis.controller.displayDiv.append('<div id=\"chatHolder\" class=\"col-sm-6\"><h3 class=\"col-sm-12\"><img src=\"images/negotiation.png\"></h3><ul id=\"messages\"></ul><form action=\"\"><input id=\"m\" class=\"col-sm-9\" autocomplete=\"off\" /><button id=\"sendMessage\" class=\"col-sm-2\">Choose Name</button></form></div>');\n\t}",
"function new_msg(author, content) {\n\tlet section = document.createElement('section');\n\tlet h3 = document.createElement('h3');\n\tlet p = document.createElement('p');\n\n\th3.textContent = author;\n\tp.textContent = content;\n\n\tsection.appendChild(h3);\n\tsection.appendChild(p);\n\tchat.appendChild(section);\n}",
"addMessage(message) {\n // Find the user belonging to this message or use the anonymous user if not found\n const user = message.user;\n const text = message.text\n .replace(/&/g, '&')\n .replace(/</g, '<').replace(/>/g, '>');\n\n message.text = text;\n message.createdAt = moment(message.createdAt).format('MMM Do, hh:mm:ss');\n const selUsers = message.selUsers;\n const chat = document.querySelector('.message-list');\n if (chat && selUsers.includes(this.userId)) {\n const template = require('../tmpls/auth/chat/message.html.twig');\n const messageHTML = template({user, message});\n chat.insertAdjacentHTML('beforeend', messageHTML);\n\n chat.scrollTop = chat.scrollHeight - chat.clientHeight;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handler for click on reserve buttons | handleClickReserve(event)
{
let text = event.toElement.id.replace("reserve", "");
let ISBN = text === "" ? null : text;
this.sendReservation(ISBN);
} | [
"loadReserve() {\n this._qs(\".reserve\").addEventListener(\"click\", () => this.reserve());\n }",
"function reserveSquareClicked(event) {\n reservePieceIsSelected = true;\n activePiece = event.target;\n }",
"function seatsRegisterClick() {\n\t//To each clickable assign the action\n\t$('.clickable').each(function() {\n\t\tlet id = $(this).attr('id');\n\t\t//Perform the action to the server (Reserve/Unreserve)\n\t\t$(this).click(function(e) {\n\t\t\te.preventDefault();\n\t\t\t$.ajax({\n\t\t\t\ttype: \"POST\",\n\t\t\t\turl: \"utility/perform.php\",\n\t\t\t\tdata: \"action=reserve&id=\" + id,\n\t\t\t\tsuccess: function(result) {\n\t\t\t\t\tlet parsed = JSON.parse(result);\n\t\t\t\t\tlet seat = $(\"#\" + id);\n\t\t\t\t\t//Update correctly the statistic map\n\t\t\t\t\tswitch (parsed.err) {\n\t\t\t\t\t\tcase 0: {\n\t\t\t\t\t\t\tseat.removeClass().addClass(\"seat myReserved clickable\");\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 1: {\n\t\t\t\t\t\t\tseat.removeClass().addClass(\"seat available clickable\");\n\t\t\t\t\t\t\tbreak;\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase -3: {\n\t\t\t\t\t\t\tshowResult(parsed.err, parsed.msg, true);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault: {\n\t\t\t\t\t\t\tseat.removeClass().addClass(\"seat unavailable\");\n\t\t\t\t\t\t\tseat.unbind();\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\tif($('.myReserved').length - 1 > 0) {\n\t\t\t\t\t\t$('#buyLink').css({'pointer-events': 'visible', 'opacity': '1'});\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$('#buyLink').css({'pointer-events': 'none', 'opacity': '0.2'});\n\t\t\t\t\t}\n\t\t\t\t\tupdateStatistic();\n\t\t\t\t\tshowResult(parsed.err, parsed.msg, false);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t});\n}",
"function clickHandler(event) {\n\tpressButton(event.target);\n}",
"onReserveClick(){\n let reserveBtn = this.refs.reservebtn\n reserveBtn.setSelected(!reserveBtn.getSelected())\n this.setState({\n showReservationForm: !this.state.showReservationForm\n })\n }",
"function onItemsButtonClick(){\r\n\t\tvar objButton = jQuery(this);\r\n\r\n\t\tif(objButton.hasClass(\"button-disabled\"))\r\n\t\t\treturn(false);\r\n\t\t\r\n\t\tvar action = objButton.data(\"action\");\r\n\t\tg_manager.runItemAction(action);\r\n\t}",
"function addButtonsClickListeners() {\n\t$('#button_transfer_land').click(function(e) {\n\t\tstartLandTransaction();\n\t});\n}",
"function clickedButton(e) {\n // WHEN DONE:\n if (listOfIds.length !== 0) {\n // each calibration button is popped out of the list one-by-one.\n // it is set to fade in.\n $('#' + listOfIds.pop()).show();\n } else {\n if (!dataIsSent) {\n activity.stopCollectingGazerData();\n }\n showVideoPage();\n }\n\n //hide progress after click\n $('#cal-progress').hide();\n }",
"function checkClick() {\n $(buttons).click( function() {\n removeOrder($(this));\n });\n }",
"prepareButtons () {\n\t\tif (!this.buttons.length) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (let i = 0; i < this.buttons.length; i++) {\n\t\t\tlet button = this.buttons[i];\n\n\t\t\tvenus.get(button.id).click(button.on_click);\n\t\t}\n\t}",
"function handleInterventionsButton() {\r\n var buttonInfect = $(\"buttonInfect\");\r\n var buttonInterventions = this;\r\n\r\n buttonInfect.disabled = false;\r\n buttonInfect.className = \"inactive\";\r\n buttonInterventions.disabled = true;\r\n buttonInterventions.className = \"active\";\r\n //$(\"info\").innerHTML = \"Clicking will add interventions\";\r\n }",
"reserveSelected() {\n for (let selectedSeat of this.selectedSeats) {\n this.showing.reserveSeat(selectedSeat);\n $(`:button[value=\"${selectedSeat}\"]`).css('background-color', 'var(--seat-reserved)');\n $(`:button[value=\"${selectedSeat}\"]`).prop('disabled', true);\n }\n }",
"cartButtonClicked() {}",
"performClickFunctionality(){}",
"function cb_beforeClick(cb, pos) { }",
"clickHandler() {\n // Activate if not active\n if (this.active === 'safety') {\n // Button view press effect\n this.removeSafety();\n } else if (this.active === false) {\n // Button view press effect\n this.changeToActive();\n // Click action\n this.clickAction();\n }\n }",
"function createClickListener() {\n\t\t\t$(\".sideBtn\").click(function() {\n\t\t\t\tvar clickedBtn = $(this).attr(\"id\");\n\t\t\t\tsideBtnClicked(clickedBtn);\n\t\t\t});\n\t\t}",
"function registerClick(e) {\n\t\tvar desiredResponse = copy.shift();\n\t\tvar actualResponse = $(e.target).data('tile');\n\t\tactive = (desiredResponse === actualResponse);\n\t\tcheckLose();\n\t}",
"function createOpBtns() {\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cs142MakeMultiFilter / Returns an arrayFilterer that can be used to repeatedly filter / elements out of the originalArray. | function cs142MakeMultiFilter(originalArray) {
let currentArray = originalArray.slice();
return function arrayFilterer(filterCriteria, callback) {
if (typeof(filterCriteria) !== "function") {
return currentArray;
}
for (let i = currentArray.length - 1; i >= 0; i--) {
if (!filterCriteria(currentArray[i])) {
currentArray.splice(i, 1);
}
}
if (typeof(callback) === "function") {
callback.call(originalArray, currentArray);
}
return arrayFilterer;
};
} | [
"function arrayFilterer (filterCriteria, callback) {\n if (filterCriteria !== undefined ) {\n currentArray=currentArray.filter(filterCriteria);\n if (typeof callback === 'function') {\n callback.call(originalArray, currentArray);\n }\n return arrayFilterer;\n }\n else {\n return currentArray;\n }\n }",
"function multiFilter(array, filters) {\n var filterKeys = Object.keys(filters);\n // console.log(filters);\n\n // filters all elements passing the criteria\n return array.filter(function (item) {\n // dynamically validate all filter criteria\n return filterKeys.every(function (key) {\n return !!~filters[key].indexOf(item[key]);\n });\n });\n}",
"arrayFilters(arrayFilters) {\n if (!this.bulkOperation.s.currentOp) {\n this.bulkOperation.s.currentOp = {};\n }\n this.bulkOperation.s.currentOp.arrayFilters = arrayFilters;\n return this;\n }",
"function filter1 (theArray, fnc) {\n debugger\n let newArray = [];\n theArray.forEach(function (element) {\n if (fnc(element)) {\n newArray.push(element);\n }\n });\n return newArray;\n}",
"function createFilterPairs() {\n//To be created once selection method is designed.\nreturn arrayOfFilterPairs;\n}",
"mixedArrayFilter(array, checkFunc) {\n let filteredArray = [];\n\n array.forEach((item) => {\n // if have subItems filter subItems\n if (Array.isArray(item)) {\n let filteredSubItems = [];\n\n item.forEach((subDoc) => {\n if (checkFunc(subDoc)) filteredSubItems.push(subDoc);\n });\n\n // skip if have no subItems after filter\n filteredSubItems.length && filteredArray.push(filteredSubItems);\n } else {\n if (checkFunc(item)) filteredArray.push(item);\n }\n });\n\n return filteredArray;\n }",
"function doubleAndFilter(arr) {\n return arr.map(function(value){\n return value * 2\n }).filter(function(value){\n return value % 3 === 0\n })\n}",
"filterProducts() {\n // Crear copia\n let toFilter = [...this.productsArray];\n\n // Se pasa el array por todos los filtros del objeto filters\n Object.values(this.filters).forEach((filter) => {\n toFilter = filter(toFilter) || toFilter;\n });\n\n return toFilter;\n }",
"function filter(arr, callback) {\n return filteredArray = arr.filter(callback);\n}",
"function filter (arrayToFilter, options) {\n // conditions\n const nameFilter = (senador, nombre) => {\n assert(typeof nombre === 'string' || nombre instanceof RegExp, 'El nombre solo se puede filtrar por string o expresion regular')\n\n return typeof nombre === 'string' ? wrapString(senador.nombre).indexOf(wrapString(nombre)) > -1 : nombre.test(senador.nombre)\n }\n const rutFilter = (senador, rut) => {\n assert(validate(rut), 'el rut de busqueda ingresado no es valido')\n\n return wrapString(senador.rut) === wrapString(rut)\n }\n const defualtRutFilter = (senador, rut) => {\n rut = rut.toString()\n\n return senador.rut.split('-')[0] === rut\n }\n const regionFilter = (senador, region) => {\n assert(typeof region === 'string' || region instanceof RegExp, 'La region solo se puede filtrar por string o expresion regular')\n\n return typeof region === 'string' ? wrapString(senador.region).indexOf(wrapString(region)) > -1 : region.test(senador.region)\n }\n const circunscripcionFilter = (senador, circunscripcion) => {\n assert.equal(typeof circunscripcion, 'number', 'La circunscripción ingresada para buscar debe ser un número')\n\n return senador.circunscripcion === circunscripcion\n }\n const telefonoFilter = (senador, telefono) => {\n assert(typeof telefono === 'string' || telefono instanceof RegExp, 'El telefono solo se puede filtrar por string o expresion regular')\n\n return typeof telefono === 'string' ? wrapString(senador.telefono).indexOf(wrapString(telefono)) > -1 : telefono.test(senador.telefono)\n }\n const mailFilter = (senador, mail) => {\n assert(typeof mail === 'string' || mail instanceof RegExp, 'El telefono solo se puede filtrar por string o expresion regular')\n\n return typeof mail === 'string' ? wrapString(senador.mail).indexOf(wrapString(mail)) > -1 : mail.test(senador.mail)\n }\n const partidoFilter = (senador, partido) => {\n assert(typeof partido === 'string' || partido instanceof RegExp, 'El telefono solo se puede filtrar por string o expresion regular')\n\n return typeof partido === 'string' ? wrapString(senador.partido).indexOf(wrapString(partido)) > -1 : partido.test(senador.partido)\n }\n\n const _filter = elem => {\n if (elem.hasOwnProperty('senador')) elem = elem.senador\n // default queries\n if (typeof options === 'string' && elem) return nameFilter(elem, options)\n if (typeof options === 'number' && elem) return defualtRutFilter(elem, options)\n\n return (options.nombre ? nameFilter(elem, options.nombre) : true) &&\n (options.rut ? rutFilter(elem, options.rut) : true) &&\n (options.region ? regionFilter(elem, options.region) : true) &&\n (options.circunscripcion ? circunscripcionFilter(elem, options.circunscripcion) : true) &&\n (options.telefono ? telefonoFilter(elem, options.telefono) : true) &&\n (options.mail ? mailFilter(elem, options.mail) : true) &&\n (options.partido ? partidoFilter(elem, options.partido) : true)\n }\n return arrayToFilter.filter(_filter)\n}",
"function filter (array, test){\n \n return reduce (array, function (result, curr){\n \n if (test(curr)){\n \n result.push(curr);\n \n }\n \n return result;\n \n }, []);\n \n }",
"function fnFilter(){\r\n var a = [1,2,3,4,5,6,7,8,9,10]\r\n var anew=a.filter(function(e,i){\r\n return e>5\r\n })\r\n return anew\r\n}",
"function myFilter(array, callback){\n const filterArr = []; // empty array \n // loop though array \n for(let i = 0; i < array.length; i++) {\n const result = callback(array[i], i, array); \n // push the current element if result is true \n if(result)\n filterArr.push(array[i]); \n } \n return filterArr;\n}",
"function tripleAndFilter(arr){\n return arr.map(function(value){\n return value * 3;\n }).filter(function(value){\n return value % 5 === 0;\n })\n }",
"function myFilter(arr) {\n var newArr = [];\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) { // An even number from the array (arr)\n newArr.push(arr[i]);\n }\n }\n\n return newArr;\n}",
"function filterMult(array1, array2)\n\t{\n\tvar nn1 = arrayDimension(array1);\n\tvar nn2 = arrayDimension(array2);\n\t\n\tvar ndim1 = nn1.length;\n\tvar ndim2 = nn2.length;\n\tif ((ndim1 !== 1) || (ndim2 !== 1))\n\t\tthrow \"Arrays must be in universal format!\";\n\n\tvar length1 = nn1[0];\n\tvar length2 = nn2[0];\n\tif (length1 !== length2) throw \"Arrays must have same length!\";\n\t\n\tvar output = Array(length1)\n\t\n\tvar a1r = 0; // array 1 real\n\tvar a1i = 0; // array 1 imaginary\n\tvar a2r = 0; // array 2 real\n\tvar a2i = 0; // array 2 imaginary\n\n\tfor (var i = 0; i < length1; i += 2)\n\t\t{\n\t\ta1r = array1[i];\n\t\ta1i = array1[i+1];\n\t\t\n\t\ta2r = array2[i];\n\t\ta2i = array2[i+1];\n\t\t\n\t\toutput[i] = a1r*a2r - a1i*a2i;\n\t\toutput[i+1] = a1i*a2r + a1r*a2i;\n\t\t};\n\treturn output;\n\t}",
"function destroyer(arr) {\n \n for (var i = 1; i < arguments.length; i++)\n arr = arr.filter(notEqual, arguments[i]);\n \n return arr;\n}",
"function filter (vals, array) {\n if( Array.isArray( vals ) && Array.isArray( array ) ) {\n let tmp = array.slice();\n vals.forEach( function (val) {\n while( tmp.indexOf(val) > -1 ) {\n tmp.splice( tmp.indexOf(val), 1 );\n }\n });\n return tmp;\n }\n // pass along whatever we got, since our arguments aren't right.\n return array;\n }",
"function filter(arr, glob) {\n return glob ? micromatch(arr, glob) : arr;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function hides the previous word, displays the current word, and records click times | function doTimer(words, clickTimes, divWords, prevTime, divInstr) {
// set the timer
var currTime = new Date().getTime();
var elapseTime = currTime - prevTime;
prevTime = currTime;
if(counter > 0) {
var prevWordIndex = counter-1;
var prevWord = document.getElementById("word"+prevWordIndex);
prevWord.style.display = "none";
// record how long the reader looked at the previous word
clickTimes[prevWordIndex] = elapseTime;
}
if(counter == words.length) {
for(var i = 0; i < words.length; i++) {
results += words[i] + " " + clickTimes[i] + "<br>";
}
return prevTime;
}
if(counter <= words.length) {
var word = document.getElementById("word"+counter);
word.style.display = "block";
}
counter++;
return prevTime;
} | [
"function showNewWords(data, vis, spiral, new_thread) {\n vis.update(data, spiral)\n setTimeout(function() { \n \tif (new_thread || total_thread < 2) {\n \t\tshowNewWords(data, vis, spiral, false);\n \t} else {\n \t\ttotal_thread -= 1;\n \t}\n }, 3000)\n}",
"function displayOne() {\n if (curr < words.length) {\n $(\"output\").innerHTML = words[curr];\n curr++;\n } else {\n stop();\n }\n }",
"function showWord() {\n currentWord = randomWords();\n if (currentWord === null || currentWord === undefined) {\n showResult(3);\n return;\n }\n var kanji = currentWord.kanji !== \"\" ? '(' + currentWord.kanji + ')' : \"\";\n firstWord_div.text(currentWord.hira_kata + kanji);\n // reset Ctrl count\n ctrlCount = 0;\n }",
"function changeWord (index) {\n\t\tvar m = index.shift()\n\t\t$(\"#sentenceWord\").html(sentences[m])\n\t\t$(\"#wordButton\").show()\n\t\tif (index.length == 0) {\n\t\t $(\"#wordButton\").hide()\n\t\t}\n\t }",
"function prevQuestion(){\n if (showCount > 0) {\n showCount--;\n }\n display(\"questionCat\", capitalise(memory[showCount].category));\n display(\"questionDisplay\", memory[showCount].question);\n}",
"function hide_hint() {\n if ($scope.game_phase != 'not_yet_started') {\n var e = document.getElementById(\"hint_place\");\n e.style.lineHeight = \"18px\";\n e.innerHTML = '<font size=\"4px\" color=\"silver\"><p style=\"margin-bottom:5px;\">Spell a word that stands for following meaning</font><br/></p><font size=\"5px\" color=\"white\">' + $scope.words[$scope.current_word_index].mean + '</font><font color=\"#e1e1e1\" size=\"4px\"><br/><div id=\"show_hint_div class=\"show_word_box\"> <button id=\"show_word_box\" type=\"button\" class=\"btn btn-warning btn-lg show_word_box\" onclick=\"show_hint_up(1.5);\" onmouseover=\"show_hint_up(1.5);\"><font size=\"4px><span class=\"glyphicon glyphicon-info-sign\" ></span><font color=\"#2E2E2E\">Find your word here...</font></font></button></div>';\n $scope.flip(e, \"hint\");\n\n }\n }",
"function changeText() {\r\n if (start_stop==0) {\r\n story();\r\n }\r\n }",
"function changeWords() {\n // console.log('changing words ' + idx);\n topWords.innerHTML = topSayings[idx];\n bottom.innerHTML = bottomSayings[idx];\n // signup.innerHTML = signupSayings[idx];\n // idxIterator();\n setTimeout(fadeInLeft, 10);\n // return idx;\n }",
"function TXbtnClicked() {\n if (display.innerHTML.split(\" \")[0] == selectedWordData.frequency) {\n moduleDone()\n } else {\n wrongClick()\n }\n }",
"function hideText() {\n\t\t$(\"#text\").toggle(text_effect, function() {\n\t\t\t// Next line and toggle/show.\n\t\t\t//\n\t\t\t$(\"#text\").html(text[line_count++]);\n\t\t\t\n\t\t\trandomiseTextPos();\n\t\t});\n\t}",
"function text_clicked(event) {\n\t var ranges = CKEDITOR.instances.trans_editor.getSelection().getRanges();\n\t var text = CKEDITOR.instances.trans_editor.getSelection().getSelectedText();\n\t var element = CKEDITOR.instances.trans_editor.getSelection().getStartElement();\n\n\t if((ranges[0] != undefined) || (ranges[0] != null)) {\n\t\t var selection_length = (ranges[0].endOffset - ranges[0].startOffset);\n\t\t // User can click on a time marker\n\t\t if(selection_length == 0) {\n\t\t\t if (element.getName() == 'time' ) {\n\t\t\t\t var mark = $('<p>' + element.getOuterHtml() + '</p>').find('time:first').attr('type');\n\t\t\t\t if(mark != null) {\n\t\t\t\t\t var goto_time = $('<p>' + element.getOuterHtml() + '</p>').find('time:first').attr('datetime');\n\t\t\t\t\t var duration = wavesurfer.getDuration();\n\t\t\t\t\t wavesurfer.seekAndCenter(goto_time / duration);\n\t\t\t\t }\n\t\t\t }\n\t // User has selected a word\n\t\t } else { \n\t\t\t var node = ranges[0];\n\t\t\t var pnode = node.startContainer.getParent();\n\t\t\t if (pnode.getName() == 'time' ) {\n\t\t\t\t var goto_time = $('<p>' + pnode.getOuterHtml() + '</p>').find('time:first').attr('datetime');\n\t\t\t\t var duration = wavesurfer.getDuration();\n\t\t\t\t wavesurfer.seekAndCenter(goto_time / duration);\n\t\t\t }\n\t\t\t else if(pnode.getName() == \"conf\") {\n\t\t\t\t pnode = pnode.getParent();\n\t\t\t\t var goto_time = $('<p>' + pnode.getOuterHtml() + '</p>').find('time:first').attr('datetime');\n\t\t\t\t var duration = wavesurfer.getDuration();\n\t\t\t\t wavesurfer.seekAndCenter(goto_time / duration);\n\t\t\t }\n\t\t }\n\t }\n }",
"function toggleWordCount() {\n wordCount = !wordCount;\n Cookie.set('wordCount', wordCount + '');\n\n $('#word-count').prop('hidden', !wordCount);\n\n updateToolbar();\n }",
"function show_tooltip(selection, word, event){\n /*making extra sure that no more than one tooltip is visible at a time */\n let not_found = false;\n hide_tooltip();\n \n px = x;\n py = y-160;\n /* getting accurate x & y in case of double tap */\n if(event != undefined){\n px = event.clientX; // Get the horizontal coordinate\n py = event.clientY; // Get the vertical coordinate\n }\n \n //let word = get_meaning(selection);\n console.log(\"------ Back to show tooltip -------\");\n console.log(word);\n console.log(\"-----------------------------------\");\n let text = document.createElement(\"div\");\n let strong = document.createElement(\"strong\");\n let textNode = document.createTextNode(selection);\n let meanings = document.createElement(\"ol\");\n let save_buttons = document.createElement(\"span\");\n let i=1;\n\n if(word.meanings.length <= 0){\n not_found = true;\n }\n \n if(not_found){\n meanings.appendChild(document.createTextNode(\"Definition not Found!!\"));\n let googleit = document.createElement(\"a\");\n googleit.appendChild(document.createTextNode(\"'google it'\"));\n googleit.setAttribute(\"target\", \"_blank\");\n googleit.setAttribute(\"id\", \"more-info\");\n googleit.setAttribute(\"href\", \"http://google.com/search?q=define \"+word.word);\n save_buttons.appendChild(googleit);\n }else{\n for(let meaning of word.meanings){\n //console.log(meaning);\n let li = document.createElement(\"li\");\n let partOfSpeech = document.createTextNode(\"[\"+meaning.partOfSpeech +\"] \"); \n let meaning_text = document.createTextNode(meaning.text);\n li.appendChild(partOfSpeech);\n li.appendChild(meaning_text);\n meanings.appendChild(li);\n if(i == 4){\n break;\n }\n i++;\n }\n let easy = document.createElement(\"button\");\n let medium = document.createElement(\"button\");\n let difficult = document.createElement(\"button\");\n let moreinfo = document.createElement(\"a\");\n moreinfo.appendChild(document.createTextNode(\"more..\"));\n moreinfo.setAttribute(\"target\", \"_blank\");\n moreinfo.setAttribute(\"id\", \"more-info\");\n moreinfo.setAttribute(\"href\", \"http://wordbook.com/\"+word.language+\"/\"+word.word);\n\n easy.addEventListener('click', save_word, false);\n medium.addEventListener('click', save_word, false);\n difficult.addEventListener('click', save_word, false);\n \n easy.appendChild(document.createTextNode(\"Easy\"));\n medium.appendChild(document.createTextNode(\"Medium\"));\n difficult.appendChild(document.createTextNode(\"Difficult\"));\n\n easy.setAttribute(\"difficulty\", \"easy\");\n medium.setAttribute(\"difficulty\", \"medium\");\n difficult.setAttribute(\"difficulty\", \"difficult\");\n\n save_buttons.appendChild(easy);\n save_buttons.appendChild(medium);\n save_buttons.appendChild(difficult) \n save_buttons.appendChild(moreinfo);\n }\n\n strong.appendChild(textNode);\n text.appendChild(strong);\n text.appendChild(meanings);\n text.appendChild(save_buttons);\n text.id = \"wordbook-tooltip\";\n text.style.position = \"absolute\";\n text.style.left = px+\"px\";\n text.style.top = (py+document.documentElement.scrollTop)+\"px\";\n document.body.appendChild(text);\n tooltip_visible = true;\n}",
"function showNewWords(vis, words) {\n vis.update(words)\n}",
"function doShowText(textNum)\n{\n\tpreviousClickedHotspot = textNum;\n\tvar allClicked = (hotTypeOnThisTab[currentTab] == HOTGRAPHIC) ? allHotGraphicsClicked : allHotTextClicked;\n\tvar instruction = (allClicked) ? instructionToShowOnComplete() : eval(\"tab\" + currentTab + \"theInitialInstructionText\");\n\n\tdisplayTextArray = eval(\"tab\" + currentTab + \"displayTextArray\");\n\tvar textToDisplay = displayTextArray[textNum];\n\n\tif (typeof textToDisplay == \"undefined\")\n\t{\n\t\ttextToDisplay = \"\";\n\t}\n\t\n\tif (hotTypeOnThisTab[currentTab] == HOTTEXT)\n\t{\t\t\n\t\tgraphicsInFeedback = eval(\"tab\" + currentTab + \"GraphicsInFeedback\");\n\t\tif (graphicsInFeedback)\n\t\t{\n\t\t\tgraphicFileNameArray = eval(\"tab\" + currentTab + \"graphicFileNameArray\");\n\t\t\tif(graphicFileNameArray[textNum])\n\t\t\t{\n\t\t\t\ttextToDisplay = \"<p><img border=\\\"0\\\" src=\\\"images/\" + graphicFileNameArray[textNum] + \"\\\"></p>\" + textToDisplay;\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\n\tif ((hotTypeOnThisTab[currentTab] == HOTGRAPHIC) && (!allClicked))\n\t{\n\t\ttextToDisplay += \"<span class=\\\"instructionText\\\" > \" + instruction + \"</span>\";\n\t}\n\n\tif (allClicked)\n\t{\n\t\ttextToDisplay += \"<span class=\\\"instructionText\\\" > \" + instruction + \"</span>\";\n\t\tdocument.getElementById(\"tab\" + currentTab + \"initialInstructionText\").style.visibility = \"hidden\";\n\n\t\tif (document.getElementById(\"initialInstructionText\"))\n\t\t\tdocument.getElementById(\"initialInstructionText\").style.visibility = \"hidden\";\n\t}\n\n\n\tif (eval('tab' + currentTab + 'displayTextOverwritesInitialText'))\n\t{\n\n\t\tdocument.getElementById(\"tab\" + currentTab + \"initialTextLayer\").style.visibility = \"hidden\";\n\t\t//document.getElementById(\"tab\" + currentTab + \"initialTextWithoutInstructionLayer\").style.visibility = \"visible\";\n\t\t//document.getElementById(\"tab\" + currentTab + \"initialTextLayer\").style.visibility = \"hidden\";\n\t}\n\t\n\t\n\tdocument.getElementById(\"tab\" + currentTab + \"displayTextArea\").innerHTML = textToDisplay;\n\n\tif(hotTypeOnThisTab[currentTab] == HOTTEXT)\n\t{\n\t\thighlightHotText(textNum);\n\t}\n\n\treturn;\n}",
"function addNextWord() {\n\t\t\t\tvar nextWord = myWords.pop();\n\t\t\t\tif(nextWord != undefined) {\n\t\t\t\t\tvar textNow = $(\"#introText\").text() + \" \" + nextWord;\n\t\t\t\t\t$(\"#introText\").text(textNow);\n\t\t\t\t}\n\t\t\t\tif(nextWord == \"fun!\"){\n\t\t\t\t\t$('#intro').fadeOut(700);\n\t\t\t\t}\n\t\t\t}",
"function dashes(){\r\n document.getElementById('word').innerHTML = '';\r\n for (var i = 0; i < guesses.length; i++)\r\n document.getElementById('word').innerHTML += guesses[i] + ' ';\r\n document.getElementById('start').style.visibility = \"hidden\";\r\n}",
"function update_word_count()\n \t\t{\n \t\t\tvar e=document.getElementById(\"div_rb_counter\");\n \t\t\tflip(e,\"word_conter\");\n \t\t\te.innerHTML='<font color=\"gray\" size=\"3px\">Word</font><font size=\"6px\" color=\"#404040\"> '+current_word_number+'</font><font size=\"5px\" color=\"gray\">/'+word_list.length+'</font></div>';\n \t\t}",
"function displayWord() {\n for (i = 0; i < word.length; i++) {\n hiddenWord += \"_\";\n }\n document.getElementById(\"word\").innerHTML = hiddenWord;\n document.getElementById('tries').innerHTML = 'Lives: ' + count;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for duplicate MD5 digest | function duplicate_md5(md5)
{
print("Searching for duplicate file (via MD5 digest)");
var md5_file=new File(attachment_dir + "md5.lst");
if(!md5_file.open("r"))
return(null);
var duplicate=false;
var str;
while(!md5_file.eof && !duplicate) {
str=md5_file.readln();
if(str==null)
break;
if(str.substr(0,32)==md5)
duplicate=true;
}
md5_file.close();
return(str);
} | [
"function md5(text) {\n\treturn text && text.match(/[0-9a-f]{32}/i);\n}",
"digest() {\n return crypto\n .createHash(\"md5\")\n .update(JSON.stringify(this, (key, val) =>\n val instanceof Set ? [...val].sort() : val))\n .digest(\"hex\");\n }",
"md5(input) {\n return md5(input)\n }",
"function MD5(s) {function L(k,d){return(k<<d)|(k>>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H<F){Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=(aa[Z]| (G.charCodeAt(H)<<d));H++}Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=aa[Z]|(128<<d);aa[I-2]=F<<3;aa[I-1]=F>>>29;return aa}function B(x){var k=\"\",F=\"\",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F=\"0\"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,\"n\");var d=\"\";for(var F=0;F<k.length;F++){var x=k.charCodeAt(F);if(x<128){d+=String.fromCharCode(x)}else{if((x>127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P<C.length;P+=16){h=Y;E=X;v=W;g=V;Y=u(Y,X,W,V,C[P+0],S,3614090360);V=u(V,Y,X,W,C[P+1],Q,3905402710);W=u(W,V,Y,X,C[P+2],N,606105819);X=u(X,W,V,Y,C[P+3],M,3250441966);Y=u(Y,X,W,V,C[P+4],S,4118548399);V=u(V,Y,X,W,C[P+5],Q,1200080426);W=u(W,V,Y,X,C[P+6],N,2821735955);X=u(X,W,V,Y,C[P+7],M,4249261313);Y=u(Y,X,W,V,C[P+8],S,1770035416);V=u(V,Y,X,W,C[P+9],Q,2336552879);W=u(W,V,Y,X,C[P+10],N,4294925233);X=u(X,W,V,Y,C[P+11],M,2304563134);Y=u(Y,X,W,V,C[P+12],S,1804603682);V=u(V,Y,X,W,C[P+13],Q,4254626195);W=u(W,V,Y,X,C[P+14],N,2792965006);X=u(X,W,V,Y,C[P+15],M,1236535329);Y=f(Y,X,W,V,C[P+1],A,4129170786);V=f(V,Y,X,W,C[P+6],z,3225465664);W=f(W,V,Y,X,C[P+11],y,643717713);X=f(X,W,V,Y,C[P+0],w,3921069994);Y=f(Y,X,W,V,C[P+5],A,3593408605);V=f(V,Y,X,W,C[P+10],z,38016083);W=f(W,V,Y,X,C[P+15],y,3634488961);X=f(X,W,V,Y,C[P+4],w,3889429448);Y=f(Y,X,W,V,C[P+9],A,568446438);V=f(V,Y,X,W,C[P+14],z,3275163606);W=f(W,V,Y,X,C[P+3],y,4107603335);X=f(X,W,V,Y,C[P+8],w,1163531501);Y=f(Y,X,W,V,C[P+13],A,2850285829);V=f(V,Y,X,W,C[P+2],z,4243563512);W=f(W,V,Y,X,C[P+7],y,1735328473);X=f(X,W,V,Y,C[P+12],w,2368359562);Y=D(Y,X,W,V,C[P+5],o,4294588738);V=D(V,Y,X,W,C[P+8],m,2272392833);W=D(W,V,Y,X,C[P+11],l,1839030562);X=D(X,W,V,Y,C[P+14],j,4259657740);Y=D(Y,X,W,V,C[P+1],o,2763975236);V=D(V,Y,X,W,C[P+4],m,1272893353);W=D(W,V,Y,X,C[P+7],l,4139469664);X=D(X,W,V,Y,C[P+10],j,3200236656);Y=D(Y,X,W,V,C[P+13],o,681279174);V=D(V,Y,X,W,C[P+0],m,3936430074);W=D(W,V,Y,X,C[P+3],l,3572445317);X=D(X,W,V,Y,C[P+6],j,76029189);Y=D(Y,X,W,V,C[P+9],o,3654602809);V=D(V,Y,X,W,C[P+12],m,3873151461);W=D(W,V,Y,X,C[P+15],l,530742520);X=D(X,W,V,Y,C[P+2],j,3299628645);Y=t(Y,X,W,V,C[P+0],U,4096336452);V=t(V,Y,X,W,C[P+7],T,1126891415);W=t(W,V,Y,X,C[P+14],R,2878612391);X=t(X,W,V,Y,C[P+5],O,4237533241);Y=t(Y,X,W,V,C[P+12],U,1700485571);V=t(V,Y,X,W,C[P+3],T,2399980690);W=t(W,V,Y,X,C[P+10],R,4293915773);X=t(X,W,V,Y,C[P+1],O,2240044497);Y=t(Y,X,W,V,C[P+8],U,1873313359);V=t(V,Y,X,W,C[P+15],T,4264355552);W=t(W,V,Y,X,C[P+6],R,2734768916);X=t(X,W,V,Y,C[P+13],O,1309151649);Y=t(Y,X,W,V,C[P+4],U,4149444226);V=t(V,Y,X,W,C[P+11],T,3174756917);W=t(W,V,Y,X,C[P+2],R,718787259);X=t(X,W,V,Y,C[P+9],O,3951481745);Y=K(Y,h);X=K(X,E);W=K(W,v);V=K(V,g)}var i=B(Y)+B(X)+B(W)+B(V);return i.toLowerCase()}",
"getMD5Hash() {\n return __awaiter(this, void 0, void 0, function* () {\n return \"\";\n });\n }",
"function getHash(string) {\r\n return crypto.createHash('md5').update(string).digest('hex');\r\n}",
"function makeMD5(input) {\n var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);\n var txtHash = '';\n for (i = 0; i < rawHash.length; i++) {\n var hashVal = rawHash[i];\n if (hashVal < 0) {\n hashVal += 256;\n }\n if (hashVal.toString(16).length == 1) {\n txtHash += '0';\n }\n txtHash += hashVal.toString(16);\n }\n return txtHash;\n}",
"function confirmIdenticalByDigest (item) {\n const digest = utils.digest(JSON.stringify(item), DIGEST_ALGORITHM, false)\n\n const nmParams = pgu.getNamedParametersForItem(item)\n delete nmParams.item\n nmParams.DIGEST_ALGORITHM = DIGEST_ALGORITHM\n\n // watch camelcase for __sourcetype NOT __sourceType,\n // also ES6 templates use ${var}, helper can use {}, (), [], <>, //\n const sql =\n `SELECT encode(digest(item::text, $[DIGEST_ALGORITHM]), 'hex') as digest\n FROM items\n WHERE __user=$[__user] AND __stamp=$[__stamp]\n AND __type=$[__type] AND uuid=$[uuid]\n AND __sourcetype=$[__sourcetype]`\n\n return pgu.db.oneOrNone(sql, nmParams)\n .then(result => {\n if (result === null || !result.digest) {\n return false\n }\n var dbdigest = result.digest\n var isIdentical = digest === dbdigest\n if (!isIdentical) {\n // TODO(daneroo): should probably throw if the key exists, but the digest is wrong\n let vals = Object.keys(nmParams).map(k => nmParams[k])\n log.verbose('Failed duplicate digest check', vals.join('/'))\n log.verbose('-', digest)\n log.verbose('+', dbdigest)\n } else {\n // let vals = Object.keys(nmParams).map(k=>nmParams[k]);\n // log.verbose('Checked that digest is identical', vals.join('/'), digest);\n }\n return isIdentical\n })\n}",
"function md5Hash(str) {\n return (0, crypto_1.createHash)('md5').update(str).digest('hex');\n}",
"function md5sumFile(filename){\n var match,\n re = /([a-zA-Z0-9]{32}).*/,\n bin = \"md5sum\"\n\n if(process.platform === \"win32\") {\n bin = \"md5\"\n }\n\n response = helpers.call(bin, [filename]).toString()\n match = response.match(re)\n return match[1]\n}",
"static computeMD5(path) {\n return new Promise((resolve, reject) => {\n let hash = crypto_1.createHash('md5');\n fs_1.createReadStream(path)\n .on('data', data => hash.update(data, 'utf8'))\n .on('end', () => resolve(hash.digest('hex'))) // md5 checksum\n .on('error', reject);\n });\n }",
"function md5(inputString) {\n var hc=\"0123456789abcdef\";\n function rh(n) {var j,s=\"\";for(j=0;j<=3;j++) s+=hc.charAt((n>>(j*8+4))&0x0F)+hc.charAt((n>>(j*8))&0x0F);return s;}\n function ad(x,y) {var l=(x&0xFFFF)+(y&0xFFFF);var m=(x>>16)+(y>>16)+(l>>16);return (m<<16)|(l&0xFFFF);}\n function rl(n,c) {return (n<<c)|(n>>>(32-c));}\n function cm(q,a,b,x,s,t) {return ad(rl(ad(ad(a,q),ad(x,t)),s),b);}\n function ff(a,b,c,d,x,s,t) {return cm((b&c)|((~b)&d),a,b,x,s,t);}\n function gg(a,b,c,d,x,s,t) {return cm((b&d)|(c&(~d)),a,b,x,s,t);}\n function hh(a,b,c,d,x,s,t) {return cm(b^c^d,a,b,x,s,t);}\n function ii(a,b,c,d,x,s,t) {return cm(c^(b|(~d)),a,b,x,s,t);}\n function sb(x) {\n var i;var nblk=((x.length+8)>>6)+1;var blks=new Array(nblk*16);for(i=0;i<nblk*16;i++) blks[i]=0;\n for(i=0;i<x.length;i++) blks[i>>2]|=x.charCodeAt(i)<<((i%4)*8);\n blks[i>>2]|=0x80<<((i%4)*8);blks[nblk*16-2]=x.length*8;return blks;\n }\n var i,x=sb(inputString),a=1732584193,b=-271733879,c=-1732584194,d=271733878,olda,oldb,oldc,oldd;\n for(i=0;i<x.length;i+=16) {olda=a;oldb=b;oldc=c;oldd=d;\n a=ff(a,b,c,d,x[i+ 0], 7, -680876936);d=ff(d,a,b,c,x[i+ 1],12, -389564586);c=ff(c,d,a,b,x[i+ 2],17, 606105819);\n b=ff(b,c,d,a,x[i+ 3],22,-1044525330);a=ff(a,b,c,d,x[i+ 4], 7, -176418897);d=ff(d,a,b,c,x[i+ 5],12, 1200080426);\n c=ff(c,d,a,b,x[i+ 6],17,-1473231341);b=ff(b,c,d,a,x[i+ 7],22, -45705983);a=ff(a,b,c,d,x[i+ 8], 7, 1770035416);\n d=ff(d,a,b,c,x[i+ 9],12,-1958414417);c=ff(c,d,a,b,x[i+10],17, -42063);b=ff(b,c,d,a,x[i+11],22,-1990404162);\n a=ff(a,b,c,d,x[i+12], 7, 1804603682);d=ff(d,a,b,c,x[i+13],12, -40341101);c=ff(c,d,a,b,x[i+14],17,-1502002290);\n b=ff(b,c,d,a,x[i+15],22, 1236535329);a=gg(a,b,c,d,x[i+ 1], 5, -165796510);d=gg(d,a,b,c,x[i+ 6], 9,-1069501632);\n c=gg(c,d,a,b,x[i+11],14, 643717713);b=gg(b,c,d,a,x[i+ 0],20, -373897302);a=gg(a,b,c,d,x[i+ 5], 5, -701558691);\n d=gg(d,a,b,c,x[i+10], 9, 38016083);c=gg(c,d,a,b,x[i+15],14, -660478335);b=gg(b,c,d,a,x[i+ 4],20, -405537848);\n a=gg(a,b,c,d,x[i+ 9], 5, 568446438);d=gg(d,a,b,c,x[i+14], 9,-1019803690);c=gg(c,d,a,b,x[i+ 3],14, -187363961);\n b=gg(b,c,d,a,x[i+ 8],20, 1163531501);a=gg(a,b,c,d,x[i+13], 5,-1444681467);d=gg(d,a,b,c,x[i+ 2], 9, -51403784);\n c=gg(c,d,a,b,x[i+ 7],14, 1735328473);b=gg(b,c,d,a,x[i+12],20,-1926607734);a=hh(a,b,c,d,x[i+ 5], 4, -378558);\n d=hh(d,a,b,c,x[i+ 8],11,-2022574463);c=hh(c,d,a,b,x[i+11],16, 1839030562);b=hh(b,c,d,a,x[i+14],23, -35309556);\n a=hh(a,b,c,d,x[i+ 1], 4,-1530992060);d=hh(d,a,b,c,x[i+ 4],11, 1272893353);c=hh(c,d,a,b,x[i+ 7],16, -155497632);\n b=hh(b,c,d,a,x[i+10],23,-1094730640);a=hh(a,b,c,d,x[i+13], 4, 681279174);d=hh(d,a,b,c,x[i+ 0],11, -358537222);\n c=hh(c,d,a,b,x[i+ 3],16, -722521979);b=hh(b,c,d,a,x[i+ 6],23, 76029189);a=hh(a,b,c,d,x[i+ 9], 4, -640364487);\n d=hh(d,a,b,c,x[i+12],11, -421815835);c=hh(c,d,a,b,x[i+15],16, 530742520);b=hh(b,c,d,a,x[i+ 2],23, -995338651);\n a=ii(a,b,c,d,x[i+ 0], 6, -198630844);d=ii(d,a,b,c,x[i+ 7],10, 1126891415);c=ii(c,d,a,b,x[i+14],15,-1416354905);\n b=ii(b,c,d,a,x[i+ 5],21, -57434055);a=ii(a,b,c,d,x[i+12], 6, 1700485571);d=ii(d,a,b,c,x[i+ 3],10,-1894986606);\n c=ii(c,d,a,b,x[i+10],15, -1051523);b=ii(b,c,d,a,x[i+ 1],21,-2054922799);a=ii(a,b,c,d,x[i+ 8], 6, 1873313359);\n d=ii(d,a,b,c,x[i+15],10, -30611744);c=ii(c,d,a,b,x[i+ 6],15,-1560198380);b=ii(b,c,d,a,x[i+13],21, 1309151649);\n a=ii(a,b,c,d,x[i+ 4], 6, -145523070);d=ii(d,a,b,c,x[i+11],10,-1120210379);c=ii(c,d,a,b,x[i+ 2],15, 718787259);\n b=ii(b,c,d,a,x[i+ 9],21, -343485551);a=ad(a,olda);b=ad(b,oldb);c=ad(c,oldc);d=ad(d,oldd);\n }\n return rh(a)+rh(b)+rh(c)+rh(d);\n}",
"function MD5()\r\n{\r\n this.F = function(x,y,z) { return (x & y) | ((~x) & z); };\r\n this.G = function(x,y,z) { return (x & z) | (y & (~z)); };\r\n this.H = function(x,y,z) { return (x ^ y ^ z); };\r\n this.I = function(x,y,z) { return (y ^ (x | (~z))); };\r\n this.C = function(q,a,b,x,s,ac) { return this.addu(this.rol(this.addu(this.addu(a,q),this.addu(x,ac)),s),b); };\r\n this.FF = function(a,b,c,d,x,s,ac) { return this.C((b & c) | ((~b) & d),a,b,x,s,ac); };\r\n this.GG = function(a,b,c,d,x,s,ac) { return this.C((b & d) | (c & (~d)),a,b,x,s,ac); };\r\n this.HH = function(a,b,c,d,x,s,ac) { return this.C(b ^ c ^ d,a,b,x,s,ac); };\r\n this.II = function(a,b,c,d,x,s,ac) { return this.C(c ^ (b | (~d)),a,b,x,s,ac); };\r\n\r\n this.hash = function(message)\r\n {\r\n var xl,x=[],k,aa,bb,cc,dd,a=0x67452301,b=0xEFCDAB89,c=0x98BADCFE,d=0x10325476;\r\n x = this.convertToWordArray(this.utf8Encode(message));\r\n xl = x.length;\r\n for (var j = 0; j < xl; j += 16) {\r\n aa=a; bb=b; cc=c; dd=d;\r\n a=this.FF(a,b,c,d,x[j+0],7,0xD76AA478);\r\n d=this.FF(d,a,b,c,x[j+1],12,0xE8C7B756);\r\n c=this.FF(c,d,a,b,x[j+2],17,0x242070DB);\r\n b=this.FF(b,c,d,a,x[j+3],22,0xC1BDCEEE);\r\n a=this.FF(a,b,c,d,x[j+4],7,0xF57C0FAF);\r\n d=this.FF(d,a,b,c,x[j+5],12,0x4787C62A);\r\n c=this.FF(c,d,a,b,x[j+6],17,0xA8304613);\r\n b=this.FF(b,c,d,a,x[j+7],22,0xFD469501);\r\n a=this.FF(a,b,c,d,x[j+8],7,0x698098D8);\r\n d=this.FF(d,a,b,c,x[j+9],12,0x8B44F7AF);\r\n c=this.FF(c,d,a,b,x[j+10],17,0xFFFF5BB1);\r\n b=this.FF(b,c,d,a,x[j+11],22,0x895CD7BE);\r\n a=this.FF(a,b,c,d,x[j+12],7,0x6B901122);\r\n d=this.FF(d,a,b,c,x[j+13],12,0xFD987193);\r\n c=this.FF(c,d,a,b,x[j+14],17,0xA679438E);\r\n b=this.FF(b,c,d,a,x[j+15],22,0x49B40821);\r\n a=this.GG(a,b,c,d,x[j+1],5,0xF61E2562);\r\n d=this.GG(d,a,b,c,x[j+6],9,0xC040B340);\r\n c=this.GG(c,d,a,b,x[j+11],14,0x265E5A51);\r\n b=this.GG(b,c,d,a,x[j+0],20,0xE9B6C7AA);\r\n a=this.GG(a,b,c,d,x[j+5],5,0xD62F105D);\r\n d=this.GG(d,a,b,c,x[j+10],9,0x2441453);\r\n c=this.GG(c,d,a,b,x[j+15],14,0xD8A1E681);\r\n b=this.GG(b,c,d,a,x[j+4],20,0xE7D3FBC8);\r\n a=this.GG(a,b,c,d,x[j+9],5,0x21E1CDE6);\r\n d=this.GG(d,a,b,c,x[j+14],9,0xC33707D6);\r\n c=this.GG(c,d,a,b,x[j+3],14,0xF4D50D87);\r\n b=this.GG(b,c,d,a,x[j+8],20,0x455A14ED);\r\n a=this.GG(a,b,c,d,x[j+13],5,0xA9E3E905);\r\n d=this.GG(d,a,b,c,x[j+2],9,0xFCEFA3F8);\r\n c=this.GG(c,d,a,b,x[j+7],14,0x676F02D9);\r\n b=this.GG(b,c,d,a,x[j+12],20,0x8D2A4C8A);\r\n a=this.HH(a,b,c,d,x[j+5],4,0xFFFA3942);\r\n d=this.HH(d,a,b,c,x[j+8],11,0x8771F681);\r\n c=this.HH(c,d,a,b,x[j+11],16,0x6D9D6122);\r\n b=this.HH(b,c,d,a,x[j+14],23,0xFDE5380C);\r\n a=this.HH(a,b,c,d,x[j+1],4,0xA4BEEA44);\r\n d=this.HH(d,a,b,c,x[j+4],11,0x4BDECFA9);\r\n c=this.HH(c,d,a,b,x[j+7],16,0xF6BB4B60);\r\n b=this.HH(b,c,d,a,x[j+10],23,0xBEBFBC70);\r\n a=this.HH(a,b,c,d,x[j+13],4,0x289B7EC6);\r\n d=this.HH(d,a,b,c,x[j+0],11,0xEAA127FA);\r\n c=this.HH(c,d,a,b,x[j+3],16,0xD4EF3085);\r\n b=this.HH(b,c,d,a,x[j+6],23,0x4881D05);\r\n a=this.HH(a,b,c,d,x[j+9],4,0xD9D4D039);\r\n d=this.HH(d,a,b,c,x[j+12],11,0xE6DB99E5);\r\n c=this.HH(c,d,a,b,x[j+15],16,0x1FA27CF8);\r\n b=this.HH(b,c,d,a,x[j+2],23,0xC4AC5665);\r\n a=this.II(a,b,c,d,x[j+0],6,0xF4292244);\r\n d=this.II(d,a,b,c,x[j+7],10,0x432AFF97);\r\n c=this.II(c,d,a,b,x[j+14],15,0xAB9423A7);\r\n b=this.II(b,c,d,a,x[j+5],21,0xFC93A039);\r\n a=this.II(a,b,c,d,x[j+12],6,0x655B59C3);\r\n d=this.II(d,a,b,c,x[j+3],10,0x8F0CCC92);\r\n c=this.II(c,d,a,b,x[j+10],15,0xFFEFF47D);\r\n b=this.II(b,c,d,a,x[j+1],21,0x85845DD1);\r\n a=this.II(a,b,c,d,x[j+8],6,0x6FA87E4F);\r\n d=this.II(d,a,b,c,x[j+15],10,0xFE2CE6E0);\r\n c=this.II(c,d,a,b,x[j+6],15,0xA3014314);\r\n b=this.II(b,c,d,a,x[j+13],21,0x4E0811A1);\r\n a=this.II(a,b,c,d,x[j+4],6,0xF7537E82);\r\n d=this.II(d,a,b,c,x[j+11],10,0xBD3AF235);\r\n c=this.II(c,d,a,b,x[j+2],15,0x2AD7D2BB);\r\n b=this.II(b,c,d,a,x[j+9],21,0xEB86D391);\r\n a=this.addu(a,aa); b=this.addu(b,bb); c=this.addu(c,cc); d=this.addu(d,dd);\r\n }\r\n return (this.wordToHex(a)+this.wordToHex(b)+this.wordToHex(c)+this.wordToHex(d)).toLowerCase();\r\n };\r\n\r\n this.test = function()\r\n {\r\n if (this.hash('Dustin Fineout') == '8844be37f4e8b3973b48b95b0c69f0b1') {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n this.addu = function(x, y)\r\n {\r\n var ls = (x & 0xFFFF) + (y & 0xFFFF);\r\n return (((x >> 16) + (y >> 16) + (ls >> 16)) << 16) | (ls & 0xFFFF);\r\n };\r\n\r\n this.rol = function(v, s)\r\n {\r\n return (v << s) | (v >>> (32 - s));\r\n };\r\n\r\n this.utf8Encode = function(str)\r\n {\r\n return unescape(encodeURIComponent(str));\r\n };\r\n\r\n this.convertToWordArray = function(str)\r\n {\r\n var lWordCount;\r\n var lMessageLength = str.length;\r\n var lNumberOfWords_temp1=lMessageLength + 8;\r\n var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;\r\n var lNumberOfWords = (lNumberOfWords_temp2+1)*16;\r\n var lWordArray=new Array(lNumberOfWords-1);\r\n var lBytePosition = 0;\r\n var lByteCount = 0;\r\n while ( lByteCount < lMessageLength ) {\r\n lWordCount = (lByteCount-(lByteCount % 4))/4;\r\n lBytePosition = (lByteCount % 4)*8;\r\n lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount)<<lBytePosition));\r\n lByteCount++;\r\n }\r\n lWordCount = (lByteCount-(lByteCount % 4))/4;\r\n lBytePosition = (lByteCount % 4)*8;\r\n lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);\r\n lWordArray[lNumberOfWords-2] = lMessageLength<<3;\r\n lWordArray[lNumberOfWords-1] = lMessageLength>>>29;\r\n return lWordArray;\r\n };\r\n\r\n this.wordToHex = function(lValue)\r\n {\r\n var wordToHexValue=\"\",wordToHexValue_temp=\"\",lByte,lCount;\r\n for (lCount = 0;lCount<=3;lCount++) {\r\n lByte = (lValue>>>(lCount*8)) & 255;\r\n wordToHexValue_temp = \"0\" + lByte.toString(16);\r\n wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);\r\n }\r\n return wordToHexValue;\r\n };\r\n}",
"static io_getmd5(str) {\n if (window.Settings.enableLog)\n WebUtils.log(\"Web.io_getmd5({0})\".format(str));\n return WebUtils.io_getmd5(str)\n }",
"function _md5() {\n if ( typeof window.md5 === \"function\" ) {\n // The return value is the hashed fingerprint string.\n return md5( _raw() );\n }\n else {\n // If `window.md5()` isn't available, an error is thrown.\n throw \"md5 unavailable, please get it from http://github.com/wbond/md5-js/\";\n }\n }",
"function md5(m){function g(b,d,a,c,e,f,g){return h(l(h(h(b,d&a|~d&c),h(e,g)),f),d)}function i(b,d,a,c,e,f,g){return h(l(h(h(b,d&c|a&~c),h(e,g)),f),d)}function j(b,d,a,c,e,f,g){return h(l(h(h(b,d^a^c),h(e,g)),f),d)}function k(b,d,a,c,e,f,g){return h(l(h(h(b,a^(d|~c)),h(e,g)),f),d)}function h(b,d){var a=(b&65535)+(d&65535);return(b>>16)+(d>>16)+(a>>16)<<16|a&65535}function l(b,d){return b<<d|b>>>32-d}return function(b){for(var d=\"\",a,c=0;c<b.length;c++)a=b.charCodeAt(c),d+=\"0123456789abcdef\".charAt(a>>>\r\n4&15)+\"0123456789abcdef\".charAt(a&15);return d}(function(b){for(var d=Array(b.length>>2),a=0;a<d.length;a++)d[a]=0;for(a=0;a<8*b.length;a+=8)d[a>>5]|=(b.charCodeAt(a/8)&255)<<a%32;b=8*b.length;d[b>>5]|=128<<b%32;d[(b+64>>>9<<4)+14]=b;for(var b=1732584193,a=-271733879,c=-1732584194,e=271733878,f=0;f<d.length;f+=16)var l=b,m=a,n=c,o=e,b=g(b,a,c,e,d[f+0],7,-680876936),e=g(e,b,a,c,d[f+1],12,-389564586),c=g(c,e,b,a,d[f+2],17,606105819),a=g(a,c,e,b,d[f+3],22,-1044525330),b=g(b,a,c,e,d[f+4],7,-176418897),\r\ne=g(e,b,a,c,d[f+5],12,1200080426),c=g(c,e,b,a,d[f+6],17,-1473231341),a=g(a,c,e,b,d[f+7],22,-45705983),b=g(b,a,c,e,d[f+8],7,1770035416),e=g(e,b,a,c,d[f+9],12,-1958414417),c=g(c,e,b,a,d[f+10],17,-42063),a=g(a,c,e,b,d[f+11],22,-1990404162),b=g(b,a,c,e,d[f+12],7,1804603682),e=g(e,b,a,c,d[f+13],12,-40341101),c=g(c,e,b,a,d[f+14],17,-1502002290),a=g(a,c,e,b,d[f+15],22,1236535329),b=i(b,a,c,e,d[f+1],5,-165796510),e=i(e,b,a,c,d[f+6],9,-1069501632),c=i(c,e,b,a,d[f+11],14,643717713),a=i(a,c,e,b,d[f+0],20,-373897302),\r\nb=i(b,a,c,e,d[f+5],5,-701558691),e=i(e,b,a,c,d[f+10],9,38016083),c=i(c,e,b,a,d[f+15],14,-660478335),a=i(a,c,e,b,d[f+4],20,-405537848),b=i(b,a,c,e,d[f+9],5,568446438),e=i(e,b,a,c,d[f+14],9,-1019803690),c=i(c,e,b,a,d[f+3],14,-187363961),a=i(a,c,e,b,d[f+8],20,1163531501),b=i(b,a,c,e,d[f+13],5,-1444681467),e=i(e,b,a,c,d[f+2],9,-51403784),c=i(c,e,b,a,d[f+7],14,1735328473),a=i(a,c,e,b,d[f+12],20,-1926607734),b=j(b,a,c,e,d[f+5],4,-378558),e=j(e,b,a,c,d[f+8],11,-2022574463),c=j(c,e,b,a,d[f+11],16,1839030562),\r\na=j(a,c,e,b,d[f+14],23,-35309556),b=j(b,a,c,e,d[f+1],4,-1530992060),e=j(e,b,a,c,d[f+4],11,1272893353),c=j(c,e,b,a,d[f+7],16,-155497632),a=j(a,c,e,b,d[f+10],23,-1094730640),b=j(b,a,c,e,d[f+13],4,681279174),e=j(e,b,a,c,d[f+0],11,-358537222),c=j(c,e,b,a,d[f+3],16,-722521979),a=j(a,c,e,b,d[f+6],23,76029189),b=j(b,a,c,e,d[f+9],4,-640364487),e=j(e,b,a,c,d[f+12],11,-421815835),c=j(c,e,b,a,d[f+15],16,530742520),a=j(a,c,e,b,d[f+2],23,-995338651),b=k(b,a,c,e,d[f+0],6,-198630844),e=k(e,b,a,c,d[f+7],10,1126891415),\r\nc=k(c,e,b,a,d[f+14],15,-1416354905),a=k(a,c,e,b,d[f+5],21,-57434055),b=k(b,a,c,e,d[f+12],6,1700485571),e=k(e,b,a,c,d[f+3],10,-1894986606),c=k(c,e,b,a,d[f+10],15,-1051523),a=k(a,c,e,b,d[f+1],21,-2054922799),b=k(b,a,c,e,d[f+8],6,1873313359),e=k(e,b,a,c,d[f+15],10,-30611744),c=k(c,e,b,a,d[f+6],15,-1560198380),a=k(a,c,e,b,d[f+13],21,1309151649),b=k(b,a,c,e,d[f+4],6,-145523070),e=k(e,b,a,c,d[f+11],10,-1120210379),c=k(c,e,b,a,d[f+2],15,718787259),a=k(a,c,e,b,d[f+9],21,-343485551),b=h(b,l),a=h(a,m),c=h(c,\r\nn),e=h(e,o);d=[b,a,c,e];b=\"\";for(a=0;a<32*d.length;a+=8)b+=String.fromCharCode(d[a>>5]>>>a%32&255);return b}(function(b){for(var d=\"\",a=-1,c,e;++a<b.length;)c=b.charCodeAt(a),e=a+1<b.length?b.charCodeAt(a+1):0,55296<=c&&56319>=c&&56320<=e&&57343>=e&&(c=65536+((c&1023)<<10)+(e&1023),a++),127>=c?d+=String.fromCharCode(c):2047>=c?d+=String.fromCharCode(192|c>>>6&31,128|c&63):65535>=c?d+=String.fromCharCode(224|c>>>12&15,128|c>>>6&63,128|c&63):2097151>=c&&(d+=String.fromCharCode(240|c>>>18&7,128|c>>>\r\n12&63,128|c>>>6&63,128|c&63));return d}(m)))}",
"function sumBytesToMd5Hexadecimal(bytes) {\n return encodeBytesToHexadecimal(sumBytesToMd5Bytes(bytes));\n }",
"getMd5sum() {\n return this.streamInfo.slice(18, 34).toString('hex');\n }",
"function SF_FUNC_DIGEST(content)\n{\n\tvar HASH_MIN_SIZE = 512;\n\tvar HASH_SEGMENT_SIZE = 512;\n\tvar HASH_DIGEST_SIZE = 128;\n\tif(content.length <= HASH_MIN_SIZE )\n\t\treturn SF_Encrypt.crc32(content);\n\t\n\tvar segNum = Math.round(content.length / HASH_SEGMENT_SIZE);\n\t//like 1025/1024\n\tif(content.length % HASH_SEGMENT_SIZE < (HASH_SEGMENT_SIZE/2))\n\t\t++segNum;\n\t\n\tvar digestTxt = \"\";\n\tfor(var i=0;i<segNum;i++)\n\t{\n\t\tdigestTxt += i*(HASH_SEGMENT_SIZE)+ \"|\" + content.substr(i*(HASH_SEGMENT_SIZE),HASH_DIGEST_SIZE) + \"|\" ;\n\t}\n\t\n\treturn SF_FUNC_md5(digestTxt);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PROTECTED Sets a new map's dotted selection and writes it inside the map with all the dotted network elements it involves. Initially the dotted selection is not visible. It will only turn to visible while dragged. | function setMapDottedSelection() {
this.dottedSelection = new DottedSelection();
this.dottedSelection.write();
for (var i = 0; i < this.selectedNetworkElements.getLength(); i++) {
this.dottedSelection.addDottedNe(this.selectedNetworkElements.get(i));
}
} | [
"function setMapSelection() {\n\t\tthis.selectedNetworkElements = new List();\n\t\tvar oX = this.selection.getOriginX();\n\t\tvar oY = this.selection.getOriginY();\n\t\tvar fX = oX + this.selection.getFinalX();\n\t\tvar fY = oY + this.selection.getFinalY();\n\t\tfor (var i = 0; i < this.networkElements.getLength(); i++) {\n\t\t\tvar ne = this.networkElements.get(i);\n\t\t\tif (ne.x >= oX && ne.y >= oY && ne.x + ne.width <= fX && ne.y + ne.height <= fY) {\n\t\t\t\tthis.selectedNetworkElements.add(ne);\n\t\t\t\tne.select();\n\t\t\t}\n\t\t}\n\t}",
"function updateSelectedNes() {\n\t\tif (this.dottedSelection.x != 0 && this.dottedSelection.y != 0) {\n\t\t\tvar mapScL = document.getElementById(\"MAP\").scrollLeft;\n\t\t\tvar mapScT = document.getElementById(\"MAP\").scrollTop;\n\t\t\tfor (var i = 0; i < this.selectedNetworkElements.getLength(); i++) {\n\t\t\t\tvar ne = this.selectedNetworkElements.get(i);\n\t\t\t\tif (this.dottedSelection.isHidden()) {\n\t\t\t\t\tne.allocate(ne.x + this.dottedSelection.x + mapScL, ne.y + this.dottedSelection.y + mapScT);\n\t\t\t\t} else {\n\t\t\t\t\tne.allocate(ne.x + this.dottedSelection.x - BORDER_WH + mapScL, ne.y + this.dottedSelection.y - BORDER_WH + mapScT);\n\t\t\t\t}\n\t\t\t\tif (ne.miniNE != null) {\n\t\t\t\t\tne.miniNE.writeMiniNetworkElement(ne);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (var i = 0; i < this.selectedNetworkElements.getLength(); i++) {\n\t\t\t\tthis.selectedNetworkElements.get(i).updatePorts();\n\t\t\t}\n\t\t}\n\t\tthis.dottedSelection.release();\n\t\tthis.setDottedSelection();\n\t}",
"function setSelectionHexagonVisbility(visible:boolean){\n\tselectionHexagon.renderer.enabled = visible;\n}",
"function writeSelection() {\n\t\tvar rect = document.createElement(\"v:rect\");\n\t\trect.setAttribute(\"id\", SELECTION);\n\t\tvar elem = document.getElementById(MAP).appendChild(rect);\n\t\telem.style.position = \"absolute\";\n\t\telem.style.zIndex = 15;\n\t\telem.style.visibility = \"hidden\";\n\t\telem.style.cursor = \"crosshair\";\n\t\telem.fill.type = \"solid\";\n\t\telem.fill.color = \"#003366\";\n\t\telem.fill.opacity = \"20%\";\n\t\telem.strokeColor = \"#003366\";\n\t\trect = document.createElement(\"v:rect\");\n\t\trect.setAttribute(\"id\", \"overglass\");\n\t\tvar elem = document.body.appendChild(rect);\n\t\telem.style.position = \"absolute\";\n\t\telem.style.top = 0;\n\t\telem.style.left = document.body.clientWidth - this.minimapSide;\n\t\telem.style.width = this.minimapSide;\n\t\telem.style.height = document.body.clientHeight;\n\t\telem.style.zIndex = 150;\n\t\telem.style.visibility = \"hidden\";\n\t\telem.style.cursor = \"crosshair\";\n\t\telem.fill.type = \"solid\";\n\t\telem.fill.color = \"#003366\";\n\t\telem.fill.opacity = \"0%\";\n\t\telem.stroked = \"false\";\n\t}",
"setVisibleOnMap(visible) {\n //Render Route on Map\n this.editLineOptions({ visible: visible });\n }",
"function writeDottedSelection() {\n\t\tthis.writeMainSpan();\n\t}",
"updateSelection() {\n\t\tlet x = this.selectionTL.x * this.owner.config.TileSize - this.viewport.x;\n\t\tlet y = this.selectionTL.y * this.owner.config.TileSize - this.viewport.y;\n\t\tlet x2 = (this.selectionBR.x + 1) * this.owner.config.TileSize - this.viewport.x;\n\t\tlet y2 = (this.selectionBR.y + 1) * this.owner.config.TileSize - this.viewport.y;\n\t\tif ((x2 < 0) || (y2 < 0) || (x > this.owner.config.editmapWidth) || (y > this.owner.config.editmapHeight)) {\n\t\t\tthis.selection.setVisible(false);\n\t\t\treturn;\n\t\t} else {\n\t\t\tthis.selection.setVisible(true)\n\t\t}\n\n\t\tif (x < 0) x = 0;\n\t\tif (y < 0) y = 0;\n\t\tif (x2 > this.owner.config.editmapWidth)\n\t\t\tx2 = this.owner.config.editmapWidth;\n\t\tif (y2 > this.owner.config.editmapHeight)\n\t\t\ty2 = this.owner.config.editmapHeight;\n\n\t\tlet w = x2 - x;\n\t\tlet h = y2 - y;\n\n\t\tlet pos = new SLLRectangle(x,y,w,h);\n\t\tthis.selection.adjustPosition(pos);\n\t}",
"_saveDotPositions() {\n let data = _.map(this.context.getSelection(), dot => {\n let position = this.scale.toSteps($(dot).data(\"position\"));\n return {\n dot: $(dot).data(\"dot\"),\n x: roundSmall(position.x),\n y: roundSmall(position.y),\n };\n });\n this.controller.doAction(\"moveDotsTo\", [data]);\n }",
"function DottedSelection() {\n\t\tthis.id = DOTTED_SEL;\n\t\tthis.x = 0;\n\t\tthis.y = 0;\n\t\tthis.minimumDottedX = null;\n\t\tthis.minimumDottedY = null;\n\t\tthis.write = writeDottedSelection;\n\t\tthis.writeMainSpan = writeDottedMainSpan;\n\t\tthis.list = new List();\n\t\tthis.addDottedNe = addDottedNeToList;\n\t\tthis.hide = hideDottedSelection;\n\t\tthis.show = showDottedSelection;\n\t\tthis.isHidden = isDottedSelectionHidden;\n\t\tthis.allocate = allocateDottedSelection;\n\t\tthis.release = releaseDottedSelection;\n\t}",
"function addNeToMapSelection(ne) {\n\t\tif (this.selectedNetworkElements == null) {\n\t\t\tthis.selectedNetworkElements = new List();\n\t\t}\n\t\tif (this.dottedSelection == null) {\n\t\t\tthis.dottedSelection = new DottedSelection();\n\t\t\tthis.dottedSelection.write();\n\t\t}\n\t\tthis.selectedNetworkElements.add(ne);\n\t\tne.select();\n\t\tthis.dottedSelection.addDottedNe(ne);\n\t}",
"function showDottedSelection() {\n\t\tdocument.getElementById(this.id).style.visibility = \"visible\";\n\t}",
"function enablePointSelection(){\r\n\taddPointMode = true;\r\n}",
"function allocateDottedSelection(x, y) {\n\t\tvar minX = this.minimumDottedX * (-1) + BORDER_WH - document.getElementById(MAP).scrollLeft;\n\t\tvar minY = this.minimumDottedY * (-1) + BORDER_WH - document.getElementById(MAP).scrollTop;\n\t\tthis.x = eval(x) < minX ? minX : eval(x);\n\t\tthis.y = eval(y) < minY ? minY : eval(y);\n\t\tdocument.getElementById(this.id).style.pixelLeft = this.x;\n\t\tdocument.getElementById(this.id).style.pixelTop = this.y;\n\t}",
"enableCoordinates() {\n let lines = document.getElementsByClassName('graph-dot-coordinates');\n for (let i = 0; i < lines.length; i++) {\n lines[i].style.display = 'block';\n }\n }",
"function writeDottedNE() {\n\t\tvar dotsp = document.createElement(\"span\");\n\t\tvar elem = document.getElementById(DOTTED_SEL).appendChild(dotsp);\n\t\telem.style.position = \"absolute\";\n\t\telem.style.left = this.x;\n\t\telem.style.top = this.y;\n\t\telem.style.width = this.width;\n\t\telem.style.height = this.height;\n\t\telem.style.zIndex = 6;\n\t\telem.style.borderWidth = \"thin\";\n\t\telem.style.borderStyle = \"dotted\";\n\t\telem.style.borderColor = \"#003366\";\n\t\telem.style.cursor = \"move\";\n\t}",
"function limpiarSeleccion() {\n \"use strict\";\n\n map.setView(new L.LatLng(4.5, -73.0), 6);\n map.eachLayer(function (layer) {\n map.removeLayer(layer);\n });\n map.addLayer(positron);\n map.addLayer(positronLabels);\n map.addLayer(NodosLayer);\n}",
"static set visibleLayers(value) {}",
"draw(selection) {\n let self = this;\n self.data = selection.datum();\n if (!self.properties.width) self.properties.width = selection.node().getBoundingClientRect().width;\n if (!self.properties.height) self.properties.height = self.properties.width / 1.92;\n if (!self.properties.scale) self.properties.scale = self.properties.width / 5.4;\n if (!self.properties.translate) self.properties.translate = [self.properties.width / 2, self.properties.height / 2];\n self.svg = selection.append('svg').attr('width', self.properties.width).attr('height', self.properties.height);\n self.svg.append('rect').attr('class', 'background').attr('width', self.properties.width).attr('height', self.properties.height).on('click', self.clicked.bind(self)); // Set map projection and path.\n\n let proj = self.properties.projection().scale(self.properties.scale).translate(self.properties.translate).precision(.1); // Not every projection supports rotation, e. g. albersUsa does not.\n\n if (proj.hasOwnProperty('rotate') && self.properties.rotate) proj.rotate(self.properties.rotate);\n self.path = d3Geo.geoPath().projection(proj);\n\n const drawGeoData = geo => {\n self.geo = geo;\n self.svg.append('g').attr('class', 'units zoom').selectAll('path').data(topojson.feature(geo, geo.objects[self.properties.units]).features).enter().append('path').attr('class', d => 'unit ' + this.properties.unitPrefix + self.unitName(d.properties)).attr('d', self.path).on('click', self.clicked.bind(self)).append('title').text(self.properties.unitTitle);\n self.update();\n };\n\n Promise.resolve().then(() => {\n if (self.properties.geoData) {\n return self.properties.geoData;\n }\n\n return d3Fetch.json(self.properties.geofile);\n }).then(geo => drawGeoData(geo));\n }",
"function initMap() {\n\n vis.svg = d3.select(\"#map-main\")\n .attr(\"width\", vis.width)\n .attr(\"height\", vis.height)\n\n vis.svg.append(\"rect\")\n .attr(\"id\", \"map-background\")\n .attr(\"class\", \"background\")\n .attr(\"width\", vis.width)\n .attr(\"height\", vis.height)\n .on(\"click\", handle_map_unselect_district)\n\n vis.map = vis.svg.append(\"g\")\n .attr(\"id\", \"map-elements\")\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets current key to the clicked photo and renders the image on main display | onClickPhoto(imgKey) {
this.setState({current: Number(imgKey)})
} | [
"imageClicked(imgIndex){\n\t\tvar newImageSrc = this.getNewCurrentImage(this.state.isCharacterizedViewEnabled, imgIndex);\t\t//Retrieve the new current image to be displayed on screen\n\t\tthis.setState({ currentImageIdx: imgIndex, currentImageSrc: newImageSrc });\t\t\t\t\t\t//Set new component state and re-render the DOM \n\t}",
"imageClicked(imgIndex) {\n\t\tvar newImageSrc = this.getNewCurrentImage(this.state.isCharacterizedViewEnabled, imgIndex); //Retrieve the new current image to be displayed on screen\n\t\tthis.setState({ currentImageIdx: imgIndex, currentImageSrc: newImageSrc }); //Set new component state and re-render the DOM \n\t}",
"function showSelectedPicture(e) {\n const oldImgNumber = currentImgNumber;\n const amountImages = images.length;\n\n /* change current image number */\n switch (e.keyCode) {\n case RIGHT:\n currentImgNumber = ++currentImgNumber % amountImages;\n break;\n case LEFT:\n currentImgNumber = (currentImgNumber + amountImages - 1) % amountImages;\n }\n\n showCurrentImg(currentImgNumber, oldImgNumber);\n}",
"imageSelected() {\n this.props.displayCallback(this.state.imageURL, this.state.parentAlbum, this.state.editHistory);\n }",
"function photoDisplayed() {\n $('#photo').attr(\"src\", mImages[mCurrentIndex].location);\n $('.location').text('Location: ' + mImages[mCurrentIndex].image);\n $('.description').text('Description: ' + mImages[mCurrentIndex].description);\n $('.date').text('Date: ' + mImages[mCurrentIndex].date);\n}",
"function displayImage(clickedImage) {\n\n //\"onclick\" handler finds the value of the current image\n const imagePath = clickedImage.target.getAttribute(\"src\");\n\n //sets the value of the image to display\n displayedImage.setAttribute(\"src\", imagePath);\n}",
"function changeDisplayPhoto() {\n displayPhoto.setAttribute('src', `images/${photoList[index]}.jpg`)\n }",
"function addKeyImage() {\n\t// eslint-disable-next-line no-jquery/no-sizzle\n\tconst destination = $( '#keyImages option:selected' ).val();\n\t$( `#img${destination}` ).html( image );\n\t$( '#addKeyImagepanel' ).hide();\n\t$( 'img' ).css( 'border', 'none' );\n\tkeyImages[ destination ] = image.cloneNode();\n scrollToNew(destination, 'img');\n}",
"function displayCurrentPhoto() {\n var displayPhoto = photosArrayGlobal.map (function (o) {return o.URL})\n document.getElementById(\"mainImage\").src = displayPhoto[photosIndexGlobal];\n}",
"function itemAddImgHandler(e) {\n // Change current image into the image user clicks.\n apiView.changeMainImg(e);\n}",
"function onImageClick(evt) {\n showImage(evt.target);\n }",
"function imgClicked(e)\n{\n\tlargeImg.src = e.target.src;\n}",
"function render(currentPics) {\n firstPic.src = currentPics[0].filepath;\n firstPic.alt = currentPics[0].name;\n firstPic.title = currentPics[0].name;\n\n middlePic.src = currentPics[1].filepath;\n middlePic.alt = currentPics[1].name;\n middlePic.title = currentPics[1].name;\n\n lastPic.src = currentPics[2].filepath;\n lastPic.alt = currentPics[2].name;\n lastPic.title = currentPics[2].name;\n\n firstPic.addEventListener('click', handleClick);\n middlePic.addEventListener('click', handleClick);\n lastPic.addEventListener('click', handleClick);\n}",
"function photoHandler(e){\n //Backwards compatibility\n e = e || window.event\n\n var type = e.type;\n if(type == 'click' && photoCxt){ //Run only if canvas is supported\n\n //Look for clicked index\n for(var i = 0; i < photos.length; i++)\n if(photos[i] == this) break;\n\n //Update data for further display animation\n display.sideImgs = {\n prev: photos[(i - 1 + photos.length) % photos.length].getElementsByTagName('img')[0],\n next: photos[(i + 1 + photos.length) % photos.length].getElementsByTagName('img')[0]\n };\n display.thumbImg = this.getElementsByTagName('img')[0];\n display.initRect = this.getBoundingClientRect();\n\n //Load full size image of current selection\n display.loadFlag = false;\n display.largeImg.src = display.thumbImg.src.split('/thumbs').join('');\n\n //Commence animation\n display.transDir = 'in';\n display.tweenVal = 100;\n\n hovered = null; //Cancel current hover indicator\n photoCvs.style.display = 'block'; //Show canvas topmost\n photoCvs.style.zIndex = 1;\n\n return false; //Cancels default click behavior - old school\n };\n\n //Handle rollovers in the same function\n var thisHover = type == 'mouseover';\n if(thisHover)\n hovered = this;\n else if(hovered == this) //Cursor leaves element\n hovered = null;\n}",
"imageSourceSelected(key)\n {\n this.articleImages[key].source = this.articleImages[key].selectedSource;\n }",
"function showPhoto(evt) {\n // parse index of pressed thumbnail by its id number\n var index = parseInt(evt.currentTarget.id.replace(\"thumb\", \"\")) - 1;\n if (curPhoto != index) {\n removePhotoEvent(curPhoto);\n if (curPhoto < index) {\n galleryTl.to(photos[index], 0, {visibility: \"hidden\", left: photoSize+\"px\"});\n galleryTl.to(photos[curPhoto], 1, {left: \"-\"+photoSize+\"px\"});\n }\n else {\n galleryTl.to(photos[index], 0, {visibility: \"hidden\", left: \"-\"+photoSize+\"px\"});\n galleryTl.to(photos[curPhoto], 1, {left: photoSize+\"px\"});\n }\n galleryTl.to(photos[index], 1, {visibility: \"visible\", left: 0}, \"-=0.9\");\n curPhoto = index;\n addPhotoEvent(curPhoto);\n }\n}",
"setPhotoImgClickEvent() {\n const photoListCtnEl = this.appEl.find('.photo-list');\n const cardEl = photoListCtnEl.find('.card');\n cardEl.click(this.onThumbnailImgClickEventHandler.bind(this));\n }",
"function galFocus(imgSrc)\n{\n //console.log(\"setting main pic to \" + imgSrc);\n\n //find the cur main image\n let main = document.getElementById(\"galleryMainPicImg\");\n\n //set the new pic\n main.setAttribute(\"src\", imgSrc);\n}",
"function new_image(get_image)//get_image is a variable which is used to store a specific block image on a specific key press from fabric.js\r\n{\r\n fabric.Image.fromURL(get_image, function(Img) {\r\n block_image_object = Img;\r\n\r\n block_image_object.scaleToWidth(block_image_width);\r\n block_image_object.scaleToHeight(block_image_height);\r\n \r\n block_image_object.set({\r\n top:player_y,\r\n left:player_x\r\n });\r\n canvas.add(block_image_object);\r\n\r\n });\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grade the i'est question, then call the (i+1)'est or send the score | function gradeQuestion(i) {
if (i >= questionsToGrade.length) {
$('#question-iframe-container').removeClass('gradingQuestions');
hideQuestionIframe();
sendScores();
return;
}
$('#question-iframe-container').addClass('gradingQuestions');
var curQuestion = questionsToGrade[i];
questionIframe.load({'task': true, 'grader': true}, curQuestion.questionKey, function() {
questionIframe.task.gradeAnswer(curQuestion.answer, null, function(newScore, message) {
scores[curQuestion.questionKey] = {
score: newScore,
maxScore: curQuestion.maxScore
};
teamScore += parseInt(scores[curQuestion.questionKey].score);
gradeQuestion(i + 1);
});
});
} | [
"function getQuestionJudge(i){\n progress += 1;\n scorenumber = 0;\n if(Option[i - 1] === Answer) {\n checkAnswer.innerHTML = \"Correct!\";\n rightScore += 25;\n console.log(rightScore);\n }else{\n checkAnswer.innerHTML = \"Wrong!\";\n timeremain -= penalty;\n }\n}",
"function calculateScore() {\n \n $.each(questions, function(key, value) {\n \n var valueOf = $(`input[name=${value.identifier}]:checked`).val()\n \n if (valueOf == value.answerIndex) {\n correctAnswers++;\n } else if (valueOf == undefined) {\n incompleteAnswers++;\n } else {\n wrongAnswers++;\n };\n \n });\n }",
"function correct() {\nscore += 20;\nnextQuestion();\n}",
"function grade() {\n\n//question 1 answer r1\nif (answer1 === \"r1\") {\n correct++;\n } else if ((answer1 === \"r2\") || (answer1 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n\n//question 2 answer r3\nif (answer2 === \"r3\") {\n correct++;\n } else if ((answer2 === \"r2\") || (answer2 === \"r1\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 3 answer r1\nif (answer3 === \"r1\") {\n correct++;\n } else if ((answer3 === \"r2\") || (answer3 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 4 answer r2\nif (answer4 === \"r2\") {\n correct++;\n } else if ((answer4 === \"r1\") || (answer4 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 5 answer r3\nif (answer5 === \"r3\") {\n correct++;\n } else if ((answer5 === \"r2\") || (answer5 === \"r1\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n}",
"function quizFlow(){\n qIndex++;\n if (qIndex<questions.length){\n showQuiz();\n }\n else{\n fScore();\n }\n }",
"computeGrade(){\n var cq = 0;\n \n this.questions.forEach(function(question, index, questions){\n if(question.isUserAnswerCorrect) { cq++; }\n });\n this.correctQuestions = cq;\n \n this.grade = (this.correctQuestions / this.questions.length) * 10;\n return this.grade;\n }",
"function scoring(){\n var selected = ($('input[name=check]:checked','#Q1').val());\n if(selected == \"taylor\"){\n points++;\n }\n else if (!selected){\n unanswered++;\n }\n else if (selected !== \"taylor\"){\n incorrect++;\n }\n var selected = ($('input[name=check]:checked','#Q2').val());\n if(selected == \"marie\"){\n points++;\n }\n else if (!selected){\n unanswered++;\n }\n else if (selected !== \"marie\"){\n incorrect++;\n }\n var selected = ($('input[name=check]:checked','#Q3').val());\n if(selected == \"oprah\"){\n points++;\n }\n else if (!selected){\n unanswered++;\n }\n else if (selected !== \"oprah\"){\n incorrect++;\n }\n \n var selected = ($('input[name=check]:checked','#Q4').val());\n if(selected == \"meryl\"){\n points++;\n }\n else if (!selected){\n unanswered++;\n }\n else if (selected !== \"meryl\"){\n incorrect++;\n }\n var selected = ($('input[name=check]:checked','#Q5').val());\n if(selected == \"mariah\"){\n points++;\n }\n else if (!selected){\n unanswered++;\n }\n else if (selected !== \"mariah\"){\n incorrect++;\n }\n}",
"function setNextQuestion() {\n resetQuestions()\n showQuestion(shuffledQuestions[currentQuestionIndex])\n if (userAnswer == true) {\n score += 1\n }\n console.log(score)\n}",
"function getScore(score) {\n $(\".submit\").on(\"click\", function(){\n //see what was selected \n $( \"input[type=radio]:checked\" ).val();\n //if something was selected, add one to answered questions \n if (\":checked\", \"true\") {\n questionsAnswered++;\n //check to see if selected answers are correct \n if (questionsAnswered.val([i]) === correctAnswers[i]) {\n score++;\n }\n }\n else {\n questionsNotAnswered++;\n }\n\n \n \n\n })\n }",
"function gradeQuiz() {\n var usersArray = makeUserArray();\n scoreQuiz(usersArray);\n colorAnswers(usersArray);\n}",
"function processAnswer(num1) {\n // console.log(questionCount);\n if (questionsAnswers[questionCount].options[num1] == questionsAnswers[questionCount].correctAnswer) {\n console.log(\"correct\");\n score++;\n }\n else {\n console.log(\"WRONG!!!\");\n totalSeconds -= 10;\n }\n questionCount++;\n if (questionCount <= 14) {\n nextQuestion();\n } else processScore();\n}",
"function incrementCorrectScore(){\n score++;\n}",
"increaseScore() {\n quiz.Quiz.score = quiz.Quiz.score + 1;\n }",
"function nextQuestion() {\n console.log(questions())\n\n aOrder = generateAnswer(i, generateQuestion(i++, qOrder, questions()), questions())\n console.log(aOrder, score)\n}",
"function changecorrectScore() {\n\tcorrectScore++;\n\tanswerStatus();\n}",
"function raiseScore() {\r\n\tscore += 1;\r\n}",
"function increaseScore() {\n console.log(difficultyChosen)\n score++ \n scoreCheck()\n scoreEl.innerHTML = `Goobbue Caught: ${score}`\n}",
"function correct() {\n \n//alert(\"correct\");\nscore += 20;\nnext();\n}",
"function incrementQuestion(){\n currentQuestionIndex ++;\n answeredArrayIndex ++;\n nextQuestion();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Leave Intent handler. Handle leave less than one day. Will save all line message regardless of valid status | function leaveHandler(next) {
return async agent => {
console.log('leaveHandler');
const { body } = agent.request_;
const {
specialIndicator,
action,
timePeriod,
time,
timeType
} = body.queryResult.parameters;
const { data } = body.originalDetectIntentRequest.payload;
let isVerify = true;
let rejectMessage = undefined;
let newMessageVar = body.queryResult.parameters;
try {
agent.add(
`leaveIntent: ${specialIndicator} ${action} ${timePeriod} ${time} ${timeType}`
);
if (action !== 'leave') throw new Error('not leaveIntent');
if (action !== 'leave') throw new Error('unknown format');
if (time === '') {
if (timePeriod === 'morning' || timePeriod === 'afternoon') {
newMessageVar.time = 4;
} else {
throw new Error('unknown time period');
}
}
newMessageVar.time = parseInt(newMessageVar.time, 10);
} catch (err) {
isVerify = false;
rejectMessage = err.message;
agent.add(`Error: ${rejectMessage}`);
next(err);
} finally {
await saveHistory(
_createMomentDate(specialIndicator),
{
isVerify: isVerify,
rejectMessage: rejectMessage,
lid: data.source.userId,
message: body.queryResult.queryText,
messageIntent: 'leaveIntent',
messageVar: newMessageVar
},
agent,
next
);
}
};
} | [
"function buttonLeaveHandler() {\n log('Leaving room...');\n activeRoom.disconnect();\n }",
"onLeave(e = {}) {\n if (this.isChanged()) {\n return e.returnValue = 'You haven\\'t posted your message. If you leave this page, your message will not be saved. Are you sure you want to leave?'\n }\n }",
"function handleLeave(data) {\n showInfo(usernames[data.fromSocketId] + ' has left the meeting.');\n\n if (data.isModerator) {\n reload(1);\n }\n\n let video = document.getElementById('video-' + data.fromSocketId);\n let container = document.getElementById('container-' + data.fromSocketId);\n\n if (video && container) {\n video.pause();\n video.srcObject = null;\n video.load();\n container.removeChild(video);\n videos.removeChild(container);\n layout();\n }\n\n let currentConnection = connections[data.fromSocketId];\n\n if (currentConnection) {\n currentConnection.close();\n currentConnection.onicecandidate = null;\n currentConnection.ontrack = null;\n delete connections[data.fromSocketId];\n }\n }",
"function leaveGame() {\n console.log(\"Leaving game...\");\n channelLeaveGame();\n }",
"leave() {\n let msg = new Message();\n msg.Namespace = this.nsConn.namespace;\n msg.Room = this.name;\n msg.Event = OnRoomLeave;\n return this.nsConn.askRoomLeave(msg);\n }",
"onLeaveStep(stepId)\n\t\t{\n\t\t}",
"function leaveBuilding() {\n inBuilding.inside = false;\n var eventObject = {\n \"event\": \"\",\n \"description\": \"\",\n \"image\": naratorImg\n };\n eventObject.event = \"You have left\";\n eventObject.description = inBuilding.buildingName;\n sendEventToIo(eventObject);\n // $scope.eventHistory.push(eventObject);\n resetVariables();\n updateScroll('event_home');\n }",
"leave() {\n this._broadcastToRoom('system-message', {\n message: '[' + this._user['nickname'] + '] has left the vChat room.',\n messageType: 'warning'\n });\n this.logger.log('user left the room: ' + this._roomHash\n + ' | user: ' + this._user['socketId'])\n this._socketRedisCtrl.removeUserFromRoom(this._user);\n }",
"function party_leave(){\n\n\t//log.info(this.tsid+'.party_leave()');\n\n\tif (this.party) this.party.leave(this, 'left');\n}",
"function handleLeave({name}){\n const temp = document.getElementById('info-msg-tmp');\n const p = temp.content.cloneNode(true);\n\n $('.msg-text',p).text(`${name} left the video chat.`);\n $('.msg-time',p).text(getTimestamp());\n \n chatsWrapper.appendChild(p);\n chatsWrapper.scrollTo(0,chatsWrapper.scrollHeight);\n }",
"onLeave(client, consented) {\n const name = this.state.chatUsers.get(client.sessionId).name;\n const value = 'Left!';\n const messageBody = {name, value};\n this.broadcast(\"joined-or-left\", messageBody, {except: client});\n this.state.chatUsers.delete(client.sessionId);\n }",
"function usrLeave(user) {\r\n stMsgMap[user.username] = \"\"; \r\n\r\n if (API.hasPermission(API.getUser(null).id, API.ROLE.HOST)) {\r\n API.sendChat(\"Automated message: \" + user.username + \" left the room! :(\");\r\n displayStatusList();\r\n }\r\n\r\n pollStatusChange(statusMap);\r\n }",
"function leaveMeet() {\n\t// remove screen share stream if the user is sharing screen as well\n\tif (IsscreenShareActive) {\n\t\tStopScreenShare();\n\t}\n\n\tclientinstance.leave(\n\t\tfunction () {\n\t\t\tconsole.log(\"client leaves channel\");\n\t\t\tStreamsContainer.camera.stream.stop(); // stop the camera stream playback of the user\n\t\t\tclientinstance.unpublish(StreamsContainer.camera.stream); // unpublish the camera stream of the user\n\t\t\tStreamsContainer.camera.stream.close(); // clean up and close the camera stream of the user\n\t\t\t$(\"#remote-streams\").empty();\n\t\t\t//disable the UI elements which were enabled when the stream was received first time\n\t\t\t$(\"#mic-btn\").prop(\"disabled\", true);\n\t\t\t$(\"#video-btn\").prop(\"disabled\", true);\n\t\t\t$(\"#screen-share-btn\").prop(\"disabled\", true);\n\t\t\t$(\"#exit-btn\").prop(\"disabled\", true);\n\t\t\ttoggleVisibility(\"#mute-overlay\", false);\n\t\t\ttoggleVisibility(\"#no-local-video\", false);\n\t\t\tResizeGrid(); // resize grid after the user leaves\n\t\t\tredir(); // redirect back to meet room\n\t\t},\n\t\tfunction (err) {\n\t\t\tconsole.log(\"client failed to leave\", err); //error handling in case user couldnt leave properly\n\t\t}\n\t);\n}",
"function leaveRoom() {\n socket.emit('leave');\n vm.enableChat = false;\n vm.currentRoom = 0;\n vm.online = [];\n vm.roomName = \"Please choose a room chat!\";\n $('.messages').children().remove();\n vm.counterLineOfMessage = 0;\n\n }",
"ProcessLeaveChangeCommand() {\n var newYtLink = this.commandParameters[0];\n this.leaveLink = newYtLink;\n var msg = 'Leave audio changed to the link: ' + newYtLink;\n this.ReplyToMessage(msg);\n }",
"exitLeaveStatement(ctx) {\n\t}",
"function handleLeaveRoom() {\n if (isMountedRef.current) {\n socket.emit(\"leaveRoom\", { room, user }, function() {\n setRoom(\"\");\n setUserName(\"\");\n socket.disconnect();\n navigation.goBack();\n });\n }\n }",
"doLeave() {\n logger.log('do leave', this.myroomjid);\n const pres = Object(strophe_js__WEBPACK_IMPORTED_MODULE_1__[\"$pres\"])({\n to: this.myroomjid,\n type: 'unavailable'\n });\n this.presMap.length = 0; // XXX Strophe is asynchronously sending by default. Unfortunately, that\n // means that there may not be enough time to send the unavailable\n // presence. Switching Strophe to synchronous sending is not much of an\n // option because it may lead to a noticeable delay in navigating away\n // from the current location. As a compromise, we will try to increase\n // the chances of sending the unavailable presence within the short time\n // span that we have upon unloading by invoking flush() on the\n // connection. We flush() once before sending/queuing the unavailable\n // presence in order to attemtp to have the unavailable presence at the\n // top of the send queue. We flush() once more after sending/queuing the\n // unavailable presence in order to attempt to have it sent as soon as\n // possible.\n // FIXME do not use Strophe.Connection in the ChatRoom directly\n\n !this.connection.isUsingWebSocket && this.connection.flush();\n this.connection.send(pres);\n this.connection.flush();\n }",
"function leaveGame() {\n if (ready) {\n if (inProgress) {\n socket.emit('order', { type: 'loss', player: GameInstance.myID });\n }\n socket.emit('shout', { type: 'unready' });\n }\n ready = false;\n socket.emit('leavegame');\n Multiplayer.readyPlayers = 0;\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the total number of words sent by a participant | function sentWords(conversation, participant) {
// Extract data
messages = conversation.messages
// Filter data
sentMessages = messages.filter(sentBy(participant))
// Analyze data
totalWords = 0;
sentMessages.forEach(message => totalWords += wordsInMessage(message))
// Return value
return totalWordsfilterMethod
} | [
"function receivedWords(conversation, participant) {\n // Extract data\n messages = conversation.messages;\n\n // Filter data\n receivedMessages = messages.filter(notSentBy(participant))\n\n // Analyze data\n totalWords = 0;\n receivedMessages.forEach(message => totalWords += wordsInMessage(message))\n\n // Return value\n return totalWords\n}",
"function sentMessages(conversation, participant) {\n messages = conversation.messages\n sentMessages = messages.filter(sentBy(participant))\n return sentMessages.length\n}",
"static async getTotalCountLearnedWords() {\n const data = await WordsGlobalStatistics.getWordsData({\n wordsPerPage: 1,\n filter: FILTERS.LEARNED,\n });\n\n if (!data) {\n return data;\n }\n\n const { count } = data;\n\n return count;\n }",
"function countOtherWords() {\n\tvar count = 0;\n\tvar words;\n\totherPosts = document.getElementsByClassName(\"message user_content\");\n\tfor(var i = 1; i < otherPosts.length; i++) {\n\t\twords = getAllWords(otherPosts[i]);\n\t\tcount += countWords(words);\n\t}\n\tcount = count / (otherPosts.length - 1);\n\tcount = count.toFixed();\n\treturn count;\n}",
"function nwtCounter() {\n let wordsTyped = myText.value.split(\" \").length; \n nwtTotal.innerHTML = wordsTyped++;\n }",
"function getTotalParticipant(){\n var i, sum = 0;\n for (var i = 0; i < arguments.length; i++) {\n sum += arguments[i];\n }\n return sum;\n }",
"function avSentLength(string){\n var eachSentence = string.replace(/(\\.+|\\:|\\!|\\?)(\\\"*|\\'*|\\)*|}*|]*)(\\s|\\n|\\r|\\r\\n)/gm, \"$1$2|\").split(\"|\");\n var words = string.split(\" \");\n return words.length / eachSentence.length;\n}",
"function sentenceInfo(sentence){\n\tvar numLetters = sentence.replace(/ /g,\"\").length;\n\tvar numWords = sentence.split(\" \").length;\n\tvar avgWrdLength = numLetters/numWords; \n\tconsole.log(\"There are \"+numWords+\" words in this sentence, and the average word length is \"+avgWrdLength+\" words.\")\n}",
"function totalWords() {\n // Get the string entered into the text area from portfolio.html.\n var words = document.getElementById('sentence').value;\n\n // Variable to hold the number of words counted.\n // Set to 1 because the last word has not trailing space.\n var wordCounter = 1;\n\n // Count the words in the words string.\n for (var i = 0; i <= words.length; i++) {\n if(words[i] === \" \"){\n wordCounter++;\n }\n }\n\n // Display the number of words counted.\n document.getElementById('outWords').innerHTML = \"Total Number of Words: \" + wordCounter;\n\n return wordCounter;\n}",
"countWords(sentence) {\n \tvar sentenceWords = sentence.split(\" \");\n \treturn sentenceWords.length;\n }",
"function wordCount(sentence){\n return sentence.split(' ').length;\n }",
"function outcomes_passage_wordcount(sentences) {\n\tvar totalWords = 0, totalSentences = 0, totalSyllables = 0;\n\tvar i, j;\n\ttotalSentences = sentences.length;\n\tfor (i = 0; i < sentences.length; i++) {\n\t\ttotalWords += sentences[i].length;\n\t\tfor (j = 0; j < sentences[i].length; j++) {\n\t\t\ttotalSyllables += sentences[i][j][1];\n\t\t}\n\t}\n\treturn {\n\t\ttotalWords : totalWords,\n\t\ttotalSentences : totalSentences,\n\t\ttotalSyllables : totalSyllables\n\t};\n}",
"function numOfOccurences(letter)\n{\n let counter = 0;\n let word = document.getElementsByClassName(\"join-message\");\n word = word[0].innerText;\n for(let i=0;i<word.length;i++)\n {\n if(letter.toLowerCase() == word[i].toLowerCase()) counter++;\n }\n return counter;\n}",
"function totalSentences() {\n // Get the string entered into the text area from portfolio.html.\n var textAreaString = document.getElementById(\"sentence\").value;\n\n // Variable to hold the number of periods counted.\n var periodCounter = 0;\n\n // Count the periods in textAreaString.\n for (var j = 0; j <= textAreaString.length; j++) {\n if (textAreaString[j] === \".\") {\n periodCounter++;\n }\n }\n\n // Display the number of periods counted.\n document.getElementById(\"outSentences\").innerHTML = \"Total Number of Sentences: \" + periodCounter;\n\n return periodCounter;\n}",
"function wordsCount() {\n let totalWordsNumber = originText.split(' ').length;\n let wpm = Math.floor(totalWordsNumber/((timer[3]/100)/60));\n WPM.innerHTML = wpm;\n resultsArea.style.display = \"block\";\n}",
"function wordCount() {\r\n s = document1;\r\n //s = s.replace(/(^\\s*)|(\\s*$)/gi, \"\"); //old method\r\n //s = s.replace(/[ ]{2,}/gi, \" \");\r\n //s = s.replace(/\\n /, \"\\n\");\r\n ////writeToPage(s.split(' ').length);\r\n //return s.split(' ').length;\r\n try { //new method\r\n //the try catch is incase there is a big change in the document, this can bring up an error sometimes but the try catch fixes this\r\n var word = s.match(/\\S+/g);\r\n //document.getElementById(\"req0\").value = \"\"+ word && word.length || 0; //Used for testing\r\n return word && word.length || 0;\r\n }\r\n catch (err) {\r\n return 0;\r\n }\r\n }",
"function counting (words){\n return words.split(\" \").length;\n}",
"function sentenceCount(data){\n let sentencecount=data.match(/\\w[.?](\\s|$)/g)\n \n return sentencecount.length\n}",
"function averageWords(sent) {\n var s = sent.split(\" \"),\n sum = 0,\n i;\n for (i = 0; i < s.length; i += 1) {\n sum += s[i].length;\n }\n return sum / s.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prints the chain of block | showChain() {
getAllLevelDBData()
.then(data => {
console.log('*'.repeat(100))
console.log(data)
console.log('*'.repeat(100), '\n')
})
.catch(err => {
console.log("Error occurred while calling getAllLevelDBData - showBlockChain")
})
} | [
"printCurrentChain() {\n console.log(JSON.parse(JSON.stringify(blockChain)));\n }",
"function print() {\n console.log(blocks);\n }",
"function printChain(o){\n console.log(\"=== printChain (begin) ===\");\n var level = 1;\n\n function print(level, value){\n\tconsole.log(\" \".repeat(level-1) + \"+--- \" + value);\n }\n \n function browseProperties (o,level) {\n\tvar temp = Object.getOwnPropertyNames(o);\n\tfor (var i in temp)\n\t print(level, temp[i] + ': ' + o[temp[i]]);\n\tvar proto = Object.getPrototypeOf(o);\n\tif ((proto === undefined) || (proto === null))\n\t return;\n\telse {\n\t level += 1;\n\t browseProperties(proto,level);\n\t}\n }\n\n browseProperties(o, 1);\n console.log(\"=== printChain (end) ===\");\n}",
"listBlocks() {\n console.log(this.chain);\n }",
"print()\n\t{\n\t\tconsole.log(`|\tnode\tcost\tnextHop\t|`);\n\t\t//console.log(this);\n\t\tfor(let i of this.routingTable)\n\t\t{\n\t\t\tconsole.log(`|\t${i.node}\t${i.cost}\t${i.nextHop}\t|`);\n\t\t}\n\t\tconsole.log(`\\n\\n`);\n\t}",
"function printTopBlock() {\n printLine('<span class=\"green\">==================</span>');\n printLine('<span class=\"cyan\"> dhruv bhanushali</span>');\n printLine('<span class=\"green\">==================</span>');\n printLine(`<strong>software developer and technical writer</strong>`);\n printLine(`<strong>undergraduate, IIT Roorkee</strong>`);\n printLine('<br>');\n help();\n printLine('<br>');\n printTree();\n printLine('<br>');\n}",
"print(){\n\t\tlet current = this.top;\n\t\twhile(current){\n\t\t\tcurrent = this.stack[current].prev;\t\n\t\t}\n\t\t\n\t}",
"function printMemberChain(path, options, print) {\n // The first phase is to linearize the AST by traversing it down.\n //\n // a().b()\n // has the following AST structure:\n // CallExpression(MemberExpression(CallExpression(Identifier)))\n // and we transform it into\n // [Identifier, CallExpression, MemberExpression, CallExpression]\n var printedNodes = []; // Here we try to retain one typed empty line after each call expression or\n // the first group whether it is in parentheses or not\n\n function shouldInsertEmptyLineAfter(node) {\n var originalText = options.originalText;\n var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(\n originalText,\n node,\n options\n );\n var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty\n // line after that parenthesis\n\n if (nextChar == \")\") {\n return isNextLineEmptyAfterIndex$1(\n originalText,\n nextCharIndex + 1,\n options\n );\n }\n\n return isNextLineEmpty$4(\n originalText,\n node,\n options\n );\n }\n\n function rec(path) {\n var node = path.getValue();\n\n if (\n (node.type === \"CallExpression\" ||\n node.type === \"OptionalCallExpression\") &&\n (isMemberish(node.callee) ||\n node.callee.type === \"CallExpression\" ||\n node.callee.type ===\n \"OptionalCallExpression\")\n ) {\n printedNodes.unshift({\n node: node,\n printed: concat$11([\n comments.printComments(\n path,\n function () {\n return concat$11([\n printOptionalToken(path),\n printFunctionTypeParameters(\n path,\n options,\n print\n ),\n printArgumentsList(\n path,\n options,\n print\n ),\n ]);\n },\n options\n ),\n shouldInsertEmptyLineAfter(node)\n ? hardline$8\n : \"\",\n ]),\n });\n path.call(function (callee) {\n return rec(callee);\n }, \"callee\");\n } else if (isMemberish(node)) {\n printedNodes.unshift({\n node: node,\n needsParens: needsParens_1(path, options),\n printed: comments.printComments(\n path,\n function () {\n return node.type ===\n \"OptionalMemberExpression\" ||\n node.type === \"MemberExpression\"\n ? printMemberLookup(\n path,\n options,\n print\n )\n : printBindExpressionCallee(\n path,\n options,\n print\n );\n },\n options\n ),\n });\n path.call(function (object) {\n return rec(object);\n }, \"object\");\n } else if (node.type === \"TSNonNullExpression\") {\n printedNodes.unshift({\n node: node,\n printed: comments.printComments(\n path,\n function () {\n return \"!\";\n },\n options\n ),\n });\n path.call(function (expression) {\n return rec(expression);\n }, \"expression\");\n } else {\n printedNodes.unshift({\n node: node,\n printed: path.call(print),\n });\n }\n } // Note: the comments of the root node have already been printed, so we\n // need to extract this first call without printing them as they would\n // if handled inside of the recursive call.\n\n var node = path.getValue();\n printedNodes.unshift({\n node: node,\n printed: concat$11([\n printOptionalToken(path),\n printFunctionTypeParameters(\n path,\n options,\n print\n ),\n printArgumentsList(path, options, print),\n ]),\n });\n path.call(function (callee) {\n return rec(callee);\n }, \"callee\"); // Once we have a linear list of printed nodes, we want to create groups out\n // of it.\n //\n // a().b.c().d().e\n // will be grouped as\n // [\n // [Identifier, CallExpression],\n // [MemberExpression, MemberExpression, CallExpression],\n // [MemberExpression, CallExpression],\n // [MemberExpression],\n // ]\n // so that we can print it as\n // a()\n // .b.c()\n // .d()\n // .e\n // The first group is the first node followed by\n // - as many CallExpression as possible\n // < fn()()() >.something()\n // - as many array acessors as possible\n // < fn()[0][1][2] >.something()\n // - then, as many MemberExpression as possible but the last one\n // < this.items >.something()\n\n var groups = [];\n var currentGroup = [printedNodes[0]];\n var i = 1;\n\n for (; i < printedNodes.length; ++i) {\n if (\n printedNodes[i].node.type ===\n \"TSNonNullExpression\" ||\n printedNodes[i].node.type ===\n \"OptionalCallExpression\" ||\n printedNodes[i].node.type ===\n \"CallExpression\" ||\n ((printedNodes[i].node.type ===\n \"MemberExpression\" ||\n printedNodes[i].node.type ===\n \"OptionalMemberExpression\") &&\n printedNodes[i].node.computed &&\n isNumericLiteral(\n printedNodes[i].node.property\n ))\n ) {\n currentGroup.push(printedNodes[i]);\n } else {\n break;\n }\n }\n\n if (\n printedNodes[0].node.type !== \"CallExpression\" &&\n printedNodes[0].node.type !==\n \"OptionalCallExpression\"\n ) {\n for (; i + 1 < printedNodes.length; ++i) {\n if (\n isMemberish(printedNodes[i].node) &&\n isMemberish(printedNodes[i + 1].node)\n ) {\n currentGroup.push(printedNodes[i]);\n } else {\n break;\n }\n }\n }\n\n groups.push(currentGroup);\n currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by\n // a sequence of CallExpression. To compute it, we keep adding things to the\n // group until we has seen a CallExpression in the past and reach a\n // MemberExpression\n\n var hasSeenCallExpression = false;\n\n for (; i < printedNodes.length; ++i) {\n if (\n hasSeenCallExpression &&\n isMemberish(printedNodes[i].node)\n ) {\n // [0] should be appended at the end of the group instead of the\n // beginning of the next one\n if (\n printedNodes[i].node.computed &&\n isNumericLiteral(\n printedNodes[i].node.property\n )\n ) {\n currentGroup.push(printedNodes[i]);\n continue;\n }\n\n groups.push(currentGroup);\n currentGroup = [];\n hasSeenCallExpression = false;\n }\n\n if (\n printedNodes[i].node.type ===\n \"CallExpression\" ||\n printedNodes[i].node.type ===\n \"OptionalCallExpression\"\n ) {\n hasSeenCallExpression = true;\n }\n\n currentGroup.push(printedNodes[i]);\n\n if (\n printedNodes[i].node.comments &&\n printedNodes[i].node.comments.some(function (\n comment\n ) {\n return comment.trailing;\n })\n ) {\n groups.push(currentGroup);\n currentGroup = [];\n hasSeenCallExpression = false;\n }\n }\n\n if (currentGroup.length > 0) {\n groups.push(currentGroup);\n } // There are cases like Object.keys(), Observable.of(), _.values() where\n // they are the subject of all the chained calls and therefore should\n // be kept on the same line:\n //\n // Object.keys(items)\n // .filter(x => x)\n // .map(x => x)\n //\n // In order to detect those cases, we use an heuristic: if the first\n // node is an identifier with the name starting with a capital\n // letter or just a sequence of _$. The rationale is that they are\n // likely to be factories.\n\n function isFactory(name) {\n return /^[A-Z]|^[_$]+$/.test(name);\n } // In case the Identifier is shorter than tab width, we can keep the\n // first call in a single line, if it's an ExpressionStatement.\n //\n // d3.scaleLinear()\n // .domain([0, 100])\n // .range([0, width]);\n //\n\n function isShort(name) {\n return name.length <= options.tabWidth;\n }\n\n function shouldNotWrap(groups) {\n var parent = path.getParentNode();\n var isExpression =\n parent && parent.type === \"ExpressionStatement\";\n var hasComputed =\n groups[1].length && groups[1][0].node.computed;\n\n if (groups[0].length === 1) {\n var firstNode = groups[0][0].node;\n return (\n firstNode.type === \"ThisExpression\" ||\n (firstNode.type === \"Identifier\" &&\n (isFactory(firstNode.name) ||\n (isExpression &&\n isShort(firstNode.name)) ||\n hasComputed))\n );\n }\n\n var lastNode = getLast$3(groups[0]).node;\n return (\n (lastNode.type === \"MemberExpression\" ||\n lastNode.type ===\n \"OptionalMemberExpression\") &&\n lastNode.property.type === \"Identifier\" &&\n (isFactory(lastNode.property.name) ||\n hasComputed)\n );\n }\n\n var shouldMerge =\n groups.length >= 2 &&\n !groups[1][0].node.comments &&\n shouldNotWrap(groups);\n\n function printGroup(printedGroup) {\n var printed = printedGroup.map(function (tuple) {\n return tuple.printed;\n }); // Checks if the last node (i.e. the parent node) needs parens and print\n // accordingly\n\n if (\n printedGroup.length > 0 &&\n printedGroup[printedGroup.length - 1]\n .needsParens\n ) {\n return concat$11(\n [\"(\"].concat(_toConsumableArray(printed), [\n \")\",\n ])\n );\n }\n\n return concat$11(printed);\n }\n\n function printIndentedGroup(groups) {\n if (groups.length === 0) {\n return \"\";\n }\n\n return indent$6(\n group$10(\n concat$11([\n hardline$8,\n join$7(\n hardline$8,\n groups.map(printGroup)\n ),\n ])\n )\n );\n }\n\n var printedGroups = groups.map(printGroup);\n var oneLine = concat$11(printedGroups);\n var cutoff = shouldMerge ? 3 : 2;\n var flatGroups = groups\n .slice(0, cutoff)\n .reduce(function (res, group) {\n return res.concat(group);\n }, []);\n var hasComment =\n flatGroups.slice(1, -1).some(function (node) {\n return hasLeadingComment(node.node);\n }) ||\n flatGroups.slice(0, -1).some(function (node) {\n return hasTrailingComment(node.node);\n }) ||\n (groups[cutoff] &&\n hasLeadingComment(groups[cutoff][0].node)); // If we only have a single `.`, we shouldn't do anything fancy and just\n // render everything concatenated together.\n\n if (groups.length <= cutoff && !hasComment) {\n return group$10(oneLine);\n } // Find out the last node in the first group and check if it has an\n // empty line after\n\n var lastNodeBeforeIndent = getLast$3(\n shouldMerge ? groups.slice(1, 2)[0] : groups[0]\n ).node;\n var shouldHaveEmptyLineBeforeIndent =\n lastNodeBeforeIndent.type !== \"CallExpression\" &&\n lastNodeBeforeIndent.type !==\n \"OptionalCallExpression\" &&\n shouldInsertEmptyLineAfter(lastNodeBeforeIndent);\n var expanded = concat$11([\n printGroup(groups[0]),\n shouldMerge\n ? concat$11(groups.slice(1, 2).map(printGroup))\n : \"\",\n shouldHaveEmptyLineBeforeIndent ? hardline$8 : \"\",\n printIndentedGroup(\n groups.slice(shouldMerge ? 2 : 1)\n ),\n ]);\n var callExpressions = printedNodes\n .map(function (_ref) {\n var node = _ref.node;\n return node;\n })\n .filter(isCallOrOptionalCallExpression); // We don't want to print in one line if there's:\n // * A comment.\n // * 3 or more chained calls.\n // * Any group but the last one has a hard line.\n // If the last group is a function it's okay to inline if it fits.\n\n if (\n hasComment ||\n callExpressions.length >= 3 ||\n printedGroups.slice(0, -1).some(willBreak$1) ||\n /**\n * scopes.filter(scope => scope.value !== '').map((scope, i) => {\n * // multi line content\n * })\n */\n ((function (lastGroupDoc, lastGroupNode) {\n return (\n isCallOrOptionalCallExpression(\n lastGroupNode\n ) && willBreak$1(lastGroupDoc)\n );\n })(\n getLast$3(printedGroups),\n getLast$3(getLast$3(groups)).node\n ) &&\n callExpressions.slice(0, -1).some(function (n) {\n return n.arguments.some(\n isFunctionOrArrowExpression\n );\n }))\n ) {\n return group$10(expanded);\n }\n\n return concat$11([\n // We only need to check `oneLine` because if `expanded` is chosen\n // that means that the parent group has already been broken\n // naturally\n willBreak$1(oneLine) ||\n shouldHaveEmptyLineBeforeIndent\n ? breakParent$3\n : \"\",\n conditionalGroup$1([oneLine, expanded]),\n ]);\n }",
"function printMemberChain(path, options, print) {\n // The first phase is to linearize the AST by traversing it down.\n //\n // a().b()\n // has the following AST structure:\n // CallExpression(MemberExpression(CallExpression(Identifier)))\n // and we transform it into\n // [Identifier, CallExpression, MemberExpression, CallExpression]\n const printedNodes = [];\n\n // Here we try to retain one typed empty line after each call expression or\n // the first group whether it is in parentheses or not\n function shouldInsertEmptyLineAfter(node) {\n const originalText = options.originalText;\n const nextCharIndex = util.getNextNonSpaceNonCommentCharacterIndex(\n originalText,\n node\n );\n const nextChar = originalText.charAt(nextCharIndex);\n\n // if it is cut off by a parenthesis, we only account for one typed empty\n // line after that parenthesis\n if (nextChar == \")\") {\n return util.isNextLineEmptyAfterIndex(originalText, nextCharIndex + 1);\n }\n\n return util.isNextLineEmpty(originalText, node);\n }\n\n function rec(path) {\n const node = path.getValue();\n if (\n node.type === \"CallExpression\" &&\n (isMemberish(node.callee) || node.callee.type === \"CallExpression\")\n ) {\n printedNodes.unshift({\n node: node,\n printed: concat([\n comments.printComments(\n path,\n () =>\n concat([\n printOptionalToken(path),\n printFunctionTypeParameters(path, options, print),\n printArgumentsList(path, options, print)\n ]),\n options\n ),\n shouldInsertEmptyLineAfter(node) ? hardline : \"\"\n ])\n });\n path.call(callee => rec(callee), \"callee\");\n } else if (isMemberish(node)) {\n printedNodes.unshift({\n node: node,\n printed: comments.printComments(\n path,\n () =>\n node.type === \"MemberExpression\"\n ? printMemberLookup(path, options, print)\n : printBindExpressionCallee(path, options, print),\n options\n )\n });\n path.call(object => rec(object), \"object\");\n } else {\n printedNodes.unshift({\n node: node,\n printed: path.call(print)\n });\n }\n }\n // Note: the comments of the root node have already been printed, so we\n // need to extract this first call without printing them as they would\n // if handled inside of the recursive call.\n const node = path.getValue();\n printedNodes.unshift({\n node,\n printed: concat([\n printOptionalToken(path),\n printFunctionTypeParameters(path, options, print),\n printArgumentsList(path, options, print)\n ])\n });\n path.call(callee => rec(callee), \"callee\");\n\n // Once we have a linear list of printed nodes, we want to create groups out\n // of it.\n //\n // a().b.c().d().e\n // will be grouped as\n // [\n // [Identifier, CallExpression],\n // [MemberExpression, MemberExpression, CallExpression],\n // [MemberExpression, CallExpression],\n // [MemberExpression],\n // ]\n // so that we can print it as\n // a()\n // .b.c()\n // .d()\n // .e\n\n // The first group is the first node followed by\n // - as many CallExpression as possible\n // < fn()()() >.something()\n // - as many array acessors as possible\n // < fn()[0][1][2] >.something()\n // - then, as many MemberExpression as possible but the last one\n // < this.items >.something()\n const groups = [];\n let currentGroup = [printedNodes[0]];\n let i = 1;\n for (; i < printedNodes.length; ++i) {\n if (\n printedNodes[i].node.type === \"CallExpression\" ||\n (printedNodes[i].node.type === \"MemberExpression\" &&\n printedNodes[i].node.computed &&\n isNumericLiteral(printedNodes[i].node.property))\n ) {\n currentGroup.push(printedNodes[i]);\n } else {\n break;\n }\n }\n if (printedNodes[0].node.type !== \"CallExpression\") {\n for (; i + 1 < printedNodes.length; ++i) {\n if (\n isMemberish(printedNodes[i].node) &&\n isMemberish(printedNodes[i + 1].node)\n ) {\n currentGroup.push(printedNodes[i]);\n } else {\n break;\n }\n }\n }\n groups.push(currentGroup);\n currentGroup = [];\n\n // Then, each following group is a sequence of MemberExpression followed by\n // a sequence of CallExpression. To compute it, we keep adding things to the\n // group until we has seen a CallExpression in the past and reach a\n // MemberExpression\n let hasSeenCallExpression = false;\n for (; i < printedNodes.length; ++i) {\n if (hasSeenCallExpression && isMemberish(printedNodes[i].node)) {\n // [0] should be appended at the end of the group instead of the\n // beginning of the next one\n if (\n printedNodes[i].node.computed &&\n isNumericLiteral(printedNodes[i].node.property)\n ) {\n currentGroup.push(printedNodes[i]);\n continue;\n }\n\n groups.push(currentGroup);\n currentGroup = [];\n hasSeenCallExpression = false;\n }\n\n if (printedNodes[i].node.type === \"CallExpression\") {\n hasSeenCallExpression = true;\n }\n currentGroup.push(printedNodes[i]);\n\n if (\n printedNodes[i].node.comments &&\n printedNodes[i].node.comments.some(comment => comment.trailing)\n ) {\n groups.push(currentGroup);\n currentGroup = [];\n hasSeenCallExpression = false;\n }\n }\n if (currentGroup.length > 0) {\n groups.push(currentGroup);\n }\n\n // There are cases like Object.keys(), Observable.of(), _.values() where\n // they are the subject of all the chained calls and therefore should\n // be kept on the same line:\n //\n // Object.keys(items)\n // .filter(x => x)\n // .map(x => x)\n //\n // In order to detect those cases, we use an heuristic: if the first\n // node is just an identifier with the name starting with a capital\n // letter, just a sequence of _$ or this. The rationale is that they are\n // likely to be factories.\n function isFactory(name) {\n return name.match(/(^[A-Z])|^[_$]+$/);\n }\n const shouldMerge =\n groups.length >= 2 &&\n !groups[1][0].node.comments &&\n ((groups[0].length === 1 &&\n (groups[0][0].node.type === \"ThisExpression\" ||\n (groups[0][0].node.type === \"Identifier\" &&\n (isFactory(groups[0][0].node.name) ||\n (groups[1].length && groups[1][0].node.computed))))) ||\n (groups[0].length > 1 &&\n groups[0][groups[0].length - 1].node.type === \"MemberExpression\" &&\n groups[0][groups[0].length - 1].node.property.type === \"Identifier\" &&\n (isFactory(groups[0][groups[0].length - 1].node.property.name) ||\n (groups[1].length && groups[1][0].node.computed))));\n\n function printGroup(printedGroup) {\n return concat(printedGroup.map(tuple => tuple.printed));\n }\n\n function printIndentedGroup(groups) {\n if (groups.length === 0) {\n return \"\";\n }\n return indent(\n group(concat([hardline, join(hardline, groups.map(printGroup))]))\n );\n }\n\n const printedGroups = groups.map(printGroup);\n const oneLine = concat(printedGroups);\n\n const cutoff = shouldMerge ? 3 : 2;\n const flatGroups = groups\n .slice(0, cutoff)\n .reduce((res, group) => res.concat(group), []);\n\n const hasComment =\n flatGroups.slice(1, -1).some(node => hasLeadingComment(node.node)) ||\n flatGroups.slice(0, -1).some(node => hasTrailingComment(node.node)) ||\n (groups[cutoff] && hasLeadingComment(groups[cutoff][0].node));\n\n // If we only have a single `.`, we shouldn't do anything fancy and just\n // render everything concatenated together.\n if (groups.length <= cutoff && !hasComment) {\n return group(oneLine);\n }\n\n // Find out the last node in the first group and check if it has an\n // empty line after\n const lastNodeBeforeIndent = util.getLast(\n shouldMerge ? groups.slice(1, 2)[0] : groups[0]\n ).node;\n const shouldHaveEmptyLineBeforeIndent =\n lastNodeBeforeIndent.type !== \"CallExpression\" &&\n shouldInsertEmptyLineAfter(lastNodeBeforeIndent);\n\n const expanded = concat([\n printGroup(groups[0]),\n shouldMerge ? concat(groups.slice(1, 2).map(printGroup)) : \"\",\n shouldHaveEmptyLineBeforeIndent ? hardline : \"\",\n printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))\n ]);\n\n const callExpressionCount = printedNodes.filter(\n tuple => tuple.node.type === \"CallExpression\"\n ).length;\n\n // We don't want to print in one line if there's:\n // * A comment.\n // * 3 or more chained calls.\n // * Any group but the last one has a hard line.\n // If the last group is a function it's okay to inline if it fits.\n if (\n hasComment ||\n callExpressionCount >= 3 ||\n printedGroups.slice(0, -1).some(willBreak)\n ) {\n return group(expanded);\n }\n\n return concat([\n // We only need to check `oneLine` because if `expanded` is chosen\n // that means that the parent group has already been broken\n // naturally\n willBreak(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent : \"\",\n conditionalGroup([oneLine, expanded])\n ]);\n}",
"printInfo() {\n // console.log('EXCHANGE: investor list:');\n // Object.values(this.investors).forEach(investor => void console.log(investor));\n // console.log(`EXCHANGE: chain length: ${this.chain.lastBlock().index}, total BTC: ${this.totalBtc}`);\n }",
"function printMemberChain(path,options,print){// The first phase is to linearize the AST by traversing it down.\n//\n// a().b()\n// has the following AST structure:\n// CallExpression(MemberExpression(CallExpression(Identifier)))\n// and we transform it into\n// [Identifier, CallExpression, MemberExpression, CallExpression]\nvar printedNodes=[];// Here we try to retain one typed empty line after each call expression or\n// the first group whether it is in parentheses or not\nfunction shouldInsertEmptyLineAfter(node){var originalText=options.originalText;var nextCharIndex=getNextNonSpaceNonCommentCharacterIndex$3(originalText,node,options.locEnd);var nextChar=originalText.charAt(nextCharIndex);// if it is cut off by a parenthesis, we only account for one typed empty\n// line after that parenthesis\nif(nextChar===\")\"){return isNextLineEmptyAfterIndex$2(originalText,nextCharIndex+1,options.locEnd);}return isNextLineEmpty$4(originalText,node,options.locEnd);}function rec(path){var node=path.getValue();if((node.type===\"CallExpression\"||node.type===\"OptionalCallExpression\")&&(isMemberish$1(node.callee)||node.callee.type===\"CallExpression\"||node.callee.type===\"OptionalCallExpression\")){printedNodes.unshift({node:node,printed:concat$d([comments.printComments(path,function(){return concat$d([printOptionalToken(path),printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)]);},options),shouldInsertEmptyLineAfter(node)?hardline$9:\"\"])});path.call(function(callee){return rec(callee);},\"callee\");}else if(isMemberish$1(node)){printedNodes.unshift({node:node,needsParens:needsParens_1(path,options),printed:comments.printComments(path,function(){return node.type===\"OptionalMemberExpression\"||node.type===\"MemberExpression\"?printMemberLookup(path,options,print):printBindExpressionCallee(path,options,print);},options)});path.call(function(object){return rec(object);},\"object\");}else if(node.type===\"TSNonNullExpression\"){printedNodes.unshift({node:node,printed:comments.printComments(path,function(){return\"!\";},options)});path.call(function(expression){return rec(expression);},\"expression\");}else{printedNodes.unshift({node:node,printed:path.call(print)});}}// Note: the comments of the root node have already been printed, so we\n// need to extract this first call without printing them as they would\n// if handled inside of the recursive call.\nvar node=path.getValue();printedNodes.unshift({node:node,printed:concat$d([printOptionalToken(path),printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)])});path.call(function(callee){return rec(callee);},\"callee\");// Once we have a linear list of printed nodes, we want to create groups out\n// of it.\n//\n// a().b.c().d().e\n// will be grouped as\n// [\n// [Identifier, CallExpression],\n// [MemberExpression, MemberExpression, CallExpression],\n// [MemberExpression, CallExpression],\n// [MemberExpression],\n// ]\n// so that we can print it as\n// a()\n// .b.c()\n// .d()\n// .e\n// The first group is the first node followed by\n// - as many CallExpression as possible\n// < fn()()() >.something()\n// - as many array accessors as possible\n// < fn()[0][1][2] >.something()\n// - then, as many MemberExpression as possible but the last one\n// < this.items >.something()\nvar groups=[];var currentGroup=[printedNodes[0]];var i=1;for(;i<printedNodes.length;++i){if(printedNodes[i].node.type===\"TSNonNullExpression\"||printedNodes[i].node.type===\"OptionalCallExpression\"||printedNodes[i].node.type===\"CallExpression\"||(printedNodes[i].node.type===\"MemberExpression\"||printedNodes[i].node.type===\"OptionalMemberExpression\")&&printedNodes[i].node.computed&&isNumericLiteral$1(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);}else{break;}}if(printedNodes[0].node.type!==\"CallExpression\"&&printedNodes[0].node.type!==\"OptionalCallExpression\"){for(;i+1<printedNodes.length;++i){if(isMemberish$1(printedNodes[i].node)&&isMemberish$1(printedNodes[i+1].node)){currentGroup.push(printedNodes[i]);}else{break;}}}groups.push(currentGroup);currentGroup=[];// Then, each following group is a sequence of MemberExpression followed by\n// a sequence of CallExpression. To compute it, we keep adding things to the\n// group until we has seen a CallExpression in the past and reach a\n// MemberExpression\nvar hasSeenCallExpression=false;for(;i<printedNodes.length;++i){if(hasSeenCallExpression&&isMemberish$1(printedNodes[i].node)){// [0] should be appended at the end of the group instead of the\n// beginning of the next one\nif(printedNodes[i].node.computed&&isNumericLiteral$1(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);continue;}groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}if(printedNodes[i].node.type===\"CallExpression\"||printedNodes[i].node.type===\"OptionalCallExpression\"){hasSeenCallExpression=true;}currentGroup.push(printedNodes[i]);if(printedNodes[i].node.comments&&printedNodes[i].node.comments.some(function(comment){return comment.trailing;})){groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}}if(currentGroup.length>0){groups.push(currentGroup);}// There are cases like Object.keys(), Observable.of(), _.values() where\n// they are the subject of all the chained calls and therefore should\n// be kept on the same line:\n//\n// Object.keys(items)\n// .filter(x => x)\n// .map(x => x)\n//\n// In order to detect those cases, we use an heuristic: if the first\n// node is an identifier with the name starting with a capital\n// letter or just a sequence of _$. The rationale is that they are\n// likely to be factories.\nfunction isFactory(name){return /^[A-Z]|^[_$]+$/.test(name);}// In case the Identifier is shorter than tab width, we can keep the\n// first call in a single line, if it's an ExpressionStatement.\n//\n// d3.scaleLinear()\n// .domain([0, 100])\n// .range([0, width]);\n//\nfunction isShort(name){return name.length<=options.tabWidth;}function shouldNotWrap(groups){var parent=path.getParentNode();var isExpression=parent&&parent.type===\"ExpressionStatement\";var hasComputed=groups[1].length&&groups[1][0].node.computed;if(groups[0].length===1){var firstNode=groups[0][0].node;return firstNode.type===\"ThisExpression\"||firstNode.type===\"Identifier\"&&(isFactory(firstNode.name)||isExpression&&isShort(firstNode.name)||hasComputed);}var lastNode=getLast$3(groups[0]).node;return(lastNode.type===\"MemberExpression\"||lastNode.type===\"OptionalMemberExpression\")&&lastNode.property.type===\"Identifier\"&&(isFactory(lastNode.property.name)||hasComputed);}var shouldMerge=groups.length>=2&&!groups[1][0].node.comments&&shouldNotWrap(groups);function printGroup(printedGroup){var printed=printedGroup.map(function(tuple){return tuple.printed;});// Checks if the last node (i.e. the parent node) needs parens and print\n// accordingly\nif(printedGroup.length>0&&printedGroup[printedGroup.length-1].needsParens){return concat$d([\"(\"].concat(_toConsumableArray2(printed),[\")\"]));}return concat$d(printed);}function printIndentedGroup(groups){if(groups.length===0){return\"\";}return indent$7(group$b(concat$d([hardline$9,join$9(hardline$9,groups.map(printGroup))])));}var printedGroups=groups.map(printGroup);var oneLine=concat$d(printedGroups);var cutoff=shouldMerge?3:2;var flatGroups=groups.reduce(function(res,group){return res.concat(group);},[]);var hasComment=flatGroups.slice(1,-1).some(function(node){return hasLeadingComment$3(node.node);})||flatGroups.slice(0,-1).some(function(node){return hasTrailingComment$1(node.node);})||groups[cutoff]&&hasLeadingComment$3(groups[cutoff][0].node);// If we only have a single `.`, we shouldn't do anything fancy and just\n// render everything concatenated together.\nif(groups.length<=cutoff&&!hasComment){if(isLongCurriedCallExpression$1(path)){return oneLine;}return group$b(oneLine);}// Find out the last node in the first group and check if it has an\n// empty line after\nvar lastNodeBeforeIndent=getLast$3(shouldMerge?groups.slice(1,2)[0]:groups[0]).node;var shouldHaveEmptyLineBeforeIndent=lastNodeBeforeIndent.type!==\"CallExpression\"&&lastNodeBeforeIndent.type!==\"OptionalCallExpression\"&&shouldInsertEmptyLineAfter(lastNodeBeforeIndent);var expanded=concat$d([printGroup(groups[0]),shouldMerge?concat$d(groups.slice(1,2).map(printGroup)):\"\",shouldHaveEmptyLineBeforeIndent?hardline$9:\"\",printIndentedGroup(groups.slice(shouldMerge?2:1))]);var callExpressions=printedNodes.map(function(_ref29){var node=_ref29.node;return node;}).filter(isCallOrOptionalCallExpression$1);// We don't want to print in one line if the chain has:\n// * A comment.\n// * Non-trivial arguments.\n// * Any group but the last one has a hard line.\n// If the last group is a function it's okay to inline if it fits.\nif(hasComment||callExpressions.length>2&&callExpressions.some(function(expr){return!expr.arguments.every(function(arg){return isSimpleCallArgument$1(arg,0);});})||printedGroups.slice(0,-1).some(willBreak$1)||/**\n * scopes.filter(scope => scope.value !== '').map((scope, i) => {\n * // multi line content\n * })\n */function(lastGroupDoc,lastGroupNode){return isCallOrOptionalCallExpression$1(lastGroupNode)&&willBreak$1(lastGroupDoc);}(getLast$3(printedGroups),getLast$3(getLast$3(groups)).node)&&callExpressions.slice(0,-1).some(function(n){return n.arguments.some(isFunctionOrArrowExpression$1);})){return group$b(expanded);}return concat$d([// We only need to check `oneLine` because if `expanded` is chosen\n// that means that the parent group has already been broken\n// naturally\nwillBreak$1(oneLine)||shouldHaveEmptyLineBeforeIndent?breakParent$3:\"\",conditionalGroup$1([oneLine,expanded])]);}",
"print() {\n var runner = this.front; // Start at the front\n while(runner !== null) { // While we're not at the end\n console.log(runner.val); // Print value at current node\n runner = runner.next; // Move to next node\n }\n }",
"function printMemberChain(path,options,print){// The first phase is to linearize the AST by traversing it down.\n//\n// a().b()\n// has the following AST structure:\n// CallExpression(MemberExpression(CallExpression(Identifier)))\n// and we transform it into\n// [Identifier, CallExpression, MemberExpression, CallExpression]\nvar printedNodes=[];function rec(path){var node=path.getValue();if(node.type===\"CallExpression\"&&isMemberish(node.callee)){printedNodes.unshift({node:node,printed:comments$3.printComments(path,function(){return concat$2([printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)]);},options)});path.call(function(callee){return rec(callee);},\"callee\");}else if(isMemberish(node)){printedNodes.unshift({node:node,printed:comments$3.printComments(path,function(){return node.type===\"MemberExpression\"?printMemberLookup(path,options,print):printBindExpressionCallee(path,options,print);},options)});path.call(function(object){return rec(object);},\"object\");}else{printedNodes.unshift({node:node,printed:path.call(print)});}}// Note: the comments of the root node have already been printed, so we\n// need to extract this first call without printing them as they would\n// if handled inside of the recursive call.\nprintedNodes.unshift({node:path.getValue(),printed:concat$2([printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)])});path.call(function(callee){return rec(callee);},\"callee\");// Once we have a linear list of printed nodes, we want to create groups out\n// of it.\n//\n// a().b.c().d().e\n// will be grouped as\n// [\n// [Identifier, CallExpression],\n// [MemberExpression, MemberExpression, CallExpression],\n// [MemberExpression, CallExpression],\n// [MemberExpression],\n// ]\n// so that we can print it as\n// a()\n// .b.c()\n// .d()\n// .e\n// The first group is the first node followed by\n// - as many CallExpression as possible\n// < fn()()() >.something()\n// - then, as many MemberExpression as possible but the last one\n// < this.items >.something()\nvar groups=[];var currentGroup=[printedNodes[0]];var i=1;for(;i<printedNodes.length;++i){if(printedNodes[i].node.type===\"CallExpression\"){currentGroup.push(printedNodes[i]);}else{break;}}for(;i+1<printedNodes.length;++i){if(isMemberish(printedNodes[i].node)&&isMemberish(printedNodes[i+1].node)){currentGroup.push(printedNodes[i]);}else{break;}}groups.push(currentGroup);currentGroup=[];// Then, each following group is a sequence of MemberExpression followed by\n// a sequence of CallExpression. To compute it, we keep adding things to the\n// group until we has seen a CallExpression in the past and reach a\n// MemberExpression\nvar hasSeenCallExpression=false;for(;i<printedNodes.length;++i){if(hasSeenCallExpression&&isMemberish(printedNodes[i].node)){// [0] should be appended at the end of the group instead of the\n// beginning of the next one\nif(printedNodes[i].node.computed&&isLiteral(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);continue;}groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}if(printedNodes[i].node.type===\"CallExpression\"){hasSeenCallExpression=true;}currentGroup.push(printedNodes[i]);if(printedNodes[i].node.comments&&printedNodes[i].node.comments.some(function(comment){return comment.trailing;})){groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}}if(currentGroup.length>0){groups.push(currentGroup);}// There are cases like Object.keys(), Observable.of(), _.values() where\n// they are the subject of all the chained calls and therefore should\n// be kept on the same line:\n//\n// Object.keys(items)\n// .filter(x => x)\n// .map(x => x)\n//\n// In order to detect those cases, we use an heuristic: if the first\n// node is just an identifier with the name starting with a capital\n// letter, just a sequence of _$ or this. The rationale is that they are\n// likely to be factories.\nvar shouldMerge=groups.length>=2&&!groups[1][0].node.comments&&groups[0].length===1&&(groups[0][0].node.type===\"ThisExpression\"||groups[0][0].node.type===\"Identifier\"&&groups[0][0].node.name.match(/(^[A-Z])|^[_$]+$/));function printGroup(printedGroup){return concat$2(printedGroup.map(function(tuple){return tuple.printed;}));}function printIndentedGroup(groups){if(groups.length===0){return\"\";}return indent$2(group$1(concat$2([hardline$2,join$2(hardline$2,groups.map(printGroup))])));}var printedGroups=groups.map(printGroup);var oneLine=concat$2(printedGroups);var cutoff=shouldMerge?3:2;var flatGroups=groups.slice(0,cutoff).reduce(function(res,group){return res.concat(group);},[]);var hasComment=flatGroups.slice(1,-1).some(function(node){return hasLeadingComment(node.node);})||flatGroups.slice(0,-1).some(function(node){return hasTrailingComment(node.node);})||groups[cutoff]&&hasLeadingComment(groups[cutoff][0].node);// If we only have a single `.`, we shouldn't do anything fancy and just\n// render everything concatenated together.\nif(groups.length<=cutoff&&!hasComment&&// (a || b).map() should be break before .map() instead of ||\ngroups[0][0].node.type!==\"LogicalExpression\"){return group$1(oneLine);}var expanded=concat$2([printGroup(groups[0]),shouldMerge?concat$2(groups.slice(1,2).map(printGroup)):\"\",printIndentedGroup(groups.slice(shouldMerge?2:1))]);// If there's a comment, we don't want to print in one line.\nif(hasComment){return group$1(expanded);}// If any group but the last one has a hard line, we want to force expand\n// it. If the last group is a function it's okay to inline if it fits.\nif(printedGroups.slice(0,-1).some(willBreak)){return group$1(expanded);}return concat$2([// We only need to check `oneLine` because if `expanded` is chosen\n// that means that the parent group has already been broken\n// naturally\nwillBreak(oneLine)?breakParent$2:\"\",conditionalGroup$1([oneLine,expanded])]);}",
"print() {\n let node = this.head;\n while (node) {\n console.log(`${node.data}\\n`);\n node = node.next;\n }\n }",
"function printMemberChain(path,options,print){// The first phase is to linearize the AST by traversing it down.\n//\n// a().b()\n// has the following AST structure:\n// CallExpression(MemberExpression(CallExpression(Identifier)))\n// and we transform it into\n// [Identifier, CallExpression, MemberExpression, CallExpression]\nvar printedNodes=[];// Here we try to retain one typed empty line after each call expression or\n// the first group whether it is in parentheses or not\nfunction shouldInsertEmptyLineAfter(node){var originalText=options.originalText;var nextCharIndex=getNextNonSpaceNonCommentCharacterIndex$2(originalText,node,options);var nextChar=originalText.charAt(nextCharIndex);// if it is cut off by a parenthesis, we only account for one typed empty\n// line after that parenthesis\nif(nextChar==\")\"){return isNextLineEmptyAfterIndex$1(originalText,nextCharIndex+1,options);}return isNextLineEmpty$2(originalText,node,options);}function rec(path){var node=path.getValue();if((node.type===\"CallExpression\"||node.type===\"OptionalCallExpression\")&&(isMemberish(node.callee)||node.callee.type===\"CallExpression\"||node.callee.type===\"OptionalCallExpression\")){printedNodes.unshift({node:node,printed:concat$4([comments.printComments(path,function(){return concat$4([printOptionalToken(path),printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)]);},options),shouldInsertEmptyLineAfter(node)?hardline$3:\"\"])});path.call(function(callee){return rec(callee);},\"callee\");}else if(isMemberish(node)){printedNodes.unshift({node:node,needsParens:needsParens_1(path,options),printed:comments.printComments(path,function(){return node.type===\"OptionalMemberExpression\"||node.type===\"MemberExpression\"?printMemberLookup(path,options,print):printBindExpressionCallee(path,options,print);},options)});path.call(function(object){return rec(object);},\"object\");}else if(node.type===\"TSNonNullExpression\"){printedNodes.unshift({node:node,printed:comments.printComments(path,function(){return\"!\";},options)});path.call(function(expression){return rec(expression);},\"expression\");}else{printedNodes.unshift({node:node,printed:path.call(print)});}}// Note: the comments of the root node have already been printed, so we\n// need to extract this first call without printing them as they would\n// if handled inside of the recursive call.\nvar node=path.getValue();printedNodes.unshift({node:node,printed:concat$4([printOptionalToken(path),printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)])});path.call(function(callee){return rec(callee);},\"callee\");// Once we have a linear list of printed nodes, we want to create groups out\n// of it.\n//\n// a().b.c().d().e\n// will be grouped as\n// [\n// [Identifier, CallExpression],\n// [MemberExpression, MemberExpression, CallExpression],\n// [MemberExpression, CallExpression],\n// [MemberExpression],\n// ]\n// so that we can print it as\n// a()\n// .b.c()\n// .d()\n// .e\n// The first group is the first node followed by\n// - as many CallExpression as possible\n// < fn()()() >.something()\n// - as many array acessors as possible\n// < fn()[0][1][2] >.something()\n// - then, as many MemberExpression as possible but the last one\n// < this.items >.something()\nvar groups=[];var currentGroup=[printedNodes[0]];var i=1;for(;i<printedNodes.length;++i){if(printedNodes[i].node.type===\"TSNonNullExpression\"||printedNodes[i].node.type===\"OptionalCallExpression\"||printedNodes[i].node.type===\"CallExpression\"||(printedNodes[i].node.type===\"MemberExpression\"||printedNodes[i].node.type===\"OptionalMemberExpression\")&&printedNodes[i].node.computed&&isNumericLiteral(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);}else{break;}}if(printedNodes[0].node.type!==\"CallExpression\"&&printedNodes[0].node.type!==\"OptionalCallExpression\"){for(;i+1<printedNodes.length;++i){if(isMemberish(printedNodes[i].node)&&isMemberish(printedNodes[i+1].node)){currentGroup.push(printedNodes[i]);}else{break;}}}groups.push(currentGroup);currentGroup=[];// Then, each following group is a sequence of MemberExpression followed by\n// a sequence of CallExpression. To compute it, we keep adding things to the\n// group until we has seen a CallExpression in the past and reach a\n// MemberExpression\nvar hasSeenCallExpression=false;for(;i<printedNodes.length;++i){if(hasSeenCallExpression&&isMemberish(printedNodes[i].node)){// [0] should be appended at the end of the group instead of the\n// beginning of the next one\nif(printedNodes[i].node.computed&&isNumericLiteral(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);continue;}groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}if(printedNodes[i].node.type===\"CallExpression\"||printedNodes[i].node.type===\"OptionalCallExpression\"){hasSeenCallExpression=true;}currentGroup.push(printedNodes[i]);if(printedNodes[i].node.comments&&printedNodes[i].node.comments.some(function(comment){return comment.trailing;})){groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}}if(currentGroup.length>0){groups.push(currentGroup);}// There are cases like Object.keys(), Observable.of(), _.values() where\n// they are the subject of all the chained calls and therefore should\n// be kept on the same line:\n//\n// Object.keys(items)\n// .filter(x => x)\n// .map(x => x)\n//\n// In order to detect those cases, we use an heuristic: if the first\n// node is an identifier with the name starting with a capital letter.\n// The rationale is that they are likely to be factories.\nfunction isFactory(name){return /^[A-Z]/.test(name);}// In case the Identifier is shorter than tab width, we can keep the\n// first call in a single line, if it's an ExpressionStatement.\n//\n// d3.scaleLinear()\n// .domain([0, 100])\n// .range([0, width]);\n//\nfunction isShort(name){return name.length<=options.tabWidth;}function shouldNotWrap(groups){var parent=path.getParentNode();var isExpression=parent&&parent.type===\"ExpressionStatement\";var hasComputed=groups[1].length&&groups[1][0].node.computed;if(groups[0].length===1){var firstNode=groups[0][0].node;return firstNode.type===\"ThisExpression\"||firstNode.type===\"Identifier\"&&(isFactory(firstNode.name)||isExpression&&isShort(firstNode.name)||hasComputed);}var lastNode=getLast$4(groups[0]).node;return(lastNode.type===\"MemberExpression\"||lastNode.type===\"OptionalMemberExpression\")&&lastNode.property.type===\"Identifier\"&&(isFactory(lastNode.property.name)||isExpression&&isShort(lastNode.property.name)||hasComputed);}var shouldMerge=groups.length>=2&&!groups[1][0].node.comments&&shouldNotWrap(groups);function printGroup(printedGroup){var result=[];for(var _i3=0;_i3<printedGroup.length;_i3++){// Checks if the next node (i.e. the parent node) needs parens\n// and print accordingl y\nif(printedGroup[_i3+1]&&printedGroup[_i3+1].needsParens){result.push(\"(\",printedGroup[_i3].printed,printedGroup[_i3+1].printed,\")\");_i3++;}else{result.push(printedGroup[_i3].printed);}}return concat$4(result);}function printIndentedGroup(groups){if(groups.length===0){return\"\";}return indent$2(group$1(concat$4([hardline$3,join$2(hardline$3,groups.map(printGroup))])));}var printedGroups=groups.map(printGroup);var oneLine=concat$4(printedGroups);var cutoff=shouldMerge?3:2;var flatGroups=groups.slice(0,cutoff).reduce(function(res,group){return res.concat(group);},[]);var hasComment=flatGroups.slice(1,-1).some(function(node){return hasLeadingComment(node.node);})||flatGroups.slice(0,-1).some(function(node){return hasTrailingComment(node.node);})||groups[cutoff]&&hasLeadingComment(groups[cutoff][0].node);// If we only have a single `.`, we shouldn't do anything fancy and just\n// render everything concatenated together.\nif(groups.length<=cutoff&&!hasComment){return group$1(oneLine);}// Find out the last node in the first group and check if it has an\n// empty line after\nvar lastNodeBeforeIndent=getLast$4(shouldMerge?groups.slice(1,2)[0]:groups[0]).node;var shouldHaveEmptyLineBeforeIndent=lastNodeBeforeIndent.type!==\"CallExpression\"&&lastNodeBeforeIndent.type!==\"OptionalCallExpression\"&&shouldInsertEmptyLineAfter(lastNodeBeforeIndent);var expanded=concat$4([printGroup(groups[0]),shouldMerge?concat$4(groups.slice(1,2).map(printGroup)):\"\",shouldHaveEmptyLineBeforeIndent?hardline$3:\"\",printIndentedGroup(groups.slice(shouldMerge?2:1))]);var callExpressionCount=printedNodes.filter(function(tuple){return tuple.node.type===\"CallExpression\"||tuple.node.type===\"OptionalCallExpression\";}).length;// We don't want to print in one line if there's:\n// * A comment.\n// * 3 or more chained calls.\n// * Any group but the last one has a hard line.\n// If the last group is a function it's okay to inline if it fits.\nif(hasComment||callExpressionCount>=3||printedGroups.slice(0,-1).some(willBreak$1)){return group$1(expanded);}return concat$4([// We only need to check `oneLine` because if `expanded` is chosen\n// that means that the parent group has already been broken\n// naturally\nwillBreak$1(oneLine)||shouldHaveEmptyLineBeforeIndent?breakParent$2:\"\",conditionalGroup$1([oneLine,expanded])]);}",
"function showBlocks() {\n\tconsole.log(blocks)\n}",
"print() {\n var cur_node = this.head;\n while (cur_node) {\n console.log(cur_node.data);\n cur_node = cur_node.next;\n }\n }",
"function printMemberChain( path, options, print ) {\n\t// The first phase is to linearize the AST by traversing it down.\n\t//\n\t// a().b()\n\t// has the following AST structure:\n\t// CallExpression(MemberExpression(CallExpression(Identifier)))\n\t// and we transform it into\n\t// [Identifier, CallExpression, MemberExpression, CallExpression]\n\tconst printedNodes = []; // Here we try to retain one typed empty line after each call expression or\n\t// the first group whether it is in parentheses or not\n\n\tfunction shouldInsertEmptyLineAfter( node ) {\n\t\tconst { originalText } = options;\n\t\tconst nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3( originalText, node, options.locEnd );\n\t\tconst nextChar = originalText.charAt( nextCharIndex ); // if it is cut off by a parenthesis, we only account for one typed empty\n\t\t// line after that parenthesis\n\n\t\tif ( nextChar === ')' ) {\n\t\t\treturn isNextLineEmptyAfterIndex$2( originalText, nextCharIndex + 1, options.locEnd );\n\t\t}\n\n\t\treturn isNextLineEmpty$2( originalText, node, options.locEnd );\n\t}\n\n\tfunction rec( path ) {\n\t\tconst node = path.getValue();\n\n\t\tif ( ( node.type === 'CallExpression' || node.type === 'OptionalCallExpression' ) && ( isMemberish$1( node.callee ) || node.callee.type === 'CallExpression' || node.callee.type === 'OptionalCallExpression' ) ) {\n\t\t\tprintedNodes.unshift( {\n\t\t\t\tnode,\n\t\t\t\tprinted: concat$6( [ comments.printComments( path, () => concat$6( [ printOptionalToken( path ), printFunctionTypeParameters( path, options, print ), printArgumentsList( path, options, print ) ] ), options ), shouldInsertEmptyLineAfter( node ) ? hardline$4 : '' ] ),\n\t\t\t} );\n\t\t\tpath.call( ( callee ) => rec( callee ), 'callee' );\n\t\t} else if ( isMemberish$1( node ) ) {\n\t\t\tprintedNodes.unshift( {\n\t\t\t\tnode,\n\t\t\t\tneedsParens: needsParens_1( path, options ),\n\t\t\t\tprinted: comments.printComments( path, () => ( node.type === 'OptionalMemberExpression' || node.type === 'MemberExpression' ? printMemberLookup( path, options, print ) : printBindExpressionCallee( path, options, print ) ), options ),\n\t\t\t} );\n\t\t\tpath.call( ( object ) => rec( object ), 'object' );\n\t\t} else if ( node.type === 'TSNonNullExpression' ) {\n\t\t\tprintedNodes.unshift( {\n\t\t\t\tnode,\n\t\t\t\tprinted: comments.printComments( path, () => '!', options ),\n\t\t\t} );\n\t\t\tpath.call( ( expression ) => rec( expression ), 'expression' );\n\t\t} else {\n\t\t\tprintedNodes.unshift( {\n\t\t\t\tnode,\n\t\t\t\tprinted: path.call( print ),\n\t\t\t} );\n\t\t}\n\t} // Note: the comments of the root node have already been printed, so we\n\t// need to extract this first call without printing them as they would\n\t// if handled inside of the recursive call.\n\n\tconst node = path.getValue();\n\tprintedNodes.unshift( {\n\t\tnode,\n\t\tprinted: concat$6( [ printOptionalToken( path ), printFunctionTypeParameters( path, options, print ), printArgumentsList( path, options, print ) ] ),\n\t} );\n\tpath.call( ( callee ) => rec( callee ), 'callee' ); // Once we have a linear list of printed nodes, we want to create groups out\n\t// of it.\n\t//\n\t// a().b.c().d().e\n\t// will be grouped as\n\t// [\n\t// [Identifier, CallExpression],\n\t// [MemberExpression, MemberExpression, CallExpression],\n\t// [MemberExpression, CallExpression],\n\t// [MemberExpression],\n\t// ]\n\t// so that we can print it as\n\t// a()\n\t// .b.c()\n\t// .d()\n\t// .e\n\t// The first group is the first node followed by\n\t// - as many CallExpression as possible\n\t// < fn()()() >.something()\n\t// - as many array accessors as possible\n\t// < fn()[0][1][2] >.something()\n\t// - then, as many MemberExpression as possible but the last one\n\t// < this.items >.something()\n\n\tconst groups = [];\n\tlet currentGroup = [ printedNodes[ 0 ] ];\n\tlet i = 1;\n\n\tfor ( ; i < printedNodes.length; ++i ) {\n\t\tif ( printedNodes[ i ].node.type === 'TSNonNullExpression' || printedNodes[ i ].node.type === 'OptionalCallExpression' || printedNodes[ i ].node.type === 'CallExpression' || ( ( printedNodes[ i ].node.type === 'MemberExpression' || printedNodes[ i ].node.type === 'OptionalMemberExpression' ) && printedNodes[ i ].node.computed && isNumericLiteral$1( printedNodes[ i ].node.property ) ) ) {\n\t\t\tcurrentGroup.push( printedNodes[ i ] );\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ( printedNodes[ 0 ].node.type !== 'CallExpression' && printedNodes[ 0 ].node.type !== 'OptionalCallExpression' ) {\n\t\tfor ( ; i + 1 < printedNodes.length; ++i ) {\n\t\t\tif ( isMemberish$1( printedNodes[ i ].node ) && isMemberish$1( printedNodes[ i + 1 ].node ) ) {\n\t\t\t\tcurrentGroup.push( printedNodes[ i ] );\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tgroups.push( currentGroup );\n\tcurrentGroup = []; // Then, each following group is a sequence of MemberExpression followed by\n\t// a sequence of CallExpression. To compute it, we keep adding things to the\n\t// group until we has seen a CallExpression in the past and reach a\n\t// MemberExpression\n\n\tlet hasSeenCallExpression = false;\n\n\tfor ( ; i < printedNodes.length; ++i ) {\n\t\tif ( hasSeenCallExpression && isMemberish$1( printedNodes[ i ].node ) ) {\n\t\t\t// [0] should be appended at the end of the group instead of the\n\t\t\t// beginning of the next one\n\t\t\tif ( printedNodes[ i ].node.computed && isNumericLiteral$1( printedNodes[ i ].node.property ) ) {\n\t\t\t\tcurrentGroup.push( printedNodes[ i ] );\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tgroups.push( currentGroup );\n\t\t\tcurrentGroup = [];\n\t\t\thasSeenCallExpression = false;\n\t\t}\n\n\t\tif ( printedNodes[ i ].node.type === 'CallExpression' || printedNodes[ i ].node.type === 'OptionalCallExpression' ) {\n\t\t\thasSeenCallExpression = true;\n\t\t}\n\n\t\tcurrentGroup.push( printedNodes[ i ] );\n\n\t\tif ( printedNodes[ i ].node.comments && printedNodes[ i ].node.comments.some( ( comment ) => comment.trailing ) ) {\n\t\t\tgroups.push( currentGroup );\n\t\t\tcurrentGroup = [];\n\t\t\thasSeenCallExpression = false;\n\t\t}\n\t}\n\n\tif ( currentGroup.length > 0 ) {\n\t\tgroups.push( currentGroup );\n\t} // There are cases like Object.keys(), Observable.of(), _.values() where\n\t// they are the subject of all the chained calls and therefore should\n\t// be kept on the same line:\n\t//\n\t// Object.keys(items)\n\t// .filter(x => x)\n\t// .map(x => x)\n\t//\n\t// In order to detect those cases, we use an heuristic: if the first\n\t// node is an identifier with the name starting with a capital\n\t// letter or just a sequence of _$. The rationale is that they are\n\t// likely to be factories.\n\n\tfunction isFactory( name ) {\n\t\treturn /^[A-Z]|^[_$]+$/.test( name );\n\t} // In case the Identifier is shorter than tab width, we can keep the\n\t// first call in a single line, if it's an ExpressionStatement.\n\t//\n\t// d3.scaleLinear()\n\t// .domain([0, 100])\n\t// .range([0, width]);\n\t//\n\n\tfunction isShort( name ) {\n\t\treturn name.length <= options.tabWidth;\n\t}\n\n\tfunction shouldNotWrap( groups ) {\n\t\tconst parent = path.getParentNode();\n\t\tconst isExpression = parent && parent.type === 'ExpressionStatement';\n\t\tconst hasComputed = groups[ 1 ].length && groups[ 1 ][ 0 ].node.computed;\n\n\t\tif ( groups[ 0 ].length === 1 ) {\n\t\t\tconst firstNode = groups[ 0 ][ 0 ].node;\n\t\t\treturn firstNode.type === 'ThisExpression' || ( firstNode.type === 'Identifier' && ( isFactory( firstNode.name ) || ( isExpression && isShort( firstNode.name ) ) || hasComputed ) );\n\t\t}\n\n\t\tconst lastNode = getLast$2( groups[ 0 ] ).node;\n\t\treturn ( lastNode.type === 'MemberExpression' || lastNode.type === 'OptionalMemberExpression' ) && lastNode.property.type === 'Identifier' && ( isFactory( lastNode.property.name ) || hasComputed );\n\t}\n\n\tconst shouldMerge = groups.length >= 2 && ! groups[ 1 ][ 0 ].node.comments && shouldNotWrap( groups );\n\n\tfunction printGroup( printedGroup ) {\n\t\tconst printed = printedGroup.map( ( tuple ) => tuple.printed ); // Checks if the last node (i.e. the parent node) needs parens and print\n\t\t// accordingly\n\n\t\tif ( printedGroup.length > 0 && printedGroup[ printedGroup.length - 1 ].needsParens ) {\n\t\t\treturn concat$6( [ '(', ...printed, ')' ] );\n\t\t}\n\n\t\treturn concat$6( printed );\n\t}\n\n\tfunction printIndentedGroup( groups ) {\n\t\tif ( groups.length === 0 ) {\n\t\t\treturn '';\n\t\t}\n\n\t\treturn indent$3( group$2( concat$6( [ hardline$4, join$4( hardline$4, groups.map( printGroup ) ) ] ) ) );\n\t}\n\n\tconst printedGroups = groups.map( printGroup );\n\tconst oneLine = concat$6( printedGroups );\n\tconst cutoff = shouldMerge ? 3 : 2;\n\tconst flatGroups = groups.reduce( ( res, group ) => res.concat( group ), [] );\n\tconst hasComment = flatGroups.slice( 1, -1 ).some( ( node ) => hasLeadingComment$3( node.node ) ) || flatGroups.slice( 0, -1 ).some( ( node ) => hasTrailingComment$1( node.node ) ) || ( groups[ cutoff ] && hasLeadingComment$3( groups[ cutoff ][ 0 ].node ) ); // If we only have a single `.`, we shouldn't do anything fancy and just\n\t// render everything concatenated together.\n\n\tif ( groups.length <= cutoff && ! hasComment ) {\n\t\tif ( isLongCurriedCallExpression$1( path ) ) {\n\t\t\treturn oneLine;\n\t\t}\n\n\t\treturn group$2( oneLine );\n\t} // Find out the last node in the first group and check if it has an\n\t// empty line after\n\n\tconst lastNodeBeforeIndent = getLast$2( shouldMerge ? groups.slice( 1, 2 )[ 0 ] : groups[ 0 ] ).node;\n\tconst shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== 'CallExpression' && lastNodeBeforeIndent.type !== 'OptionalCallExpression' && shouldInsertEmptyLineAfter( lastNodeBeforeIndent );\n\tconst expanded = concat$6( [ printGroup( groups[ 0 ] ), shouldMerge ? concat$6( groups.slice( 1, 2 ).map( printGroup ) ) : '', shouldHaveEmptyLineBeforeIndent ? hardline$4 : '', printIndentedGroup( groups.slice( shouldMerge ? 2 : 1 ) ) ] );\n\tconst callExpressions = printedNodes.map( ( { node } ) => node ).filter( isCallOrOptionalCallExpression$1 ); // We don't want to print in one line if the chain has:\n\t// * A comment.\n\t// * Non-trivial arguments.\n\t// * Any group but the last one has a hard line.\n\t// If the last group is a function it's okay to inline if it fits.\n\n\tif (\n\t\thasComment ||\n\t\t( callExpressions.length > 2 && callExpressions.some( ( expr ) => ! expr.arguments.every( ( arg ) => isSimpleCallArgument$1( arg, 0 ) ) ) ) ||\n\t\tprintedGroups.slice( 0, -1 ).some( willBreak$1 ) ||\n\t\t/**\n\t\t * scopes.filter(scope => scope.value !== '').map((scope, i) => {\n\t\t * // multi line content\n\t\t * })\n\t\t */\n\t\t( ( ( lastGroupDoc, lastGroupNode ) => isCallOrOptionalCallExpression$1( lastGroupNode ) && willBreak$1( lastGroupDoc ) )( getLast$2( printedGroups ), getLast$2( getLast$2( groups ) ).node ) && callExpressions.slice( 0, -1 ).some( ( n ) => n.arguments.some( isFunctionOrArrowExpression$1 ) ) )\n\t) {\n\t\treturn group$2( expanded );\n\t}\n\n\treturn concat$6( [\n\t\t// We only need to check `oneLine` because if `expanded` is chosen\n\t\t// that means that the parent group has already been broken\n\t\t// naturally\n\t\twillBreak$1( oneLine ) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : '',\n\t\tconditionalGroup$1( [ oneLine, expanded ] ),\n\t] );\n}",
"function printBlockInfo(block) {\n console.log(`id: ${block.id} - CSS classes: ${block.className}`); // just a log ...\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
crea el grupo de radios asociados a un nombre y lo inserta en el elemento que se le dice. no devuelve nada xD | function createRadioGroup(options, name, parent) {
for (let i = 0; i < options.length; i++) {
let radioTemp = document.createElement("input");
radioTemp.type = "radio";
radioTemp.value = options[i];
radioTemp.id = options[i];
radioTemp.name = name;
let label = crearLabel(options[i], radioTemp.id);
parent.appendChild(radioTemp);
parent.appendChild(label);
}
} | [
"function AddRadioButtonGroup(row, caption, name) {\n // ajout de caption dans la cellule (row, 0)\n CellSetText(row, 0, caption);\n\n // parcourt des arguments qui suivent row, caption et name\n // exemple: si on fait l'appel suivant\n // AddRadioButtonGroup(row, caption, name, \"masculin\", \"féminin\")\n // arguments[0] = row, arguments[1] = caption, arguments[2] = name\n // arguments[3]=\"masculin\" et argumuments[4]=\"féminin\"\n for (i = 3; i < arguments.length; i++) {\n // Création d'un div conteneur du bouton radio\n divObject = document.createElement(\"div\");\n divObject.setAttribute(\"class\", \"radio\");\n // alternance de couleur de fond\n if (i % 2)\n divObject.style.backgroundColor = \"#eee\";\n else\n divObject.style.backgroundColor = \"#ddd\";\n // Création du bouton radio\n radioObject = document.createElement(\"input\");\n radioObject.type = \"radio\";\n radioObject.name = name;\n radioObject.value = i - 3;\n radioObject.id = name + \"_\" + (i - 3);\n if (i == 3) {\n // premier bouton du groupe\n // servira éventuellement à repérer un groupe\n // afin de déterminer si un choix a été fait\n radioObject.setAttribute(\"class\", \"RadioButtonGroup\");\n }\n\n // Création du label associé au bouton radio\n labelObject = document.createElement(\"label\");\n labelObject.setAttribute(\"for\", radioObject.id);\n labelObject.appendChild(document.createTextNode(arguments[i]));\n\n // insertion du bouton radio et de son label dans le div \n divObject.appendChild(radioObject);\n divObject.appendChild(labelObject);\n\n // insertion du div dans la cellule (row,2)\t\n CellAppendChild(row, 1, divObject);\n }\n}",
"function segment_add_groupe(){\n\t//Get the remaining groupes\n\t\n\t//The limitation\n\tvar local_hidden_groupe_limitation = document.getElementById('hidden_groupe_limitation').value;\n\t\n\t//The row to increment !\n\tvar local_hidden_groupe_incrementation \t= document.getElementById('hidden_groupe_incrementation').value;\n\n\t\n\t//Test if we have the right to add a new row \n\tif(local_hidden_groupe_limitation>0){\n\t\t//Disable the add buttons (Fields, Groupes)\n\t\tdisable_add_buttons();\n\t\t\n\t\t//Incrementing to put the new id !\n\t\tlocal_hidden_groupe_incrementation++;\n\t\tdocument.getElementById('hidden_groupe_incrementation').value\t= local_hidden_groupe_incrementation;\n\t\t\n\t\t\n\t\t//Decrementing the remaining rows\n\t\tlocal_hidden_groupe_limitation--;\n\t\tdocument.getElementById('hidden_groupe_limitation').value\t= local_hidden_groupe_limitation;\n\t\t\n\t\t//Tell the user the number of remaining items\n\t\ttell_user_remaining_items(local_hidden_groupe_limitation, document.getElementById('hidden_field_limitation').value);\n\t\t\n\t\t\n\t\t//Start Building element !\n\t\tvar actual_groupe_id= local_hidden_groupe_incrementation;\n\t\t\n\t\tvar groupe_row_radio\t\t= \" <input type=\\\"radio\\\" id=\\\"row_groupe_what_\"+local_hidden_groupe_incrementation+\"_and\\\" name=\\\"row_groupe_what\"+local_hidden_groupe_incrementation+\"\\\" value=\\\"AND\\\" checked=\\\"true\\\" />\"+\n\t\t\t\t\t\t\t\t\t\"<label for=\\\"row_groupe_what_\"+local_hidden_groupe_incrementation+\"_and\\\">Et</label>\"+\n\t\t\t\t\t\t\t\t\t\"<input type=\\\"radio\\\" id=\\\"row_groupe_what_\"+local_hidden_groupe_incrementation+\"_or\\\" name=\\\"row_groupe_what\"+local_hidden_groupe_incrementation+\"\\\" value=\\\"OR\\\" />\"+\n\t\t\t\t\t\t\t\t\t\"<label for=\\\"row_groupe_what_\"+local_hidden_groupe_incrementation+\"_or\\\">Ou</label>\";\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\tvar built_element\t= \" <div id=\\\"groupe_\"+actual_groupe_id+\"\\\" class=\\\"groupe_container\\\">\"+\n\t\t\t\t\t\t\t\t\t\"<div class=\\\"segment-groupe-line-separator\\\"> </div>\"+\n\t\t\t\t\t\t\t\t\t\"<div class=\\\"groupe_top\\\">\"+\n\t\t\t\t\t\t\t\t\t\t\"<div id=\\\"groupe_\"+actual_groupe_id+\"_what\\\" \"+ \n\t\t\t\t\t\t\t\t\t\t\t\"class=\\\"groupe_what\\\">\"+groupe_row_radio+\"</div>\"+\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\"<div id=\\\"groupe_\"+actual_groupe_id+\"_delete\\\" \"+ \n\t\t\t\t\t\t\t\t\t\t\t\"class=\\\"groupe_delete\\\">\"+\n\t\t\t\t\t\t\t\t\t\t\t\"<div title=\\\"Supprimer ce groupe\\\" onclick=\\\"field_listner_delete_groupe('\"+actual_groupe_id+\"');\\\">\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\"<i class=\\\"fa fa-trash\\\"></i>\"+\n\t\t\t\t\t\t\t\t\t\t\t\"</div>\"+\n\t\t\t\t\t\t\t\t\t\t\"</div>\"+\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\"<div id=\\\"groupe_\"+actual_groupe_id+\"_name\\\" class=\\\"groupe_name\\\">\"+\n\t\t\t\t\t\t\t\t\t\t\t\"<input type=\\\"search\\\" id=\\\"groupe_name_\"+actual_groupe_id+\"\\\" placeholder=\\\"Nom du groupe \"+actual_groupe_id+\"\\\" />\"+\n\t\t\t\t\t\t\t\t\t\t\"</div>\"+\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\"<div class=\\\"groupe_add_listner_field\\\">\"+\n\t\t\t\t\t\t\t\t\t\t\t\"<input type=\\\"button\\\" class=\\\"btn btn-default btn_row_field_add\\\" value=\\\"Ajouter un champ\\\" onclick=\\\"segment_add_new_field_row('\"+actual_groupe_id+\"')\\\" />\"+\n\t\t\t\t\t\t\t\t\t\t\"</div>\"+\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\"</div><!-- end div .groupe_top -->\"+\n\t\t\t\t\n\t\t\t\t\t\t\t\t\t\"<div id=\\\"groupe_middle_\"+actual_groupe_id+\"\\\" class=\\\"groupe_middle\\\">\"+\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\"</div><!-- end div .groupe_middle-->\"+\n\t\t\t\t\n\t\t\t\t\t\t\t\t\"</div><!-- div #groupe_X-->\";\n\t\t\n\t\t//Put the Built element on place !\n\t\t//document.getElementById('segment_middle_part').innerHTML\t+= built_element;\n\t\t$(\"#segment_middle_part\").append(built_element);\n\n\t\t//Add a effect when the new groupe is on page !\n\t\t$(\"#groupe_\"+actual_groupe_id).effect('slide', 500, function(){\n\t\t\t//Enable the Add Buttons (Field, Groupe..)\n\t\t\tenable_add_buttons();\n\t\t});\n\t\t\n\t}else{\n\t\tvar title \t= 'Limite des \\351lements !';\n\t\tvar errors\t= 'Vous avez atteint la limite des groupes !';\n\t\tsegment_error_display_modal('segment_errors', title, errors);\n\t}//end else if test remaining groupes !\n}",
"function newOptionRadio(ele) {\n item = ele.id.split(\"_\")[ele.id.split(\"_\").length - 1];\n opt = $('.option-radio_'+item);\n num = opt.length;\n if (num) {\n id = opt[num - 1].id.split(\"_\")[opt[num - 1].id.split(\"_\").length - 1];\n num = parseInt(id) + 1;\n }else{\n num = 1\n } \n newELemento = $(\"#option-radio\").clone().appendTo(\"#option_destion_\"+item);\n newELemento.addClass('option-radio_'+item);\n newELemento.children().children().children().children().attr('id','delete_option_radio_'+item+'_'+num).click(function (e) {\n e.preventDefault();\n deleteOptionRadio(this);\n });\n newELemento.attr('id','option-radio_'+item+'_'+num);\n newELemento.children().children().children().val('Option '+num);\n $('#num_option_'+item).val((opt.length + 1));\n}",
"function createRadioButtonsDatabase() {\n // alle Bilder in Array.lenght\n // for (let i: number, i<array.lenght, i++)\n //let radioButton.createElement(\"input\")\n // .type=\"radio\"\n // .id= i + \"_radioDB\"\n // .name = radioButtons_startPage\n // . class=\"radioButtons_startPage_db\"\n // .value =[i].db.width\n //append to parent\n //createElement(\"label\")\n //let label.createElement(\"label\")\n // .for = radio.id\n // .innerText = db.name + db.author + db.date\n }",
"function newRadioGroup() {\n var label = document.createElement(\"input\");\n label.type = \"text\";\n label.placeholder = \"Put the radio group's text here\";\n label.style.margin = \"10px 0px\";\n var deleteButton = document.createElement(\"button\");\n deleteButton.style.backgroundColor = \"red\";\n deleteButton.innerHTML = \"X\";\n deleteButton.onclick = function() {this.remove();deleteElement(this.className);};\n var newLine = document.createElement(\"br\");\n\n questionsLength = questions.length;\n label.className = \"_\" + questionsLength;\n deleteButton.className = \"_\" + questionsLength;\n newLine.className = \"_\" + questionsLength;\n\n questions.push([\"radioGroup\", label]);\n insideEditor.appendChild(label);\n insideEditor.appendChild(deleteButton);\n insideEditor.appendChild(newLine);\n}",
"function crearRadio(i) {\n\n var numSol = xmlDoc.getElementsByTagName('pregunta')[i].getElementsByTagName('respuesta').length;\n var element = document.getElementById(\"myForm\");\n\n var div = document.createElement(\"div\");\n div.setAttribute(\"id\", \"div\" + i);\n div.setAttribute(\"class\", \"pregunta\");\n element.appendChild(div);\n\n var enunciado = document.createElement(\"label\");\n enunciado.setAttribute('for', i);\n enunciado.innerHTML = xmlDoc.getElementsByTagName('pregunta')[i].getElementsByTagName('enunciado')[0].innerHTML + \"<br>\";\n\n\n /*Mostrar imagen del XML en caso de haberla*/\n var imagen = xmlDoc.getElementsByTagName('pregunta')[i].getElementsByTagName('img')[0];\n if (imagen){\n var img = document.createElement(\"img\");\n img.setAttribute(\"src\", xmlDoc.getElementsByTagName('pregunta')[i].getElementsByTagName('img')[0].innerHTML);\n div.appendChild(img)\n }\n div.appendChild(enunciado);\n \n for (var k = 0; k < numSol; k++) {\n\n var question = xmlDoc.getElementsByTagName('pregunta')[i].getElementsByTagName('respuesta')[k].innerHTML;\n var radioBut = document.createElement(\"input\");\n\n radioBut.setAttribute(\"type\", \"radio\");\n radioBut.setAttribute(\"name\", i);\n radioBut.setAttribute(\"value\", k);\n radioBut.setAttribute('id', k + \"radio\");\n div.appendChild(radioBut);\n\n var label = document.createElement('label');\n label.setAttribute('for', i);\n label.innerHTML = question + \"<br>\";\n\n div.appendChild(label);\n }\n\n\n}",
"function newRadioButton(){\n var radioButton = document.createElement(\"input\");\n radioButton.type = \"radio\";\n radioButton.style.margin = \"0px 0px 0px 10px\";\n lastRadioGroup = 0;\n for (var i = 0; i < questions.length; i++) {\n if(questions[i][0] === \"radioGroup\"){\n lastRadioGroup = i;\n }\n }\n radioButton.name = \"\" + lastRadioGroup;\n radioButton.disabled = \"yes\";\n var label = document.createElement(\"input\");\n label.type = \"text\";\n label.placeholder = \"Put the radio button's text here\";\n label.style.margin = \"10px 0px\";\n var deleteButton = document.createElement(\"button\");\n deleteButton.style.backgroundColor = \"red\";\n deleteButton.innerHTML = \"X\";\n deleteButton.onclick = function() {this.remove();deleteElement(this.className);};\n var newLine = document.createElement(\"br\");\n\n questionsLength = questions.length;\n radioButton.className = \"_\" + questionsLength;\n label.className = \"_\" + questionsLength;\n deleteButton.className = \"_\" + questionsLength;\n newLine.className = \"_\" + questionsLength;\n\n questions.push([\"radioButton\", label]);\n insideEditor.appendChild(radioButton);\n insideEditor.appendChild(label);\n insideEditor.appendChild(deleteButton);\n insideEditor.appendChild(newLine);\n}",
"function add_node_of_treeview(p_radio_obj, p_hdn_item_id_obj, p_fuseaction) {\n //Xac dinh Radio dang chon\n var v_count;\n var v_current_radio_id = \"\"\n try {\n v_count = p_radio_obj.length;\n if (v_count) {\n for (i = 0; i < v_count; i++) {\n if (p_radio_obj[i].checked) {\n v_current_radio_id = p_radio_obj[i].value;\n break;\n }\n }\n } else {\n if (p_radio_obj.checked) {\n v_current_radio_id = p_radio_obj.value;\n }\n }\n } catch (e) {\n ;\n }\n p_hdn_item_id_obj.value = v_current_radio_id;\n document.forms[0].fuseaction.value = p_fuseaction;\n document.forms[0].submit();\n}",
"function llenarSubtipo(respuesta)\n{\n var cont = 0;\n for(valor of respuesta[\"respuesta\"])\n {\n var divP = document.createElement(\"div\");\n var rad = document.createElement(\"input\");\n var labl = document.createElement(\"label\");\n rad.type = \"radio\";\n rad.name = \"ProdSeleccionado\";\n rad.id = \"Producto\"+cont;\n labl.setAttribute(\"for\",\"Producto\"+cont);\n labl.innerHTML = valor;\n labl.id = \"labProd\"+cont;\n rad.value = valor;\n divP.classList.add(\"flexFatherLeftRow\",\"global\",\"width100\");\n rad.classList.add(\"flexItem\",\"global\");\n labl.classList.add(\"global\",\"textLeftMargin\");\n if(cont==0)\n {\n rad.setAttribute(\"checked\",\"true\");\n }\n divP.appendChild(rad);\n divP.appendChild(labl);\n global.formElemento.appendChild(divP);\n cont++;\n }\n if(respuesta[\"toppings\"]!=\"false\")\n { \n document.querySelector(\"#pedirProd\").insertBefore(global.separador,document.querySelector(\"#precio\"));\n global.topps.innerHTML = global.askNumTop1;\n askNumTop = document.querySelector(\"#num_Toppings\");\n if(askNumTop)\n {\n crearEventosRadios();\n }\n if(!global.banderaCreado)\n {\n var sicSpec = behavePizzas()[1];\n var regSpec = behavePizzas()[2];\n var regPizza = behavePizzas()[5];\n var sicPizza = behavePizzas()[6];\n\n askNumTop.addEventListener(\"change\",function(){\n noMayoraCinco(regSpec,sicSpec,regPizza,sicPizza);\n document.querySelector(\"#selTopFather\").innerHTML = \"\";\n global.banderaCreado = true;\n if(askNumTop.value==\"\")\n askNumTop.value = 0;\n \n for(let i=0;i<askNumTop.value;i++)\n {\n var seltopps = document.createElement(\"div\");\n seltopps.innerHTML = \"<select class='global form-control' id='selToppings\"+(i+1)+\"'></select>\";\n for(valor of respuesta[\"toppings\"])\n {\n var opciontop = document.createElement(\"option\");\n opciontop.innerHTML = valor;\n seltopps.children[0].appendChild(opciontop);\n }\n document.querySelector(\"#selTopFather\").appendChild(seltopps);\n }\n });\n askNumTop.dispatchEvent(global.eventoCambio);\n }\n }\n global.pedirProd.addEventListener(\"change\",cargarPrecio);\n global.pedirProd.dispatchEvent(global.eventoCambio);\n}",
"function createRadios(quesAndAns) {\n var radioList = document.createElement('div');\n for (var i = 0; i < quesAndAns.choices.length; i++) {\n radioList.appendChild(document.createElement('br'));\n var inputObj = document.createElement('div');\n inputObj.innerHTML = '<input type = \"radio\" name= \"answer\" value='+i+'></input>'+quesAndAns.choices[i];\n radioList.appendChild(inputObj);\n }\n return radioList;\n}",
"_createRadioButton() {\n const outerCircle = this._createCircle({\n r: this.outerRadius + this.border * 0.5,\n color: '#bdbdbd',\n stroke: true,\n border: this.border,\n });\n this.outerCircle = outerCircle;\n outerCircle.x = this.outerRadius + this.border * 0.5;\n outerCircle.y = this.outerRadius + this.border * 0.5;\n\n const container = new createjs.Container();\n\n const inCircle = this._createCircle({\n r: this.outerRadius,\n color: '#3896fc',\n fill: true,\n });\n inCircle.x = outerCircle.x;\n inCircle.y = outerCircle.y;\n this.radioContainer = inCircle;\n\n const innerCircle = this._createCircle({\n r: this.innerRadius,\n color: '#FFFFFF',\n fill: true,\n });\n innerCircle.x = outerCircle.x;\n innerCircle.y = outerCircle.y;\n\n container.addChild(inCircle, innerCircle);\n this.addChild(outerCircle, container);\n }",
"function datosClubSki() {\n //para prevenir que se le de una y otra vez.\n this.disabled = true;\n let regExSocio = \"^[1-9][0-9]{4}$\";\n let nSocio = crearInputText(regExSocio, \"socio\", \"Número de socio\", false, \"Tu numero de socio de 5 cifras\");\n //cambiar donde se adjuntan\n this.parentNode.appendChild(nSocio);\n createRadioGroup([\"infantil\", \"juvenil\", \"senior\"], \"categoria\", this.parentNode);\n}",
"function createRadioGroup(name, descriptions, initiallyCheckedIndex) {\n var fragment = document.createDocumentFragment();\n for (var i = 0; i < descriptions.length; i++) {\n var radio = document.createElement(\"input\");\n radio.type = \"radio\";\n radio.name = name;\n radio.value = i;\n if (i==initiallyCheckedIndex) {\n radio.checked = true;\n }\n fragment.appendChild(radio);\n fragment.appendChild(document.createTextNode(descriptions[i]));\n fragment.appendChild(document.createElement(\"br\"));\n }\n return fragment;\n}",
"function createShapeInputs() {\n let ShapeSelectionDiv = document.getElementById('shape_selction');\n\n listOfShapes.forEach(element => {\n let radioInput = document.createElement('input');\n radioInput.setAttribute('name','shape');\n radioInput.setAttribute('type','radio');\n radioInput.setAttribute('id',element);\n radioInput.setAttribute('value',element);\n \n let labelTpl = document.createElement('label');\n labelTpl.setAttribute('for',element);\n labelTpl.innerHTML = element;\n \n let containerPara = document.createElement('p');\n \n containerPara.appendChild(radioInput);\n containerPara.appendChild(labelTpl);\n ShapeSelectionDiv.appendChild(containerPara);\n });\n\n}",
"function createRadios(index) {\n var radioList = $('<ul>');\n var item;\n var input = '';\n for (var i = 0; i < questions[index].choices.length; i++) {\n item = $('<li>');\n input = '<input type=\"radio\" name=\"answer\" value=' + i + ' />';\n input += questions[index].choices[i];\n item.append(input);\n radioList.append(item);\n }\n return radioList;\n }",
"function makeRadio() {\n radio = createRadio();\n radio.position(width/2 - 80, 10);\n radio.option(\"Rectangle\");\n radio.option(\"Ellipse\");\n}",
"createRegionRadioButtons() {\n let regionList = this.regions.getAllRegions();\n \n let parent = document.getElementById('region-selector-container');\n this.clearChildNodes(parent);\n \n for (let region of regionList) {\n this.createRegionRadioButton(region, parent);\n }\n \n let defaultBtn = document.querySelector(`#region-World`);\n defaultBtn.checked = true;\n }",
"function createRadios(index) {\n \n var item;\n var radioList = $('<ul>'); \n var input = '';\n for (var i = 0; i < questions[index].choices.length; i++) {\n \n item = $('<li>');\n \n \n input = '<input type=\"radio\" name=\"answer\" value=' + i + ' />';\n \n input += questions[index].choices[i];\n item.append(input);\n var label = document.createElement(\"label\");\n label.name = \"answer\";\n item.append(label) \n radioList.append(item);\n\n }\n return radioList;\n }",
"function creatButton() {\n for (let i = 0; i < 60; i++) {\n let newButton = document.createElement(\"input\");\n newButton.setAttribute(\"type\", \"radio\");\n newButton.setAttribute(\"name\", \"dirts\");\n newButton.className = \"dirts\";\n gameContainer.appendChild(newButton);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the index of the current segment we are in given time elapsed. Will return the last segment still if race has ended | _getSegIndex (timeElapsed) {
let i = this._cachedIndex
// Invariant a[0..i].startTime < timeElapsed
while (i+1 < this._dna.length && this._dna[i+1].startTime < timeElapsed) i++
this._cachedIndex = i
return i
} | [
"function currentTimeSegment(timeFrame) {\n\t\tvar step = $scope.timeSegmentsList[0].segmentRange;\n\t\tvar indexInTimeSegments = Math.floor(timeFrame / step);\n\t\tif (indexInTimeSegments == $scope.timeSegmentsList.length) indexInTimeSegments--;\n\t\treturn indexInTimeSegments;\n\t}",
"getSegment(deltaTime) {\n for (let i = this.segments.length - 1; i >= 0; i--) {\n if (deltaTime >= this.segments[i].init_time) {\n return this.segments[i];\n }\n }\n }",
"function findCurrentSegment(time) {\n var numCaptions = $(\".caption\").length;\n var timeAccumulator = 0;\n\n var currentSegment = $(\".caption\").first();\n for (var i = 0; i < numCaptions; i++) {\n if (timeAccumulator > time) {\n break;\n }\n\n currentSegment = $(\".caption\").eq(i);\n currentSegment.data(\"startingTime\", timeAccumulator);\n timeAccumulator += parseFloat(currentSegment.data(\"time\")) + (2/64); // 2/64 accounts for border...\n }\n return currentSegment;\n}",
"_search(time, param = \"time\") {\n if (this._timeline.length === 0) {\n return -1;\n }\n let beginning = 0;\n const len = this._timeline.length;\n let end = len;\n if (len > 0 && this._timeline[len - 1][param] <= time) {\n return len - 1;\n }\n while (beginning < end) {\n // calculate the midpoint for roughly equal partition\n let midPoint = Math.floor(beginning + (end - beginning) / 2);\n const event = this._timeline[midPoint];\n const nextEvent = this._timeline[midPoint + 1];\n if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"EQ\"])(event[param], time)) {\n // choose the last one that has the same time\n for (let i = midPoint; i < this._timeline.length; i++) {\n const testEvent = this._timeline[i];\n if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"EQ\"])(testEvent[param], time)) {\n midPoint = i;\n }\n else {\n break;\n }\n }\n return midPoint;\n }\n else if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"LT\"])(event[param], time) && Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"GT\"])(nextEvent[param], time)) {\n return midPoint;\n }\n else if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"GT\"])(event[param], time)) {\n // search lower\n end = midPoint;\n }\n else {\n // search upper\n beginning = midPoint + 1;\n }\n }\n return -1;\n }",
"_search(time, param = \"time\") {\n if (this._timeline.length === 0) {\n return -1;\n }\n\n let beginning = 0;\n const len = this._timeline.length;\n let end = len;\n\n if (len > 0 && this._timeline[len - 1][param] <= time) {\n return len - 1;\n }\n\n while (beginning < end) {\n // calculate the midpoint for roughly equal partition\n let midPoint = Math.floor(beginning + (end - beginning) / 2);\n const event = this._timeline[midPoint];\n const nextEvent = this._timeline[midPoint + 1];\n\n if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"EQ\"])(event[param], time)) {\n // choose the last one that has the same time\n for (let i = midPoint; i < this._timeline.length; i++) {\n const testEvent = this._timeline[i];\n\n if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"EQ\"])(testEvent[param], time)) {\n midPoint = i;\n } else {\n break;\n }\n }\n\n return midPoint;\n } else if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"LT\"])(event[param], time) && Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"GT\"])(nextEvent[param], time)) {\n return midPoint;\n } else if (Object(_Math__WEBPACK_IMPORTED_MODULE_3__[\"GT\"])(event[param], time)) {\n // search lower\n end = midPoint;\n } else {\n // search upper\n beginning = midPoint + 1;\n }\n }\n\n return -1;\n }",
"function findCurrentPosition(t) {\n const pos = timingData.findIndex((i) => i.seconds > t);\n return pos > 0 ? pos - 1 : 0;\n}",
"function findDataIndex(arr, time, lo, hi) {\n if (lo >= hi)\n return -1;\n var mid = Math.floor(lo + (hi - lo) / 2);\n if (time >= arr[mid].end)\n return findDataIndex(arr, time, mid, hi);\n if (time < arr[mid].start)\n return findDataIndex(arr, time, lo, mid);\n return mid;\n }",
"segmentMoveIndex(moveNumber, segment) {\n return Math.ceil(moveNumber / 2 ** segment)\n }",
"function whichSub(currentTime) {\n var time = 0;\n var id = 0;\n while (time < currentTime) {\n time = content[id][\"end_time\"];\n id += 1;\n }\n id -= 1;\n return id\n}",
"segment (idx) { return this._segments[idx] }",
"getCurrentTimeSlotIndex() {\n let r = -1;\n this.settings.map((setting, i) => {\n if ((setting.begin[0] < now().hour ||\n (setting.begin[1] <= now().minute &&\n setting.begin[0] == now().hour)) &&\n (setting.end[0] > now().hour ||\n (setting.end[1] > now().minute && setting.end[0] == now().hour))) {\n r = i;\n }\n });\n if (r == -1) {\n if (this.settings[0].begin[0] > now().hour ||\n (this.settings[0].begin[1] > now().minute &&\n this.settings[0].begin[0] == now().hour)) {\n r = -2;\n }\n }\n return r;\n }",
"function findSegmentIndex(t, parameterSubdivision)\n{\n var x = t;\n var index = 0;\n var rawX = t;\n\n for(var i = 0; i < parameterSubdivision.length; i++)\n {\n if(x - parameterSubdivision[i] < 0)\n {\n index = i + 1;\n x = THREE.Math.clamp(x / parameterSubdivision[i], 0, 1);\n break;\n }\n else\n {\n x -= parameterSubdivision[i];\n rawX -= parameterSubdivision[i];\n }\n }\n\n return [index, x, rawX];\n}",
"function whichSub(currentTime) {\n var time = 0;\n var id = 0;\n while (time < currentTime) {\n time = content[id][\"end_time\"];\n id += 1;\n }\n id -= 1;\n return id\n}",
"function getMeetingIndex(start_time, end_time) {\n var sTime = start_time.split(':');\n var lTime = end_time.split(':');\n return Math.floor(Math.abs(((new Date().setHours(sTime[0], sTime[1]) - new Date().setHours(lTime[0], lTime[1])) / 1000) / (minutes_in_slot * 60)));\n}",
"getSegmentIndexByDistance(distance, firstPointIndex, lastPointIndex) {\n let toIndex = lastPointIndex;\n\n for (let i = firstPointIndex; i <= lastPointIndex; i++) {\n let relativeDistance = this.distances[i] - this.distances[firstPointIndex];\n\n if (relativeDistance > distance) {\n toIndex = i;\n break;\n }\n }\n\n return toIndex - 1;\n }",
"lastSegment () {\n const idx = this.lastIdx()\n return (idx >= 0) ? this._segments[this.lastIdx()] : null\n }",
"findSegmentIndex(z) {\n let segment = this.segments[Math.floor(z / ROAD_PARAM.SEGMENT_LENGTH) % this.segments.length];\n return this.segments.findIndex(x => x === segment);\n }",
"function callIndexSearch (calls, t)\r\n{\r\n var tot = calls.length;\r\n var upper = tot;\r\n var lower = 0;\r\n while(upper - lower > 1) {\r\n var curr = Math.floor((upper + lower)/2);\r\n if(calls[curr].startTime <= t) {\r\n lower = curr + 1;\r\n }\r\n else {\r\n upper = curr;\r\n }\r\n }\r\n return lower;\r\n}",
"function getIndexIfInSectionTimeExists(time, sectionTimes){\n\tfor (var i = 0; i < sectionTimes.length; i++){\n\t\tif ((time.day == sectionTimes[i].day)\n\t\t\t\t&& (time.startTime == sectionTimes[i].startTime)\n\t\t\t\t&& (time.endTime == sectionTimes[i].endTime)){ \n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary | pipeResponseToFile(response, destinationStream, isGzip) {
return __awaiter(this, void 0, void 0, function* () {
yield new Promise((resolve, reject) => {
if (isGzip) {
const gunzip = zlib.createGunzip();
response.message
.on('error', error => {
core.error(`An error occurred while attempting to read the response stream`);
gunzip.close();
destinationStream.close();
reject(error);
})
.pipe(gunzip)
.on('error', error => {
core.error(`An error occurred while attempting to decompress the response stream`);
destinationStream.close();
reject(error);
})
.pipe(destinationStream)
.on('close', () => {
resolve();
})
.on('error', error => {
core.error(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
reject(error);
});
}
else {
response.message
.on('error', error => {
core.error(`An error occurred while attempting to read the response stream`);
destinationStream.close();
reject(error);
})
.pipe(destinationStream)
.on('close', () => {
resolve();
})
.on('error', error => {
core.error(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
reject(error);
});
}
});
return;
});
} | [
"pipeResponseToFile(response, destinationStream, isGzip) {\n return __awaiter(this, void 0, void 0, function* () {\n yield new Promise((resolve, reject) => {\n if (isGzip) {\n const gunzip = zlib.createGunzip();\n response.message\n .pipe(gunzip)\n .pipe(destinationStream)\n .on('close', () => {\n resolve();\n })\n .on('error', error => {\n core.error(`An error has been encountered while decompressing and writing a downloaded file to ${destinationStream.path}`);\n reject(error);\n });\n }\n else {\n response.message\n .pipe(destinationStream)\n .on('close', () => {\n resolve();\n })\n .on('error', error => {\n core.error(`An error has been encountered while writing a downloaded file to ${destinationStream.path}`);\n reject(error);\n });\n }\n });\n return;\n });\n }",
"function unzipAndStreamRemote(fileName)\n{\n //console.log(\"Unzipping \"+fileName );\n return request(fileName)\n .pipe(unzip.Parse());\n}",
"async read(output, startIndex, count) {\n if (this.containsDownloadParam(this.context.request.rawUrl)) {\n this.addContentDisposition(this.name);\n }\n const fd = await util_1.promisify(fs_1.open)(this.fullPath, 'r');\n const fileStream = fs_1.createReadStream(this.fullPath, {\n flags: 'r',\n fd: fd,\n start: startIndex,\n end: startIndex + count\n });\n await new Promise((resolve, reject) => {\n fileStream.pipe(output);\n fileStream.on('error', (error) => reject(error));\n output.on('finish', () => resolve());\n output.on('end', () => resolve());\n output.on('error', (error) => reject(error));\n });\n }",
"function decompress(){ \n const zipFile = __dirname + '/source2.txt.gz'; \n const readStream = fs.createReadStream(zipFile);\n const newFileName = __dirname + '/destination.txt'; \n const writeStream = fs.createWriteStream(newFileName); \n readStream.pipe(gunzip).pipe(writeStream);\n}",
"function processUngzipStream(extract, callbackfn) {\n var data = [];\n\n extract.on('data', chunk => { data += chunk; });\n extract.on('end', () => { callbackfn(data); });\n}",
"sendFileContents() {\n\n\t\ttry {\n\n\t\t\t// If the file wasnt found, stop here and let the router handler stuff\n\t\t\tlet fileStream$= this.fetchFileContents(this.props.request.url);\n\n\t\t\t// Stop rendering other stuff because this is the stuff needed\n\t\t\tthis.terminate();\n\n\t\t\t// Set the mime-type of the file requested\n\t\t\tthis.props.response\n\t\t\t\t.setHeader(\n\t\t\t\t\t'Content-Type', \n\t\t\t\t\tmime.lookup(this.props.request.url) || 'text/plain'\n\t\t\t\t);\n\n\t\t\t// Wrapper for the response stream\n\t\t\tfileStream$= this._compressStream(fileStream$);\n\n\t\t\tfileStream$.pipe(this.props.response);\n\n\t\t} catch(e) { if(this.hadPrefix) console.log(e); }\n\t}",
"download()/*:Promise<Response>*/ {\n const { sourceResponse } = this;\n if (sourceResponse) {\n return sourceResponse\n } else {\n const sourceResponse = Resource.download(this);\n this.sourceResponse = sourceResponse;\n return sourceResponse\n }\n }",
"async function download (samlinger, callback) {\n const fileList = samlinger\n const museum = fileList[0].filMetadata.museum\n for (i = 1, len = fileList.length; i < len; i++) {\n// for (i = 1, len = fileList.length; i < 4; i++) {\n let fileName = './src/data/' + fileList[i].name + \"_\" + museum + '.zip'\n\n const response = await fetch(fileList[i].url, { signal: controller.signal })\n .then(response => streamPipeline(response.body, fs.createWriteStream(fileName)))\n .catch(err => console.log(chalk.red(err)))\n \n // reading archives\n try {\n const zip = new AdmZip(fileName);\n // extracts everything, overwrite = true\n zip.extractAllTo(\"./src/data/unzip/\", true)\n makeFileNames (fileList[i], museum)\n } catch (error) {\n console.log(chalk.red(error));\n }\n } \n if (i = fileList.length) {\n console.log(chalk.green('done!'))\n // process.exit() // hvis alle filer er downloaded og unzipped så slå av programmet\n } \n}",
"function responseHandler(srcResponse, numer)\n{\n camz[numer].headers = srcResponse.headers;\n srcResponse.on('data', function(chunk) {dataHandler(chunk, numer)});\n}",
"function do_fileRequest(request, response) {\n var url = parse(request.url);\n var path = join(root, url.pathname);\n var stream = fs.createReadStream(path);\n stream.pipe(response);\n stream.on('error', function(err) {\n\t do_error(request, response);\n\t});\n}",
"stream(filePath, stats) {\n const res = this.res;\n let stream;\n const range = this.req.headers.range;\n if (range) {\n const index = range.indexOf('-');\n const start = parseInt(range.slice('bytes='.length, index), 10);\n const end = index === range.length - 1 ?\n stats.size - 1 :\n parseInt(range.slice(index + 1), 10);\n const chunkSize = (end - start) + 1;\n res.statusCode = 206;\n res.setHeader('Content-Range', stats.size);\n res.setHeader('Content-Length', chunkSize);\n const cRange = `bytes ${start}-${end}/${stats.size}`;\n res.setHeader('Content-Range', cRange);\n res.setHeader('Accept-Ranges', 'bytes');\n stream = api.fs.createReadStream(filePath, { start, end });\n } else {\n const config = this.application.config.sections.application;\n if (config) {\n const origin = config.allowOrigin;\n if (origin) this.allowOrigin(origin);\n }\n res.setHeader('Content-Length', stats.size);\n res.setHeader('Last-Modified', stats.mtime.toGMTString());\n stream = api.fs.createReadStream(filePath);\n }\n\n stream.on('open', () => {\n stream.pipe(this.res);\n });\n\n stream.on('error', () => {\n impress.log.error(impress.CANT_READ_FILE + filePath);\n });\n }",
"static downlaodFile(url) {\n const file_name = url.split('/').pop();\n request(url)\n .pipe(fs.createWriteStream('./downloaded/' + file_name))\n .on('close', function () {\n return { path: '/downloaded/'+ file_name, downloaded: true }\n });\n }",
"download(fileUrl, opt) {\n if (typeof fileUrl === 'object' && fileUrl && typeof fileUrl.url === 'string') {\n fileUrl = fileUrl.url;\n }\n if (!opt) opt = {};\n if (typeof fileUrl !== 'string' || !fileUrl) {\n return Promise.reject(thorin.error('UPLOAD.DOWNLOAD_FAILED', 'Download URL is not valid'));\n }\n let fopt = {};\n if (fileUrl.indexOf('://') !== -1) {\n fopt = getUrlOptions(fileUrl);\n if (!fopt.key) {\n return Promise.reject(thorin.error('UPLOAD.DOWNLOAD_FAILED', 'Download URL is not valid'));\n }\n } else {\n fopt.key = fileUrl;\n }\n if (!fopt.bucket) fopt.bucket = this[config].bucket;\n return new Promise((resolve, reject) => {\n const bucketObj = this[sdk].bucket(fopt.bucket);\n let sFileObj = new File(bucketObj, fopt.key);\n let readStr = sFileObj.createReadStream(opt);\n if (opt.raw === true) {\n return resolve(readStr);\n }\n let contentType, isDone = false;\n\n function onDone(e) {\n if (isDone) return;\n isDone = true;\n if (e.code !== 404) {\n logger.warn(`Failed to download file ${fopt.key}`);\n logger.debug(e);\n }\n let err = thorin.error('UPLOAD.DOWNLOAD_FAILED', 'Could not download file', e);\n err.statusCode = e.code;\n reject(err);\n }\n\n function onData(d) {\n if (isDone) return;\n isDone = true;\n if (!contentType) return resolve(d);\n let isString = false;\n if (contentType.indexOf('text/') !== -1) {\n isString = true;\n } else if (contentType.indexOf('json') !== -1) {\n isString = true;\n } else if (contentType.indexOf('javascript') !== -1) {\n isString = true;\n }\n if (isString) d = d.toString();\n resolve(d);\n }\n\n function onRes(res) {\n if (res.headers['content-type']) {\n contentType = res.headers['content-type'];\n }\n }\n\n readStr\n .on('error', onDone)\n .on('response', onRes)\n .pipe(concat(onData));\n });\n }",
"interceptDownload(http, fileRef, version) {\n let path;\n\n if (fileRef && fileRef.versions && fileRef.versions[version] && fileRef.versions[version].meta && fileRef.versions[version].meta.pipePath) {\n path = fileRef.versions[version].meta.pipePath;\n }\n\n if (path) {\n // If file is successfully moved to AWS:S3\n // We will pipe request to AWS:S3\n // So, original link will stay always secure\n\n // To force ?play and ?download parameters\n // and to keep original file name, content-type,\n // content-disposition, chunked \"streaming\" and cache-control\n // we're using low-level .serve() method\n const opts = {\n Bucket: s3Conf.bucket,\n Key: path\n };\n\n if (http.request.headers.range) {\n const vRef = fileRef.versions[version];\n let range = _.clone(http.request.headers.range);\n const array = range.split(/bytes=([0-9]*)-([0-9]*)/);\n const start = parseInt(array[1]);\n let end = parseInt(array[2]);\n if (isNaN(end)) {\n // Request data from AWS:S3 by small chunks\n end = (start + this.chunkSize) - 1;\n if (end >= vRef.size) {\n end = vRef.size - 1;\n }\n }\n opts.Range = `bytes=${start}-${end}`;\n http.request.headers.range = `bytes=${start}-${end}`;\n }\n\n const fileColl = this;\n s3.getObject(opts, function (error) {\n if (error) {\n console.error(error);\n if (!http.response.finished) {\n http.response.end();\n }\n } else {\n if (http.request.headers.range && this.httpResponse.headers['content-range']) {\n // Set proper range header in according to what is returned from AWS:S3\n http.request.headers.range = this.httpResponse.headers['content-range'].split('/')[0].replace('bytes ', 'bytes=');\n }\n\n const dataStream = new stream.PassThrough();\n fileColl.serve(http, fileRef, fileRef.versions[version], version, dataStream);\n dataStream.end(this.data.Body);\n }\n });\n\n return true;\n }\n // While file is not yet uploaded to AWS:S3\n // It will be served file from FS\n return false;\n }",
"_handleRead (request, response) {\n this.emit('download', request.resource, request.mode || 'r')\n this._store.createReadStream(request.resource, request.mode || 'r').then(({ stream, stats }) => {\n response.original.writeHead(200, { 'Content-Length': stats.size, 'Last-Modified': stats.ctime.toUTCString() })\n stream.pipe(response.original)\n }).catch(err => {\n if (!(err instanceof Request.Error)) {\n err = Request.Error.wrap(err, 404, 'Resource Not Accessible')\n }\n debug(`_handleRead('${request.resource}', '${request.mode}') error: ${err.original ? err.original.message : err.message}`)\n response.writeError(err)\n })\n }",
"decode(response) {\n const encoding = response.headers['content-encoding'];\n if (encoding) {\n if (encoding in DECODERS) {\n // Decode the stream\n const decoded = DECODERS[encoding]();\n response.pipe(decoded);\n // Copy response properties\n decoded.statusCode = response.statusCode;\n decoded.headers = this.convertRequestHeadersToFetchHeaders(response.headers);\n return decoded;\n }\n // Error when no suitable decoder found\n setImmediate(() => {\n response.emit('error', new Error(`Unsupported encoding: ${encoding}`));\n });\n }\n response.headers = this.convertRequestHeadersToFetchHeaders(response.headers);\n return response;\n }",
"function unzip(response, callback) {\n var buffer = [];\n var gunzip = zlib.createGunzip();\n response.pipe(gunzip);\n gunzip.on('data', function(data) {\n buffer.push(data.toString());\n }).on(\"end\", function() {\n callback(buffer.join(\"\"));\n });\n}",
"function downloadProxy(req, res) {\n req.setEncoding('utf8');\n\n var url = req.query.url;\n var name = req.query.name;\n var provider = req.query.provider;\n console.log(`Downloading:\n name: ${name}\n url: ${url}\n provider: ${provider}`);\n\n setDownloadName(req, res, name);\n\n let headers = {};\n if (provider === 'alexandria.works') {\n console.log('alexandria');\n headers = {\n 'AW-API-KEY': process.env.AW_API_KEY\n };\n nodeFetch(url, {\n headers\n })\n .then(r => r.json())\n .then(json => {\n console.log(json);\n setDownloadName(req, res, json.filename);\n const dlUri = `${'https://digipolis-poc.alexandria.works/v0.1'}${\n json.file.uri\n }`;\n var stream = request.get(dlUri, { headers }).pipe(res);\n stream.on('error', function(err) {\n res.send(500, err);\n });\n });\n } else {\n headers = {\n Authorization: `Bearer ${nalantisApi.token.value}`,\n Accept: 'application/octet-stream'\n };\n var stream = request.get(url, { headers }).pipe(res);\n stream.on('error', function(err) {\n res.send(500, err);\n });\n }\n}",
"function unzip(response) {\n var _a;\n if (((_a = response.getHeader(constants_1.HTTP_HEADERS.contentEncoding)) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'gzip' &&\n response.body instanceof Buffer) {\n response.removeHeader(constants_1.HTTP_HEADERS.contentEncoding);\n response.removeHeader(constants_1.HTTP_HEADERS.contentLength);\n response.body = zlib_1.gunzipSync(response.body);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the route manager. Don't call this until the app is ready to consume the route parameters. | initialize() {
this.rootScope_.$on('$routeUpdate', this.onRouteUpdate.bind(this));
this.initialized_ = true;
this.onRouteUpdate();
} | [
"async init() {\n let routesJsonData = await app.LocalLoad.jsonFile(\n app.PathHelper.getPath(app.Config.ROUTE_INFO_FILE));\n\n app.Log(\"Call router to resolve\");\n routesJsonData.routes.forEach(item => {\n item.path = item.path.toLowerCase();\n item.controller = item.controller.toLowerCase();\n item.action = item.action.toLowerCase();\n });\n this.router = new app.Router(routesJsonData.routes);\n }",
"initialize () {\n this.app.routes = _.compact(\n _.map(this.app.config.routes, route => lib.Util.buildRoute(this.app, route))\n )\n }",
"initRoutes() {\n }",
"init() {\n this.router.get(this.path, this.process);\n }",
"initRoute(route){\n this.notifyRoute(route);\n switch (route.method){\n case \"GET\":\n this.app.get(route.endpoint, route.handler);\n break;\n case \"PUT\":\n this.app.put(route.endpoint, route.handler);\n break;\n case \"POST\":\n this.app.post(route.endpoint, route.handler);\n break;\n case \"DELETE\":\n this.app.delete(route.endpoint, route.handler);\n break;\n default:\n throw new Error(\"Invalid http method \"+route.method);\n }\n }",
"initializeRoutes(){\n if(this.routes.length > 0) return;\n this.routes = [\n {\n method: \"GET\",\n permission: \"STANDARD\",\n endpoint: this.controllerEndpoint + \"/searches\",\n handler: getSearchesHandler\n },\n {\n method: \"GET\",\n permission: \"STANDARD\",\n endpoint: this.controllerEndpoint + \"/loads\",\n handler: getLoadsHandler\n }\n ];\n }",
"initializeRoutes(){\n if(this.routes.length > 0) return;\n this.routes = [\n {\n method: \"GET\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: getHandler\n },\n {\n method: \"PUT\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: putHandler\n },\n {\n method: \"POST\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: postHandler\n },\n {\n method: \"DELETE\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: deleteHandler\n }\n ];\n }",
"constructor(routes){\n this.routes=routes;\n this._loadInitialRoute();\n }",
"constructor() {\n this.createRoutes() //constructor will run method that creates routes. method declares routes within the app\n }",
"function init() {\n\n\t\t// Check if on mobile\n\t\tif (global.innerWidth <= 1000) {\n\t\t\tmobile = true;\n\t\t}\n\n\t\t// Load tutorials\n\t\tm.request({\n\t\t\tmethod: 'GET',\n\t\t\turl: 'config/tutorials.json',\n\t\t}).then(function (data) {\n\t\t\ttutorials = data;\n\t\t\tloaded = true;\n\t\t});\n\n\t\t// Load i18n strings\n\t\tlanguages.forEach(function (lang) {\n\t\t\tm.request({\n\t\t\t\tmethod: 'GET',\n\t\t\t\turl: `config/i18n/${lang}.json`\n\t\t\t}).then(function (data) {\n\t\t\t\tstrings[lang] = data;\n\t\t\t});\n\t\t});\n\n\t\t// Configure routes\n\t\tm.route(root, '/', {\n\t\t\t'/': HomeView,\n\t\t\t'/learn/:id': PlaygroundView,\n\t\t\t'/play/:simulator': PlaygroundView\n\t\t});\n\n\t}",
"static setupRoutes() {\n // this is a route. the asterisk denotes that the route applies to \n // all incoming path requests.\n //\n // *** IMPORTANT ***\n //\n // it's very *important* the order in which routes are added, since \n // an incoming request will be checked against the available routes in\n // order!\n Server.app.all('*', function(req, res, next) {\n console.log('Requested path: ', req.path); // the reuested URI\n console.log('Query string: ', req.query); // the querystring for GET requests\n\n // our req object tells about the HTTP request.\n // our res object gives us access to control the response.\n // our next object allows us to programmatically goto the next route\n next(); // goto the next routes\n\n // if we didn't call next, we'd never fulfill the request!\n });\n }",
"_setup() {\n this._parent = {\n routeEntry: this.options.baseRoute,\n routeItem: this.options.baseRoute,\n dir: this.options.controllersDir,\n parentDir: this.options.controllersDir,\n }\n this._parseRoutes(this._parent, this.options.baseRoute, this.options.routes);\n }",
"constructor() {\n\t\tthis.route = new Route();\n\t}",
"async setupRouter() {\n try {\n // Populate this.router with all routes\n // Then register all routes with the app\n await botsRoutes(this);\n // Register all router routes with the app\n this.app.use(this.router.routes()).use(this.router.allowedMethods());\n logger.info('Bots router setup complete');\n } catch (ex) {\n logger.error('Bots router setup error', ex);\n }\n }",
"loadRoutes() {\n Routes(this.app);\n }",
"function setUpRouting() {\n\n // Set up routing table\n app.router.mount(paths.routes);\n app.router.configure({ \n recurse: false\n , strict: false\n , async: true\n });\n\n // Attach HTTP utilities to route context\n app.router.attach(function() {\n var self = this;\n Object.keys(hu).forEach(function(name) {\n self[name] = hu[name];\n });\n });\n}",
"function initRouter() {\n attachNavLinkEvents();\n\n let defaultPath = \"#/\";\n if (routes[location.hash]) {\n defaultPath = location.hash;\n }\n navigateTo(defaultPath);\n}",
"startRouting() {\n var router = get(this, 'router');\n router.startRouting(isResolverModuleBased(this));\n this._didSetupRouter = true;\n }",
"function init() {\n const app = new Koa();\n const router = new KoaRouter();\n\n // Logger instance available from the context\n app.context.logger = logger;\n\n // Cross-Origin Resource Sharing(CORS)\n app.use(cors());\n\n // x-response-time\n app.use(async (ctx, next) => {\n const start = new Date();\n await next();\n const ms = new Date() - start;\n ctx.set('X-Response-Time', `${ms}ms`);\n logger.info(`X-Response-Time: ${ms}ms`);\n });\n\n // Logger\n app.use(async (ctx, next) => {\n const start = new Date();\n await next();\n const ms = new Date() - start;\n logger.info(`${ctx.method} ${ctx.url} - ${ms}`);\n });\n\n app.use(koaBodyParser());\n loadRoutes(router, (attachedRouter) => {\n app.use(attachedRouter.routes());\n app.use(attachedRouter.allowedMethods());\n app.listen(process.env.PORT, () => {\n logger.info('%s listening at %s', process.env.APP_NAME, process.env.PORT);\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reflectSprite loads a sprite from disk, reflects it about the center of the given dimension, and outputs the result to disk Arguments: dimension: reflect over either 'x' or 'y' dimensions inputFile: filename of JSON sprite to load outputFile: filename to save JSON sprite | function reflectSprite (dimension, inputFile, outputFile) {
var sprite = JSON.parse(fs.readFileSync(inputFile, { encoding: 'utf8' }));
sprite.pixels = reflect(dimension, sprite.pixels);
fs.writeFileSync(outputFile, JSON.stringify(sprite));
} | [
"function displaySprite(sprite, x, y, width, height) {\r\n\t\tif (x === void 0) { x = sprite.x + sprite.velocity.x; }\r\n\t\tif (y === void 0) { y = sprite.y + sprite.velocity.y; }\t\r\n\t\t\r\n\t\tif (width !== void 0) { sprite.scale.width = width;}\r\n\t\tif (height !== void 0) { sprite.scale.height = height; }\r\n\t\t\r\n\t\tif (sprite.scale.width === undefined) {\r\n\t\t\tsprite.scale.width = sprite.width;\r\n\t\t}\r\n\r\n\t\tif (sprite.scale.height === undefined) {\r\n\t\t\tsprite.scale.height = sprite.height;\r\n\t\t}\r\n\t\t\r\n\t\tsprite.remove = false;\r\n\t\tsprite.x = x;\r\n\t\tsprite.y = y;\r\n\r\n\t\tif (sprite.rotate.vAngle + sprite.rotate.angle > 360) {\r\n\t\t\tsprite.rotate.vAngle -= 360; \r\n\t\t}\r\n\t\t\r\n\t\tif (sprite.rotate.relatif = true) {\r\n\t\t\tsprite.rotate.vAngle += sprite.rotate.angle;\t//Rotation relative\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t// Affichage du sprite - Show sprite\r\n\t\tgame.context.save();\r\n\t\r\n\t\tgame.context.globalAlpha = sprite.opacity;\r\n\t\tgame.context.translate(sprite.x, sprite.y);\r\n\t\tgame.context.rotate(sprite.rotate.vAngle * game.TO_RADIANS);\r\n\t\r\n\t\tgame.context.scale(sprite.flip.h, sprite.flip.v);\r\n\t\r\n\t\tgame.context.drawImage(\r\n\t\t\tsprite.image, // sprite sheet\r\n\t\t\r\n\t\t\t//Source\r\n\t\t\tsprite.clip.x,\r\n\t\t\tsprite.clip.y,\r\n\t\t\tsprite.clip.width,\r\n\t\t\tsprite.clip.height,\r\n\t\t\r\n\t\t\t//Destination)\r\n\t\t\t- sprite.scale.width * sprite.anchor.x, \t// Position x\r\n\t\t\t- sprite.scale.height * sprite.anchor.y,\t// Position y\r\n\t\t\tsprite.scale.width,\r\n\t\t\tsprite.scale.height\r\n\t\t);\r\n\t\t\r\n\t\tgame.context.restore();\r\n\t}",
"function downsize (input, output, factor) {\n var spriteObj = JSON.parse(fs.readFileSync(input, { encoding: 'utf8' }));\n var sprite = new Sprite(spriteObj.pixels);\n var bounds = sprite.bounds();\n\n var dimensions = { width: bounds.xmax - bounds.xmin + 1,\n height: bounds.ymax - bounds.ymin + 1 };\n var grid = make2DArray(dimensions);\n\n _.each(spriteObj.pixels, function (p) {\n grid[p.x - bounds.xmin][p.y - bounds.ymin] = p;\n });\n\n var sums = { x: 0, y: 0 };\n var downsizedPixels = [];\n for (var i=0; i<dimensions.width; i+=factor) {\n for (var j=0; j<dimensions.height; j+=factor) {\n var p = { x: Math.floor(i/factor) + bounds.xmin,\n y: Math.floor(j/factor) + bounds.ymin,\n color: reduceArea(grid, { x: i, y: j }, factor) };\n if (p.color) {\n downsizedPixels.push(p);\n sums.x += p.x;\n sums.y += p.y;\n }\n }\n }\n\n spriteObj.pixels = downsizedPixels;\n spriteObj.center.x = sums.x/downsizedPixels.length;\n spriteObj.center.y = sums.y/downsizedPixels.length;\n\n fs.writeFileSync(output, JSON.stringify(spriteObj));\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 reflect(v, n) {\n vec2.negate(v, v);\n let p = vec2.dot(v, n);\n let proj = vec2.create();\n vec2.scale(proj, n, p);\n let perp = vec2.create();\n vec2.sub(perp, v, proj);\n let img = vec2.create();\n vec2.scaleAndAdd(img, v, perp, -2);\n return img;\n}",
"function parseSpriteDefinition ($xml, player) {\n var targetObj = xmlToObject($xml);\n \n //properties needing special handling\n if (targetObj.alpha) { targetObj.alpha = parseFloat(targetObj.alpha, 10); }\n targetObj.zoom = parseFloat(targetObj.zoom, 10);\n targetObj.rotation = parseFloat(targetObj.rotation, 10);\n if (targetObj.scale) {\n targetObj.scalex = targetObj.scaley = targetObj.scale;\n } else {\n targetObj.scalex = parseFloat(targetObj.scalex, 10);\n targetObj.scaley = parseFloat(targetObj.scaley, 10);\n }\n \n targetObj.skewx = parseFloat(targetObj.skewx, 10);\n targetObj.skewy = parseFloat(targetObj.skewy, 10);\n targetObj.x = parseFloat(targetObj.x, 10);\n targetObj.y = parseFloat(targetObj.y, 10);\n targetObj.delay = parseFloat(targetObj.delay) * 1000 || 0;\n \n targetObj.player = player;\n \n return targetObj;\n}",
"reflect(x, y, ray, depth) {\n //make sure this isn't base case\n if (depth > 0) {\n //create reflect vector\n var i = ray.dir.clone(); //incident ray\n i.normalize(1); //make it a unit vector\n var n = ray.obj.normal(ray.pos); //normal from object collided (unit vec)\n var angle = n.dot(i); //calculate cosine of angle between them\n n.normalize(2 * angle); //scale the normal vector to subtract away the correct amount\n i.subtract(n); //reverse the direction of the incident but only the part that matches up with the normal\n \n //cast reflection ray\n i.add(ray.obj.surface(ray.pos)); //calculate point in 3D space from the our reflected incident vector and the surface of the object\n var len = maxRayLength;\n if (i.y > ray.y) { //determine if it will hit ground\n len = maxRayLength * 3;\n }\n var reflectRay = new Ray(ray.obj.surface(ray.pos), i, len);\n\n //weight transparency of reflection\n var weight = Math.floor(255 * Math.pow(reflectivity, maxReflections - depth + 1) * Math.pow(2, depth - 1) / Math.pow(2, maxReflections)).toString(16);\n if (weight.length === 1) {\n weight = \"0\" + weight;\n }\n \n //if reflection does not hit sky\n if (reflectRay.obj !== null) {\n //draw base color of reflected object\n context.fillStyle = reflectRay.obj.color + weight;\n context.fillRect(x, y, 1, 1);\n \n //draw shadows and highlights on reflected object\n var refShadow = this.getLightAmount(reflectRay);\n this.drawLight(x, y, refShadow, parseInt(weight, 16) / 255);\n \n //if it hits another reflected object then the cycle continues\n if (reflectRay.obj.ref) {\n this.reflect(x, y, reflectRay, depth - 1);\n }\n } else {\n //draw sky color (weighted)\n context.fillStyle = backgroundColor + weight;\n context.fillRect(x, y, 1, 1);\n }\n }\n }",
"function drawSprite(imageObject, x, y, rotation, scale)\n{\n\n\n var w = imageObject.width;\n var h = imageObject.height;\n\n // save state\n ctx.save();\n\n // set screen position\n ctx.translate(x, y);\n\n // set rotation\n ctx.rotate(-rotation);\n\n // set scale value\n ctx.scale(scale, scale);\n\n // draw image to screen drawImage(imageObject, sourceX, sourceY, sourceWidth, sourceHeight,\n // destinationX, destinationY, destinationWidth, destinationHeight)\n ctx.drawImage(imageObject, 0, 0, w, h, -w/2, -h/2, w, h);\n \n // restore state\n ctx.restore();\n}",
"addCollisionProperties(sprite) {\n\n //Add properties to Pixi sprites\n if (this.renderer === \"pixi\") {\n\n //gx\n if (sprite.gx === undefined) {\n Object.defineProperty(sprite, \"gx\", {\n get() {\n return sprite.getGlobalPosition()\n .x\n },\n enumerable: true,\n configurable: true\n });\n }\n\n //gy\n if (sprite.gy === undefined) {\n Object.defineProperty(sprite, \"gy\", {\n get() {\n return sprite.getGlobalPosition()\n .y\n },\n enumerable: true,\n configurable: true\n });\n }\n\n //centerX\n if (sprite.centerX === undefined) {\n Object.defineProperty(sprite, \"centerX\", {\n get() { return sprite.x + sprite.width / 2 },\n enumerable: true,\n configurable: true\n });\n }\n\n //centerY\n if (sprite.centerY === undefined) {\n Object.defineProperty(sprite, \"centerY\", {\n get() { return sprite.y + sprite.height / 2 },\n enumerable: true,\n configurable: true\n });\n }\n\n //halfWidth\n if (sprite.halfWidth === undefined) {\n Object.defineProperty(sprite, \"halfWidth\", {\n get() { return sprite.width / 2 },\n enumerable: true,\n configurable: true\n });\n }\n\n //halfHeight\n if (sprite.halfHeight === undefined) {\n Object.defineProperty(sprite, \"halfHeight\", {\n get() { return sprite.height / 2 },\n enumerable: true,\n configurable: true\n });\n }\n\n //xAnchorOffset\n if (sprite.xAnchorOffset === undefined) {\n Object.defineProperty(sprite, \"xAnchorOffset\", {\n get() {\n if (sprite.anchor !== undefined) {\n return sprite.width * sprite.anchor.x;\n } else {\n return 0;\n }\n },\n enumerable: true,\n configurable: true\n });\n }\n\n //yAnchorOffset\n if (sprite.yAnchorOffset === undefined) {\n Object.defineProperty(sprite, \"yAnchorOffset\", {\n get() {\n if (sprite.anchor !== undefined) {\n return sprite.height * sprite.anchor.y;\n } else {\n return 0;\n }\n },\n enumerable: true,\n configurable: true\n });\n }\n\n if (sprite.circular && sprite.radius === undefined) {\n Object.defineProperty(sprite, \"radius\", {\n get() { return sprite.width / 2 },\n enumerable: true,\n configurable: true\n });\n }\n\n //Earlier code - not needed now.\n /*\n Object.defineProperties(sprite, {\n \"gx\": {\n get(){return sprite.getGlobalPosition().x},\n enumerable: true, configurable: true\n },\n \"gy\": {\n get(){return sprite.getGlobalPosition().y},\n enumerable: true, configurable: true\n },\n \"centerX\": {\n get(){return sprite.x + sprite.width / 2},\n enumerable: true, configurable: true\n },\n \"centerY\": {\n get(){return sprite.y + sprite.height / 2},\n enumerable: true, configurable: true\n },\n \"halfWidth\": {\n get(){return sprite.width / 2},\n enumerable: true, configurable: true\n },\n \"halfHeight\": {\n get(){return sprite.height / 2},\n enumerable: true, configurable: true\n },\n \"xAnchorOffset\": {\n get(){\n if (sprite.anchor !== undefined) {\n return sprite.height * sprite.anchor.x;\n } else {\n return 0;\n }\n },\n enumerable: true, configurable: true\n },\n \"yAnchorOffset\": {\n get(){\n if (sprite.anchor !== undefined) {\n return sprite.width * sprite.anchor.y;\n } else {\n return 0;\n }\n },\n enumerable: true, configurable: true\n }\n });\n */\n }\n\n //Add a Boolean `_bumpPropertiesAdded` property to the sprite to flag it\n //as having these new properties\n sprite._bumpPropertiesAdded = true;\n }",
"function reflect (dimension, pixels) {\n var bounds = _.reduce(pixels, function (b, p) {\n if (p[dimension] < b.min) b.min = p[dimension];\n if (p[dimension] > b.max) b.max = p[dimension];\n return b;\n }, { min: Infinity, max: -Infinity });\n\n return _.map(pixels, function (p) {\n var rp = _.clone(p);\n rp[dimension] = bounds.max - p[dimension] + bounds.min;\n return rp;\n });\n}",
"reflect (rect, vertical) {\n if (vertical) {\n this.x = 2 * rect.x - this.x\n } else {\n this.y = 2 * rect.y - this.y\n }\n return this\n }",
"__updateReflection() {\n this._reflectionCamera.position.z = -this._camera.position.z;\n this._reflectionCamera.position.y = this._camera.position.y;\n this._reflectionCamera.position.x = this._camera.position.x;\n\n this._scene.traverse((object) => {\n if (object.name == \"reflection\") {\n object.visible = false;\n }\n });\n\n this._reflectionCamera.update(this._renderer, this._scene);\n\n this._scene.traverse((object) => {\n if (object.name == \"reflection\") {\n object.visible = true;\n }\n });\n }",
"adjustSprite(sprite){\n sprite.width = sprite.width * this.scaleFactor;\n sprite.height = sprite.height * this.scaleFactor;\n }",
"function updateProperties(sprite)\n{\n elements.position.x.val( sprite.position.x );\n elements.position.y.val( sprite.position.y );\n elements.rotation.val( sprite.rotation );\n elements.scale.x.val( sprite.scale.x );\n elements.scale.y.val( sprite.scale.y );\n}",
"draw() {\n sprite(this.spriteNumber, this.x, this.y)\n }",
"function drawSprite(imageObject, x, y, rotation, scale)\r\n{\r\n\tvar w = imageObject.width;\r\n\tvar h = imageObject.height;\r\n\r\n\t// save state\r\n\tctx.save();\r\n\t// set screen position\r\n\tctx.translate(x, y);\r\n\t// set rotation\r\n\tctx.rotate(-rotation);\r\n\t// set scale value\r\n\tctx.scale(scale, scale);\r\n\t// draw image to screen drawImage(imageObject, sourceX, sourceY, sourceWidth, sourceHeight,\r\n\t// destinationX, destinationY, destinationWidth, destinationHeight)\r\n\tctx.drawImage(imageObject, 0, 0, w, h, -w/2, -h/2, w, h);\r\n\t// restore state\r\n\tctx.restore();\r\n}",
"addCollisionProperties(sprite) {\n //Add properties to Pixi sprites\n if (this.renderer === \"pixi\") {\n //gx\n if (sprite.gx === undefined) {\n Object.defineProperty(sprite, \"gx\", {\n get() {\n return sprite.getGlobalPosition().x;\n },\n enumerable: true, configurable: true\n });\n }\n //gy\n if (sprite.gy === undefined) {\n Object.defineProperty(sprite, \"gy\", {\n get() {\n return sprite.getGlobalPosition().y;\n },\n enumerable: true, configurable: true\n });\n }\n //centerX\n if (sprite.centerX === undefined) {\n Object.defineProperty(sprite, \"centerX\", {\n get() {\n return sprite.x + sprite.width / 2;\n },\n enumerable: true, configurable: true\n });\n }\n //centerY\n if (sprite.centerY === undefined) {\n Object.defineProperty(sprite, \"centerY\", {\n get() {\n return sprite.y + sprite.height / 2;\n },\n enumerable: true, configurable: true\n });\n }\n //halfWidth\n if (sprite.halfWidth === undefined) {\n Object.defineProperty(sprite, \"halfWidth\", {\n get() {\n return sprite.width / 2;\n },\n enumerable: true, configurable: true\n });\n }\n //halfHeight\n if (sprite.halfHeight === undefined) {\n Object.defineProperty(sprite, \"halfHeight\", {\n get() {\n return sprite.height / 2;\n },\n enumerable: true, configurable: true\n });\n }\n //xAnchorOffset\n if (sprite.xAnchorOffset === undefined) {\n Object.defineProperty(sprite, \"xAnchorOffset\", {\n get() {\n if (sprite.anchor !== undefined) {\n return sprite.width * sprite.anchor.x;\n }\n else {\n return 0;\n }\n },\n enumerable: true, configurable: true\n });\n }\n //yAnchorOffset\n if (sprite.yAnchorOffset === undefined) {\n Object.defineProperty(sprite, \"yAnchorOffset\", {\n get() {\n if (sprite.anchor !== undefined) {\n return sprite.height * sprite.anchor.y;\n }\n else {\n return 0;\n }\n },\n enumerable: true, configurable: true\n });\n }\n if (sprite.circular && sprite.radius === undefined) {\n Object.defineProperty(sprite, \"radius\", {\n get() {\n return sprite.width / 2;\n },\n enumerable: true, configurable: true\n });\n }\n //Earlier code - not needed now.\n /*\n Object.defineProperties(sprite, {\n \"gx\": {\n get(){return sprite.getGlobalPosition().x},\n enumerable: true, configurable: true\n },\n \"gy\": {\n get(){return sprite.getGlobalPosition().y},\n enumerable: true, configurable: true\n },\n \"centerX\": {\n get(){return sprite.x + sprite.width / 2},\n enumerable: true, configurable: true\n },\n \"centerY\": {\n get(){return sprite.y + sprite.height / 2},\n enumerable: true, configurable: true\n },\n \"halfWidth\": {\n get(){return sprite.width / 2},\n enumerable: true, configurable: true\n },\n \"halfHeight\": {\n get(){return sprite.height / 2},\n enumerable: true, configurable: true\n },\n \"xAnchorOffset\": {\n get(){\n if (sprite.anchor !== undefined) {\n return sprite.height * sprite.anchor.x;\n } else {\n return 0;\n }\n },\n enumerable: true, configurable: true\n },\n \"yAnchorOffset\": {\n get(){\n if (sprite.anchor !== undefined) {\n return sprite.width * sprite.anchor.y;\n } else {\n return 0;\n }\n },\n enumerable: true, configurable: true\n }\n });\n */\n }\n //Add a Boolean `_bumpPropertiesAdded` property to the sprite to flag it\n //as having these new properties\n sprite._bumpPropertiesAdded = true;\n }",
"function scaledDraw(sprite, x, y) {\r\n\tcontext.drawImage(sprite, Math.round(x * scalex), Math.round(y * scaley), sprite.width * scalex, sprite.height * scaley);\r\n}",
"DrawSprite(name, pos)\n {\n this.DrawSpriteInfo(this.metadata.lookup[name], pos); //changed to work with multiple texture pages\n }",
"constructor(name, sprite, x, y){\n\t\tthis.name = name\n\t\tthis.sprite = sprite\n\t\tthis.x = x * window.tileSize\n\t\tthis.y = y * window.tileSize\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deep map values (not array) | function deepMapValues(collection, mapper = _.identity) {
return _.mapValues(collection, (i, k) => {
return _.isObject(i) && !_.isArray(i)
? deepMapValues(i, mapper)
: mapper(i, k);
});
} | [
"function deepMap(obj, fn) {\n // If the transform function transforms the value, regardless of type, return\n // the transformed value.\n const mapped = fn(obj)\n if (mapped !== obj) {\n return mapped\n }\n\n // Recursively deep map arrays and plain objects, otherwise return the value.\n if (Array.isArray(obj)) {\n return obj.map(value => deepMap(value, fn))\n }\n if (isPlainObject(obj)) {\n return mapValues(obj, value => deepMap(value, fn))\n }\n return obj\n}",
"function mapVals(fields) {\n return R.map(f => {\n if (Array.isArray(f)) return mapVals(f)\n if (R.has('value', f)) return R.prop('value', f)\n return mapVals(f)\n }, fields)\n}",
"function map(array, depth) {\n if (depth >= keys.length) return rollup\n ? rollup.call(nest, array) : (sortValues\n ? array.sort(sortValues)\n : array);\n\n var i = -1,\n n = array.length,\n key = keys[depth++],\n keyValue,\n object,\n valuesByKey = new d3_Map,\n values,\n o = {};\n\n while (++i < n) {\n if (values = valuesByKey.get(keyValue = key(object = array[i]))) {\n values.push(object);\n } else {\n valuesByKey.set(keyValue, [object]);\n }\n }\n\n valuesByKey.forEach(function(keyValue) {\n o[keyValue] = map(valuesByKey.get(keyValue), depth);\n });\n\n return o;\n }",
"function mapValues(mapper) {\n var obj = this.value(), result = {};\n Object.keys(obj).forEach(function (key) {\n var value = mapper(key, obj[key]);\n result[key] = value;\n });\n return new __WEBPACK_IMPORTED_MODULE_0__lift__[\"d\" /* ObjectOps */](result);\n}",
"function step2 (step1Map) {\n var children = [];\n for (var key in step1Map) {\n var value = step1Map[key];\n var myObj = {_id: key};\n if (typeof value === 'number') {\n myObj.value = value\n } else {\n myObj.children = step2(value.children);\n }\n children.push(myObj)\n }\n return children;\n}",
"function deepMap(input, mapFn) {\n return deepMapInternal(input, mapFn);\n}",
"function map(tree, fn) {\n var mapped = tree;\n entries(tree).forEach(function (_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n key = _ref4[0],\n value = _ref4[1];\n\n var computed = fn(value, key);\n if (computed !== value) {\n mapped = set(mapped, key, computed);\n }\n });\n return mapped;\n}",
"function deep_map(array, func){\r\n return array.map((x, index, array)=>{\r\n if(Array.isArray(x)) return deep_map(x, func);\r\n return func(x, index, array);\r\n });\r\n}",
"function value_map(f, m) {\n for (var k in m) {\n m[k] = f(m[k])\n }\n return m\n }",
"function mapObjectRecursive(object, map, context = {}) {\n const clone = Array.isArray(object) ? [] : {};\n for (const k of Object.keys(object)) {\n let key = k;\n const value = object[key];\n if (Array.isArray(object))\n key = +key;\n const contextClone = Object.assign({}, context);\n let result = map(key, value, object, contextClone);\n if (typeof result !== 'undefined' && typeof result !== 'object' && !Array.isArray(result))\n throw new Error('mapObjectRecursive: return value of map function must be undefined, object, or array!');\n if (typeof result === 'undefined') {\n result = { [key]: value };\n }\n for (const kk in result) {\n let value = result[kk];\n if ((0, isPlainObject_1.isPlainObject)(value) || Array.isArray(value))\n value = mapObjectRecursive(value, map, contextClone);\n if (typeof value !== 'undefined')\n clone[kk] = value;\n }\n }\n return clone;\n}",
"function toPropertyValueMap(values) {\n var result = {}\n var length = values.length\n var index = -1\n var value\n\n while (++index < length) {\n value = values[index]\n\n if (value && typeof value === 'object' && 'length' in value) {\n result[value[0]] = value.slice(1)\n } else {\n result[value] = []\n }\n }\n\n return result\n}",
"function mapValues(value, fn) {\n if (typeof value !== 'object' || value == null) {\n throw new Error(`Expected object type, got ${JSON.stringify(value)}`);\n }\n const out = {};\n for (const [k, v] of Object.entries(value)) {\n const wireValue = fn(v, k);\n if (wireValue === undefined) {\n continue;\n }\n out[k] = wireValue;\n }\n return out;\n}",
"function mapWalkObject(obj, fn) {\n let objCopy = Object.assign({}, obj);\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key))\n continue;\n const value = obj[key];\n if (value.constructor === Object) {\n objCopy[key] = mapWalkObject(value, fn);\n }\n else if (value.constructor === Array) {\n objCopy[key] = objCopy[key].map((e) => {\n if (e.constructor === Object) {\n return mapWalkObject(e, fn);\n }\n else {\n return e;\n }\n });\n }\n }\n objCopy = fn(objCopy);\n return objCopy;\n}",
"function replace_values_in(obj, from, to) {\n if (obj === from) { return to; }\n var recur = function(val, key) {\n return replace_values_in(val, from, to);\n };\n if (Array.isArray(obj)) {\n return _.map(obj, recur);\n } else if (typeof(obj) === 'object') {\n return _.mapObject(obj, recur);\n } else {\n return obj;\n }\n}",
"function deepParse(val) {\n if (typeof val !== 'object') return parse(val);\n if (Array.isArray(val)) return val.map(deepParse);\n return Object.keys(val).reduce(function(acc, key) {\n acc[key] = deepParse(val[key])\n return acc;\n }, {});\n}",
"function mapNode(node, f) {\n // check null first since typeof null is \"object\".\n if (node === null) {\n return f(node);\n } else if (node.constructor === Array) {\n return node.map(f);\n } else if (typeof(node) === 'object') {\n var out = {};\n for (var key in node) {\n out[key] = f(node[key]);\n }\n return out;\n } else {\n return f(node);\n }\n }",
"function entries(map) {\n var array = [];\n for (var k in map) {\n var v = map[k];\n array.push({key: k, values: (v instanceof Array) ? v : entries(v)});\n };\n return array;\n }",
"function mapToValues(v){\n function mapRec(e){\n if(!isAVector(e)) return e;\n return mapRec(e.get(0));\n }\n return v.map(mapRec);\n }",
"function entries(map) {\n var array = [];\n for (var k in map) {\n var v = map[k];\n array.push({ key: k, values: (v instanceof Array) ? v : entries(v) });\n };\n return array;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3. determine which AI to use// determins which AI to use & if it is the AI's turn | function aiFunc(){
if (playerTurn ==1){
return
}
if (playerTurn == 0){
if (ai ==1){
pickSquare ()
}
if (ai==2){
mediumAI ()
}
}
} | [
"AI(){\n // determine AI Stance\n if ( (this.first ==='ai' && this.turn===0) || (this.first==='ai'&&this.turn===1) ){\n this.aiStance='setup'\n }\n else if(this.playerboard.length >3){\n // AI tries to kill your monsters\n this.aiStance= 'clearBoard';\n }\n else if(this.aiMana <=50 || this.aiboard.length <=0){\n this.aiStance='defensive';\n } else if(this.playerboard.length<=1 || this.playerMana<=50){\n this.aiStance='aggressive';\n }else{\n this.aiStance='neutral';\n }\n // determine AI Moves\n if(this.aiStance==='setup'){\n\n }else if(this.aiStance==='clearBoard'){\n\n }else if(this.aiStance==='defensive'){\n\n }else if(this.aiStance==='aggressive'){\n\n } else if(this.aiStance==='neutral'){\n\n }else{\n\n }\n\n }",
"is_ai() {\n return (this.players[(1 + this.ply) & 1].name == AI);\n }",
"function ai() {\n let bestMoves = getBestMove(gamestate, 0);\n let nextMove = bestMoves[Math.floor(Math.random()*bestMoves.length)];\n let player = gamestate.turn % 2;\n\n // Move is initiated.\n ++gamestate.turn;\n gamestate.tiles[nextMove.x][nextMove.y].player = player;\n\n // Check move consequence and render.\n updateMoves(gamestate, player, nextMove);\n checkWin();\n render();\n\n // UNCOMMENT TO LET THE AI PLAY AGAINST ITSELF AFTER FIRST HUMAN MOVE.\n //setTimeout(() => ai(), 200);\n}",
"function aiTurn(){\n\tif(turnCount > 0){\n\t\tif(difficulty == 'easy'){\n\t\t\teasyShot();\n\t\t}else if(difficulty == 'medium'){\n\t\t\tmediumShot();\n\t\t}else if(difficulty == 'hard'){\n\t\t\thardShot();\n\t\t}\n\t\tturnDone = 1;\n\t\tchangeTurn();\n\t\tconfirmChange();\n\t}\n}",
"function takeANoviceMove(turn) {\n var available = game.currentState.emptyCells();\n //enumerate and calculate the score for each available actions to the ai player\n var availableActions = available.map(function(pos) {\n var action = new AIAction(pos);//create the action object\n //get next state by applying the action\n var next = action.applyTo(game.currentState);\n //calculate and set the action's minimax value;\n action.minimaxVal = minimaxVal(next);\n return action;\n });\n //sort the enumerated actions list by score\n //X maximizes ---> descend sort the actions to have the largest minimax at first\n if (turn === 'X') availableActions.sort(AIAction.DESCENDING);\n //else sort ascending\n else availableActions.sort(AIAction.ASCENDING);\n //take the optimal action 40% of the time\n var chosenAction;\n if (Math.random() * 100 <= 40) chosenAction = availableActions[0];\n //if there are two or more available actions, choose the 1st suboptimal\n else if(availableActions.length >= 2) chosenAction = availableActions[1];\n //choose the only available action\n else chosenAction = availableActions[0];\n var next = chosenAction.applyTo(game.currentState);\n ui.insertAt(chosenAction.movePosition, turn);\n //take the game to the next state\n game.advanceTo(next);\n}",
"function chaosAI(board) {\r\n // Currently, chaos AI is \"get order AI and do the opposite mark\"\r\n var chaosMove = orderAI(board, true);\r\n if (chaosMove && chaosMove.mark) {\r\n chaosMove.mark = notMark(chaosMove.mark);\r\n }\r\n return chaosMove;\r\n}",
"function takeANoviceMove(turn) {\n let available = game.currentState.emptyCells();\n\n // enumerate and a calculate the score for each available action to the ai player\n let availableActions = available.map(function(pos) {\n let action = new AIAction(pos); // create the action object\n\n //get next state by applying the action\n let nextState = action.applyTo(game.currentState);\n\n //calculate and set the action's minimax value\n action.minimaxVal = minimaxValue(nextState);\n\n return action;\n\n });\n\n //sort enumerated actions list by score\n if(turn === \"X\")\n // X maximizes -> decend sort the the actions to have the maximum minimax at first\n availableActions.sort(AIAction.DESCENDING);\n else\n // O minimizes -> ascend sort the actions to have the minimum minimax at first\n availableActions.sort(AIAction.ASCENDING);\n\n\n /*\n * take the optimal action 40% of the time\n * take the 1st supoptimal action 60 % of the time\n */\n\n let chosenAction;\n if(Math.random()*100 < 40) {\n chosenAction = availableActions[0];\n }\n else {\n if(availableActions.length >= 2) {\n //if there is two or more available actions, choose the 1st suboptimal\n chosenAction = availableActions[1];\n }\n else {\n //choose the only available action\n chosenAction = availableActions[0];\n }\n }\n let next = chosenAction.applyTo(game.currentState);\n\n ui.insertAt(chosenAction.movePosition, turn);\n\n game.advanceTo(next);\n }",
"function comAIMove() \n{\n //console.log('Computer AI turn')\n \n\n var allNextState = []\n var allNextAction = []\n var allNextMovingTiki = []\n // get legal actions\n for(var i = 0 ; i < state.comActions.length ; i++)\n for(var j = 0 ; j < state.tikiOrder.length ; j++)\n {\n var nextState = new State()\n copyState(nextState,state)\n //console.log(\"try state \" , state , \"with op and tikiOrder \" , state.comActions[i] , state.tikiOrder[j])\n var illegal = checkLegalAction(state.comActions[i] , state.tikiOrder[j] , nextState)\n\n\n if (illegal == 1) \n continue\n\n nextState = tryNextState(state.comActions[i] , state.tikiOrder[j] , nextState)\n allNextState.push(nextState)\n allNextAction.push(i)\n allNextMovingTiki.push(j)\n \n //console.log(\"The nextState oeder is \" , nextState.tikiOrder)\n\n }\n\n var maxIndex = 0 ;\n var maxValue = -100000 ;\n\n for(var i = 0 ; i < allNextState.length ; i++)\n {\n var tmpValue = evaluationFunction(allNextState[i])\n if(tmpValue > maxValue)\n {maxValue = tmpValue\n maxIndex = i\n }\n }\n\n console.log(\"AI say do operation \" , state.comActions[allNextAction[maxIndex]] , \" on tiki \" , state.tikiOrder[allNextMovingTiki[maxIndex]])\n var operation = state.comActions[allNextAction[maxIndex]];\n updateState(operation, allNextMovingTiki[maxIndex], 0);\n\n var AIscore = computeAISocre(state)\n console.log(\"AI now scores \", AIscore)\n\n}",
"function aiInit() {\n if (singlePlayer) {\n const aiPlayer = Math.floor(Math.random() * 2) + 1;\n if (aiPlayer === 1) {\n aiMove(1);\n }\n }\n }",
"aiInit() {\n if (this.props.singlePlayer) {\n const aiPlayer = Math.floor(Math.random() * 2) + 1;\n if (aiPlayer === 1) {\n this.aiMove();\n }\n }\n }",
"function initAIsetup() {\n // note: for fairness place AI3 first\n\n // remaining 26 armies per player, each AI take turn place 2\n for (var i = 0; i < 26/2; i++) {\n _.each(AIlist, placeTwo);\n };\n // get and place one army\n function placeTwo(ai) {\n AIupdate(ai);\n var army_given = ai.getArmies(2);\n ai.placeArmies();\n }\n}",
"function takeANoviceMove(turn) {\n var available = game.currentState.emptyCells();\n\n //enumerate and calculate the score for each available actions to the ai player\n var availableActions = available.map(function(pos) {\n var action = new AIAction(pos); //create the action object\n var nextState = action.applyTo(game.currentState); //get next state by applying the action\n\n action.minimaxVal = minimaxValue(nextState); //calculate and set the action's minimax value\n\n return action;\n });\n\n //sort the enumerated actions list by score\n if(turn === \"X\")\n //X maximizes --> sort the actions in a descending manner to have the action with maximum minimax at first\n availableActions.sort(AIAction.DESCENDING);\n else\n //O minimizes --> sort the actions in an ascending manner to have the action with minimum minimax at first\n availableActions.sort(AIAction.ASCENDING);\n\n /*\n * take the optimal action 40% of the time, and take the 1st suboptimal action 60% of the time\n */\n var chosenAction;\n if(Math.random()*100 <= 40) {\n chosenAction = availableActions[0];\n }\n else {\n if(availableActions.length >= 2) {\n //if there is two or more available actions, choose the 1st suboptimal\n chosenAction = availableActions[1];\n }\n else {\n //choose the only available actions\n chosenAction = availableActions[0];\n }\n }\n var next = chosenAction.applyTo(game.currentState);\n\n ui.insertAt(chosenAction.movePosition, turn);\n\n game.advanceTo(next);\n }",
"function aiChoice(){\n aiAnswer = Math.floor((Math.random() * 3) + 1);\n if (aiAnswer === 1){\n //cc = \"paper\";\n return \"paper\";\n }\n else if (aiAnswer === 2){\n //cc = \"rock\";\n return \"rock\";\n }\n else if (aiAnswer === 3){\n //cc = \"scissors\";\n return \"scissors\";\n }\n }",
"function handleAI(paddle1Pos, paddle2Pos, paddle1Height, paddle2Height){\r\n\r\n\tif(GAME.player1 == 'CPU'){\r\n\t\tartificialIntelligence(paddle1Pos,paddle1Height,1,GAME.frameCounter);\r\n\t}\r\n\tif(GAME.player2 == 'CPU'){\r\n\t\tartificialIntelligence(paddle2Pos,paddle2Height,2,GAME.frameCounter);\r\n\t}\r\n}",
"function aiChoice() {\n aiAnswer = Math.floor((Math.random() * 3) + 1);\n if (aiAnswer === 1) {\n cc = \"paper\";\n return \"paper\";\n }\n else if (aiAnswer === 2) {\n cc = \"rock\";\n return \"rock\";\n }\n else if (aiAnswer === 3) {\n cc = \"scissors\";\n return \"scissors\";\n }\n}",
"function playMostWinsVSAlphaBeta(choiceFirstPlayer){\r\n let p1 = new AI_alphabeta(\"X\");\r\n let p2 = new AI_heuristicMostWins(\"O\");\r\n startGamePringMsg(\"AI AlphaBeta\", \"AI MostWins\");\r\n\r\n let tictactoe = new TicTacToe;\r\n\r\n if (choiceFirstPlayer == \"MostWinsHeuristic\"){\r\n turnAI(p2, p1, tictactoe);\r\n AIvsAI(p1, p2, tictactoe);\r\n } else AIvsAI(p1, p2, tictactoe);\r\n}",
"changeToAiTurn() {\n if (this.gameSettings.difficulty === 'hard') {\n this.playSmartAiTurn();\n }\n else {\n this.playRandomAiTurn();\n }\n }",
"function AI(actor, type) {\n this.type = type;\n this.actor = actor;\n if (this.type == 'human') {\n this.makeAction = this.makeHumanAction;\n } else if (this.type == 'comp') {\n this.makeAction = this.makeDumbAIAction;\n };\n}",
"AI(){\n this.aimanaUsed=0;\n this.aiPlayedCards=0;\n let cardspLayedThisTurn=[];\n // determine AI Stance\n if ( (this.first ==='ai' && this.turn===0) || (this.first==='player'&&this.turn===1) ){\n this.aiStance='setup'\n this.maxaiPlay=2;\n this.maxManaUse=20;\n }\n else if(this.playerboard.length >3){\n // AI tries to kill your monsters\n this.aiStance= 'clearBoard';\n this.maxaiPlay=3;\n this.maxManaUse=30;\n\n }\n else if(this.aiMana <=50 || this.aiboard.length <=0){\n this.aiStance='defensive';\n this.maxaiPlay=4;\n this.maxManaUse=10;\n } else if(this.playerboard.length<=1 || this.playerMana<=40){\n this.aiStance='aggressive';\n this.maxaiPlay=3;\n this.maxManaUse=20;\n }else{\n this.aiStance='neutral';\n this.maxaiPlay=1;\n this.maxManaUse=10;\n }\n\n // determine AI Moves\n if(this.aiStance==='setup'){\n\n for(let i=0; i<this.aihand.length;i++){\n if(this.aiPlayedCards===this.maxaiPlay ||this.aimanaUsed===this.maxManaUse){\n break;\n }\n if( (this.aihand[i].type ==='legendary creature' &&this.aihand[i].cost+this.aimanaUsed<=this.maxManaUse) || (this.aihand[i].type==='creature'&&this.aihand[i].cost+this.aimanaUsed<=this.maxManaUse)){\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n this.playCard(i, false);\n }\n }\n if(this.aiPlayedCards===0){\n let healplayed=false;\n let hurtplayed=false;\n for(let i=0; i<this.aihand.length;i++){\n if(this.aiPlayedCards===this.maxaiPlay ||this.aimanaUsed===this.maxManaUse){\n break;\n }\n else if(healplayed===false &&this.aihand[i].type ==='heal'){\n healplayed=true;\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n this.playCard(i, false);\n }\n else if(hurtplayed===false &&this.aihand[i].type ==='hurt'){\n hurtplayed=true;\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n this.playCard(i, false);\n }\n }\n for(let i=0; i<this.aihand.length;i++){\n if(this.aiPlayedCards===this.maxaiPlay ||this.aimanaUsed===this.maxManaUse){\n break;\n }\n else if( (healplayed===true&&hurtplayed===false) &&this.aihand[i].type ==='heal'){\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n this.playCard(i, false);\n }\n else if( (hurtplayed===true &&healplayed===false) &&this.aihand[i].type ==='hurt'){\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n this.playCard(i, false);\n }\n }\n this.endTurn();\n }\n }else if(this.aiStance==='clearBoard'){\n for(let i=0; i<this.aihand.length;i++) {\n if (this.aiPlayedCards === this.maxaiPlay || this.aimanaUsed === this.maxManaUse) {\n break;\n }\n if(this.aihand.type==='hurt'&&this.aihand[i].cost+this.aimanaUsed<=this.maxManaUse){\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n cardspLayedThisTurn.push(this.aihand[i]);\n this.playCard(i, false);\n }\n\n }\n for(let i=0; i<this.aiboard.length;i++){\n let canplay=true;\n let hasattacked=false;\n for(let j=0;j <cardspLayedThisTurn.length;j++){\n if(this.aiboard[i]===cardspLayedThisTurn[j]){\n canplay=false;\n }\n }\n if(canplay===true&& hasattacked===false){\n for(let k=0; k<this.playerboard.length;k++){\n if(this.playerboard[k].defense <= this.aiboard[i].attack){\n hasattacked=true;\n this.attackCard(i,k,true);\n }\n }\n }\n }\n this.endTurn();\n\n }else if(this.aiStance==='defensive'){\n let onePlay=false;\n for(let i=0; i<this.aihand.length;i++){\n if(this.aiPlayedCards===this.maxaiPlay ||this.aimanaUsed===this.maxManaUse){\n break;\n }\n if(this.aihand[i].type==='heal'){\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n this.playCard(i, false);\n }\n if( onePlay===false&&((this.aihand[i].type ==='legendary creature' &&this.aihand[i].cost+this.aimanaUsed<=this.maxManaUse) || (this.aihand[i].type==='creature'&&this.aihand[i].cost+this.aimanaUsed<=this.maxManaUse))){\n this.playCard(i, false);\n onePlay=true;\n }\n }\nthis.endTurn();\n }else if(this.aiStance==='aggressive'){\n for(let i=0; i<this.aihand.length;i++) {\n if (this.aiPlayedCards === this.maxaiPlay || this.aimanaUsed === this.maxManaUse) {\n break;\n }\n if(this.aihand.type==='hurt'&&this.aihand[i].cost+this.aimanaUsed<=this.maxManaUse){\n this.aiPlayedCards++;\n this.aimanaUsed+= this.aihand[i].cost;\n cardspLayedThisTurn.push(this.aihand[i]);\n this.playCard(i, false);\n }\n\n }\n for(let i=0; i<this.aiboard.length;i++){\n let canplay=true;\n let hasattacked=false;\n for(let j=0;j <cardspLayedThisTurn.length;j++){\n if(this.aiboard[i]===cardspLayedThisTurn[j]){\n canplay=false;\n }\n }\n if(canplay===true&& hasattacked===false){\n hasattacked=true;\n this.attackPlayer(i,true)\n }\n }\n this.endTurn();\n } else if(this.aiStance==='neutral') {\n for (let i = 0; i < this.aihand.length; i++) {\n if (this.aiPlayedCards === this.maxaiPlay || this.aimanaUsed === this.maxManaUse) {\n break;\n }\n if ((this.aihand[i].type === 'legendary creature' && this.aihand[i].cost + this.aimanaUsed <= this.maxManaUse) || (this.aihand[i].type === 'creature' && this.aihand[i].cost + this.aimanaUsed <= this.maxManaUse)) {\n this.aiPlayedCards++;\n this.aimanaUsed += this.aihand[i].cost;\n this.playCard(i, false);\n }\n }\n if (this.aiPlayedCards === 0) {\n let x = Math.round(Math.random());\n let played = false;\n if (x === 0) {\n for (let j = 0; j < this.aihand.length; j++) {\n if (this.aihand[j].type === 'heal')\n this.aiPlayedCards++;\n this.aimanaUsed += this.aihand[j].cost;\n played = true;\n this.playCard(j, false);\n }\n } else {\n for (let j = 0; j < this.aihand.length; j++) {\n if (this.aihand[j].type === 'hurt')\n this.aiPlayedCards++;\n this.aimanaUsed += this.aihand[j].cost;\n played = true;\n this.playCard(j, false);\n }\n }\n if (x === 0 && played === false) {\n for (let j = 0; j < this.aihand.length; j++) {\n if (this.aihand[j].type === 'hurt')\n this.aiPlayedCards++;\n this.aimanaUsed += this.aihand[j].cost;\n played = true;\n this.playCard(j, false);\n }\n } else if (played === false) {\n for (let j = 0; j < this.aihand.length; j++) {\n if (this.aihand[j].type === 'heal')\n this.aiPlayedCards++;\n this.aimanaUsed += this.aihand[j].cost;\n played = true;\n this.playCard(j, false);\n }\n }\n\n }\n }\n\n this.endTurn();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Goal: Build a molecular structure from a URL pdbfile | function ReadPDBurl(URL,callback)
{
var name = PDButil.stripName(URL);
var request = new XMLHttpRequest();
request.open('GET', URL, true);
request.onload = function() {
var text = request.responseText;
loadStructureHandler(text);
};
request.send();
//When file is read, this function is called
function loadStructureHandler(text)
{
var content = text.split("\n");
//console.log(content[1]);
BuildStructure(name,content,callback, new ProgressDialog("Assimilating PDB file "+name+"..."));
};
function errorStructureHandler(event)
{
console.log("Error while reading the file");
};
} | [
"function LM_getUrlStructure(anode,pdbname){\r\n pdbname = pdbname.toLowerCase();\r\n if (pdbname.length === 4) {\r\n if (anode.data.surface)\r\n {\r\n if (anode.data.opm === 1){\r\n //replace purl\r\n return opm_url+ pdbname +\".pdb\";//cellpack_repo+\"opm/\" + pdbname + \".mmtf\";\r\n }\r\n else if (anode.data.opm === 0)\r\n {\r\n //check if exists\r\n var search_url = cellpack_repo+\"opm/\"+pdbname+ \".mmtf\";\r\n var results = syncCall(search_url);\r\n if (results !==\"\")\r\n {\r\n purl = cellpack_repo+\"opm/\" + pdbname + \".mmtf\";\r\n anode.data.opm = 1;\r\n return purl;\r\n }\r\n else {\r\n anode.data.opm = -1;\r\n }\r\n //check if exist in opm..doesnt work\r\n //var search_url = \"http://opm.phar.umich.edu/protein.php?search=\"+aname//1l7v\r\n //var results = syncCall(search_url);\r\n //var parser = new DOMParser();\r\n //var hdoc = parser.parseFromString(results,\"text/xml\");\r\n //console.log(hdoc);\r\n }\r\n }\r\n return \"https://files.rcsb.org/download/\" + pdbname + \".cif\";\r\n //return \"https://www.ebi.ac.uk/pdbe/static/entry/\" + pdbname + \".cif\";\r\n }\r\n else\r\n {\r\n var ext = pdbname.slice(-4, pdbname.length);\r\n if (pdbname.startsWith(\"EMD\") || pdbname.startsWith(\"EMDB\") || pdbname.slice(-4, pdbname.length) === \".map\") {\r\n var params = {\r\n defaultRepresentation: false\r\n };\r\n //this is async!\r\n console.log(\"try to load \", pdbname, ext);\r\n if (ext !== \".map\") pdbname = pdbname + \".map\";\r\n if (folder_elem && folder_elem.files.length != \"\")\r\n {\r\n return pathList_[pdbname];\r\n }\r\n else\r\n {\r\n return cellpack_repo+\"other/\" + pdbname;\r\n }\r\n }\r\n else\r\n {\r\n //what about emdb\r\n if (folder_elem && folder_elem.files.length != \"\") {\r\n //alert(pathList_[d.data.source]),\r\n return pathList_[pdbname];\r\n }\r\n else\r\n {\r\n return cellpack_repo+\"other/\" + pdbname;\r\n }\r\n }\r\n }\r\n return \"\";\r\n}",
"function loadPDB(name, callback) {\n console.log(\"Loading \" + name + \" ...\");\n jQuery.get('http://www.adcworks.com/api/pdb/' + name, function(data) {\n\n var lines = data.split(\"\\n\");\n if (lines.length > 0) {\n pdb = lines.join(\"<br>\");\n var mol = new Molecule();\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n var recordName = line.substring(1 - 1, 6).trim();\n if (recordName === \"ATOM\" || recordName === \"HETATM\") {\n\n var symbol = line.substring(77 - 1, 78).trim().toUpperCase();\n symbol = symbol.replace(/[^A-Z]/g, '');\n if (symbol.length === 0) {\n var name = line.substring(13 - 1, 15).trim().toUpperCase();\n name = name.replace(/[^A-Z]/g, '');\n symbol = symByPDBName(name);\n }\n\n var x = parseFloat(line.substring(31 - 1, 38).trim());\n var y = parseFloat(line.substring(39 - 1, 46).trim());\n var z = parseFloat(line.substring(47 - 1, 54).trim());\n var ref = refElement(symbol);\n mol.add(new Atom(i, symbol, x, y, z, ref.r));\n }\n }\n\n mol.finalise();\n callback(pdb, mol);\n }\n }, 'text');\n}",
"function pdb(text) {\n console.time('pdb'); \n var structure = new Mol();\n var currChain = null;\n var currRes = null;\n var currAtom = null;\n \n var helices = [];\n var sheets = [];\n \n function parseAndAddAtom(line, hetatm) {\n var alt_loc = line[16];\n if (alt_loc !== ' ' && alt_loc !== 'A') {\n return;\n }\n var chainName = line[21];\n var res_name = line.substr(17, 3);\n var atomName = line.substr(12, 4).trim();\n var rnumNum = parseInt(line.substr(22, 4), 10);\n var ins_code = line[26];\n var updateResidue = false;\n var updateChain = false;\n if (!currChain || currChain.name() !== chainName) {\n updateChain = true;\n updateResidue = true;\n }\n if (!currRes || currRes.num() !== rnumNum) {\n updateResidue = true;\n }\n if (updateChain) {\n // residues of one chain might appear interspersed with residues from\n // other chains.\n currChain = structure.chain(chainName) || structure.addChain(chainName);\n }\n if (updateResidue) {\n currRes = currChain.addResidue(res_name, rnumNum,\n currChain.residues().length);\n }\n var pos = vec3.create();\n for (var i=0;i<3;++i) {\n pos[i] = (parseFloat(line.substr(30+i*8, 8)));\n }\n currRes.addAtom(atomName, pos, line.substr(76, 2).trim());\n }\n var lines = text.split(/\\r\\n|\\r|\\n/g);\n var i = 0;\n for (i = 0; i < lines.length; i++) {\n var line = lines[i];\n var recordName = line.substr(0, 6);\n\n if (recordName === 'ATOM ') {\n parseAndAddAtom(line, false);\n continue;\n }\n if (recordName === 'HETATM') {\n parseAndAddAtom(line, true);\n continue;\n }\n if (recordName === 'HELIX ') {\n helices.push(parseHelixRecord(line));\n continue;\n }\n if (recordName === 'SHEET ') {\n sheets.push(parseSheetRecord(line));\n continue;\n }\n if (recordName === 'END') {\n break;\n }\n }\n var chain = null;\n for (i = 0; i < sheets.length; ++i) {\n var sheet = sheets[i];\n chain = structure.chain(sheet.chainName);\n if (chain) {\n chain.assign_ss(sheet.first, sheet.last, 'E');\n }\n }\n for (i = 0; i < helices.length; ++i) {\n var helix = helices[i];\n chain = structure.chain(helix.chainName);\n if (chain) {\n chain.assign_ss(helix.first, helix.last, 'H');\n }\n }\n structure.deriveConnectivity();\n console.log('imported', structure.chains().length, 'chain(s),',\n structure.residueCount(), 'residue(s)');\n console.timeEnd('pdb');\n\n return structure;\n}",
"function pdb(id = '4glf') {\n // const data = posturi('https://files.rcsb.org/download/' + id.toUpperCase() + '.pdb');\n const url = 'https://files.rcsb.org/download/' + id.toUpperCase() + '.pdb';\n CSynth.handlefileset( {eventParms: [{ canonpath: url}] })\n}",
"function readPDBfile(lines) {\n // Declare local variables\n var i, j;\n var x, y, z;\n var bond1, bond2;\n var A, symbol, line;\n var Qtitle = new Array();\n var molecule = Mol();\n var atomnum_limit = 2000;\n\n // Write file information to information window\n var molname = lines[0].split(/\\s+/)[1];\n\n // Reset molecule object and contents\n delMolecule();\n\n // Read data\n for(i = 2; i < lines.length; i++) {\n if(lines[i].substring(0, 6) == \"HETATM\" || lines[i].substring(0, 4) == \"ATOM\") {\n symbol = lines[i].substring(12, 16);\n symbol = symbol.replace(/\\s+/, \"\");\n A = lookupSymbol(symbol.trim());\n x = parseFloat(lines[i].substring(30, 38));\n y = parseFloat(lines[i].substring(38, 46));\n z = parseFloat(lines[i].substring(46, 54));\n addAtom(A, x, y, z, 0);\n }\n if(lines[i].substring(0, 6) == \"CONECT\") {\n bond1 = parseFloat(lines[i].substr(6, 5));\n for(j = 11; j < lines[i].length; j = j + 5) {\n var bonds = BondMatrix();\n bond2 = parseFloat(lines[i].substr(j, 5));\n bonds[bond1][0]++;\n bonds[bond1][bond2] = 1;\n }\n }\n }\n \n formula();\n }",
"function loadPDB(pdb,rotate) {\n\t\t\t\t\t\tconsole.log('loadPDB');\n\t\t\t\t\t\tvar structure = pv.io.pdb(pdb);\n\t\t\t\t\t\tvar ligand = structure.select({rnames : ['UNL']});\n\t\t\t\t\t\t//Attach protein viewer to element\n\t\t\t\t\t\tvar viewer = pv.Viewer(document.getElementById(scope.ngid), { quality : 'high', width: 'auto', height : 'auto', antialias : true, outline : false, });\n\t\t\t\t\t\tviewer.on('viewerReady', function() {\n\t\t\t\t\t\t\tviewer.clear();\n\t\t\t\t\t\t\tviewer.ballsAndSticks('ligand', ligand);\n\t\t\t\t\t\t\tviewer.centerOn(ligand);\n\t\t\t\t\t\t\tviewer.autoZoom();\n\t\t\t\t\t\t\t//viewer.fitParent();\n\t\t\t\t\t\t\tviewer.spin(rotate);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}",
"function ReadPDBfile(file,callback)\r\n{\r\n\tvar self = this;\r\n\tvar name= PDButil.stripName(file.name);\r\n\t\r\n\t//Assigning Properties by reading the file\r\n\tvar pdbfileReader = new FileReader();\r\n\t\r\n\t//Reads the file\r\n\tpdbfileReader.readAsText(file);\r\n\t\r\n\t//When file is read, this function is called\r\n\tpdbfileReader.onload = loadStructureHandler;\r\n\tpdbfileReader.onerror = errorStructureHandler;\r\n\t\r\n\tfunction loadStructureHandler(event)\r\n\t{\r\n\t var content = event.target.result.split(\"\\n\");\r\n\t //console.log(content[1]);\r\n\t BuildStructure(name,content,callback, new ProgressDialog(\"Assimilating PDB file \"+name+\"...\"));\r\n\t};\r\n\r\n\tfunction errorStructureHandler(event)\r\n\t{\r\n\t console.log(\"Error while reading the file\");\r\n\t};\r\n \r\n}",
"function pdb(text) {\n console.time('pdb'); \n var reader = new PDBReader();\n var lines = text.split(/\\r\\n|\\r|\\n/g);\n var i = 0;\n for (i = 0; i < lines.length; i++) {\n if (!reader.processLine(lines[i])) {\n break;\n }\n }\n var structure = reader.finish();\n console.timeEnd('pdb');\n return structure;\n}",
"function makeSciForm(mol) {\n var lines = mol.split(\"\\n\");\n var nodes = [];\n var bonds = [];\n var ncount = 0;\n var bcount = 0;\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n if (i == 3) {\n ncount = line.substring(0, 3).trim() - 0;\n bcount = line.substring(4, 7).trim() - 0;\n }\n if (i > 3 && i <= ncount + 3) {\n var node = {};\n node.id = \"cdj\" + (i - 3);\n node.pos = {};\n node.pos.x = line.substring(0, 10).trim() - 0;\n node.pos.y = -1 * (line.substring(11, 20).trim() - 0);\n //node.z=line.substring(0,10).trim()-0;\n node.sym = line.substring(31, 34).trim();\n node.type = \"ring_or_chain\";\n node.nodeNumber = (i - 3);\n nodes.push(node);\n }\n if (i > ncount + 3 && i <= ncount + 3 + bcount) {\n var b1 = line.substring(0, 3).trim() - 0;\n var b2 = line.substring(3, 6).trim() - 0;\n var or = line.substring(6, 9).trim() - 0;\n var bond = {};\n bond.id = \"cdj\" + (i - 3);\n bond.fromId = \"cdj\" + b1;\n bond.toId = \"cdj\" + b2;\n if (or == 1) {\n bond.order = \"single\";\n } else if (or == 2) {\n bond.order = \"double\";\n } else if (or == 3) {\n bond.order = \"triple\";\n }\n bond.type = \"ring_or_chain\";\n bond.locked = false;\n bonds.push(bond);\n\n }\n }\n return {\n nodes: nodes,\n bonds: bonds\n };\n }",
"downloadPdb(pdbid, bAf) {\n let ic = this.icn3d,\n me = ic.icn3dui\n let url, dataType\n\n if (bAf) {\n url = 'https://alphafold.ebi.ac.uk/files/AF-' + pdbid + '-F1-model_v1.pdb'\n ic.ParserUtilsCls.setYourNote(pdbid.toUpperCase() + '(AlphaFold) in iCn3D')\n } else {\n url = 'https://files.rcsb.org/view/' + pdbid + '.pdb'\n ic.ParserUtilsCls.setYourNote(pdbid.toUpperCase() + '(PDB) in iCn3D')\n }\n\n dataType = 'text'\n\n ic.bCid = undefined\n\n $.ajax({\n url: url,\n dataType: dataType,\n cache: true,\n tryCount: 0,\n retryLimit: 1,\n beforeSend: function () {\n ic.ParserUtilsCls.showLoading()\n },\n complete: function () {\n //ic.ParserUtilsCls.hideLoading();\n },\n success: function (data) {\n //ic.pdbParserCls.loadPdbData(data, pdbid);\n ic.deferredOpm = $.Deferred(function () {\n //ic.loadPdbOpmData(data, pdbid);\n if (bAf) {\n ic.opmParserCls.parseAtomData(data, pdbid, undefined, 'pdb', undefined)\n } else {\n ic.opmParserCls.loadOpmData(data, pdbid, undefined, 'pdb')\n }\n })\n\n return ic.deferredOpm.promise()\n },\n error: function (xhr, textStatus, errorThrown) {\n this.tryCount++\n if (this.tryCount <= this.retryLimit) {\n //try again\n $.ajax(this)\n return\n }\n return\n },\n })\n }",
"async loadStructureFromData (url, format, reprParams, cards) {\n this.cards = cards;\n await this.plugin.clear();\n console.log('Loading...');\n this.plugin.behaviors.layout.leftPanelTabName.next('data');\n const data = await this.plugin.builders.data.download({url}, { state: { isGhost: true } });\n this.originalData = data;\n // console.log(data);\n // console.log(format);\n try {\n const trajectory = await this.plugin.builders.structure.parseTrajectory(data, format);\n const model = await this.plugin.builders.structure.createModel(trajectory);\n if (!model) return;\n const structure = await this.plugin.builders.structure.createStructure(model);\n this.structureDefault = structure;\n\n const {type, coloring, uniformColor} = reprParams;\n let props = {\n type: type,\n // color: coloring,\n size: 'uniform',\n sizeParams: {value: 1.5}\n }\n if (coloring === 'uniform') {\n props.colorParams = {value: Color.fromRgb(uniformColor.r, uniformColor.g, uniformColor.b)}\n }\n if (type === 'cartoon') {\n props.typeParams = {visuals: ['polymer-trace', 'polymer-gap', 'nucleotide-block']}\n }\n this.defaultProps = props;\n // console.log('begin');\n if (structure) {\n cards.forEach(async card => {\n let card_props = JSON.parse(JSON.stringify(props));\n card_props.color = 'uniform';\n card_props.colorParams = {value: ColorNames[card.color]};\n const card_query = await this.queryChain(card.chain);\n const card_component = await this.createChainComponent(structure, card_query, 'Chain' + card.chain)\n if (card_component) {\n let card_structure = await this.addStructRepr(card_component, card_props);\n this.viewer_data[card.chain] = {'query': card_query,\n 'props': card_props,\n 'component': card_component,\n 'structure': card_structure\n }\n }\n });\n }\n } catch (error) {\n // console.log(error);\n }\n }",
"parse( text ) {\n\n\t\tfunction trim( text ) {\n\n\t\t\treturn text.replace( /^\\s\\s*/, '' ).replace( /\\s\\s*$/, '' );\n\n\t\t}\n\n\t\tfunction capitalize( text ) {\n\n\t\t\treturn text.charAt( 0 ).toUpperCase() + text.slice( 1 ).toLowerCase();\n\n\t\t}\n\n\t\tfunction hash( s, e ) {\n\n\t\t\treturn 's' + Math.min( s, e ) + 'e' + Math.max( s, e );\n\n\t\t}\n\n\t\tfunction parseBond( start, length, satom, i ) {\n\n\t\t\tconst eatom = parseInt( lines[ i ].slice( start, start + length ) );\n\n\t\t\tif ( eatom ) {\n\n\t\t\t\tconst h = hash( satom, eatom );\n\n\t\t\t\tif ( _bhash[ h ] === undefined ) {\n\n\t\t\t\t\t_bonds.push( [ satom - 1, eatom - 1, 1 ] );\n\t\t\t\t\t_bhash[ h ] = _bonds.length - 1;\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// doesn't really work as almost all PDBs\n\t\t\t\t\t// have just normal bonds appearing multiple\n\t\t\t\t\t// times instead of being double/triple bonds\n\t\t\t\t\t// bonds[bhash[h]][2] += 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction buildGeometry() {\n\n\t\t\tconst build = {\n\t\t\t\tgeometryAtoms: new BufferGeometry(),\n\t\t\t\tgeometryBonds: new BufferGeometry(),\n\t\t\t\tjson: {\n\t\t\t\t\tatoms: atoms\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst geometryAtoms = build.geometryAtoms;\n\t\t\tconst geometryBonds = build.geometryBonds;\n\n\t\t\tconst verticesAtoms = [];\n\t\t\tconst colorsAtoms = [];\n\t\t\tconst verticesBonds = [];\n\n\t\t\t// atoms\n\n\t\t\tconst c = new Color();\n\n\t\t\tfor ( let i = 0, l = atoms.length; i < l; i ++ ) {\n\n\t\t\t\tconst atom = atoms[ i ];\n\n\t\t\t\tconst x = atom[ 0 ];\n\t\t\t\tconst y = atom[ 1 ];\n\t\t\t\tconst z = atom[ 2 ];\n\n\t\t\t\tverticesAtoms.push( x, y, z );\n\n\t\t\t\tconst r = atom[ 3 ][ 0 ] / 255;\n\t\t\t\tconst g = atom[ 3 ][ 1 ] / 255;\n\t\t\t\tconst b = atom[ 3 ][ 2 ] / 255;\n\n\t\t\t\tc.set( r, g, b ).convertSRGBToLinear();\n\n\t\t\t\tcolorsAtoms.push( c.r, c.g, c.b );\n\n\t\t\t}\n\n\t\t\t// bonds\n\n\t\t\tfor ( let i = 0, l = _bonds.length; i < l; i ++ ) {\n\n\t\t\t\tconst bond = _bonds[ i ];\n\n\t\t\t\tconst start = bond[ 0 ];\n\t\t\t\tconst end = bond[ 1 ];\n\n\t\t\t\tconst startAtom = _atomMap[ start ];\n\t\t\t\tconst endAtom = _atomMap[ end ];\n\n\t\t\t\tlet x = startAtom[ 0 ];\n\t\t\t\tlet y = startAtom[ 1 ];\n\t\t\t\tlet z = startAtom[ 2 ];\n\n\t\t\t\tverticesBonds.push( x, y, z );\n\n\t\t\t\tx = endAtom[ 0 ];\n\t\t\t\ty = endAtom[ 1 ];\n\t\t\t\tz = endAtom[ 2 ];\n\n\t\t\t\tverticesBonds.push( x, y, z );\n\n\t\t\t}\n\n\t\t\t// build geometry\n\n\t\t\tgeometryAtoms.setAttribute( 'position', new Float32BufferAttribute( verticesAtoms, 3 ) );\n\t\t\tgeometryAtoms.setAttribute( 'color', new Float32BufferAttribute( colorsAtoms, 3 ) );\n\n\t\t\tgeometryBonds.setAttribute( 'position', new Float32BufferAttribute( verticesBonds, 3 ) );\n\n\t\t\treturn build;\n\n\t\t}\n\n\t\tconst CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], be: [ 194, 255, 0 ], b: [ 255, 181, 181 ], c: [ 144, 144, 144 ], n: [ 48, 80, 248 ], o: [ 255, 13, 13 ], f: [ 144, 224, 80 ], ne: [ 179, 227, 245 ], na: [ 171, 92, 242 ], mg: [ 138, 255, 0 ], al: [ 191, 166, 166 ], si: [ 240, 200, 160 ], p: [ 255, 128, 0 ], s: [ 255, 255, 48 ], cl: [ 31, 240, 31 ], ar: [ 128, 209, 227 ], k: [ 143, 64, 212 ], ca: [ 61, 255, 0 ], sc: [ 230, 230, 230 ], ti: [ 191, 194, 199 ], v: [ 166, 166, 171 ], cr: [ 138, 153, 199 ], mn: [ 156, 122, 199 ], fe: [ 224, 102, 51 ], co: [ 240, 144, 160 ], ni: [ 80, 208, 80 ], cu: [ 200, 128, 51 ], zn: [ 125, 128, 176 ], ga: [ 194, 143, 143 ], ge: [ 102, 143, 143 ], as: [ 189, 128, 227 ], se: [ 255, 161, 0 ], br: [ 166, 41, 41 ], kr: [ 92, 184, 209 ], rb: [ 112, 46, 176 ], sr: [ 0, 255, 0 ], y: [ 148, 255, 255 ], zr: [ 148, 224, 224 ], nb: [ 115, 194, 201 ], mo: [ 84, 181, 181 ], tc: [ 59, 158, 158 ], ru: [ 36, 143, 143 ], rh: [ 10, 125, 140 ], pd: [ 0, 105, 133 ], ag: [ 192, 192, 192 ], cd: [ 255, 217, 143 ], in: [ 166, 117, 115 ], sn: [ 102, 128, 128 ], sb: [ 158, 99, 181 ], te: [ 212, 122, 0 ], i: [ 148, 0, 148 ], xe: [ 66, 158, 176 ], cs: [ 87, 23, 143 ], ba: [ 0, 201, 0 ], la: [ 112, 212, 255 ], ce: [ 255, 255, 199 ], pr: [ 217, 255, 199 ], nd: [ 199, 255, 199 ], pm: [ 163, 255, 199 ], sm: [ 143, 255, 199 ], eu: [ 97, 255, 199 ], gd: [ 69, 255, 199 ], tb: [ 48, 255, 199 ], dy: [ 31, 255, 199 ], ho: [ 0, 255, 156 ], er: [ 0, 230, 117 ], tm: [ 0, 212, 82 ], yb: [ 0, 191, 56 ], lu: [ 0, 171, 36 ], hf: [ 77, 194, 255 ], ta: [ 77, 166, 255 ], w: [ 33, 148, 214 ], re: [ 38, 125, 171 ], os: [ 38, 102, 150 ], ir: [ 23, 84, 135 ], pt: [ 208, 208, 224 ], au: [ 255, 209, 35 ], hg: [ 184, 184, 208 ], tl: [ 166, 84, 77 ], pb: [ 87, 89, 97 ], bi: [ 158, 79, 181 ], po: [ 171, 92, 0 ], at: [ 117, 79, 69 ], rn: [ 66, 130, 150 ], fr: [ 66, 0, 102 ], ra: [ 0, 125, 0 ], ac: [ 112, 171, 250 ], th: [ 0, 186, 255 ], pa: [ 0, 161, 255 ], u: [ 0, 143, 255 ], np: [ 0, 128, 255 ], pu: [ 0, 107, 255 ], am: [ 84, 92, 242 ], cm: [ 120, 92, 227 ], bk: [ 138, 79, 227 ], cf: [ 161, 54, 212 ], es: [ 179, 31, 212 ], fm: [ 179, 31, 186 ], md: [ 179, 13, 166 ], no: [ 189, 13, 135 ], lr: [ 199, 0, 102 ], rf: [ 204, 0, 89 ], db: [ 209, 0, 79 ], sg: [ 217, 0, 69 ], bh: [ 224, 0, 56 ], hs: [ 230, 0, 46 ], mt: [ 235, 0, 38 ], ds: [ 235, 0, 38 ], rg: [ 235, 0, 38 ], cn: [ 235, 0, 38 ], uut: [ 235, 0, 38 ], uuq: [ 235, 0, 38 ], uup: [ 235, 0, 38 ], uuh: [ 235, 0, 38 ], uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] };\n\n\t\tconst atoms = [];\n\n\t\tconst _bonds = [];\n\t\tconst _bhash = {};\n\t\tconst _atomMap = {};\n\n\t\t// parse\n\n\t\tconst lines = text.split( '\\n' );\n\n\t\tfor ( let i = 0, l = lines.length; i < l; i ++ ) {\n\n\t\t\tif ( lines[ i ].slice( 0, 4 ) === 'ATOM' || lines[ i ].slice( 0, 6 ) === 'HETATM' ) {\n\n\t\t\t\tconst x = parseFloat( lines[ i ].slice( 30, 37 ) );\n\t\t\t\tconst y = parseFloat( lines[ i ].slice( 38, 45 ) );\n\t\t\t\tconst z = parseFloat( lines[ i ].slice( 46, 53 ) );\n\t\t\t\tconst index = parseInt( lines[ i ].slice( 6, 11 ) ) - 1;\n\n\t\t\t\tlet e = trim( lines[ i ].slice( 76, 78 ) ).toLowerCase();\n\n\t\t\t\tif ( e === '' ) {\n\n\t\t\t\t\te = trim( lines[ i ].slice( 12, 14 ) ).toLowerCase();\n\n\t\t\t\t}\n\n\t\t\t\tconst atomData = [ x, y, z, CPK[ e ], capitalize( e ) ];\n\n\t\t\t\tatoms.push( atomData );\n\t\t\t\t_atomMap[ index ] = atomData;\n\n\t\t\t} else if ( lines[ i ].slice( 0, 6 ) === 'CONECT' ) {\n\n\t\t\t\tconst satom = parseInt( lines[ i ].slice( 6, 11 ) );\n\n\t\t\t\tparseBond( 11, 5, satom, i );\n\t\t\t\tparseBond( 16, 5, satom, i );\n\t\t\t\tparseBond( 21, 5, satom, i );\n\t\t\t\tparseBond( 26, 5, satom, i );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build and return geometry\n\n\t\treturn buildGeometry();\n\n\t}",
"function parsePdfs(database, url) {\n let parsedUrl = new urlparser.URL(url);\n let baseUrl = parsedUrl.origin + parsedUrl.pathname;\n\n requestPage(url, body => {\n // Use cheerio to find all URLs that refer to PDFs.\n \n let pdfUrls = [];\n let $ = cheerio.load(body);\n $(\"h3.generic-list__title a\").each((index, element) => {\n let parsedPdfUrl = new urlparser.URL(element.attribs.href, baseUrl);\n if (!pdfUrls.some(url => url === parsedPdfUrl.href)) // avoid duplicates\n pdfUrls.push(parsedPdfUrl.href);\n });\n console.log(`Found ${pdfUrls.length} PDF file(s) to download and parse at ${url}. Selecting two to parse.`);\n\n // Select the most recent PDF. And randomly select one other PDF (avoid processing all\n // PDFs at once because this may use too much memory, resulting in morph.io terminating\n // the current process).\n\n let selectedPdfUrls = [];\n selectedPdfUrls.push(pdfUrls.shift());\n if (pdfUrls.length > 0)\n selectedPdfUrls.push(pdfUrls[getRandom(0, pdfUrls.length)]);\n\n // Read and parse each PDF, extracting the development application text.\n\n for (let pdfUrl of selectedPdfUrls) {\n // Parse the PDF into a collection of PDF rows. Each PDF row is simply an array of\n // strings, being the text that has been parsed from the PDF.\n\n let pdfParser = new pdf2json();\n let pdfPipe = request({ url: pdfUrl, proxy: process.env.MORPH_PROXY, encoding: null }).pipe(pdfParser);\n pdfPipe.on(\"pdfParser_dataError\", error => { console.error(error); });\n pdfPipe.on(\"pdfParser_dataReady\", pdf => {\n // Convert the JSON representation of the PDF into a collection of PDF rows.\n\n console.log(`Parsing PDF: ${pdfUrl}`);\n let pdfRows = convertPdfToText(pdf);\n\n let developmentApplications = [];\n let haveApplicationNumber = false;\n let haveAddress = false;\n let applicationNumber = null;\n let address = null;\n let description = null;\n let informationUrl = pdfUrl;\n let commentUrl = CommentUrl;\n let scrapeDate = moment().format(\"YYYY-MM-DD\");\n let lodgementDate = null;\n\n let previousPdfRow = null;\n for (let pdfRow of pdfRows) {\n // Ignore the lines associated with a page break (that is, ignore the header\n // and footer text that appears at the top and bottom of every page).\n\n let line = pdfRow.join(\"\").replace(/\\s/g, \"\").toLowerCase();\n if (line.startsWith(\"publicregisterofdevelopmentapplications\") ||\n line.startsWith(\"lodgementdatefrom\") ||\n line.startsWith(\"lodgementdateto\") ||\n line.startsWith(\"monday,\") ||\n line.startsWith(\"tuesday,\") ||\n line.startsWith(\"wednesday,\") ||\n line.startsWith(\"thursday,\") ||\n line.startsWith(\"friday,\") ||\n line.startsWith(\"saturday,\") ||\n line.startsWith(\"sunday,\"))\n continue;\n\n // If there are two forward slashes within the first 20 characters then it is\n // very likely an application number (and it is not formatted as a date such\n // as \"31/12/2008\"). For example, \"162/0082/12\".\n //\n // Note that sometimes the lodgement date will be difficult to correctly\n // obtain. For example, if the date is split across two elements in a PDF\n // row:\n //\n // [\"26/10/2017\", \"02/\", \"11/2017\", \"Allot 1 DP ...\"]\n //\n // The parseLodgementDate function makes an effort to resolve this situation.\n \n let parsedApplicationNumber = parseApplicationNumber(pdfRow);\n if (parsedApplicationNumber !== null) {\n // Extract the development application number and lodgement date.\n\n applicationNumber = parsedApplicationNumber;\n address = null;\n description = null;\n lodgementDate = parseLodgementDate(pdfRow, 2, \"nnn/nnnn/nn\".length); // dates appear after the application number\n haveApplicationNumber = true;\n haveAddress = false;\n } else if (haveApplicationNumber && !haveAddress) {\n // Attempt to extract the lodgement date (if it was not found earlier).\n\n if (lodgementDate === null)\n lodgementDate = parseLodgementDate(pdfRow, 1, 0);\n\n // Extract the address of the development application. It is assumed to\n // always appear on the next line after the text \"Property Address\"\n // (ignoring any header or footer text).\n\n if (previousPdfRow !== null && previousPdfRow.join(\"\").replace(/\\s/g, \"\").toLowerCase().startsWith(\"propertyaddress\")) {\n address = pdfRow.join(\"\").trim();\n haveApplicationNumber = true;\n haveAddress = true;\n }\n } else if (haveApplicationNumber && haveAddress) {\n // Extract the description for the development application. It is assumed\n // to always appear on the next line after the text \"Nature of Development\"\n // (ignoring any header or footer text).\n\n if (previousPdfRow !== null && previousPdfRow.join(\"\").replace(/\\s/g, \"\").toLowerCase().startsWith(\"natureofdevelopment\")) {\n description = pdfRow.join(\"\").trim();\n developmentApplications.push({\n applicationNumber: applicationNumber,\n address: address,\n description: description,\n informationUrl: informationUrl,\n commentUrl: commentUrl,\n scrapeDate: scrapeDate,\n lodgementDate: ((lodgementDate === null) ? null : lodgementDate.format(\"YYYY-MM-DD\")) });\n haveApplicationNumber = false;\n haveAddress = false;\n }\n }\n previousPdfRow = pdfRow;\n }\n\n // Insert all the development applications that were found into the database as\n // rows in a table. If the same development application number already exists on\n // a row then that existing row will not be replaced.\n\n let pdfFileName = decodeURIComponent(new urlparser.URL(pdfUrl).pathname.split(\"/\").pop());\n console.log(`Found ${developmentApplications.length} development application(s) in \\\"${pdfFileName}\\\".`);\n for (let developmentApplication of developmentApplications)\n insertRow(database, pdfFileName, developmentApplication);\n });\n }\n });\n}",
"function loadMolecule(filename) {\n var xhttp = new XMLHttpRequest();\n xhttp.overrideMimeType('text/xml');\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n parseResponse(this);\n }\n };\n xhttp.open('GET', filename, true);\n xhttp.send();\n}",
"downloadMmdb(mmdbid, bGi) {\n let ic = this.icn3d,\n me = ic.icn3dui\n let thisClass = this\n\n let url\n\n // b: b-factor, s: water, ft: pdbsite\n //&ft=1\n if (bGi) {\n url = me.htmlCls.baseUrl + 'mmdb/mmdb_strview.cgi?v=2&program=icn3d&b=1&s=1&ft=1&simple=1&gi=' + mmdbid\n } else {\n url = me.htmlCls.baseUrl + 'mmdb/mmdb_strview.cgi?v=2&program=icn3d&b=1&s=1&ft=1&simple=1&uid=' + mmdbid\n }\n\n // use asymmetric unit for BLAST search, e.g., https://www.ncbi.nlm.nih.gov/Structure/icn3d/full.html?from=blast&blast_rep_id=5XZC_B&query_id=1TUP_A&command=view+annotations;set+annotation+cdd;set+annotation+site;set+view+detailed+view;select+chain+5XZC_B;show+selection&log$=align&blast_rank=1&RID=EPUCYNVV014&buidx=0\n if (me.cfg.blast_rep_id !== undefined) url += '&buidx=0'\n\n ic.bCid = undefined\n\n if (me.cfg.inpara !== undefined) {\n url += me.cfg.inpara\n }\n\n if (ic.chainids2resids === undefined) ic.chainids2resids = {} // ic.chainids2resids[chainid1][chainid2] = [resid, resid]\n\n $.ajax({\n url: url,\n dataType: 'jsonp',\n cache: true,\n tryCount: 0,\n retryLimit: 1,\n beforeSend: function () {\n ic.ParserUtilsCls.showLoading()\n },\n complete: function () {\n //ic.ParserUtilsCls.hideLoading();\n },\n success: function (data) {\n if (Object.keys(data.atoms).length == 0) {\n // for large structures such as 3J3Q\n // use mmtfid\n let pdbid = data.pdbId\n ic.mmtfParserCls.downloadMmtf(pdbid)\n\n return\n }\n\n let bCalphaOnly = me.utilsCls.isCalphaPhosOnly(data.atoms) //, 'CA');\n\n if (bCalphaOnly || data.atomCount <= ic.maxatomcnt) {\n thisClass.parseMmdbData(data)\n } else {\n data = null\n\n $.ajax({\n url: url + '&complexity=2', // alpha carbons\n dataType: 'jsonp',\n cache: true,\n tryCount: 0,\n retryLimit: 1,\n beforeSend: function () {\n ic.ParserUtilsCls.showLoading()\n },\n complete: function () {\n //ic.ParserUtilsCls.hideLoading();\n },\n success: function (data2) {\n thisClass.parseMmdbData(data2)\n },\n error: function (xhr, textStatus, errorThrown) {\n this.tryCount++\n if (this.tryCount <= this.retryLimit) {\n //try again\n $.ajax(this)\n return\n }\n\n if (bGi) {\n alert('This gi ' + mmdbid + ' has no corresponding 3D structure...')\n } else {\n alert(\n 'This mmdbid ' +\n mmdbid +\n ' with the parameters ' +\n me.cfg.inpara +\n ' may not have 3D structure data. Please visit the summary page for details: ' +\n me.htmlCls.baseUrl +\n 'pdb/' +\n mmdbid,\n )\n }\n\n return\n }, // success\n }) // ajax\n }\n },\n error: function (xhr, textStatus, errorThrown) {\n this.tryCount++\n if (this.tryCount <= this.retryLimit) {\n //try again\n $.ajax(this)\n return\n }\n\n if (bGi) {\n alert('This gi ' + mmdbid + ' has no corresponding 3D structure...')\n } else {\n alert(\n 'This mmdbid ' +\n mmdbid +\n ' with the parameters ' +\n me.cfg.inpara +\n ' may not have 3D structure data. Please visit the summary page for details: ' +\n me.htmlCls.baseUrl +\n 'pdb/' +\n mmdbid,\n )\n }\n\n return\n }, // success\n }) // ajax\n }",
"function parse()\n{\n Papa.parse(\"https://raw.githubusercontent.com/eashang1/Acyclic/main/1000sents.csv\", {\n download: true,\n complete: function(results) {\n populate(results.data)\n }\n });\n}",
"function parseNMPContents(fileContents) {\n\n var table = '<table class=\"nmptable\"><thead /><tbody>';\n // all lines describe waypoints\n var lines = fileContents.replace(/\\r\\n/g,\"\\n\").split('\\n');\n waypoints = new Array();\n for (var i = 0; i < lines.length; i++) {\n\tif (lines[i].length > 0) {\n\t var xline = lines[i].split(' ');\n\t if (xline.length == 3) {\n\t\twaypoints[waypoints.length] = new Waypoint(xline[0], xline[1], xline[2], \"\", \"\");\n\t }\n\t}\n }\n // graph edges between pairs, will be drawn as connections\n var numE = waypoints.length/2;\n graphEdges = new Array(numE);\n for (var i = 0; i < numE; i++) {\n\t// add the edge\n\tgraphEdges[i] = new GraphEdge(2*i, 2*i+1, \"\", null);\n\n\t// add an entry to the table to be drawn in the pointbox\n\tvar miles = Mileage(waypoints[2*i].lat, waypoints[2*i].lon, waypoints[2*i+1].lat, waypoints[2*i+1].lon).toFixed(4);\n\tvar feet = Feet(waypoints[2*i].lat, waypoints[2*i].lon, waypoints[2*i+1].lat, waypoints[2*i+1].lon).toFixed(2);\n\ttable += \"<tr><td><table class=\\\"nmptable2\\\"><thead /><tbody><tr><td>\"\n\t + \"<a onclick=\\\"javascript:LabelClick(\" + 2*i + \",\\'\"\n\t + waypoints[2*i].label + \"\\',\"\n\t + waypoints[2*i].lat + \",\" + waypoints[2*i].lon + \",0);\\\">\"\n\t + waypoints[2*i].label + \"</a></td><td>(\"\n\t + waypoints[2*i].lat + \",\"\n\t + waypoints[2*i].lon + \")</td></tr><tr><td>\"\n\t + \"<a onclick=\\\"javascript:LabelClick(\" + 2*i+1 + \",\\'\"\n\t + waypoints[2*i+1].label + \"\\',\"\n\t + waypoints[2*i+1].lat + \",\" + waypoints[2*i+1].lon + \",0);\\\">\"\n\t + waypoints[2*i+1].label + \"</a></td><td>(\"\n\t + waypoints[2*i+1].lat + \",\"\n\t + waypoints[2*i+1].lon + \")</td></tr>\"\n\t + \"</tbody></table></td><td>\"\n\t + miles + \" mi/\"\n\t + feet + \" ft</td></tr>\";\n }\n\n table += \"</tbody></table>\";\n genEdges = false;\n return table;\n}",
"function parseNMPContents(fileContents) {\n\n var table = '<table class=\"nmptable\"><thead /><tbody>';\n // all lines describe waypoints\n var lines = fileContents.replace(/\\r\\n/g,\"\\n\").split('\\n');\n waypoints = new Array();\n for (var i = 0; i < lines.length; i++) {\n\tif (lines[i].length > 0) {\n\t var xline = lines[i].split(' ');\n\t if (xline.length == 3) {\n\t\twaypoints[waypoints.length] = new Waypoint(xline[0], xline[1], xline[2], \"\", \"\");\n\t }\n\t}\n }\n // graph edges between pairs, will be drawn as connections\n var numE = waypoints.length/2;\n graphEdges = new Array(numE);\n for (var i = 0; i < numE; i++) {\n\t// add the edge\n\tgraphEdges[i] = new GraphEdge(2*i, 2*i+1, \"\");\n\n\t// add an entry to the table to be drawn in the pointbox\n\tvar miles = Mileage(waypoints[2*i].lat, waypoints[2*i].lon, waypoints[2*i+1].lat, waypoints[2*i+1].lon).toFixed(4);\n\tvar feet = Feet(waypoints[2*i].lat, waypoints[2*i].lon, waypoints[2*i+1].lat, waypoints[2*i+1].lon).toFixed(2);\n\ttable += \"<tr><td><table class=\\\"nmptable2\\\"><thead /><tbody><tr><td>\"\n\t + \"<a onclick=\\\"javascript:LabelClick(\" + 2*i + \",\\'\"\n\t + waypoints[2*i].label + \"\\',\"\n\t + waypoints[2*i].lat + \",\" + waypoints[2*i].lon + \",0);\\\">\"\n\t + waypoints[2*i].label + \"</a></td><td>(\"\n\t + waypoints[2*i].lat + \",\"\n\t + waypoints[2*i].lon + \")</td></tr><tr><td>\"\n\t + \"<a onclick=\\\"javascript:LabelClick(\" + 2*i+1 + \",\\'\"\n\t + waypoints[2*i+1].label + \"\\',\"\n\t + waypoints[2*i+1].lat + \",\" + waypoints[2*i+1].lon + \",0);\\\">\"\n\t + waypoints[2*i+1].label + \"</a></td><td>(\"\n\t + waypoints[2*i+1].lat + \",\"\n\t + waypoints[2*i+1].lon + \")</td></tr>\"\n\t + \"</tbody></table></td><td>\"\n\t + miles + \" mi/\"\n\t + feet + \" ft</td></tr>\";\n }\n\n table += \"</tbody></table>\";\n genEdges = false;\n return table;\n}",
"loadPdbData(data, pdbid, bOpm, bAppend) {\n let ic = this.icn3d,\n me = ic.icn3dui\n ic.loadPDBCls.loadPDB(data, pdbid, bOpm, undefined, undefined, bAppend) // defined in the core library\n\n if (me.cfg.opmid === undefined) ic.ParserUtilsCls.transformToOpmOri(pdbid)\n\n if (ic.biomtMatrices !== undefined && ic.biomtMatrices.length > 1) {\n $('#' + ic.pre + 'assemblyWrapper').show()\n\n ic.asuCnt = ic.biomtMatrices.length\n } else {\n $('#' + ic.pre + 'assemblyWrapper').hide()\n }\n\n if (ic.emd !== undefined) {\n $('#' + ic.pre + 'mapWrapper1').hide()\n $('#' + ic.pre + 'mapWrapper2').hide()\n $('#' + ic.pre + 'mapWrapper3').hide()\n } else {\n $('#' + ic.pre + 'emmapWrapper1').hide()\n $('#' + ic.pre + 'emmapWrapper2').hide()\n $('#' + ic.pre + 'emmapWrapper3').hide()\n }\n\n // calculate secondary structures if not available\n // DSSP only works for structures with all atoms. The Calpha only strucutres didn't work\n //if(!ic.bSecondaryStructure && !bCalphaOnly) {\n\n if (!ic.bSecondaryStructure && Object.keys(ic.proteins).length > 0) {\n ic.deferredSecondary = $.Deferred(function () {\n let bCalphaOnly = me.utilsCls.isCalphaPhosOnly(me.hashUtilsCls.hash2Atoms(ic.proteins, ic.atoms)) //, 'CA');\n ic.dsspCls.applyDssp(bCalphaOnly)\n }) // end of me.deferred = $.Deferred(function() {\n\n return ic.deferredSecondary.promise()\n } else {\n this.loadPdbDataRender()\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the current highlighted tabs. updates active tab index and sets previous active to false | function updateCurrentActiveIndex() {
chrome.tabs.query({
highlighted: true
}, function (tabs) {
for (var index = 0; index < tabs.length; index++) {
var tab = tabs[index];
var allTabs = user.tabsSortedByWindow[tab.windowId];
var previousActiveIndex = user.activeTabIndex[tab.windowId];
var timeStamp = getTimeStamp();
console.log(tab)
if (previousActiveIndex !== tab.index && previousActiveIndex !== null && allTabs[previousActiveIndex]) {
if (user.loggedIn) {
deactivateTimeTab(allTabs[previousActiveIndex].databaseTabID);
}
allTabs[previousActiveIndex].highlighted = false;
allTabs[previousActiveIndex].timeOfDeactivation = timeStamp;
}
user.activeTabIndex[tab.windowId] = tab.index;
allTabs[tab.index].highlighted = true;
}
})
} | [
"function highlightTabs() {\n for (let el of document.getElementsByClassName('tab'))\n\t\tel.classList.remove('activeTab')\n\n for (let pane of Tracker.panes)\n pane.activeTab.element.classList.add('activeTab')\n}",
"updateTabHighlight() {\n let currentPath = window.location.pathname;\n // Tab url regular expressions must be listed in the same order as the tabs, since the\n // indices of the elements in the array on the next line are mapped to the indices of the tabs\n let urls = [/^\\/$/, /^\\/involvements\\/?$|^\\/activity/, /^\\/events\\/?$/, /^\\/people$/];\n this.value = false;\n for (let i = 0; i < urls.length; i++) {\n if (urls[i].test(currentPath)) {\n this.value = i;\n }\n }\n }",
"function highlightCurrentTab() {\r\n chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {\r\n const tabId = tabs[0].id;\r\n const tabRow = document.querySelector(`.tab-row[data-tabid=\"${tabId}\"]`);\r\n tabRow.style.backgroundColor = \"#8AB4F8\";\r\n tabRow.querySelector(\".url\").style.color = \"#000000\";\r\n tabRow.dataset.inFocus = \"true\";\r\n });\r\n}",
"function tabsCurrent() {\n\tcallOnActiveTab((tab, tabs) => {\n\t\texecuteTab(tab);\n\t});\n}",
"function getActiveTabs(cb) {\n chrome.tabs.query({highlighted: true}, (tabs) => {\n cb(tabs);\n });\n}",
"function selectActiveTabs() {\n document.querySelectorAll(\".tabset\").forEach(tabset => {\n tabset.querySelectorAll(\".tab-strip\").forEach(strip => {\n const cookieName = strip.dataset.cookieName;\n if (cookieName) {\n const cookieValue = readCookie(cookieName);\n if (cookieValue) {\n strip.querySelectorAll(\"a\").forEach(anchor => {\n if (anchor.dataset.cookieValue == cookieValue) {\n anchor.classList.add(\"active\");\n document.getElementById(anchor.dataset.tab).classList.add('active');\n } else {\n anchor.classList.remove(\"active\");\n document.getElementById(anchor.dataset.tab).classList.remove('active');\n }\n });\n }\n }\n });\n });\n }",
"function outerTabHighlight(clickedTab){\n let activeTab = document.getElementsByClassName(\"active-tab\")\n activeTab[0].classList.remove(\"active-tab\")\n\n let newActiveTab = document.getElementById(clickedTab)\n newActiveTab.classList.add(\"active-tab\")\n}",
"function highlight_current_tab(){\n\tvar homeElement = $('img#report');\n\tvar reportElement = $('div.report');\n\tvar findElement = $('div.find');\n\t\n\tvar atHome = homeElement.length > 0;\n\tvar atReport = reportElement.length > 0;\n\tvar atFind = findElement.length > 0;\n\t\n\tif(atHome){\n\t\t$('#menu li:nth-child(1)').css(\"background-color\", \"#eee\");\n\t\t$('#menu li:nth-child(1)').css(\"border-bottom\", \"3px solid #bbb\");\n\t} else if (atReport){\n\t\t$('#menu li:nth-child(2)').css(\"background-color\", \"#eee\");\n\t\t$('#menu li:nth-child(2)').css(\"border-bottom\", \"3px solid #bbb\");\n\t} else if (atFind){\n\t\t$('#menu li:nth-child(3)').css(\"background-color\", \"#eee\");\n\t\t$('#menu li:nth-child(3)').css(\"border-bottom\", \"3px solid #bbb\");\n\t}\n}",
"updateActiveElement() {\n let itemSelected;\n this.tabLinks.forEach((item, index) => {\n item.classList.contains('active') ? ((itemSelected = item), (this.currentItemIndex = index)) : '';\n });\n\n itemSelected ? '' : ((itemSelected = this.tabLinks.item(0)), (this.currentItemIndex = 0));\n const target = itemSelected.children[0].getAttribute('href');\n this.tabSelected = target;\n this.select(target.split('#')[1]);\n }",
"function ToggleHighlightedTab(itemNumber)\n{\n\tactiveMenuItem = itemNumber;\n}",
"function highlightTab(new_tab) {\r\n // reset previous tab display\r\n previous_tab = '#' + current_tab;\r\n $(previous_tab).css(\"background\", \"\");\r\n $(previous_tab).css(\"border-color\", \"#567973\");\r\n // highlight current tab\r\n $('#' + new_tab).css(\"background\", \"#A4B9B6\");\r\n $('#' + new_tab).css(\"border-color\", \"#A4B9B6\");\r\n current_tab = new_tab;\r\n}",
"function currentTabs(tabs) {\n var loc = tbr.localSession_;\n consoleDebugLog('Latest local tabs:\\n' + tabsToString(tabs));\n // Accept the new set of tabs\n loc.tabs = tabs;\n // Proceed with updated tabs in place.\n contFunc();\n }",
"getActiveTab(){\n return this.tabsList[this.activeTabIndex];\n }",
"function highlightTab(tab) {\r\n//\ttab.siblings().children(\"span\").removeClass(\"selected\")\r\n//\t//highlight the selected model\r\n//\ttab.children(\"span\").addClass(\"selected\")\r\n tab.siblings().find('.tab-icon').removeClass('selected')\r\n tab.find('.tab-icon').addClass('selected')\r\n}",
"function updateActiveTab(tabs) {\n\n function updateTab(tabs) {\n if (tabs[0]) {\n currentTab = tabs[0];\n var searching = browser.bookmarks.search({ url: currentTab.url });\n searching.then((bookmarks) => {\n currentBookmark = bookmarks[0];\n updateIcon();\n });\n }\n }\n\n var gettingActiveTab = browser.tabs.query({ active: true, currentWindow: true });\n gettingActiveTab.then(updateTab);\n}",
"function innerTabHighlight(clickedTab){\n let activeTab = document.getElementsByClassName(\"inner-active-tab\")\n activeTab[0].classList.remove(\"inner-active-tab\")\n\n let newActiveTab = document.getElementById(clickedTab)\n newActiveTab.classList.add(\"inner-active-tab\")\n}",
"function getCurrentTab() {\n return currentTab;\n}",
"function _getCurrentTab() {\n return _currentTab;\n }",
"activeTab(index) {\n this.tabContent.forEach((element) => {\n element.classList.remove(this.activeClass);\n });\n const direction = this.tabContent[index].dataset.anima;\n this.tabContent[index].classList.add(this.activeClass, direction);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open the cache and store static files | function updateStaticCache() {
return caches.open(cacheName)
.then( cache => { return cache.addAll(cacheFiles);});
} | [
"function cacheStatic(response, cache, absPath){\n\tif (cache[absPath]) {\t\t\t\t\t\t\t\t\t\t\t//Checks if file is cached in memory\n\t\tsendFile(response, absPath, cache[absPath]);\t\t\t\t//If it is, it sends it to the browser\n\t}else {\n\t\tfs.exists(absPath, function(exists) {\t\t\t\t\t\t//Check if file exists\n\t\t\tif (exists) {\n\t\t\t\tfs.readFile(absPath, function(err, data) {\t\t\t//Read file from disk\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tsend404(response);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcache[absPath] = data;\n\t\t\t\t\t\tsendFile(response, absPath, data);\t\t\t//Serve the file just read from the disk\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\terror404(response);\t\t\t\t\t\t\t\t\t//Send http error\n\t\t\t}\n\t\t});\n\t}\n}",
"function installStaticFiles() {\n\n\t//Open cache with cache name\n\treturn caches.open(CACHE).then(cache => {\n\t\t//Cache desirable files\n\t\tcache.addAll(installFilesDesirable);\n\n\t\t//Cache essential files\n\t\treturn cache.addAll(installFilesEssential);\n\t});\n}",
"function cacheAssets() {\n return caches.open('v1')\n .then(function(cache) {\n return cache.addAll([\n './',\n 'index.html',\n 'styles/app.css',\n 'scripts/app.js',\n 'scripts/sw.js',\n 'images'\n ]);\n });\n}",
"staticFile(filePath, relPath, stats) {\n api.fs.readFile(filePath, (err, data) => {\n if (err) {\n this.error(404);\n return;\n }\n const cache = { stats, compressed: true, data };\n this.end(cache);\n this.application.cache.static.add(relPath, cache);\n });\n }",
"async function cacheStatic() {\n const cache = await appCache;\n\n await Promise.all([...staticUrlsToCache, ...manifest.map((entry) => entry.url)].map((url) => cacheUrl(cache, url)));\n}",
"getStatic(path, ...args) {\n const ret = new FileCache(path, ...args);\n this.route('GET', path, ret.makeCallback());\n return ret;\n }",
"static loadCache() {\n try {\n if (this.cache) {\n return;\n }\n if (!fs_1.default.existsSync(config_1.default.CACHE_PATH)) {\n fs_1.default.mkdirSync(config_1.default.CACHE_PATH);\n }\n if (!fs_1.default.existsSync(CACHE_FILE_PATH)) {\n this.cache = {};\n return;\n }\n this.cache = JSON.parse(fs_1.default.readFileSync(CACHE_FILE_PATH).toString());\n }\n catch (_) {\n this.cache = {};\n }\n }",
"serveStatic(request, response) {\n const fileName = request.pathname.replace('/static/', '');\n const filePath = path.join(STATIC_DIR, fileName);\n const fileMimeType = MIME_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream';\n\n const data = this.application.cache.get(fileName);\n if (data) {\n response.writeHead(200, { 'Content-Type': fileMimeType });\n response.end(data);\n } else {\n this.error(response, 404);\n }\n }",
"function serveStatic(res, cache, absPath) {\n if (cache[absPath]) {\n sendFile(res, absPath, cache[absPath]); // serve cached file\n } else {\n setFileToCache(res, cache, absPath);\n }\n}",
"staticCache(relPath, onNotServed) {\n const cache = this.application.cache.static.get(relPath);\n const isNum = typeof cache === 'number';\n const cached = cache && !isNum;\n if (cached) this.buffer(cache);\n else if (isNum) onNotServed();\n return cached;\n }",
"async function precache() {\n const cache = await caches.open(staticAssets);\n\n log('precache:Installing: adding the static assets into the cache')\n await cache.addAll(staticAssetsToCache)\n log('precache: added static assets to cache');\n}",
"handle() {\n let url = this.urlFromRequest();\n caches.open(staticCacheName).then(cache => {\n cache.match(url.pathname).then(cached => Promise.resolve(cached));\n });\n this.event.respondWith(getStaticAsset(url.pathname));\n return true;\n }",
"getFromCache(fileCache,file,res){\n\n // Reviso si el archivo existe dentro de la cache.\n if (fs.existsSync(fileCache)){\n\n console.log('CACHE '+fileCache);\n\n // Devuelvo el archivo del directorio cache.\n res.sendFile(file, { root : path.dirname(__dirname)+config.cache.downloads});\n\n }\n else{\n res.status(404).send('File not found in cache');\n console.log('CACHE 404'+fileCache);\n }\n\n }",
"async open({path}) { return { fh: Cache.storeObject(toUtf8Array(await getData(path))) }; }",
"function loadStaticBeersCache() {\n var beersCache = $http.get('static-beers.json')\n .then(function(response) {\n $localStorage.setObject('beersCache',response.data);\n });\n }",
"cacheFile() {\n let file = nova.path.join(nova.extension.globalStoragePath, 'php', '.php_cs.cache');\n\n try {\n nova.fs.open(file, 'x');\n } catch (error) {\n log('Using existing cache file');\n }\n\n file = file.replace(/([ \"#&%'$`\\\\])/g, '\\\\$1');\n log(`Cache file path is ${file}`);\n\n return file;\n }",
"function precache() {\n return caches.open(CACHE).then(function (cache) {\n return cache.addAll(filesToCache);\n });\n}",
"load() {\n try {\n this._data = require(`../${CACHE_DIRECTORY}/${this._name}.json`);\n } catch (e) {\n this._debug(`${this._name} cache created anew`);\n }\n }",
"function initCache() {\n try {\n fs.mkdirSync(CACHE_PATH);\n } catch (e) {\n if (e.code !== 'EEXIST') throw e;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the next set of results, or resolves to null if no results are available | getNext() {
if (this.hasNext) {
const items = new Items(this.nextUrl, null).configureFrom(this.parent);
return items.getPaged(this.innerParser);
}
return new Promise(r => r(null));
} | [
"get next() {\n if (this.last !== null) {\n try {\n let { data } = this.last;\n let { offset, limit, total, count } = data;\n if (offset + count < total) {\n this.params.offset = offset + limit;\n return this;\n }\n } catch (e) {\n return null;\n }\n }\n return null;\n }",
"getNext() {\n const idx = Math.min(this.entries.length, this.cursor + 1);\n this.cursor = idx;\n return this.entries[idx];\n }",
"function getNextSearchResultsPage(smartApi, response, results) {\n var requestId = response.headers('x-request-id');\n var responseData = response.data.entry || [];\n results = results.concat(responseData.map(function (result) { return new _fhir_resources_sets_fhir_resource_set__WEBPACK_IMPORTED_MODULE_7__[\"RawResource\"](result.resource, requestId); }));\n // if there are anymore pages, get the next set of results.\n if (response.data.link.some(function (linkItem) { return linkItem.relation === 'next'; })) {\n return smartApi.patient.api.nextPage({ bundle: response.data })\n .then(function (nextResponse) {\n return getNextSearchResultsPage(smartApi, nextResponse, results);\n }, function (rejection) {\n throw rejection;\n });\n }\n return Promise.resolve(results);\n}",
"async load_next() {\n\t\tif(this.#queue.length === 0) return null;\n\n\t\treturn this.#load(this.#queue.shift());\n\t}",
"next() {\n if (this._iter < this._items.length) {\n return this._items[this._iter++];\n }\n return null;\n }",
"function next() {\n const elem = iterator.next();\n index++;\n\n // If we get this far, no promises ever resolved\n if (elem.done) {\n reject();\n return;\n }\n\n /**\n * Promise iterator function.\n * @callback IteratorFunction\n * @param value - Current value in iteration.\n * @param {Integer} index - Current index in iteration.\n * @param iterable - Complete series being iterated through.\n * @returns {Promise} Promise containing some value.\n */\n fn(elem.value, index, iterable)\n .then(v => {\n resolve({\n index: index,\n value: v\n });\n })\n .catch(next);\n }",
"getNext(){\n if (\n this.loadingNext ||\n this.refreshing ||\n !this.fetchServices.hasNextPage \n )\n return;\n this.beforeNext();\n this.fetchServices\n .fetch()\n .then((res) => {\n this.onNext(res);\n })\n .catch((error) => {\n this.onNextError(error);\n });\n }",
"getNext(){\n if (\n this.loadingNext ||\n this.refreshing ||\n !this.modelFetch.hasNextPage \n )\n return;\n this.beforeNext();\n this.modelFetch\n .fetch()\n .then((res) => {\n this.onNext(res);\n })\n .catch((error) => {\n this.onNextError(error);\n });\n }",
"getNextRequest() {\n const nextIndex = this.requestIndex;\n const nextRequest = this.requests[nextIndex];\n\n if(nextRequest) {\n this.requestIndex = nextIndex + 1;\n\n return nextRequest;\n }\n\n return null;\n }",
"fetchNext(options={}, context=undefined) {\n if (!this.hasNext && options.enforceHasNext !== false) {\n return false;\n }\n\n this._fetchURL = this._links.next.href;\n\n return this.fetch(\n _.defaults({\n page: this.currentPage + 1\n }, options),\n context);\n }",
"next() {\n // return previous word object\n if (this.CURRENT_WORD.next) {\n this.CURRENT_WORD = this.CURRENT_WORD.next;\n this.index++;\n\n // load more if reach the threshold\n if ((this.index / this.total) >= this.GROWTH_FACTOR) this.loadMore();\n }\n this.record();\n\n return Promise.resolve(this.CURRENT_WORD);\n }",
"getNext() {\n return this.next || null;\n }",
"getNext(){\n\n // If the list has questions\n if(this.questions.length > 0){\n this.current++;\n\n // If at the end, restart at question 0\n if(this.current >= this.questions.length){\n this.current = 0;\n }\n\n // Return the next question\n return this.questions[this.current];\n }\n // If no questions, return the default question\n else{\n return this.defaultQuestion;\n }\n }",
"function next() {\n\t\tif (!data) {\n\t\t\tloadFile();\n\t\t}\n\t\tcounter++;\n\t\treturn data[counter-1];\n\t}",
"next() {\n let base = null\n while(true) {\n base = iterator.next()\n if (base.done) {\n return base\n }\n\n const value = this[xfKey](base.value)\n if (this[predicateKey](value)) {\n return {\n ...base,\n value\n }\n }\n }\n }",
"next() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.currentPage == null) {\n this.currentPage = yield new TransactionPage_1.TransactionPage().init(this.book, this.query, this.lastCursor);\n }\n if (this.currentPage.hasNext()) {\n return this.currentPage.next();\n }\n else if (!this.currentPage.hasReachEnd()) {\n this.lastCursor = this.currentPage.getCursor();\n if (this.nextPage != null) {\n this.currentPage = this.nextPage;\n this.nextPage = null;\n }\n else {\n this.currentPage = yield new TransactionPage_1.TransactionPage().init(this.book, this.query, this.lastCursor);\n }\n return this.currentPage.next();\n }\n else {\n return null;\n }\n });\n }",
"function next() {\n // Get the items only when the current position is less than items length.\n if (cursor < list.length) {\n // Get the item by cursor position.\n var item = list[cursor];\n\n // Increase the position.\n cursor += 1;\n\n // Call the iteration handler.\n handler.call(self, item.key, item.value, next, stop);\n } else {\n // Mark the iterator as complete.\n self.status = 'complete';\n\n // Call the resolver if defined.\n if ('function' === typeof self.resolve) {\n self.resolve(self);\n }\n }\n }",
"function next(returnedIterator){\n if(returnedIterator.done) return;\n\n returnedIterator.value.then(onResolve, onReject);\n }",
"async getNext() {\n /**\n * This is only for the example.\n */\n this.count++;\n /**\n * We will inject 100 records in the step chain.\n */\n if (this.count <= 100) {\n /**\n * It has to return a BatchRecord composed by an recordId and a payload.\n * Basically you will use your own record id to keep track of the record until all execution.\n * The payload is whatever you want.\n */\n return new BatchRecord(this.count, String(this.count));\n }\n /**\n * When there is no more records you will return null to let batch-engine null,\n * that this is the end.\n */\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if consonant ends in "qu" | function quCheck(string, i){
if (string.substr(i - 1, 2) === "qu") {
return true;
} else {
return false;
}
} | [
"function containsQu(solutions, ending) {\n\n let regEx = /(qu{1})|(Qu{1})/;\n\n solutions.forEach(word => {\n word = word.toLowerCase();\n\n let test = regEx.test(word);\n if (test == true) {\n return ending = true;\n }\n });\n return ending;\n\n\n}",
"function isConsonant(char){\r\n return !/[aeiou]/.test(char)\r\n }",
"function isConsonant(char) {\n return !/[aeiou]/.test(char);\n}",
"function isConsonant(char) {\n return !/[aeiou]/.test(char);\n }",
"function isConsonant(char) {\n return !/[aeiou]/.test(char);\n }",
"function isConsonant(letter) {\n\n}",
"function isConsonant(word) {\n if (word.length <= 0) {\n return true;\n }\n if (vowels.indexOf(word[0]) === -1) {\n // returns sliced off char before 1st index\n return isVowel(word.slice(1));\n } else {\n return false;\n }\n }",
"function isConsonant(letter){\n if (letter !== \"a\" && letter !== \"e\" && letter !== \"i\" && letter !== \"o\" && letter !== \"u\")\n return true;\n else\n return false;\n}",
"function endsWithQ(solutions, ending) {\n\n solutions.forEach(word => {\n word = word.toLowerCase();\n\n if (word.substr(-1) == \"q\" || word.substr(-1) == \"Q\") {\n return ending = true;\n }\n });\n return ending;\n\n\n}",
"function isConsonant(char) {\n return !/[aeiouyåäöÅÄÖ]/.test(char.toLowerCase())\n}",
"function isConsonant(letter) {\n return (!(/[aeiouAEIOU]/).test(letter));\n }",
"function solution(str, ending) {\n return ending === \"\" ? true : str.slice(-ending.length) === ending;\n}",
"function isConsonant(letter){\n return ['a', 'e', 'i', 'o', 'u'].indexOf(letter.toLowerCase()) !== 0\n}",
"function solution(str, ending){\n // TODO: complete\n if(str.slice(str.length - ending.length, str.length) === ending){\n console.log(true);\n return true;\n } else {\n console.log(false);\n return false;\n }\n}",
"function confirmEnding (str, target) {\n var strEndsWith = str.slice(str.length - target.length, str.length)\n return (strEndsWith === target)\n}",
"function endsWithDoublCons(token) {\n return token.match(/([^aeiou])\\1$/);\n}",
"function confirmEnding(str, target) {\n const targetLength = target.length;\n const startIndex = str.length - targetLength;\n return str.substring(startIndex) === target;\n}",
"function hasConsonantEnding(id) {\n if (_.includes([5,6,7,8,12], id)) {\n return false;\n }\n else {\n return true;\n }\n }",
"function endsWithDoublCons (token) {\n return token.match(/([^aeiou])\\1$/)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if the /complete/trends/apple route in the API has a response length of more than 5 | test_complete_trends_apple() {
axios.get("https://protected-ravine-04165.herokuapp.com/complete/trends/apple")
.then((response) => {
if(response.data.length > 5) {
console.log("TEST: API /complete/trends/apple returns data - PASSED");
} else {
console.log("TEST: API /complete/trends/apple returns data - FAILED");
}
}).catch(() => {
console.log("TEST: API /complete/trends/apple returns data - FAILED");
});
} | [
"test_trends_apple() {\n axios.get(\"https://protected-ravine-04165.herokuapp.com/trends/apple\")\n .then((response) => {\n if(response.data.length > 5) {\n console.log(\"TEST: API /trends/apple returns data - PASSED\");\n } else {\n console.log(\"TEST: API /trends/apple returns data - FAILED\");\n }\n \n }).catch(() => {\n console.log(\"TEST: API /trends/apple returns data - FAILED\");\n });\n }",
"function CheckDataLength(receivedData) {\n let length = receivedData.length;\n if (length < 250) {\n alert(`Sorry, we can get only Top${length} artists for ${Genre()} genre this time`);\n }\n }",
"test_sentimet_blank() {\n axios.get(\"https://protected-ravine-04165.herokuapp.com/sentiment/apple\")\n .then((response) => {\n if(response.data.length > 5) {\n console.log(\"TEST: API /sentiment/apple returns data - FAILED\");\n } else {\n console.log(\"TEST: API /sentiment/apple returns data - PASSED\");\n }\n \n }).catch(() => {\n console.log(\"TEST: API /sentiment/apple returns data - PASSED\");\n });\n }",
"function checkLimit() {\n if (FormApp.getActiveForm().getResponses().length >= RESPONSE_COUNT ) {\n closeForm();\n } \n}",
"checkReviewTooLong(review) {\n if(review.length > 250) {\n return true;\n } else {\n return false;\n }\n }",
"function isApiMapExhausted(apiMapForFactor,inputSize) {\n var object = Object.keys(apiMapForFactor).filter(\n function(element){\n return (apiMapForFactor[element].totalCount - inputSize >= 0);\n }\n );\n return (object.length == 0);\n}",
"function less(){\n if(todoDocs.data.length <= 100) return docs.data.length;\n else return 100;\n}",
"function testSearchResponseLimit(endpoint, term, limit) {\n\t\tmediawikiSearch.search(endpoint, term, limit).done(function(data, status, xhr) {\n\t\t\tconsole.log(data.query);\n\t\t\tok(data.query.search.length <= limit, 'Response length for term ' + term + ' under or equal to ' + limit +'.');\n\t\t}).always(countDown);\n\t}",
"function allPartsReceived(data) {\n if(typeof multiBulkCount != 'undefined') {\n var size = data.split(CRLF + '$').length - 1;\n debug('> The current response size is (' + size + ')');\n\n if(size < multiBulkCount) {\n debug('> We havent received all of the parts yet!');\n return false;\n }\n }\n\n return true;\n}",
"function isLongEnough( url )\r\n{\r\n\treturn url.length > ( config.BASE_URL.length + config.CODE_LENGTH);\r\n}",
"function hasMaxTripCount (trips) {\n // TODO: Obtain the maximum number from a query to middleware (it is currently hard coded there too).\n return trips && trips.length >= 5\n}",
"function resultsReady() {\n /*console.log(\"resultsReady \", surveyStorage.allAnswers.length, (\n surveyStorage.allAnswers.length >= MIN_RES));*/\n return (surveyStorage.allAnswers.length < MIN_RES);\n }",
"function hasMaxTripCount(trips) {\n // TODO: Obtain the maximum number from a query to middleware (it is currently hard coded there too).\n return trips && trips.length >= 5;\n}",
"isConveyerBeltFull() {\n const { items } = this.state;\n return items.length >= 10;\n }",
"function moreTweets(response) {\n var json = JSON.parse(response);\n console.log(\"pulled tweets: \" + json.length);\n if(json.length == 0) {\n finished = true;\n loadingTweets = false;\n console.log(\"FINISHED!\");\n } else {\n for (var x = 0; x < json.length; x++) {\n queue.push(json[x]);\n }\n max_id = bigInt(json[json.length - 1].id_str);\n loadingTweets = false;\n }\n}",
"function validTrip (req, res, next){\n //if (!req.body.guide_id || !req.body.title || !req.body.description || req.body.professional === null || !req.body.type_id || !req.body.duration || !req.body.date){\n if(Object.values(req.body).length < 7){\n res.status(404).json({message: 'Trip is missing some data'});\n } else {\n next();\n }\n \n}",
"function favLessThanLimit() {\n var currentFavouriteKeys = Object.keys(favouritesCollection)\n return currentFavouriteKeys.length < 5\n}",
"async limitReached(id) {\n const timestamps = await this.getTimestamps(id, true);\n const numTimestamps = timestamps.length;\n\n return numTimestamps > this.maxRequests;\n }",
"checkResponse(res) {\n // Variables\n const regexFail = /2\\d+/;\n // Check Response Formed Well\n if (res) {\n // Get Data\n const transportCode = res.status.transport.code;\n const commandCode = res.status.command.code;\n // Check Response Body\n if (regexFail.test(transportCode)) {\n return 2;\n } else if (regexFail.test(commandCode)) {\n return 1;\n } else {\n return 0;\n }\n } else {\n return 3;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dispatching 'remove Sound' in order to remove the selected sound from the array receiving the object of the selected sound to be remove | removeSound({commit}, data){
commit('removeActiveSound', data)
} | [
"removeSound() {\n this._soundAssetUUID = null;\n }",
"function del_sound(id) {\n console.log(\"Deleting sound by index:\" + id);\n var arr = geo_audio_samples.splice(id, 1);\n update_geo();\n return arr[0];\n}",
"function removeOne(event) {\n\tvar instance = getCurrentSound();\n\tif (instance == null) { return; }\n\tinstance.stop();\n\t// console.log(\"Want to remove: \" + instance.name);\n\tremoveSound(instance);\n}",
"deleteCb(message) {\n console.log(\"CALLING FROM CONTAINER MESSAGE: \", message)\n this.audioStack.delete(message)\n this.state.audioRecords.forEach((ar, idx) => {\n if(ar.fileURL === message) {\n let tempArr = this.state.audioRecords\n tempArr.splice(idx, 1)\n this.setState({\n audioRecords: tempArr\n })\n }\n })\n }",
"function removeFromDatabase(index) {\n\tvar removed = positionArray.splice(index, 1); //removes sound once it's played\n\tconsole.log(removed[0]);\n\tremoved = sndArray.splice(index, 1);\n\tconsole.log(removed[0]);\n\t\n}",
"function removeTrack(mouseEvent) {\n\t//Check id of the track which as been delete and pass it to int\n\tvar idtrack = mouseEvent.target.parentElement.parentElement.id;\n\tidtrack = idtrack.substring(10);\n\tidtrack = parseInt(idtrack, 10);\n\n\t//Search element in array of track\n\tvar i = 0;\n\tvar found = (idtrack == trackArray[i].getTrackId());\n\tvar index;\n\twhile (!found && i < trackArray.length) {\n\t\ti = i + 1\n\t\tfound = (idtrack == trackArray[i].getTrackId())\n\t}\n\tif (found) {\n\t\tindex = i;\n\t} else {\n\t\talert(\"changeSound : Element not found\");\n\t\treturn;\n\t}\n\n\t//Add color and number in our array of remainColor and remainTrack\n\tidRemaining.push(trackArray[i].getTrackId());\n\tcolorRemaining.push(trackArray[i].getTrackColor())\n\n\t//Delete track for our array of track\n\ttrackArray.splice(index, 1);\n\n\t//Remove the track of the interface\n\tmouseEvent.target.parentElement.parentElement.remove();\n\tnbTrack--;\n\tif (nbTrack==0)\n\t\tplaying=0;\n}",
"function removeAll(event) {\n\tcreatejs.Sound.stop();\n\tremoveAllSound();\n}",
"alarmDelete(e) {\n const selectHTML = $('#alarm-sound');\n const ID = selectHTML[0].value;\n const { alarmChanged } = this.props;\n\n // Default (Preloaded) alarm sounds shall not be deleted\n if (ID < 3) {\n window.alert('Please do not delete default alarm sounds!');\n return;\n }\n\n // Change the selected alarm sound to the first one, preloaded alarm sound\n alarmChanged(0);\n selectHTML[0].value = \"0\";\n\n // Remove the targeted Option HTML from Select HTML element\n selectHTML.children(`[value='${ID}']`)[0].remove();\n\n // Remove the targeted alarm sound from Local Storage\n window.localStorage.removeItem(ID);\n \n }",
"removeHandler(event) {\n const del = event.target.dataset.val;\n //console.log(\"items \" + this.recordData);\n let sel_rec = this.recordData;\n let records = this.selectedRecords;\n records.splice(del, 1);\n sel_rec.splice(del, 1);\n this.selectedRecords = records;\n this.recordData = sel_rec;\n this.countItem = this.countItem - 1\n if(this.countItem <= MAXLIMIT)\n this.hitLimit = false;\n //console.log(\"deleted item \");\n if (this.recordData.length === 0) {\n this.recordVisibility = false;\n this.btn_clear = false;\n }\n const removeEvent = new CustomEvent('remove',{detail:this.selectedRecords});\n this.dispatchEvent(removeEvent);\n \n }",
"removeSong(selectedSong){\r\n this.userSetlist.pop(selectedSong);\r\n }",
"clear() {\n this.sounds = [];\n }",
"deleteWaveEvent() {\n const waveEventId = this.clickedWaveEvent_.id;\n this.closeWaveEventMenu();\n Dispatcher.getInstance().sendAction({\n actionType: Dispatcher.ActionType.DELETE_WAVE_EVENT,\n data: {\n id: waveEventId,\n },\n });\n }",
"removeSoundSensor(){\n this.logger.recordEvent(this.logger.createEvent(EVENT_NAMES.removeRobotComponent, TypesEnum.SOUND));\n\n let id = this._numberOfComponentsOfType[TypesEnum.SOUND];\n this.removeRobotComponentWithTypeAndId(TypesEnum.SOUND, id);\n }",
"unloadSound(label) {\n for (var i = 0; i < this.sound_count; i++) {\n if (this.sound[i].getLabel() == label) {\n utility.arrayRemove(this.sound,this.sound[i]);\n this.sound_count--;\n return 0;\n }\n }\n return -1;\n }",
"function removeSong() {\n}",
"function deleteSong(a){\n songs.splice(a, 1);\n displaySongs();\n }",
"RemovePlaying(name) {\n if(this.IsPlaying(name)) {\n for(let i = 0; i < this.playingSounds.length; ++i) {\n if(this.playingSounds[i].name == name) {\n this.playingSounds.splice(i, 1);\n return;\n }\n }\n }\n }",
"function playAndRemoveFire(){\n const sound = fireSounds.shift();\n sound.volume = 0.1;\n sound.play();\n}",
"_onClickRemoveButton () {\n if (!(this.props.music)) { return }\n\n if (this.props.playbackState !== PlaybackState.Stopped) {\n if (this.props.playMusic && this.props.playMusic.id === this.props.music.id) { return }\n }\n\n this.props.musicListAction.remove(this.props.music)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DescriptionParametrically drive a user parameter /! Copyright (C) 2015 Hans Kellner: MIT License: See / This is a script for Autodesk Fusion 360 that parametrically drives a user parameter. Installation: Copy this scripts folder into your Fusion 360 "My Scripts" folder. You may find this folder using the following steps: 1) Start Fusion 360 and then select the File > Scripts... menu item 2) The Scripts Manager dialog will appear and display the "My Scripts" folder and "Sample Scripts" folders 3) Select one of the "My Scripts" files and then click on the "+" Details icon near the bottom of the dialog. a) If there are no files in the "My Scripts" folder then create a default one. b) Click the Create button, select JavaScript, and then OK. 5) With the user script selected, click the Full Path "..." button to display a file explorer window that will display the "My Scripts" folder 6) Copy the files into the folder For example, on a Mac the folder is located in: /Users/USERNAME/Library/Application Support/Autodesk/Autodesk Fusion 360/API/Scripts /globals adsk | function run(context) {
"use strict";
if (adsk.debug === true) {
/*jslint debug: true*/
debugger;
/*jslint debug: false*/
}
var PARAM_OPERATION = {
LOOP_ONLY: 0,
//CLONE_SELECTION: 1,
EXPORT_FUSION: 1,
EXPORT_IGES: 2,
EXPORT_SAT: 3,
EXPORT_SMT: 4,
EXPORT_STEP: 5,
EXPORT_STL: 6,
LAST: 6
};
var appTitle = 'ParaParam';
var app = adsk.core.Application.get(), ui;
if (app) {
ui = app.userInterface;
if (!ui) {
adsk.terminate();
return;
}
}
var design = adsk.fusion.Design(app.activeProduct);
if (!design) {
ui.messageBox('No active design', appTitle);
adsk.terminate();
return;
}
// Get the current user parameters
var paramsList = design.userParameters;
// Create the command definition.
var createCommandDefinition = function() {
var commandDefinitions = ui.commandDefinitions;
// Be fault tolerant in case the command is already added...
var cmDef = commandDefinitions.itemById('ParaParam');
if (!cmDef) {
cmDef = commandDefinitions.addButtonDefinition('ParaParam',
'ParaParam',
'Parametrically drives a user parameter.',
'./resources'); // relative resource file path is specified
}
return cmDef;
};
// CommandCreated event handler.
var onCommandCreated = function(args) {
try {
// Connect to the CommandExecuted event.
var command = args.command;
command.execute.add(onCommandExecuted);
// Terminate the script when the command is destroyed
command.destroy.add(function () { adsk.terminate(); });
// Define the inputs.
var inputs = command.commandInputs;
var paramInput = inputs.addDropDownCommandInput('param', 'Which Parameter', adsk.core.DropDownStyles.TextListDropDownStyle );
// Get the parameter names
for (var iParam = 0; iParam < paramsList.count; ++iParam) {
paramInput.listItems.add(paramsList.item(iParam).name,(iParam === 0));
}
var valueStart = adsk.core.ValueInput.createByReal(1.0);
inputs.addValueInput('valueStart', 'Start Value', 'cm' , valueStart);
var valueEnd = adsk.core.ValueInput.createByReal(10.0);
inputs.addValueInput('valueEnd', 'End Value', 'cm' , valueEnd);
var valueInc = adsk.core.ValueInput.createByReal(1.0);
inputs.addValueInput('valueInc', 'Increment Value', 'cm' , valueInc);
var operInput = inputs.addDropDownCommandInput('operation', 'Operation', adsk.core.DropDownStyles.TextListDropDownStyle );
operInput.listItems.add('Value Only',true);
//operInput.listItems.add('Clone Selected Bodies',false);
operInput.listItems.add('Export to Fusion',false);
operInput.listItems.add('Export to IGES',false);
operInput.listItems.add('Export to SAT',false);
operInput.listItems.add('Export to SMT',false);
operInput.listItems.add('Export to STEP',false);
operInput.listItems.add('Export to STL',false);
//SelectionCommandInput
//var selInput = inputs.addSelectionInput('selection','Selection','Select bodies for operation or none');
//selInput.addSelectionFilter( 'Bodies' ); // and Faces and/or sketch elements?
//BoolValueCommandInput
inputs.addBoolValueInput('pause', 'Pause each iteration', true);
}
catch (e) {
ui.messageBox('Failed to create command : ' + (e.description ? e.description : e));
}
};
// CommandExecuted event handler.
var onCommandExecuted = function(args) {
try {
// Extract input values
var unitsMgr = app.activeProduct.unitsManager;
var command = adsk.core.Command(args.firingEvent.sender);
var inputs = command.commandInputs;
var paramInput, valueStartInput, valueEndInput, valueIncInput, operationInput, selInput, pauseInput;
// REVIEW: Problem with a problem - the inputs are empty at this point. We
// need access to the inputs within a command during the execute.
for (var n = 0; n < inputs.count; n++) {
var input = inputs.item(n);
if (input.id === 'param') {
paramInput = adsk.core.DropDownCommandInput(input);
}
else if (input.id === 'valueStart') {
valueStartInput = adsk.core.ValueCommandInput(input);
}
else if (input.id === 'valueEnd') {
valueEndInput = adsk.core.ValueCommandInput(input);
}
else if (input.id === 'valueInc') {
valueIncInput = adsk.core.ValueCommandInput(input);
}
else if (input.id === 'operation') {
operationInput = adsk.core.DropDownCommandInput(input);
}
else if (input.id === 'selection') {
selInput = adsk.core.SelectionCommandInput(input);
}
else if (input.id === 'pause') {
pauseInput = adsk.core.BoolValueCommandInput(input);
}
}
if (!paramInput || !valueStartInput || !valueEndInput || !valueIncInput || !operationInput || !pauseInput) { // || !selInput) {
ui.messageBox("One of the inputs does not exist.");
return;
}
// holds the parameters that drive the parameter. How meta!
var params = {
paramName: "",
valueStart: 0.0,
valueEnd: 1.0,
valueInc: 0.1,
operation: PARAM_OPERATION.LOOP_ONLY,
pause: false,
exportFilename: ""
};
var iParam = paramInput.selectedItem.index;
if (iParam < 0) {
ui.messageBox("No parameter name selected");
return false;
}
params.paramName = paramsList.item(iParam).name;
params.valueStart = unitsMgr.evaluateExpression(valueStartInput.expression);
params.valueEnd = unitsMgr.evaluateExpression(valueEndInput.expression);
params.valueInc = unitsMgr.evaluateExpression(valueIncInput.expression);
params.operation = operationInput.selectedItem.index;
if (params.operation < 0 || params.operation > PARAM_OPERATION.LAST) {
ui.messageBox("Invalid operation");
return false;
}
var isExporting = (params.operation >= PARAM_OPERATION.EXPORT_FUSION && params.operation <= PARAM_OPERATION.EXPORT_STL);
params.pause = pauseInput.value;
// If operation is an export then prompt for folder location.
if (isExporting) {
// Prompt for the base filename to use for the exports. This will
// be appended with a counter or step value.
var dlg = ui.createFileDialog();
dlg.title = 'Select Export Filename';
dlg.filter = 'All Files (*.*)';
if (dlg.showSave() !== adsk.core.DialogResults.DialogOK) {
return false;
}
// Strip extension
var filename = dlg.filename;
var extIdx = filename.lastIndexOf('.');
if (extIdx >= 0) {
filename = filename.substring(0, extIdx);
}
if (filename === '') {
ui.messageBox('Invalid export filename');
return false;
}
params.exportFilename = filename;
}
// Validate loop params
if (params.valueInc <= 0) {
ui.messageBox("Value increment must be positive and none zero");
return false;
}
if (params.valueStart > params.valueEnd) {
params.valueInc = -params.valueInc;
}
else if (params.valueStart == params.valueEnd) {
ui.messageBox("Start value must not equal end value");
return false;
}
// Get the actual parameter to modify
var param = paramsList.itemByName(params.paramName);
if (!param) {
return false;
}
var exportMgr = design.exportManager; // used if exporting
var resExport = 0;
// Loop from valueStart to valueEnd incrementing by valueInc
for (var iStep = params.valueStart;
(params.valueInc > 0) ? iStep <= params.valueEnd : iStep >= params.valueEnd;
iStep += params.valueInc) {
// note - setting the 'value' property does not change the value. Must set expression
param.expression = '' + iStep; // + ' cm';
// If exporting then we need to build the name for this iteration
var exportFilenamePrefix = params.exportFilename;
if (isExporting) {
exportFilenamePrefix += '_'+params.paramName+'_'+iStep;
}
// Now do the post increment operation
switch (params.operation)
{
case PARAM_OPERATION.LOOP_ONLY:
// Nothing
break;
case PARAM_OPERATION.CLONE_SELECTION:
// Need to clone selected bodies
var selCount = selInput.selectionCount;
if (selCount > 0) {
for (var iSel = 0; iSel < selCount; ++iSel) {
var selItem = selInput.selection(iSel);
//if (selItem.objectType === 'BRepBody')
if (selItem.copy()) {
// ARGH - No support for paste in the API
}
}
}
break;
case PARAM_OPERATION.EXPORT_FUSION:
var fusionArchiveOptions = exportMgr.createFusionArchiveExportOptions(exportFilenamePrefix+'.f3d');
resExport = exportMgr.execute(fusionArchiveOptions);
break;
case PARAM_OPERATION.EXPORT_IGES:
var igesOptions = exportMgr.createIGESExportOptions(exportFilenamePrefix+'.igs');
resExport = exportMgr.execute(igesOptions);
break;
case PARAM_OPERATION.EXPORT_SAT:
var satOptions = exportMgr.createSATExportOptions(exportFilenamePrefix+'.sat');
resExport = exportMgr.execute(satOptions);
break;
case PARAM_OPERATION.EXPORT_SMT:
var smtOptions = exportMgr.createSMTExportOptions(exportFilenamePrefix+'.smt');
resExport = exportMgr.execute(smtOptions);
break;
case PARAM_OPERATION.EXPORT_STEP:
var stepOptions = exportMgr.createSTEPExportOptions(exportFilenamePrefix+'.step');
resExport = exportMgr.execute(stepOptions);
break;
case PARAM_OPERATION.EXPORT_STL:
var stlOptions = exportMgr.createSTLExportOptions(design.rootComponent, exportFilenamePrefix+'.stl');
stlOptions.isBinaryFormat = true;
stlOptions.meshRefinement = adsk.fusion.MeshRefinementSettings.MeshRefinementHigh;
resExport = exportMgr.execute(stlOptions);
break;
}
// Pause each iteration?
if (params.pause) {
//DialogResults
var dlgres = ui.messageBox('Pausing iteration at ' + iStep, 'Iteration Paused', adsk.core.MessageBoxButtonTypes.OKCancelButtonType);
if (dlgres !== 0) {
break; // Cancel iteration.
}
}
}
}
catch (e) {
ui.messageBox('Failed to execute command : ' + (e.description ? e.description : e));
}
};
// Create and run command
try {
var command = createCommandDefinition();
var commandCreatedEvent = command.commandCreated;
commandCreatedEvent.add(onCommandCreated);
command.execute();
}
catch (e) {
ui.messageBox('Script Failed : ' + (e.description ? e.description : e));
adsk.terminate();
}
} | [
"function run(context) {\n\n \"use strict\";\n\n if (adsk.debug === true) {\n /*jslint debug: true*/\n debugger;\n /*jslint debug: false*/\n }\n\n var PARAM_OPERATION = {\n LOOP_ONLY: 0,\n EXPORT_FUSION: 1,\n EXPORT_IGES: 2,\n EXPORT_SAT: 3,\n EXPORT_SMT: 4,\n EXPORT_STEP: 5,\n EXPORT_STL: 6,\n LAST: 6\n };\n\n var appTitle = 'ParaParam';\n\n var app = adsk.core.Application.get(), ui;\n if (app) {\n ui = app.userInterface;\n if (!ui) {\n adsk.terminate();\n return;\n }\n }\n\n var design = adsk.fusion.Design(app.activeProduct);\n if (!design) {\n ui.messageBox('No active design', appTitle);\n adsk.terminate();\n return;\n }\n\n var progressDialog = null;\n\n // What to do after each update (export, etc)\n var paramOperation = null;\n\n // This is the parameter info to update. The format is:\n // ParamName, StartValue, EndValue, StepValue\n var paramsInfo = [];\n\n // Get the current user parameters\n var userParamsList = design.userParameters;\n\n var paramGroupInput = null; // Group input control in dialog\n\n // Create the command definition.\n var createCommandDefinition = function() {\n var commandDefinitions = ui.commandDefinitions;\n\n // Be fault tolerant in case the command is already added...\n var cmDef = commandDefinitions.itemById('ParaParam');\n if (!cmDef) {\n cmDef = commandDefinitions.addButtonDefinition('ParaParam',\n 'ParaParam',\n 'Parametrically drives user parameters.',\n './resources'); // relative resource file path is specified\n }\n return cmDef;\n };\n\n // CommandCreated event handler.\n var onCommandCreated = function(args) {\n try {\n var command = args.command;\n\n // Connect to the events.\n command.execute.add(onCommandExecuted);\n command.inputChanged.add(onInputChangedHandler);\n\n // Terminate the script when the command is destroyed\n command.destroy.add(function () { adsk.terminate(); });\n\n // Define the inputs.\n var inputs = command.commandInputs;\n\n var paramInput = inputs.addDropDownCommandInput('param', 'Which Parameter', adsk.core.DropDownStyles.TextListDropDownStyle );\n\n // The first item indicates a CSV file for param info should be selected and used\n paramInput.listItems.add(\"Use Param CSV File\", true);\n\n // Add the user parameter names\n for (var iParam = 0; iParam < userParamsList.count; ++iParam) {\n paramInput.listItems.add(userParamsList.item(iParam).name, false);\n }\n\n // Create group to hold single param inputs (non CSV)\n var groupInput = inputs.addGroupCommandInput(\"groupinput\", \"Single Parameter\");\n groupInput.isExpanded = true;\n groupInput.isEnabled = true;\n\n paramGroupInput = groupInput; // HACK: Save off so changed handler can ref\n\n var valueStart = adsk.core.ValueInput.createByReal(1.0);\n groupInput.children.addValueInput('valueStart', 'Start Value', 'cm' , valueStart);\n\n var valueEnd = adsk.core.ValueInput.createByReal(10.0);\n groupInput.children.addValueInput('valueEnd', 'End Value', 'cm' , valueEnd);\n\n var valueStep = adsk.core.ValueInput.createByReal(1.0);\n groupInput.children.addValueInput('valueStep', 'Increment Value', 'cm' , valueStep);\n\n // Operation section\n\n var operInput = inputs.addDropDownCommandInput('operation', 'Operation', adsk.core.DropDownStyles.TextListDropDownStyle );\n operInput.listItems.add('Value Only',true);\n operInput.listItems.add('Export to Fusion',false);\n operInput.listItems.add('Export to IGES',false);\n operInput.listItems.add('Export to SAT',false);\n operInput.listItems.add('Export to SMT',false);\n operInput.listItems.add('Export to STEP',false);\n operInput.listItems.add('Export to STL',false);\n\n var exportSTLPerBody = inputs.addBoolValueInput('exportSTLPerBody', 'Export STL for each body', true);\n exportSTLPerBody.value = false;\n\n var restoreValues = inputs.addBoolValueInput('restoreValues', 'Restore Values On Finish', true);\n restoreValues.value = false;\n }\n catch (e) {\n ui.messageBox('Failed to create command : ' + (e.message ? e.message : e));\n }\n };\n\n // Event handler for the inputChanged event.\n var onInputChangedHandler = function(args) {\n eventArgs = adsk.core.InputChangedEventArgs(args);\n\n var cmdInput = eventArgs.input;\n if (cmdInput != null)\n {\n if (cmdInput.id == \"param\") {\n var paramInput = adsk.core.DropDownCommandInput(cmdInput);\n\n var iParam = paramInput.selectedItem.index;\n if (paramGroupInput) {\n var enable = (iParam > 0); // Enable/Disable group\n //paramGroupInput.isEnabled = enable;\n paramGroupInput.isExpanded = enable;\n }\n }\n /** TODO: Enable/Disable checkbox depending on operation\n else if (cmdInput.id == \"operation\") {\n //var exportInput = adsk.core.BoolValueCommandInput(cmdInput);\n var operationInput = adsk.core.DropDownCommandInput(cmdInput);\n var paramOperation = operationInput.selectedItem.index;\n val bEnableBoolInput = (paramOperation == PARAM_OPERATION.EXPORT_STL);\n }\n */\n }\n };\n\n var Uint8ToString = function(u8Arr) {\n var CHUNK_SIZE = 0x8000; //arbitrary number\n var index = 0;\n var length = u8Arr.length;\n var result = '';\n var slice;\n while (index < length) {\n slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));\n result += String.fromCharCode.apply(null, slice);\n index += CHUNK_SIZE;\n }\n return result; //btoa(result);\n };\n\n var decode_utf8 = function(s)\n {\n return decodeURIComponent(escape(s));\n }\n\n var LoadParamsCSVFile = function() {\n\n // prompt for the filename\n var dlg = ui.createFileDialog();\n dlg.title = 'Select Parameters CSV File';\n dlg.filter = 'CSV Files (*.csv);;All Files (*.*)';\n\n if (dlg.showOpen() != adsk.core.DialogResults.DialogOK)\n return false;\n\n var csvFilename = dlg.filename;\n\n // Read the csv file.\n var cnt = 0;\n var arrayBuffer = adsk.readFile(csvFilename);\n var allLines = decode_utf8(Uint8ToString(new Uint8Array(arrayBuffer)));\n\n var linesCSV = allLines.split(/\\r?\\n/);\n\n var linesCSVCount = linesCSV.length;\n for (var i = 0; i < linesCSVCount; ++i) {\n\n var line = linesCSV[i].trim();\n\n // Is this line empty?\n if (line === \"\") {\n\n // Skip over multiple blank lines (treat as one)\n for (++i ; line === \"\" && i < linesCSVCount; ++i) {\n line = linesCSV[i].trim();\n }\n\n if (i == linesCSVCount) {\n break; // No more lines\n }\n }\n\n // Get the values from the csv line.\n // Format:\n // ParamName, StartValue, EndValue, Step\n var pieces = line.split(',');\n\n if ( pieces.length != 4 ) {\n ui.messageBox(\"Invalid line: \" + cnt + \" - CSV file: \" + csvFilename);\n adsk.terminate();\n }\n\n if (isNaN(pieces[1]) || isNaN(pieces[2]) || isNaN(pieces[3])) {\n ui.messageBox(\"Invalid param value at line: \" + cnt + \" - CSV file: \" + csvFilename);\n adsk.terminate();\n }\n\n var paramName = pieces[0];\n var paramStart = Number(pieces[1]);\n var paramEnd = Number(pieces[2]);\n var paramStep = Number(pieces[3]);\n\n paramsInfo.push({name: paramName, valueStart: paramStart, valueEnd: paramEnd, valueStep: paramStep});\n\n cnt += 1;\n }\n\n return true;\n };\n\n // Now begin the param updates. This is a recursive function which will\n // iterate over each param and update.\n var UpdateParams = function(whichParam, paramValues, exportFilenamePrefix, exportSTLPerBody) {\n\n var curParam = paramsInfo[whichParam];\n\n // Validate loop params\n if (curParam.valueStep <= 0) {\n ui.messageBox(\"Value increment must be greater than zero\");\n return false;\n }\n\n if (curParam.valueStart > curParam.valueEnd) {\n curParam.valueStep = -curParam.valueStep;\n }\n else if (curParam.valueStart == curParam.valueEnd) {\n ui.messageBox(\"Start value must not equal End value\");\n return false;\n }\n\n // Get the actual parameter to modify\n var userParam = userParamsList.itemByName(curParam.name);\n if (!userParam) {\n return false;\n }\n\n var resExport = 0;\n\n // Loop from valueStart to valueEnd incrementing by valueStep\n for (var val = curParam.valueStart;\n (curParam.valueStep > 0) ? val <= curParam.valueEnd : val >= curParam.valueEnd;\n val += curParam.valueStep) {\n\n // note - setting the 'value' property does not change the value. Must set expression.\n // REVIEW: Handle unit conversion\n userParam.expression = '' + val; // + ' cm';\n\n // TODO: dialog not hiding at end\n //progressDialog.message = \"Updating parameter '\" + curParam.name + \"' to \" + userParam.expression;\n\n // Track in running values\n paramValues[curParam.name] = userParam.expression;\n\n // If exporting then we need to build the name for this iteration\n var exportFilename = \"\";\n if (exportFilenamePrefix && exportFilenamePrefix !== \"\") {\n // TODO: Better name based on all params\n exportFilename = exportFilenamePrefix + '_' + curParam.name + '_' + val;\n }\n\n // Is this a leaf node?\n if ( whichParam == paramsInfo.length - 1 ) {\n\n // Yes, so perform the operation specified.\n var exportMgr = design.exportManager;\n\n switch (paramOperation)\n {\n case PARAM_OPERATION.LOOP_ONLY:\n // Nothing\n break;\n\n case PARAM_OPERATION.EXPORT_FUSION:\n var fusionArchiveOptions = exportMgr.createFusionArchiveExportOptions(exportFilename+'.f3d');\n resExport = exportMgr.execute(fusionArchiveOptions);\n break;\n\n case PARAM_OPERATION.EXPORT_IGES:\n var igesOptions = exportMgr.createIGESExportOptions(exportFilename+'.igs');\n resExport = exportMgr.execute(igesOptions);\n break;\n\n case PARAM_OPERATION.EXPORT_SAT:\n var satOptions = exportMgr.createSATExportOptions(exportFilename+'.sat');\n resExport = exportMgr.execute(satOptions);\n break;\n\n case PARAM_OPERATION.EXPORT_SMT:\n var smtOptions = exportMgr.createSMTExportOptions(exportFilename+'.smt');\n resExport = exportMgr.execute(smtOptions);\n break;\n\n case PARAM_OPERATION.EXPORT_STEP:\n var stepOptions = exportMgr.createSTEPExportOptions(exportFilename+'.step');\n resExport = exportMgr.execute(stepOptions);\n break;\n\n case PARAM_OPERATION.EXPORT_STL:\n\n if ( exportSTLPerBody ) {\n var bodies = design.rootComponent.bRepBodies;\n for (var iBodies=0; iBodies < bodies.count; iBodies++)\n {\n var body = bodies.item(iBodies);\n var name = body.name;\n console.log(\"STL Export Body '\"+body+\"' : Name '\"+name+\"'\");\n\n // Create a clean filename\n var exportFilename = exportFilenamePrefix + '_' + name + '_' + curParam.name + '_' + val + '.stl';\n\n var stlOptions = exportMgr.createSTLExportOptions(body, exportFilename);\n\n //stlOptions.isBinaryFormat = true;\n //stlOptions.isBinaryFormat = true;\n //stlOptions.meshRefinement = adsk.fusion.MeshRefinementSettings.MeshRefinementHigh;\n resExport = exportMgr.execute(stlOptions);\n }\n }\n else {\n var stlOptions = exportMgr.createSTLExportOptions(design.rootComponent, exportFilename+'.stl');\n //stlOptions.isBinaryFormat = true;\n //stlOptions.meshRefinement = adsk.fusion.MeshRefinementSettings.MeshRefinementHigh;\n resExport = exportMgr.execute(stlOptions);\n }\n\n break;\n }\n }\n else { // Not a leaf node so iterate downward\n\n for (var iParam = whichParam+1; iParam < paramsInfo.length; ++iParam) {\n UpdateParams(iParam, paramValues, exportFilename, false);\n }\n }\n }\n };\n\n // CommandExecuted event handler.\n var onCommandExecuted = function(args) {\n try {\n\n // Extract input values\n var unitsMgr = app.activeProduct.unitsManager;\n var command = adsk.core.Command(args.firingEvent.sender);\n var inputs = command.commandInputs;\n\n var paramInput, valueStartInput, valueEndInput, valueStepInput, operationInput, exportSTLPerBodyInput, restoreValuesInput;\n\n // REVIEW: Problem with a problem - the inputs are empty at this point. We\n // need access to the inputs within a command during the execute.\n for (var n = 0; n < inputs.count; n++) {\n var input = inputs.item(n);\n if (input.id === 'param') {\n paramInput = adsk.core.DropDownCommandInput(input);\n }\n else if (input.id === 'valueStart') {\n valueStartInput = adsk.core.ValueCommandInput(input);\n }\n else if (input.id === 'valueEnd') {\n valueEndInput = adsk.core.ValueCommandInput(input);\n }\n else if (input.id === 'valueStep') {\n valueStepInput = adsk.core.ValueCommandInput(input);\n }\n else if (input.id === 'operation') {\n operationInput = adsk.core.DropDownCommandInput(input);\n }\n else if (input.id === 'exportSTLPerBody') {\n exportSTLPerBodyInput = adsk.core.BoolValueCommandInput(input);\n }\n else if (input.id === 'restoreValues') {\n restoreValuesInput = adsk.core.BoolValueCommandInput(input);\n }\n }\n\n if (!paramInput || !valueStartInput || !valueEndInput || !valueStepInput || !operationInput || !exportSTLPerBodyInput || !restoreValuesInput) {\n ui.messageBox(\"One of the inputs does not exist.\");\n return;\n }\n\n // What param to use or param CSV file?\n var iParam = paramInput.selectedItem.index;\n if (iParam < 0) {\n ui.messageBox(\"No parameter selected\");\n return false;\n }\n\n // Use param CSV file?\n if (iParam == 0) {\n // Prompt for then load param info from file.\n if (!LoadParamsCSVFile()) {\n return false;\n }\n }\n else {\n // Add single param info to the list.\n paramsInfo.push({\n name: userParamsList.item(iParam-1).name, // Note, subtract 1 since iParam == 0 is CSV file entry\n valueStart: unitsMgr.evaluateExpression(valueStartInput.expression),\n valueEnd: unitsMgr.evaluateExpression(valueEndInput.expression),\n valueStep: unitsMgr.evaluateExpression(valueStepInput.expression)\n });\n }\n\n // What to do after each param update?\n paramOperation = operationInput.selectedItem.index;\n if (paramOperation < 0 || paramOperation > PARAM_OPERATION.LAST) {\n ui.messageBox(\"Invalid operation\");\n return false;\n }\n\n // If operation is an export then prompt for folder location.\n var exportFilenamePrefix = \"\";\n var isExporting = (paramOperation >= PARAM_OPERATION.EXPORT_FUSION && paramOperation <= PARAM_OPERATION.EXPORT_STL);\n if (isExporting) {\n\n // Prompt for the base filename to use for the exports. This will\n // be appended with a counter or step value.\n var dlg = ui.createFileDialog();\n dlg.title = 'Select Export Filename Prefix';\n dlg.filter = 'All Files (*.*)';\n if (dlg.showSave() !== adsk.core.DialogResults.DialogOK) {\n return false;\n }\n\n // Strip extension\n var filename = dlg.filename;\n var extIdx = filename.lastIndexOf('.');\n if (extIdx >= 0) {\n filename = filename.substring(0, extIdx);\n }\n\n if (filename === '') {\n ui.messageBox('Invalid export filename');\n return false;\n }\n\n // TESTING\n //var tmpDir = adsk.tempDirectory();\n //exportFilenamePrefix = tmpDir + \"test\";\n // \"/var/folders/hx/nckzmpbd78xgd90krgjrwq940000gn/T/com.autodesk.mas.fusion360/test_Width_1\"\n\n exportFilenamePrefix = filename;\n }\n\n // Before doing the potential long param update operations, display a progress dialog\n // TODO: dialog not hiding at end\n //progressDialog = ui.createProgressDialog();\n //progressDialog.cancelButtonText = 'Cancel';\n //progressDialog.isBackgroundTranslucent = false;\n //progressDialog.isCancelButtonShown = true;\n\n // Show dialog\n //progressDialog.show('ParaParam Progress', 'Generating parameters...', 0, paramsInfo.length);\n\n // How many params are we changing?\n var paramsCount = paramsInfo.length;\n\n // Track current param value (expression) while iterating over all\n var paramValues = {};\n\n // Save off the original param values so we can restore later\n var userParamValuesOriginal = [];\n for (var iParam = 0; iParam < paramsCount; ++iParam) {\n\n // Get the custom param info\n var curParam = paramsInfo[iParam];\n\n // Get the actual parameter to modify\n var userParam = userParamsList.itemByName(curParam.name);\n if (!userParam) {\n break;\n }\n\n userParamValuesOriginal[curParam.name] = userParam.expression;\n\n paramValues[curParam.name] = userParam.expression;\n }\n\n // Now begin the param updates. This is a recursive function which will\n // iterate over each param and update. It's really just a way of doing\n // the following but for an arbitrary number of params:\n // for (i = 0; i < iCount; ++i)\n // for (j = 0; j < jCount; ++j)\n // for (k = 0; k < kCount; ++k)\n // print value(i,j,k)\n UpdateParams(0, paramValues, exportFilenamePrefix, exportSTLPerBodyInput.value);\n\n // Restore original param values on finish?\n if ( restoreValuesInput.value ) {\n for (var paramName in userParamValuesOriginal) {\n if (userParamValuesOriginal.hasOwnProperty(paramName)) {\n // Get the actual parameter to modify\n var userParam = userParamsList.itemByName(paramName);\n userParam.expression = userParamValuesOriginal[paramName];\n }\n }\n }\n }\n catch (e) {\n ui.messageBox('Failed to execute command : ' + (e.description ? e.description : e));\n }\n\n // Make sure this is gone. Sometimes hangs around!\n // TODO: dialog not hiding at end\n //if (progressDialog) {\n // progressDialog.hide();\n // progressDialog = null;\n //}\n };\n\n // Create and run command\n\ttry {\n var command = createCommandDefinition();\n var commandCreatedEvent = command.commandCreated;\n commandCreatedEvent.add(onCommandCreated);\n\n command.execute();\n }\n catch (e) {\n ui.messageBox('Script Failed : ' + (e.message ? e.message : e));\n adsk.terminate();\n }\n}",
"function loadParameter() {\r\n\tvar lines = \"\";\r\n\tlines += \"# Simulations\\n\";\r\n\tlines += \"t_min 0\\n\"; \r\n\tlines += \"t_max 20\\n\";\r\n\tlines += \"t_start 0\\n\"; \r\n\tlines += \"t_end 18\\n\"; \r\n\tlines += \"dt 0.01\\n\";\r\n\tlines += \"tproc 0.01\\n\";\r\n\tlines += \"t_delay 1\\n\"\r\n\tlines += \"N_irf 2\\n\"\r\n \r\n\tlines += \"\\n\";\r\n\tlines += \"# Ray's Properties \\n\";\r\n\tlines += \"r_x 250\\n\"; \r\n\tlines += \"r_y 0\\n\";\r\n\tlines += \"r_z 0\\n\";\r\n\tlines += \"n_x 0\\n\"; \r\n\tlines += \"n_y 0.8\\n\";\r\n\tlines += \"n_z 0\\n\";\r\n\tlines += \"v_ray 1000\\n\";\r\n\t\r\n\tlines += \"\\n\";\r\n\tlines += \"# Detector's Properties\\n\";\r\n\tlines += \"det_x 500\\n\";\r\n\tlines += \"det_y 250\\n\";\t\r\n\tlines += \"det_z 0\\n\";\r\n\tlines += \"R_det 50\\n\";\r\n\t\r\n\tlines += \"\\n\";\r\n\tlines += \"# Particle's Properties\\n\";\r\n\tlines += \"num_par 20\\n\";\r\n\tlines += \"R_par 5\\n\";\r\n\tlines += \"s_obs 100\\n\"\r\n\t\r\n\ttaIn.value = lines;\r\n\ttaIn.scrollTop = taIn.scrollHeight;\r\n}",
"function PrintUsage() {\nvar s = \"\";\n\ns = s + \"\\n ChangeProperties_ADSI.js\";\ns = s + \"\\n \";\ns = s + \"\\n \\t Description:\";\ns = s + \"\\n Sample script that uses ADSI to change properties on machines as listed in a tab-delimited file.\";\ns = s + \"\\n \";\ns = s + \"\\n \\t Syntax:\";\ns = s + \"\\n ChangeProperties_ADSI.js <file name>\";\ns = s + \"\\n \";\ns = s + \"\\n \\t Example:\";\ns = s + \"\\n Cscript /nologo ChangeProperties_ADSI.js c:\\\\mymachines.txt\";\ns = s + \"\\n Cscript /nologo ChangeProperties_ADSI.js mymachines.txt\";\ns = s + \"\\n \";\ns = s + \"\\n \\t Syntax of File:\";\ns = s + \"\\n <machine name> \\t <metabase path> \\t <property name> \\t <value>\";\ns = s + \"\\n \";\ns = s + \"\\n \\t Example of File:\";\ns = s + \"\\n Server1 \\t w3svc \\t ConnectionTimeout \\t 999\";\ns = s + \"\\n Server2 \\t w3svc\\/1 \\t ServerComment \\t My Default Server\";\ns = s + \"\\n Server2 \\t w3svc\\/1\\/root \\t Path \\t c:\\\\webroot\";\ns = s + \"\\n Server1 \\t msftpsvc \\t ConnectionTimeout \\t 999\";\ns = s + \"\\n \";\ns = s + \"\\n \\t Notes:\";\ns = s + \"\\n - The property must exist at the level you specify in the file.\";\ns = s + \"\\n - Not all properties propogate to child nodes. ConnectionTimeout does, ServerComment does not.\";\ns = s + \"\\n - The property value must be of a string, boolean, or integer data type.\";\ns = s + \"\\n - The file must be in ANSI format\";\ns = s + \"\\n - Each line in the file corresponds to one property change. A quick way to create the file that has repeated text is to use Excel where the first column is the machine name, the second column is the metabase path, the third column is the property name and the fourth column is the value you want set. Then, copy all the fields and paste into Notepad. Each line is automatically tab-delimited.\";\ns = s + \"\\n - The user of the script must be an administrator on all of the machines that are listed in the file. If the user account is not an administrator on all of the machines, but there is an account that is an administrator on all of the machines, alter the call to ConnectServer in this script to add a user name and password, or any other parameters like Locale ID.\";\ns = s + \"\\n \";\n\nWScript.Echo(s);\nreturn 1;\n}",
"function MvNasoduodenalTube(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n//var objData = Data.getData(TestName,\"MedicalCare\");\nvar tcDesc = Data.getData(TestName,\"MedicalCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start of Nasoduodenal tube documentation for \"+tcDesc ,\"The flow is started\");\n\t//Start of the feature \n\t\n\t\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t \n \n // Slection of menu value \n \t exestatus = mvObjects.selectMenuOption(exestatus,\"Nursing\", \"Input / Output Devices and Observations\",\"Tubes\",\"Gastrointestinal\",\"Nasoduodenal Tube\");\n\t// Wait for screen to appear\n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"Button\\\", \\\"Initiate\\\", 1)\", 120,exestatus);\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"Button\\\", \\\"Initiate\\\", 1)\",exestatus);\n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"lblNumeric_1\\\")\", 120,exestatus);\n \n \n// ** Fill in the details for Nasoduodenal Tube **\nLog.Message(\"*** enter details for Nasoduodenal Tube ***\");\n\t\nvar Size = Data.getData(TestName,\"MedicalCare\",\"Size\");\nvar PositionAtNare = Data.getData(TestName,\"MedicalCare\",\"PositionAtNare\");\n \n \n\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_1\\\")\",Size,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_2\\\")\",PositionAtNare,exestatus);\n\n\n\n \n // Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\ttimeSavedValue = aqString.Replace(timeSavedValue, \":00\", \"\", false);\n\ttimeSavedValue = aqString.Replace(timeSavedValue, \"0\", \"\", false);\n\tLog.Checkpoint(\"Nasoduodenal Tube: \"+ timeSavedValue);\n \n // Save and close the form data\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdSave\\\")\",exestatus);\n exestatus = mvObjects.waitForObjectNotVisible(vProcess, \"WPFObject(\\\"cmdSave\\\")\", 120,exestatus);\n \n // selection input/output tab\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"TabItem\\\", \\\"\\\", 6)\",exestatus);\n \n \n //var objData = Data.getData(TestName,\"Patient\");\n \t//var newPatientMRN = objData(\"MRN\").Value;\n\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Successfully documented Nasoduodenal Tube\");\n Log.Checkpoint(\"End of Nasoduodenal Tube\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped Nasoduodenal Tube documentation \",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvRenalReplacementTherapies(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n//var objData = Data.getData(TestName,\"MedicalCare\");\nvar tcDesc = Data.getData(TestName,\"MedicalCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start CRRT form documentation for \"+tcDesc ,\"The flow is started\");\n\t\n \n //Start of the feature \n\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n \n \n // Select the RRT tab \n exestatus = mvObjects.waitForObject(vProcess,\"WPFObject(\\\"TabItem\\\", \\\"\\\", 8)\",120,exestatus);\n \texestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"TabItem\\\", \\\"\\\", 8)\",exestatus);\n \n\t\n // Wait for screen to appear and selection of button\n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"ImdButton\\\", \\\"\\\", 1)\", 120,exestatus);\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"ImdButton\\\", \\\"\\\", 1)\",exestatus);\n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"txtFreeText_1\\\")\", 120,exestatus);\n \n \n \n// ** Fill in the details for CRRT Orders **\nLog.Message(\"*** enter details for CRRT Orders ***\");\n\t\nvar RRT_Other = Data.getData(TestName,\"MedicalCare\",\"RRT_Other\");\nvar CRRT_BloodFlow = Data.getData(TestName,\"MedicalCare\",\"CRRT_BloodFlow\");\nvar CRRT_Filter = Data.getData(TestName,\"MedicalCare\",\"CRRT_Filter\");\nvar CRRT_Dialysate = Data.getData(TestName,\"MedicalCare\",\"CRRT_Dialysate\");\nvar CRRT_OtherDialysate = Data.getData(TestName,\"MedicalCare\",\"CRRT_OtherDialysate\");\nvar CRRT_Dial_Additive = Data.getData(TestName,\"MedicalCare\",\"CRRT_Dial_Additive\");\nvar CRRT_Dial_Add_DD = Data.getData(TestName,\"MedicalCare\",\"CRRT_Dial_Add_DD\");\nvar CRRT_Dial_Final = Data.getData(TestName,\"MedicalCare\",\"CRRT_Dial_Final\");\nvar CRRT_Dial_FluidRate = Data.getData(TestName,\"MedicalCare\",\"CRRT_Dial_FluidRate\");\nvar CRRT_PBP = Data.getData(TestName,\"MedicalCare\",\"CRRT_PBP\");\nvar CRRT_PBP_OtherPBP = Data.getData(TestName,\"MedicalCare\",\"CRRT_PBP_OtherPBP\");\nvar CRRT_PBP_Additive = Data.getData(TestName,\"MedicalCare\",\"CRRT_PBP_Additive\");\nvar CRRT_PBP_Add_DD = Data.getData(TestName,\"MedicalCare\",\"CRRT_PBP_Add_DD\");\nvar CRRT_PBP_Final = Data.getData(TestName,\"MedicalCare\",\"CRRT_PBP_Final\");\n//var CRRT_PBP_Pre-Filter = objData (\"CRRT_PBP_Pre-Filter\").Value\nvar CRRT_FluidRemoval_ML = Data.getData(TestName,\"MedicalCare\",\"CRRT_FluidRemoval_ML\");\nvar CRRT_FluidRemovalDD = Data.getData(TestName,\"MedicalCare\",\"CRRT_FluidRemovalDD\");\nvar CRRT_FluidRemoval_BalanceIncl = Data.getData(TestName,\"MedicalCare\",\"CRRT_FluidRemoval_BalanceIncl\");\nvar CRRT_PostBalanceFluid = Data.getData(TestName,\"MedicalCare\",\"CRRT_PostBalanceFluid\");\nvar CRRT_PostBalanceFluidOther = Data.getData(TestName,\"MedicalCare\",\"CRRT_PostBalanceFluidOther\");\nvar CRRT_PostBalance_Add = Data.getData(TestName,\"MedicalCare\",\"CRRT_PostBalance_Add\");\nvar CRRT_PostBalance_Add_DD = Data.getData(TestName,\"MedicalCare\",\"CRRT_PostBalance_Add_DD\");\nvar CRRT_PostBalance_FinalPotta = Data.getData(TestName,\"MedicalCare\",\"CRRT_PostBalance_FinalPotta\");\nvar CRRT_PostBalance_FilterRate = Data.getData(TestName,\"MedicalCare\",\"CRRT_PostBalance_FilterRate\");\nvar CRRT_Comments = Data.getData(TestName,\"MedicalCare\",\"CRRT_Comments\");\nvar CRRT_Mode = Data.getData(TestName,\"MedicalCare\",\"CRRT_Mode\");\nvar CRRT_Dose = Data.getData(TestName,\"MedicalCare\",\"CRRT_Dose\");\nvar CRRT_DoseWeight = Data.getData(TestName,\"MedicalCare\",\"CRRT_DoseWeight\");\nvar CRRT_DoseRate = Data.getData(TestName,\"MedicalCare\",\"CRRT_DoseRate\");\n\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_1\\\")\",CRRT_Mode,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_2\\\")\",CRRT_DoseWeight,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",\"Acid-base\",exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",\"Fluid balance\",exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",\"Hyperkalaemia\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_1\\\")\",RRT_Other,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_6\\\")\",CRRT_BloodFlow,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_2\\\")\",CRRT_Filter,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_2\\\")\",CRRT_Dialysate,exestatus);\n //Handle Pop-up for low Dialysate fluid\n //To proceed with windowspopup \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n if (MsgForm.Exists)\n { \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n } \nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_3\\\")\",CRRT_OtherDialysate,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_7\\\")\",CRRT_Dial_Additive,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_3\\\")\",CRRT_Dial_Add_DD,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_8\\\")\",CRRT_Dial_Final,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_4\\\")\",CRRT_PBP,exestatus);\n //Handle Pop-up for low Dialysate fluid\n //To proceed with windowspopup \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n if (MsgForm.Exists)\n { \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n }\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_4\\\")\",CRRT_PBP_OtherPBP,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_10\\\")\",CRRT_PBP_Additive,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_5\\\")\",CRRT_PBP_Add_DD,exestatus);\n //Handle Pop-up for low Dialysate fluid\n //To proceed with windowspopup \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n if (MsgForm.Exists)\n { \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n }\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_11\\\")\",CRRT_PBP_Final,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_5\\\")\",CRRT_FluidRemoval_ML,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_6\\\")\",CRRT_FluidRemovalDD,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_6\\\")\",CRRT_FluidRemoval_BalanceIncl,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_7\\\")\",CRRT_PostBalanceFluid,exestatus);\n //Handle Pop-up for low Dialysate fluid\n //To proceed with windowspopup \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n if (MsgForm.Exists)\n { \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n }\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_7\\\")\",CRRT_PostBalanceFluidOther,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_13\\\")\",CRRT_PostBalance_Add,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_8\\\")\",CRRT_PostBalance_Add_DD,exestatus);\n //Handle Pop-up for low Dialysate fluid\n //To proceed with windowspopup \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n if (MsgForm.Exists)\n { \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n }\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtNumeric_14\\\")\",CRRT_PostBalance_FinalPotta,exestatus);\nexestatus = mvObjects.enterEditText(vProcess,\"WPFObject(\\\"txtFreeText_8\\\")\",CRRT_Comments,exestatus);\n \n \n // Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\ttimeSavedValue = aqString.Replace(timeSavedValue, \":00\", \"\", false);\n\ttimeSavedValue = aqString.Replace(timeSavedValue, \"0\", \"\", false);\n\tLog.Checkpoint(\"Pericardial Drain Saved Time: \"+ timeSavedValue);\n \n \n \n // Save the form data\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdApply\\\")\",exestatus);\n \n \n //Get the form saved time and date\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n var savedTimevalue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus);\n \n // Save and close the form data\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"ucFormBuilder_FBForm\\\")\",exestatus);\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n \n //Validation part open form again\n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"ImdButton\\\", \\\"\\\", 1)\", 120,exestatus);\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"ImdButton\\\", \\\"\\\", 1)\",exestatus);\n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"txtFreeText_1\\\")\", 120,exestatus);\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n \n var timedocumentedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus); \n \n if(aqString.Compare(savedTimevalue,timedocumentedValue,false) ==0)\n {\n Log.Checkpoint(\"Time and date are matching\");\n }\n else\n {\n Log.Error(\"time and date are not matched\");\n exestatus =false;\n } \n //Validation of documented values\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_1\\\")\", \"Text\",CRRT_Mode,\"CRRT_Mode\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_4\\\")\", \"Value\",CRRT_Dose,\"CRRT_Dose\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_2\\\")\", \"Value\",CRRT_DoseWeight,\"CRRT_DoseWeight\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_3\\\")\", \"Value\",CRRT_DoseRate,\"CRRT_DoseRate\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_1\\\")\", \"Text\",RRT_Other,\"RRT_Other\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_2\\\")\", \"Text\",CRRT_Filter,\"CRRT_Filter\",exestatus);\n \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_3\\\")\", \"Text\",CRRT_OtherDialysate,\"CRRT_OtherDialysate\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_3\\\")\", \"Text\",CRRT_Dial_Add_DD,\"CRRT_Dial_Add_DD\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_9\\\")\", \"Value\",CRRT_Dial_FluidRate,\"CRRT_Dial_FluidRate\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_4\\\")\", \"Text\",CRRT_PBP,\"CRRT_PBP\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_4\\\")\", \"Text\",CRRT_PBP_OtherPBP,\"CRRT_PBP_OtherPBP\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\", \"Text\",CRRT_PBP_Add_DD,\"CRRT_PBP_Add_DD\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_5\\\")\", \"Text\",CRRT_FluidRemoval_ML,\"CRRT_FluidRemoval_ML\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_6\\\")\", \"Text\",CRRT_FluidRemovalDD,\"CRRT_FluidRemovalDD\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_6\\\")\", \"Text\",CRRT_FluidRemoval_BalanceIncl,\"CRRT_FluidRemoval_BalanceIncl\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_7\\\")\", \"Text\",CRRT_PostBalanceFluid,\"CRRT_PostBalanceFluid\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_7\\\")\", \"Text\",CRRT_PostBalanceFluidOther,\"CRRT_PostBalanceFluidOther\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_8\\\")\", \"Text\",CRRT_PostBalance_Add_DD,\"CRRT_PostBalance_Add_DD\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_14\\\")\", \"Value\",CRRT_PostBalance_FinalPotta,\"CRRT_PostBalance_FinalPotta\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_8\\\")\", \"Text\",CRRT_Comments,\"CRRT_Comments\",exestatus);\n \n // close the form data\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n \n \n //var objData = Data.getData(TestName,\"Patient\");\n \t//var newPatientMRN = objData(\"MRN\").Value;\n\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Successfully documented CRRT form\");\n Log.Checkpoint(\"End of CRRT form\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped CRRT documentation \",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function update_parameters() {\n world.ignition_rate = ignition_rate_slider.element.value;\n world.sprout_rate = sprout_rate_slider.element.value;\n\n seed_viability_rate = Number(seed_viability_rate_slider.element.value);\n growth_rate = Number(growth_rate_slider.element.value);\n reproductive_maturity = Number(reproductive_maturity_slider.element.value);\n max_fire_resistance = Number(max_fire_resistance_slider.element.value);\n}",
"static GetParticleParameterValue() {\n // Enable display of particle type selection arrows.\n Test.fullscreenUI.SetParticleParameterSelectionEnabled(true);\n return Test.particleParameter.GetValue();\n }",
"function MvModifyVariableDose(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n\n\n\nvar tcDesc = Data.getData(TestName,\"Medications\",\"TC_DESC\");\nLog.Checkpoint(\"Start of modify variable dose medication \"+tcDesc ,\"The flow is started\");\n\t\n \n//Start of the feature \nvProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\n//** Fill in the details for prescribe medication tab** \nLog.Message(\"*** Enter details for Prescribe medication\");\n\nvar drug = Data.getData(TestName,\"Medications\",\"drug\");\nvar template=Data.getData(TestName,\"Medications\",\"template\");\nvar medicaltype=Data.getData(TestName,\"Medications\",\"medicaltype\");\nvar SetInterval=Data.getData(TestName,\"Medications\",\"SetInterval\");\nvar Password = Data.getData(TestName,\"Navigation\",\"Password\");\n \n\n\nLog.Message(\"*** Enter details for Medication\");\n//Prescribe Medication\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n\n//Click on Prescribe \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",1)\",exestatus);\n\naqUtils.Delay(10000);\n\n\n//Entering values in orderable window \nexestatus = mvObjects.SearchSelectItem(vProcess, \"WPFObject(\\\"FindComboBoxEdit\\\")\",5,2,drug,2,exestatus);\nexestatus = mvObjects.selectToggleItem(vProcess,\"Text\",template,exestatus);\n//Frequency\nexestatus = mvObjects.wildcardfullname(vProcess, \"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"ComboBoxEdit\\\", \\\"\\\", 1).WPFObject(\\\"ButtonContainer\\\", \\\"\\\", 1).WPFObject(\\\"PART_Item\\\")\",\"ComboBoxEditItem\", medicaltype,exestatus);\n\n// Enter medication frequency\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 3).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"SpinEdit\\\", \\\"\\\", 1)\",SetInterval,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Save & Close\\\",1)\",exestatus);\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review and resolve the issue\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus); \n\n// final validation is pending- Flowsheet\n\n\n\n\n \n if (equal(exestatus,true)) {\n\n\t \t Log.Checkpoint(\"Successfully modified dose of varibale medication\");\n Log.Checkpoint(\"End of modify variable dose medication \",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped modify variable dose medication\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function vfact_SetCustomParams(SP, G, Q, pitchMode) {\n extendedplayer = true;\n vFact_Current_Speedsetting = SP;\n vFact_Current_InternetSetting = Q;\n vFact_Current_GenderSetting = G;\n vFact_Current_Pitchsetting = pitchMode;\n}",
"function C009_Library_Jennifer_Untie() {\n\tActorUntie();\n\tC009_Library_Jennifer_CalcParams();\n}",
"function MvReviewBurnDepthDescrip(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\nvar tcDesc = Data.getData(TestName,\"OtherCare1\",\"TC_DESC\");\nLog.Checkpoint(\"Start ReviewBurnDepthDescrip for \"+tcDesc ,\"The flow is started\");\n//Start of the feature \n \nvProcess = Sys.Process(\"iMDSoft.Metavision\");\n\nexestatus = mvObjects.selectMenuOption(exestatus,\"Medical\",\"Burns\",\"Burns Admission Management\");\n// Wait for screen to appear\n//ReviewBurnDepthDescription\n\n \n var DHead = Data.getData(TestName,\"OtherCare1\",\"DHead\");\n var FHead = Data.getData(TestName,\"OtherCare1\",\"FHead\");\n var DNeck = Data.getData(TestName,\"OtherCare1\",\"DNeck\");\n var FNeck = Data.getData(TestName,\"OtherCare1\",\"FNeck\");\n var DAntTrunk = Data.getData(TestName,\"OtherCare1\",\"DAntTrunk\");\n var FAntTrunk = Data.getData(TestName,\"OtherCare1\",\"FAntTrunk\");\n var DPostTrunk = Data.getData(TestName,\"OtherCare1\",\"DPostTrunk\");\n var FPostTrunk = Data.getData(TestName,\"OtherCare1\",\"FPostTrunk\");\n var DLeftArm = Data.getData(TestName,\"OtherCare1\",\"DLeftArm\");\n var FLeftArm = Data.getData(TestName,\"OtherCare1\",\"FLeftArm\");\n var DRightArm = Data.getData(TestName,\"OtherCare1\",\"DRightArm\");\n var FRightArm = Data.getData(TestName,\"OtherCare1\",\"FRightArm\");\n var DButtocks = Data.getData(TestName,\"OtherCare1\",\"DButtocks\");\n var FButtocks = Data.getData(TestName,\"OtherCare1\",\"FButtocks\");\n var DGenitalia = Data.getData(TestName,\"OtherCare1\",\"DGenitalia\");\n var FGenitalia = Data.getData(TestName,\"OtherCare1\",\"FGenitalia\");\n var DLeftLeg = Data.getData(TestName,\"OtherCare1\",\"DLeftLeg\");\n var FLeftLeg = Data.getData(TestName,\"OtherCare1\",\"FLeftLeg\");\n var DRightLeg = Data.getData(TestName,\"OtherCare1\",\"DRightLeg\");\n var FRightLeg = Data.getData(TestName,\"OtherCare1\",\"FRightLeg\");\n var DTotal = Data.getData(TestName,\"OtherCare1\",\"DTotal\");\n var FTotal = Data.getData(TestName,\"OtherCare1\",\"FTotal\");\n \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdAction_2\\\")\",exestatus); \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_1\\\").WPFObject(\\\"txtNumeric_1\\\")\",DHead,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_11\\\")\",FHead,exestatus);\n \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_2\\\").WPFObject(\\\"txtNumeric_2\\\")\",DNeck,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_12\\\")\",FNeck,exestatus);\n \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_3\\\").WPFObject(\\\"txtNumeric_3\\\")\",DAntTrunk,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_13\\\")\",FAntTrunk,exestatus);\n\t \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_4\\\").WPFObject(\\\"txtNumeric_4\\\")\",DPostTrunk,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_14\\\")\",FPostTrunk,exestatus);\n\t \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_5\\\").WPFObject(\\\"txtNumeric_5\\\")\",DLeftArm,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_15\\\")\",FLeftArm,exestatus);\n\t \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_6\\\").WPFObject(\\\"txtNumeric_6\\\")\",DRightArm,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_16\\\")\",FRightArm,exestatus);\n\t \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_7\\\").WPFObject(\\\"txtNumeric_7\\\")\",DButtocks,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_17\\\")\",FButtocks,exestatus);\n \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_8\\\").WPFObject(\\\"txtNumeric_8\\\")\",DGenitalia,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_18\\\")\",FGenitalia,exestatus);\n \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_9\\\").WPFObject(\\\"txtNumeric_9\\\")\",DLeftLeg,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_19\\\")\",FLeftLeg,exestatus);\n \n exestatus = mvObjects.Fullnametext(vProcess, \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picNumeric_10\\\").WPFObject(\\\"txtNumeric_10\\\")\",DRightLeg,exestatus);\n exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_20\\\")\",FRightLeg,exestatus);\n\n //Saving and closing the Lund and Browder tool \n exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"BottomGrid\\\").WPFObject(\\\"FormActionStackPanel\\\").WPFObject(\\\"cmdApply\\\")\",exestatus);\n\n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n \n if (MsgForm.Exists)\n {\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"OK\\\")\",exestatus);\n }\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picFreeText_1\\\").WPFObject(\\\"txtFreeText_1\\\")\",\"Text\",DTotal, \"DTotal\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"picFreeText_2\\\").WPFObject(\\\"txtFreeText_2\\\")\",\"Text\",FTotal, \"FTotal\",exestatus);\n //Open Burns Depth Information\n exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"PicTabsGrid\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"picTabs\\\").WPFObject(\\\"picTab_1\\\").WPFObject(\\\"picFrame_1\\\").WPFObject(\\\"picFrameIn_1\\\").WPFObject(\\\"cmdAction_1\\\")\",exestatus);\n //Close - Burns depth Information\n exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"BottomGrid\\\").WPFObject(\\\"FormActionStackPanel\\\").WPFObject(\\\"cmdCancel\\\")\",exestatus);\n //Close - Lund and Browder\n exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\", 1).WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"BottomGrid\\\").WPFObject(\\\"FormActionStackPanel\\\").WPFObject(\\\"cmdCancel\\\")\",exestatus);\n //Close - Burns Management\n exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"HwndSource: frmMain\\\", \\\"\\\").WPFObject(\\\"frmMain\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ucFormBuilder_FBForm\\\").WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"MainGrid\\\").WPFObject(\\\"BottomGrid\\\").WPFObject(\\\"FormActionStackPanel\\\").WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\n \n if (equal(exestatus,true)) {\n Log.Checkpoint(\" successfully completed ReviewBurnDepthDescription\");\n Log.Checkpoint(\"End ReviewBurnDepthDescription\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped ReviewBurnDepthDescription \",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvEnterPathologyForANZICS(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\nvar tcDesc = Data.getData(TestName,\"NursingCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start EnterPathology documentation for \"+tcDesc ,\"The flow is started\");\n//Start of the feature \n \n \nvProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n// Enter data in Pathology tab\n \n //Enter data for Blood gases------------\n //enter data for ph arterial\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,27,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(10);\n \n //enter data for paO2 arterial\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,100,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(20);\n \n //enter data for paCO2 arterial\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,132,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(30);\n \n //enter data for Hb\n var HbHi = Data.getData(TestName,\"ANZICS\",\"HbHigh\");\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,672,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(HbHi);\n\n //enter data for FiO2 oxygen inhaled\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,780,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(40);\n \n //contract blood gases\n exestatus = mvObjects.ClickCoordinates(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",12,8,exestatus);\n \n //Enter data for Blood chemistry --------------\n var NaHigh = Data.getData(TestName,\"ANZICS\",\"NaHigh\");\n var KHigh = Data.getData(TestName,\"ANZICS\",\"KHigh\");\n var BicarbHigh = Data.getData(TestName,\"ANZICS\",\"BicarbHigh\");\n var CreatHigh = Data.getData(TestName,\"ANZICS\",\"CreatHigh\");\n var Urea = Data.getData(TestName,\"ANZICS\",\"Urea\");\n var Bilirubin = Data.getData(TestName,\"ANZICS\",\"Bilirubin\");\n var AlbuminHi = Data.getData(TestName,\"ANZICS\",\"AlbHigh\");\n \n \n //Enter data for Sodium\n\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,42,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(NaHigh);\n \n //Enter data for Potassium\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,80,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(KHigh);\n \n //Enter data for BiCarbonate\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,152,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(BicarbHigh);\n \n //Enter data for Urea\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,186,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(Urea);\n \n //Enter data for Albumin\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,596,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(AlbuminHi);\n \n //Enter data for Creatinine\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,226,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(CreatHigh);\n \n //Enter data for Bilirubin\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,418,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(Bilirubin);\n \n //contract blood Chemistry\n exestatus = mvObjects.ClickCoordinates(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",9,23,exestatus);\n \n //Enter data for Haemotology ------------\n var WCCHigh = Data.getData(TestName,\"ANZICS\",\"WBCHigh\");\n var PlateletHigh = Data.getData(TestName,\"ANZICS\",\"PlateletsHigh\");\n var HaematocritHigh = Data.getData(TestName,\"ANZICS\",\"HctHigh\");\n \n //enter data for WCC\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,59,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(WCCHigh);\n\n //enter data for Platelet\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,166,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(PlateletHigh);\n\n //enter data for HCT\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1659,240,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(HaematocritHigh);\n \n if (equal(exestatus,true)) {\n Log.Checkpoint(\" successfully initiated ViewPathology\");\n Log.Checkpoint(\"End MvEnterPathologyForANZICS\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped MvEnterPathologyForANZICS\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvCAMICU(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n\nvar tcDesc = Data.getData(TestName,\"HandOver\",\"TC_DESC\");\nLog.Checkpoint(\"Start of documenting CAM-ICU for \"+tcDesc ,\"The flow is started\");\n \n //Start of the feature \n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n // To select CAM-ICU\n\texestatus = mvObjects.selectMenuOption(exestatus,\"Scores\", \"CAM-ICU\");\n\n\t// Wait for screen to appear\nexestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"cboTextCombo_1\\\")\", 120,exestatus);\n\n \n \n// ** Fill in the details for CAM-ICU **\nLog.Message(\"***Enter details for CAM-ICU Scores ***\");\n\t\n\nvar AcuteChnge = Data.getData(TestName,\"HandOver\",\"AcuteChnge\");\nvar Inattention = Data.getData(TestName,\"HandOver\",\"Inattention\");\nvar CurrentRASS = Data.getData(TestName,\"HandOver\",\"CurrentRASS\");\nvar CAMICUNegative = Data.getData(TestName,\"HandOver\",\"CAMICUNegative\");\nvar CAMICUPositive = Data.getData(TestName,\"HandOver\",\"CAMICUPositive\");\nvar DisorganThinking = Data.getData(TestName,\"HandOver\",\"DisorganThinking\");\n\n// To enter input details for CAM- ICU\n\nswitch (AcuteChnge){\n\ncase (\"No\"):{\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_1\\\")\",AcuteChnge,exestatus);\n}\nbreak;\n\ncase (\"Yes\"):{\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_1\\\")\",AcuteChnge,exestatus);\n\n switch (Inattention)\n {\n case (\"0-2 errors\"):\n {\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_2\\\")\",Inattention,exestatus);\n }\n break;\n case (\">2 errors\"):\n {\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_2\\\")\",Inattention,exestatus);\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_3\\\")\",CurrentRASS,exestatus);\n var ObjVisible = vProcess.Find(\"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\", 1000);\n \n if (ObjVisible.Visible == true)\n { \n \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUPositive,\"CAMICUPositive\",exestatus);\n }\n \n switch(CurrentRASS)\n {\n\n case(\"0 - Alert and calm\"):\n {\n \n switch (DisorganThinking)\n {\n case(\"0-1 error\"):\n {\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_4\\\")\",DisorganThinking,exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUNegative,\"CAMICUNegative\",exestatus);\n } \n break;\n case (\">1 error\"):\n {\n exestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_4\\\")\",DisorganThinking,exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUPositive,\"CAMICUPositive\",exestatus);\n }\n break;\n \n } \n } \n \n }\n break;\n }\n }\n break;\n }\n \n} \n\n\n// Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\ttimeSavedValue = aqString.Replace(timeSavedValue, \":00\", \"\", false);\n\ttimeSavedValue = aqString.Replace(timeSavedValue, \"0\", \"\", false);\n\tLog.Checkpoint(\"Saved Time: \"+ timeSavedValue);\n\n\n// To save the form\n\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdApply\\\")\",exestatus);\n\n\n// wait for the form to save.. maybe this object if below don't work -> WPFObject(\"sessionscontrol\") \n exestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"cmdNewSessionText\\\")\", 120,exestatus);\n \n//Get the form saved time and date\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n var savedTimevalue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus);\n \n \n// close the form\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\t\n \n//Validation part open form again\n exestatus = mvObjects.selectMenuOption(exestatus,\"Scores\", \"CAM-ICU\");\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdCancelNewSessionText\\\")\",exestatus);\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus); \n \n var timedocumentedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus); \n \n if(aqString.Compare(savedTimevalue,timedocumentedValue,false) ==0)\n {\n Log.Checkpoint(\"Time and date are matching\");\n }\n else\n {\n Log.Error(\"time and date are not matched\");\n exestatus =false;\n }\n\n\n\n// Validation of documented values\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus); \n switch (AcuteChnge){\n\ncase (\"No\"):\n {\n\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_1\\\")\",\"Text\",AcuteChnge,\"AcuteChnge\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUNegative,\"CAMICUNegative\",exestatus);\n }\nbreak;\n\ncase (\"Yes\"):\n{\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_1\\\")\",\"Text\",AcuteChnge,\"AcuteChnge\",exestatus);\n\n switch (Inattention)\n {\n case (\"0-2 errors\"):\n {\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_2\\\")\",\"Text\",Inattention,\"Inattention\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUNegative,\"CAMICUNegative\",exestatus); \n }\n break;\n case (\">2 errors\"):\n {\n \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_2\\\")\",\"Text\",Inattention,\"Inattention\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_3\\\")\",\"Text\",CurrentRASS,\"CurrentRASS\",exestatus);\n \n switch(CurrentRASS)\n {\n \n case(\"0 - Alert and calm\"):\n {\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_3\\\")\",\"Text\",CurrentRASS,\"CurrentRASS\",exestatus);\n \n switch (DisorganThinking)\n {\n case(\"0-1 error\"):\n {\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_4\\\")\",\"Text\",DisorganThinking,\"DisorganThinking\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUNegative,\"CAMICUNegative\",exestatus);\n } \n break;\n case (\">1 error\"):\n {\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_4\\\")\",\"Text\",DisorganThinking,\"DisorganThinking\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\",\"Text\",CAMICUPositive,\"CAMICUPositive\",exestatus);\n }\n break;\n \n } \n } \n \n }\n \n break;\n }\n }\n break;\n }\n \n }\n\n// To close the form\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\n \n\n \n// Validation of data in input and output tab\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"TabItem\\\", \\\"\\\", 1)\",exestatus);\naqUtils.Delay(2000); \n\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Successfully documented Confusion Assessment (CAM-ICU)\");\n Log.Checkpoint(\"End of documenting Confusion Assessment (CAM-ICU)\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped Confusion Assessment (CAM-ICU) documentation\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvPrescribeAdministerVariableDose(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n\n\n\nvar tcDesc = Data.getData(TestName,\"Medications\",\"TC_DESC\");\nLog.Checkpoint(\"Start of prescribe and administer variable dose medication \"+tcDesc ,\"The flow is started\");\n\t\n \n//Start of the feature \nvProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\n//** Fill in the details for prescribe medication tab** \nLog.Message(\"*** Enter details for Prescribe medication\");\n\nvar drug = Data.getData(TestName,\"Medications\",\"drug\");\nvar template=Data.getData(TestName,\"Medications\",\"template\");\nvar medicaltype=Data.getData(TestName,\"Medications\",\"medicaltype\");\nvar SetInterval=Data.getData(TestName,\"Medications\",\"SetInterval\");\nvar Diluent_Drug = Data.getData(TestName,\"Medications\",\"Diluent_Drug\")\nvar Diluent_Quant = Data.getData(TestName,\"Medications\",\"Diluent_Quant\")\nvar Password = Data.getData(TestName,\"Navigation\",\"Password\");\n \n\n\nLog.Message(\"*** Enter details for Medication\");\n//Prescribe Medication\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n\n//Click on Prescribe \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",1)\",exestatus);\n\naqUtils.Delay(10000);\n\n\n//Entering values in orderable window \nexestatus = mvObjects.SearchSelectItem(vProcess, \"WPFObject(\\\"FindComboBoxEdit\\\")\",5,2,drug,2,exestatus);\nexestatus = mvObjects.selectToggleItem(vProcess,\"Text\",template,exestatus);\n\n//Frequency\nexestatus = mvObjects.wildcardfullname(vProcess, \"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 2).WPFObject(\\\"ComboBoxEdit\\\", \\\"\\\", 1).WPFObject(\\\"ButtonContainer\\\", \\\"\\\", 1).WPFObject(\\\"PART_Item\\\")\",\"ComboBoxEditItem\", medicaltype,exestatus);\n\n// Enter medication frequency\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"Frequency_Row2\\\").WPFObject(\\\"LayoutItem\\\", \\\"\\\", 3).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"SpinEdit\\\", \\\"\\\", 1)\",SetInterval,exestatus);\n\n//Select the Diluent button\nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"OrderEntryView\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Main_Group\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"OrderingStyle\\\").WPFObject(\\\"OrderingStyleView\\\", \\\"\\\", 1).WPFObject(\\\"Order_Style_Group\\\").WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 1).WPFObject(\\\"LayoutItem\\\", \\\"\\\", 7).WPFObject(\\\"StackPanel\\\", \\\"\\\", 1).WPFObject(\\\"Button\\\", \\\"\\\", 1)\",exestatus);\n\n//Enter the diluent and quantity\n //Added Auto-Created script as Unable to click on the Diluent due to non visibility\n //This can be researched in Testcomplete 14.\n let imdGenericWindow = Aliases.iMDSoft_Metavision.HwndSource_ImdGenericWindow.ImdGenericWindow;\n imdGenericWindow.Button.Keys(\"[ScrollLock][ScrollLock][ScrollLock][ScrollLock]\");\n imdGenericWindow.GridRow.GridCellContentPresenter.Click(93, 13);\n \nexestatus = mvObjects.SearchSelectItem(vProcess,\"WPFObject(\\\"HwndSource: ImdGenericWindow\\\", \\\"\\\").WPFObject(\\\"ImdGenericWindow\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"Border\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"OrderEntryView\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"Main_Group\\\").WPFObject(\\\"ScrollViewer\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"OrderingStyle\\\").WPFObject(\\\"OrderingStyleView\\\", \\\"\\\", 1).WPFObject(\\\"Order_Style_Group\\\").WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"GridMedications\\\").WPFObject(\\\"DVGridMedications\\\").WPFObject(\\\"view\\\").WPFObject(\\\"HierarchyPanel\\\", \\\"\\\", 1).WPFObject(\\\"GridRow\\\", \\\"\\\", 2).WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1).WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 1).WPFObject(\\\"CustomTextEdit\\\", \\\"\\\", 1).WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"FindComboBoxEdit\\\")\",5,2,Diluent_Drug,2,exestatus);\nexestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"Grid\\\", \\\"\\\", 1).WPFObject(\\\"OrderingStyle\\\").WPFObject(\\\"OrderingStyleView\\\", \\\"\\\", 1).WPFObject(\\\"Order_Style_Group\\\").WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"GridMedications\\\").WPFObject(\\\"DVGridMedications\\\").WPFObject(\\\"view\\\").WPFObject(\\\"HierarchyPanel\\\", \\\"\\\", 1).WPFObject(\\\"GridRow\\\", \\\"\\\", 2).WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1).WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 4).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",Diluent_Quant,exestatus);\n\n// Saving the order\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\", \\\"Save & Close\\\",1)\",exestatus);\n\n\n//Click on Signow\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSign\\\")\",exestatus);\n\n//Click on Signnow in Signature Review and resolve the issue\n\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WinFormsObject(\\\"cmdSignNow\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"PasswordBoxEdit\\ ,\\\"\\\"\\,1)\", Password,exestatus);\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"Button\\\" , \\\"OK\\\",1)\",exestatus); \n\n// final validation is pending- Flowsheet\n\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n\n// Enter medication quantity \n//exestatus = mvObjects.Fullnametext(vProcess,\"*WPFObject(\\\"LayoutGroup\\\", \\\"\\\", 2).WPFObject(\\\"ContentControl\\\", \\\"\\\", 1).WPFObject(\\\"GridMedications\\\").WPFObject(\\\"DVGridMedications\\\").WPFObject(\\\"view\\\").WPFObject(\\\"HierarchyPanel\\\", \\\"\\\", 1).WPFObject(\\\"GridRow\\\", \\\"\\\", 1).WPFObject(\\\"BandedViewContentSelector\\\", \\\"\\\", 1).WPFObject(\\\"GridCellContentPresenter\\\", \\\"\\\", 4).WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\",quantity,exestatus);\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Successfully prescribed and administered variable dose medication\");\n Log.Checkpoint(\"End of prescribe and administer variable dose medication\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped prescribe and administer variable dose medication\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MVManualHandling(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\nvar tcDesc = Data.getData(TestName,\"OtherCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start of documenting Manual Handling for \"+tcDesc ,\"The flow is started\");\n\t\n //Start of the feature \n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t// To select the Manual Handling \n\texestatus = mvObjects.selectMenuOption(exestatus,\"Scores\", \"Manual Handling\");\n\t\n // Wait for screen to appear\n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"txtFreeText_1\\\")\", 120,exestatus);\n\t\t\n // ** Fill in the details for Manual Handling\n\tLog.Message(\"***Enter details for Manual Handling***\");\n \n var Weight = Data.getData(TestName,\"OtherCare\",\"Weight\");\n var Height = Data.getData(TestName,\"OtherCare\",\"Height\");\n var HipWidth = Data.getData(TestName,\"OtherCare\",\"HipWidth\");\n var Grith = Data.getData(TestName,\"OtherCare\",\"Grith\");\n var MidUppArm = Data.getData(TestName,\"OtherCare\",\"MidUppArm\");\n\n var ObstrSleep = Data.getData(TestName,\"OtherCare\",\"ObstrSleep\");\n var HomeNonInva = Data.getData(TestName,\"OtherCare\",\"HomeNonInva\");\n var BedPosi = Data.getData(TestName,\"OtherCare\",\"BedPosi\");\n var MoveInBed = Data.getData(TestName,\"OtherCare\",\"MoveInBed\");\n var Mobilic = Data.getData(TestName,\"OtherCare\",\"Mobilic\");\n var WalkingFrm = Data.getData(TestName,\"OtherCare\",\"WalkingFrm\");\n var WhlChar = Data.getData(TestName,\"OtherCare\",\"WhlChar\");\n var ShowrChar = Data.getData(TestName,\"OtherCare\",\"ShowrChar\");\n var LungeChr = Data.getData(TestName,\"OtherCare\",\"LungeChr\");\n\n var DeviceSett = Data.getData(TestName,\"OtherCare\",\"DeviceSett\");\n var LivingOther = Data.getData(TestName,\"OtherCare\",\"LivingOther\");\n var Diagnostic = Data.getData(TestName,\"OtherCare\",\"Diagnostic\");\n var Emergency = Data.getData(TestName,\"OtherCare\",\"Emergency\");\n var FallProcedure = Data.getData(TestName,\"OtherCare\",\"FallProcedure\");\n var DischrOrTrnsfr = Data.getData(TestName,\"OtherCare\",\"DischrOrTrnsfr\");\n var Dietition = Data.getData(TestName,\"OtherCare\",\"Dietition\");\n var OccupationalTherpy = Data.getData(TestName,\"OtherCare\",\"OccupationalTherpy\");\n var Physiothrpst = Data.getData(TestName,\"OtherCare\",\"Physiothrpst\");\n var SocialWork = Data.getData(TestName,\"OtherCare\",\"SocialWork\");\n\n var BedElect = Data.getData(TestName,\"OtherCare\",\"BedElect\");\n var EqmntBedHilo = Data.getData(TestName,\"OtherCare\",\"EqmntBedHilo\");\n var EqmntSlfHlp = Data.getData(TestName,\"OtherCare\",\"EqmntSlfHlp\");\n var EqmntHvmat = Data.getData(TestName,\"OtherCare\",\"EqmntHvmat\");\n var EqmntSlidSht = Data.getData(TestName,\"OtherCare\",\"EqmntSlidSht\");\n var EqmntCommode = Data.getData(TestName,\"OtherCare\",\"EqmntCommode\");\n\n var ToiEqPeliXlar = Data.getData(TestName,\"OtherCare\",\"ToiEqPeliXlar\");\n var ToiEqWhlChXlar = Data.getData(TestName,\"OtherCare\",\"ToiEqWhlChXlar\");\n var ToiEqOverFramStnd= Data.getData(TestName,\"OtherCare\",\"ToiEqOverFramStnd\");\n var ShwEqChrXlarg = Data.getData(TestName,\"OtherCare\",\"ShwEqChrXlarg\");\n\n var BedSafework = Data.getData(TestName,\"OtherCare\",\"BedSafework\");\n var TrantTrolyBed = Data.getData(TestName,\"OtherCare\",\"TrantTrolyBed\");\n var EnVidiMovingPatiBd = Data.getData(TestName,\"OtherCare\",\"EnVidiMovingPatiBd\");\n var EnvAidsSitPatBed = Data.getData(TestName,\"OtherCare\",\"EnvAidsSitPatBed\");\n var EnvAidsAisToWak = Data.getData(TestName,\"OtherCare\",\"EnvAidsAisToWak\");\n \n //var SitPatientBed = Data.getData(TestName,\"OtherCare\",\"SitPatientBed\");\n //var AissToWalk = Data.getData(TestName,\"OtherCare\",\"AissToWalk\");\n\n var TranBdChrSliShtXlarge = Data.getData(TestName,\"OtherCare\",\"TranBdChrSliShtXlarge\");\n \nvar NoStafReqTransToBed = Data.getData(TestName,\"OtherCare\",\"NoStafReqTransToBed\");\nvar NoStafReqMovingPatientBed = Data.getData(TestName,\"OtherCare\",\"NoStafReqMovingPatientBed\");\nvar NoStafReqSitPatientBed = Data.getData(TestName,\"OtherCare\",\"NoStafReqSitPatientBed\");\nvar NoStafReqAissToWalk = Data.getData(TestName,\"OtherCare\",\"NoStafReqAissToWalk\");\nvar NoStafReqTranBdChr = Data.getData(TestName,\"OtherCare\",\"NoStafReqTranBdChr\");\nvar NoStafReqToilet = Data.getData(TestName,\"OtherCare\",\"NoStafReqToilet\");\nvar NoStafReqShower = Data.getData(TestName,\"OtherCare\",\"NoStafReqShower\");\n\n\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_1\\\")\",Weight,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_2\\\")\",Height,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_3\\\")\",HipWidth,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_4\\\")\",Grith,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_5\\\")\",MidUppArm,exestatus);\n\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_1\\\")\",ObstrSleep,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_2\\\")\",HomeNonInva,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_3\\\")\",BedPosi,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_4\\\")\",MoveInBed,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_5\\\")\",Mobilic,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_6\\\")\",WalkingFrm,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_7\\\")\",WhlChar,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_8\\\")\",ShowrChar,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_9\\\")\",LungeChr,exestatus);\n\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_1\\\")\",DeviceSett,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_2\\\")\",LivingOther,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_3\\\")\",Diagnostic,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_4\\\")\",Emergency,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_5\\\")\",FallProcedure,exestatus);\nexestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_10\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_6\\\")\",DischrOrTrnsfr,exestatus);\nexestatus = mvObjects.scrollUntilVisible(\"WPFObject(\\\"txtFreeText_10\\\")\",exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_7\\\")\",Dietition,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_8\\\")\",OccupationalTherpy,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_9\\\")\",Physiothrpst,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtFreeText_10\\\")\",SocialWork,exestatus);\n\n\n// TO enter input details for Environment and Aids\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"DXTabItem\\\", \\\"\\\", 2)\",exestatus);\n\nexestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"picTab_2\\\").WPFObject(\\\"picFrame_4\\\").WPFObject(\\\"picFrameIn_4\\\").WPFObject(\\\"picTextList_1\\\").WPFObject(\\\"lstTextList_1\\\").WPFObject(\\\"ListBoxItem\\\", \\\"\\\", 2)\",exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",EqmntBedHilo,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",EqmntSlfHlp,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",EqmntHvmat,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",EqmntSlidSht,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_1\\\")\",EqmntCommode,exestatus);\n\n\n\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_2\\\")\",ToiEqPeliXlar,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_2\\\")\",ToiEqWhlChXlar,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_2\\\")\",ToiEqWhlChXlar,exestatus);\n//exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"picTab_2\\\").WPFObject(\\\"picFrame_4\\\").WPFObject(\\\"picFrameIn_4\\\").WPFObject(\\\"picTextList_2\\\").WPFObject(\\\"lstTextList_2\\\").WPFObject(\\\"ListBoxItem\\\", \\\"\\\", 2)\",exestatus);\n\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_3\\\")\",ToiEqPeliXlar,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_3\\\")\",ToiEqWhlChXlar,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_3\\\")\",ShwEqChrXlarg ,exestatus);\n//exestatus = mvObjects.buttonClick(vProcess, \"FullName\", \"*WPFObject(\\\"picTab_2\\\").WPFObject(\\\"picFrame_4\\\").WPFObject(\\\"picFrameIn_4\\\").WPFObject(\\\"picTextList_3\\\").WPFObject(\\\"lstTextList_3\\\").WPFObject(\\\"ListBoxItem\\\", \\\"\\\", 2)\",exestatus);\n\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_10\\\")\",BedSafework,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_11\\\")\",TrantTrolyBed,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_12\\\")\",EnVidiMovingPatiBd,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_13\\\")\",EnvAidsSitPatBed,exestatus);\nexestatus = mvObjects.selectComboItem(vProcess,\"WPFObject(\\\"cboTextCombo_14\\\")\",EnvAidsAisToWak,exestatus);\n\n\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_4\\\")\",ToiEqPeliXlar,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_4\\\")\",ToiEqWhlChXlar,exestatus);\nexestatus = mvObjects.ListCheckBoxSelection(\"WPFObject(\\\"lstTextList_4\\\")\",TranBdChrSliShtXlarge,exestatus);\n\n\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_6\\\")\",NoStafReqTransToBed,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_7\\\")\",NoStafReqMovingPatientBed,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_8\\\")\",NoStafReqSitPatientBed,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_9\\\")\",NoStafReqAissToWalk,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_10\\\")\",NoStafReqTranBdChr,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_11\\\")\",NoStafReqToilet,exestatus);\nexestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_12\\\")\",NoStafReqShower,exestatus);\n\n let NoOfStafReq = new Object();\n NoOfStafReq.DueDate = Data.getData(TestName,\"OtherCare\",\"AllDateDedect\")\n Day = aqDateTime.GetDay( NoOfStafReq.DueDate);\n\t month = aqDateTime.GetMonth(NoOfStafReq.DueDate);\n\t year = aqDateTime.GetYear(NoOfStafReq.DueDate); \n \nexestatus = mvObjects.enterImdDateTimePicker(vProcess, \"WPFObject(\\\"dtpDate_1\\\")\", Day,month,year,\"00\",\"00\",exestatus);\n \n \n \n // Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\t\n // save the form data\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdApply\\\")\",exestatus);\n \n\t// wait for the form to save.. maybe this object if below don't work -> WPFObject(\"sessionscontrol\") \n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"cmdNewSessionText\\\")\", 120,exestatus);\n \n //Get the form saved time and date\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n var savedTimevalue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus);\n \n \n\t// close the form\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\t\n \n\t//Validation part open form again\n exestatus = mvObjects.selectMenuOption(exestatus,\"Scores\", \"Manual Handling\");\n \n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus); \n \n var timedocumentedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus); \n \n if(aqString.Compare(savedTimevalue,timedocumentedValue,false) ==0)\n {\n Log.Checkpoint(\"Time and date are matching\");\n }\n else\n {\n Log.Error(\"time and date are not matched\");\n exestatus =false;\n }\n \n \n\t// Validation of documented values\nexestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_1\\\")\", \"Value\",Weight,\"Weight\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_2\\\")\", \"Value\",Height,\"Height\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_3\\\")\", \"Value\",HipWidth,\"HipWidth\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_4\\\")\", \"Value\",Grith,\"Grith\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_5\\\")\", \"Value\",MidUppArm,\"MidUppArm\",exestatus);\n\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_1\\\")\", \"Text\",ObstrSleep,\"ObstrSleep\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_2\\\")\", \"Text\",HomeNonInva,\"HomeNonInva\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_3\\\")\", \"Text\",BedPosi,\"BedPosi\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_4\\\")\", \"Text\",MoveInBed,\"MoveInBed\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_5\\\")\", \"Text\",Mobilic,\"Mobilic\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_6\\\")\", \"Text\",WalkingFrm,\"WalkingFrm\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_7\\\")\", \"Text\",WhlChar,\"WhlChar\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_8\\\")\", \"Text\",ShowrChar,\"ShowrChar\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_9\\\")\", \"Text\",LungeChr,\"LungeChr\",exestatus);\n\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_1\\\")\", \"Text\",DeviceSett,\"DeviceSett\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_2\\\")\", \"Text\",LivingOther,\"LivingOther\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_3\\\")\", \"Text\",Diagnostic,\"Diagnostic\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_4\\\")\", \"Text\",Emergency,\"Emergency\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_5\\\")\", \"Text\",FallProcedure,\"FallProcedure\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_6\\\")\", \"Text\",DischrOrTrnsfr,\"DischrOrTrnsfr\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_7\\\")\", \"Text\",Dietition,\"Dietition\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_8\\\")\", \"Text\",OccupationalTherpy,\"OccupationalTherpy\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_9\\\")\", \"Text\",Physiothrpst,\"Physiothrpst\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_10\\\")\", \"Text\",SocialWork,\"SocialWork\",exestatus);\n\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"DXTabItem\\\", \\\"\\\", 2)\",exestatus);\n\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_10\\\")\", \"Text\",BedSafework,\"BedSafework\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_11\\\")\", \"Text\",TrantTrolyBed,\"TrantTrolyBed\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_12\\\")\", \"Text\",EnVidiMovingPatiBd,\"EnVidiMovingPatiBd\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_13\\\")\", \"Text\",EnvAidsSitPatBed,\"EnvAidsSitPatBed\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"cboTextCombo_14\\\")\", \"Text\",EnvAidsAisToWak,\"EnvAidsAisToWak\",exestatus);\n\n\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_6\\\")\", \"Value\",NoStafReqTransToBed,\"NoStafReqTransToBed\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_7\\\")\", \"Value\",NoStafReqMovingPatientBed,\"NoStafReqMovingPatientBed\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_8\\\")\", \"Value\",NoStafReqSitPatientBed,\"NoStafReqSitPatientBed\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_9\\\")\", \"Value\",NoStafReqAissToWalk,\"NoStafReqAissToWalk\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_10\\\")\", \"Value\",NoStafReqTranBdChr,\"NoStafReqTranBdChr\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_11\\\")\", \"Value\",NoStafReqToilet,\"NoStafReqToilet\",exestatus);\nexestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_12\\\")\", \"Value\",NoStafReqShower,\"NoStafReqShower\",exestatus);\n \n \n\t// close the form \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\"Successfully documented Manual Handling\");\n Log.Checkpoint(\"End of Documenting Manual Handling\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped Documenting Manual Handling\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function MvBSAAutomaticallyCalculated(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\n//var objData = Data.getData(TestName,\"MedicalCare\");\nvar tcDesc = Data.getData(TestName,\"MedicalCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start BSAAutomaticallyCalculated for \"+tcDesc ,\"The flow is started\");\n\t//Start of the feature \n\t\n\t\n\t vProcess = Sys.Process(\"iMDSoft.Metavision\");\n\n\t// Patient Details and defaults\n\t var ms = 6000;\n var HelpStr = \"Delaying test run for \" + ms + \" milliseconds, To add BSAAutomaticallyCalculated.\";\n aqUtils.Delay (ms, HelpStr);\n \n\t//Select the Prescribe Medication tab\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n//Click on Weights and Dimensions button \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",7)\",exestatus);\n\t// Wait for screen to appear\n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"lblFreeText_1\\\")\", 120,exestatus);\n\t\t// ** Fill in the Patient details\n\tLog.Message(\"*** enter Weights and Heights data ***\");\n\tvar Height = Data.getData(TestName,\"MedicalCare\",\"Height\");\n\tvar WeightLatest = Data.getData(TestName,\"MedicalCare\",\"WeightLatest\");\n\tvar WeightAdmission = Data.getData(TestName,\"MedicalCare\",\"WeightAdmission\");\n\tvar WeightDrug = Data.getData(TestName,\"MedicalCare\",\"WeightDrug\");\n\tvar WeightIdeal = Data.getData(TestName,\"MedicalCare\",\"WeightIdeal\");\n var WeightAdjusted = Data.getData(TestName,\"MedicalCare\",\"WeightAdjusted\");\n var bmi = Data.getData(TestName,\"MedicalCare\",\"bmi\");\n var bsa = Data.getData(TestName,\"MedicalCare\",\"bsa\");\n\t\t\n\t \n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_1\\\")\",Height,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_2\\\")\",WeightLatest,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_3\\\")\",WeightAdmission,exestatus);\n\t exestatus = mvObjects.enterEditText(vProcess, \"WPFObject(\\\"txtNumeric_6\\\")\",WeightDrug,exestatus);\n\t \n // Get the save time value\n\tvar timeSavedValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"mvtFormTime\\\")\", \"Value\",exestatus); \n\ttimeSavedValue = aqString.Replace(timeSavedValue, \":00\", \"\", false);\n\ttimeSavedValue = aqString.Replace(timeSavedValue, \"0\", \"\", false);\n //timeSavedValue = timeSavedValue.OleValue\n\tLog.Checkpoint(\"BSAAutomaticallyCalculated Saved Time: \"+ timeSavedValue);\n\t\n\t\t// save the form data\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdApply\\\")\",exestatus);\n // to proceed with pop up\n \n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"ImdFormBase\\\")\", 1000);\n \n if (MsgForm.Exists)\n {\n // iMDSoft_Metavision.ImdFormBase.WinFormsObject(\"Buttons\").WinFormsObject(\"Yes\").Click();\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"Ok\\\")\",exestatus);\n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdApply\\\")\",exestatus);\n //exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdSave\\\")\",exestatus);\n }\n \n\n\t// wait for the form to save.. maybe this object if below don't work -> WPFObject(\"sessionscontrol\") \n\texestatus = mvObjects.waitForObject(vProcess, \"WPFObject(\\\"cmdNewSessionText\\\")\", 120,exestatus);\n //Get the form saved time and date\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n var savedUservalue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus);\n \n\t// Click Refresh\n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdRefresh\\\")\",exestatus); \n\n \n\t// close the form \n\texestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n\texestatus = mvObjects.waitForObjectNotVisible(vProcess, \"WPFObject(\\\"cmdCancel\\\")\", 120,exestatus);\n\t//Validation part open form again\n //Select the Prescribe Medication tab\nexestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"TabItem\\\"),\\\"\\\"\\,11\",exestatus);\n//Click on Weights and Dimensions button \nexestatus = mvObjects.buttonClick(vProcess,\"FullName\", \"*WPFObject(\\\"CustomWrapPanel\\\", \\\"\\\", 1).WPFObject(\\\"ImdButton\\\", \\\"\\\",7)\",exestatus);\n\t// Wait for screen to appear\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"cmdCancelNewSessionText\\\")\",exestatus);\n \n //Click No if message comes to save or not\n var MsgForm = vProcess.Find(\"Name\", \"WinFormsObject(\\\"Message\\\")\", 1000);\n if (MsgForm.Exists)\n {\n iMDSoft_Metavision.ImdFormBase.WinFormsObject(\"Buttons\").WinFormsObject(\"No\").Click();\n }\n //exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WinFormsObject(\\\"No\\\")\",exestatus);\n //exestatus = mvObjects.waitForObject(vprocess,\"WPFObject(\\\"sessionscontrol\\\")\",120,exestatus);\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus); \n\n var documentedUserValue = mvObjects.getObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"TextEdit\\\", \\\"\\\", 1)\", \"Text\",exestatus); \n \n if(aqString.Compare(savedUservalue,documentedUserValue,false) ==0)\n {\n Log.Checkpoint(\"Saved by user details are matching\");\n }\n else\n {\n Log.Error(\"Saved by user details are not matched\");\n exestatus =false;\n }\n\texestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"sessionscontrol\\\")\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_1\\\")\",\"Value\",\"160\", \"Height\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_2\\\")\",\"Value\",\"80\", \"WeightLatest\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_3\\\")\",\"Value\",\"80\", \"WeightAdmission\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_6\\\")\",\"Value\",\"80\", \"WeightDrug\",exestatus);\n //Below values are moved from here\n //exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_4\\\")\", \"BindableValue\",\"57.2\", \"WeightIdeal\",exestatus);\n //exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtNumeric_5\\\")\", \"BindableValue\",\"66.3\", \"WeightAdjusted\",exestatus);\n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_1\\\")\", \"Text\",\"31.2\", \"bmi\",exestatus); \n exestatus = mvObjects.verifyObjectProperty(vProcess, \"Name\", \"WPFObject(\\\"txtFreeText_2\\\")\", \"Text\",\"1.833\", \"bsa\",exestatus);\n \n\t// close the form \n exestatus = mvObjects.buttonClick(vProcess, \"Name\", \"WPFObject(\\\"cmdCancel\\\")\",exestatus);\n \n if (equal(exestatus,true)) {\n\t \t Log.Checkpoint(\" BSAAutomaticallyCalculated is successful\");\n Log.Checkpoint(\"End BSAAutomaticallyCalculated\",\"The flow is completed\");\n \n }\n }\n else {\n Log.Message(\"Skipped BSAAutomaticallyCalculated\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n \n }\n return exestatus;\n \n}",
"function starting_game_parameters_1(game) {\n return {\n scroll_point: 5,\n target_wpm: 20,\n min_accuracy: 60,\n }\n}",
"function MvEnterDataVitalSignsForANZICS(TestName,exestatus)\n{\n \n//Controller for executing or skipping the feature\nif (equal(exestatus,true)) {\n\nvar tcDesc = Data.getData(TestName,\"NursingCare\",\"TC_DESC\");\nLog.Checkpoint(\"Start EnterPathology documentation for \"+tcDesc ,\"The flow is started\");\n//Start of the feature \n \n \nvProcess = Sys.Process(\"iMDSoft.Metavision\");\n \n //Go to vital signs tab\n exestatus = mvObjects.buttonClick(vProcess,\"Name\",\"WPFObject(\\\"TabItem\\\", \\\"\\\", 3)\",exestatus);\n aqUtils.Delay(1000);\n //enter data for Sys BP\n \n \n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"TabularGridTChart\\\").WPFObject(\\\"MainCanvas\\\").WPFObject(\\\"Canvas\\\", \\\"\\\", 1).WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1715,72,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(102);\n aqUtils.Delay(10000);\n //enter data for Dias BP\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1715,99,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(92);\n //aqUtils.Delay(1000);\n //enter data for MAP\n exestatus = mvObjects.doubleclick(vProcess,\"FullName\", \"*WPFObject(\\\"PicContainerAll\\\").WPFObject(\\\"PicContainer\\\").WPFObject(\\\"tChartConcrol\\\")\",1715,114,exestatus);\n Aliases.iMDSoft_Metavision.HwndSource_root.root.FloatingDockPanel.Grid.Items.ContentControl.Grid.Items.WPFObject(\"TabView\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"proportionalStack\").WPFObject(\"ContentControl\", \"\", 1).WPFObject(\"Grid\", \"\", 1).WPFObject(\"viewBorder\").WPFObject(\"viewPlaceHolder\").WPFObject(\"TabularGridTChart\").WPFObject(\"MainCanvas\").WPFObject(\"Canvas\", \"\", 1).WPFObject(\"PicContainerAll\").WPFObject(\"PicContainer\").WPFObject(\"tChartConcrol\").Keys(82);\n\n \n if (equal(exestatus,true)) {\n Log.Checkpoint(\" successfully initiated MvEnterDataVitalSignsForANZICS\");\n Log.Checkpoint(\"End MvEnterDataVitalSignsForANZICS\",\"The flow is completed\");\n }\n }\n else {\n Log.Message(\"Skipped MvEnterDataVitalSignsForANZICS\",\"The feature is skipped since the execution status is set as '\"+exestatus+\"'\"); \n \n }\n return exestatus;\n \n}",
"function getParameterValue(desired /*true if desired*/, intent, session, callback) {\n var cardTitle = intent.name;\n var parameter = intent.slots.parameter.value;\n var sessionAttributes = {};\n var repromptText = \"\";\n var shouldEndSession = true;\n var speechOutput = \"\";\n\n // Check user request for validity.\n var parameterLowerCase = parameter.toLowerCase(); // no guarantee that Alexa ASR will return value in lower case\n var isValidParameter = checkIfParamIsValid(parameterLowerCase);\n\n if (isValidParameter) { // parameter valid\n var foodcomputerParam = alexaParamToFoodcomputerParam(parameterLowerCase);\n //console.log(\"FCParam: \" + foodcomputerParam);\n\n const method = \"GET\",\n path = \"/environmental_data_point/_design/openag/_view/by_variable?group_level=3\",\n postData = \"\";\n\n httpReq (method, path, postData, function (resStr) {\n var obj = JSON.parse(resStr);\n var paramValue = NaN;\n for (var i = 0; i < obj.rows.length; i++) { // search json obj for the requested information\n if (obj.rows[i].value.variable === foodcomputerParam && \n obj.rows[i].value.is_desired === desired) { // found a match\n paramValue = obj.rows[i].value.value;\n break;\n }\n }\n //console.log(\"value: \" + paramValue);\n\n var paramValueOut = (paramValue === 0 ? paramValue : paramValue.toFixed(2)); // make it sound nice\n\n if (!isNaN(paramValueOut)) {\n speechOutput = \"the value of \" + (desired ? \"desired \" : \"measured \") + parameterLowerCase +\n \" is \" + paramValueOut + \" \" + getParamUnits(foodcomputerParam);\n } else {\n speechOutput = \"error, could not get the value of \" + (desired ? \"desired \" : \"measured \") +\n parameterLowerCase;\n }\n\n callback(sessionAttributes,\n buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));\n });\n } else { // parameter not valid\n speechOutput = \"error, \" + parameterLowerCase + \" is not a valid parameter\";\n callback(sessionAttributes,\n buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a csv row from an array | function csv(array){
// this is not a world class csv generator
return array.map(function(item){
return typeof(item) === 'string' ?
item.replace(/[\",]/g,'') :
item;
}).join(',')
} | [
"function csv(array){\n\n // this is not a world class csv generator\n return array.map(function(item){\n return typeof(item) === 'string' ?\n item.replace(/[\\\",]/g,'') :\n item;\n }).join(',');\n}",
"function CSV(array) {\n // Use first element to choose the keys and the order\n var keys = Object.keys(array[0]);\n\n // Build header\n var result = keys.join(\",\") + \"\\n\";\n\n // Add the rows\n array.forEach(function (obj) {\n keys.forEach(function (k, ix) {\n if (ix) result += \"\\t\";\n result += obj[k];\n });\n result += \"\\n\";\n });\n\n return result;\n}",
"function convertToCSV(arr){\n\n}",
"function arrayToCsv(array) {\n var csvRow = [];\n for (var i = 0; i < array.length; i++) {\n csvRow.push(array[i].join(','));\n }\n var csvString = csvRow.join(\"\\r\\n\");\n\n return csvString;\n }",
"function genCSV(rows) {\n return rows.map(row =>\n [row.year, row.month, row.day, row.time, row.no, row.name, row.name_ja, row.t1 || \"\", row.t5 || \"\", row.t20 || \"\", row.t100 || \"\", row.t500 || \"\"]\n .join(\",\")\n ).join(\"\\n\");\n}",
"function arrayToCSV(arr) {\n let csvContent = 'data:text/csv;charset=utf-8,';\n arr.forEach(row => {\n csvContent += row.join(',') + '\\r\\n';\n });\n\n const URI = encodeURI(csvContent);\n const link = document.createElement('a');\n link.setAttribute('href', URI);\n link.setAttribute('download', 'dataset.csv');\n document.body.appendChild(link);\n link.click();\n}",
"function arrayToCSV (req.body) {\n csv = data.map(row => Object.values(row));\n csv.unshift(Object.keys(data[0]));\n result= csv.join('\\n');\n }",
"function _convertArrayToCSV(arr) {\n return arr.join(',').replace(/\\r?\\n/g, ' ');\n}",
"function ArrayToCSV(data) {\n var csv = data.map(function(line) {\n return line.join(\",\");\n })\n\n return csv.join(\"\\n\");\n}",
"function objectsToCSV(array) {\n // Use first element to choose the keys and the order\n var keys = Object.keys(array[0]);\n\n // Build header\n var result = keys.join(\"\\t\") + \"\\n\";\n\n // Add the rows\n array.forEach(function(obj){\n keys.forEach(function(k, ix){\n if (ix) result += \"\\t\";\n result += obj[k];\n });\n result += \"\\n\";\n });\n\n return result;\n}",
"function genCSVArray(){\n\tlet csvArray = []\n\tcsvArray.push(\"Date\",\",\",\"Amount\",\"\\n\")\n\tpayments.forEach(payment => {\n\t\tif(payment.type == \"payment\"){\n\t\t\tcsvArray.push(\n\t\t\t\tpayment.date,\n\t\t\t\t\",\",\n\t\t\t\tpayment.amount,\n\t\t\t\t\"\\n\"\n\t\t\t)\n\t\t}\n\t});\n\treturn csvArray\n}",
"function generateInqueryCSV(inquiry_array) {\n\t// console.log(data);\n\n\tvar writer = csvWriter({sendHeaders: false});\n\twriter.pipe(fs.createWriteStream(INQUIRY_FILE));\n\tvar i = 0;\n\tfor (; i < inquiry_array.length; i++) {\n\t\tvar certPem = inquiry_array[i].cert;\n\t\tvar keyObj = rs.KEYUTIL.getKey(inquiry_array[i].cert);\n\t\tvar privKey = keyObj.prvKey;\n\t\tvar msg_hash = getHashMessage(inquiry_array[i].userId);\n\t\tvar signed_hash = getSignedHash(msg_hash, privKey);\n\t\tvar certPemString = certPem.replace(/[^\\x20-\\x7E]/gmi, \"\");\n\n\t\twriter.write({'id': inquiry_array[i].userId, 'hash': msg_hash, 'signedhash': signed_hash, 'cert': certPemString});\n\t}\n\twriter.end();\n\n\tconsole.log('total: ' + inquiry_array.length);\n}",
"function convert2csv(array, columnsConfig, locale) {\n locale = locale || 'fr';\n if (!columnsConfig) {\n columnsConfig = Object.keys(array[0]);\n }\n var columns = columnsConfig.map(function(col) {\n if (typeof(col) === 'string') {\n return {\n id: col,\n label: col\n };\n } else {\n return col;\n }\n });\n\n // header line\n var header = array2csvLine(columns.map(function(col) {\n return col.label;\n }));\n\n // body\n var body = array.reduce(function(csv, item) {\n var values = columns.map(function(col) {\n return item[col.id];\n });\n return csv += array2csvLine(values, locale);\n }, '');\n return header + body;\n}",
"function createCSV(filename, rows) {\n var processRow = function (row) {\n var finalVal = '';\n for (var j = 0; j < row.length; j++) {\n var innerValue = row[j] === null ? '' : row[j].toString();\n if (row[j] instanceof Date) {\n innerValue = row[j].toLocaleString();\n };\n var result = innerValue.replace(/\"/g, '\"\"');\n if (result.search(/(\"|,|\\n)/g) >= 0)\n result = '\"' + result + '\"';\n result = result.replace(/é|è/g, 'e');\n result = result.replace(/°/g, 'um');\n result = result.replace(/€/g, 'euros');\n if (j > 0)\n finalVal += ',';\n finalVal += result;\n }\n return finalVal + '\\n';\n };\n\n var csvFile = '';\n for (var i = 0; i < rows.length; i++) {\n csvFile += processRow(rows[i]);\n }\n\n var blob = new Blob([csvFile], { type: 'text/csv;charset=ANSI;' });\n if (navigator.msSaveBlob) { // IE 10+\n navigator.msSaveBlob(blob, filename);\n } else {\n var link = document.createElement(\"a\");\n if (link.download !== undefined) { // feature detection\n // Browsers that support HTML5 download attribute\n var url = URL.createObjectURL(blob);\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", filename);\n link.style.visibility = 'hidden';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n hideAnimate(loadingScreen);\n}",
"function createCSV() {\n let data = [[\n 'EmployerName',\n 'EventId',\n 'EventName',\n 'DisplayPriority',\n 'RewardType',\n 'PointsAwarded',\n 'RewardDescription',\n 'AllowSameDayDuplicates',\n 'IsOngoing',\n 'IsDisabled',\n 'ShowInProgram',\n 'IsSelfReport',\n 'DataFeedMode',\n 'Notify',\n 'ButtonText',\n 'TargetUrl',\n 'EventImageUrl',\n 'MaxOccurrences',\n 'StartDate',\n 'EndDate',\n 'ViewPages',\n 'Dimensions',\n 'ShortDescription',\n 'HtmlDescription',\n 'SubgroupId',\n 'Field1Name',\n 'Field1Value',\n 'Field2Name',\n 'Field2Value',\n 'Field3Name',\n 'Field3Value'\n ]];\n\n\n const employerName = $('#employerName').val();\n\n const eventName = $('#eventName').val();\n const eventId = $('#eventId').val();\n const pointsAwarded = $('#pointsAwarded').val();\n const maxOccurrences = $('#maxOccurrences').val();\n\n const cie = [\n employerName,\n eventId,\n '\"' + eventName + '\"',\n '',\n 'IncentivePoints',\n pointsAwarded.replace(',', ''),\n '',\n '1',\n '0',\n '0',\n '0',\n '0',\n '0',\n '0',\n '',\n '',\n '',\n maxOccurrences,\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n ''\n ];\n\n data.push(cie);\n\n return data;\n }",
"function build_csv_string() {\n\n // Init string\n let ret_string = \"\";\n\n for(let i=0; i<headers.length; i++) {\n\n let value = row_obj[headers[i]];\n\n // Don't log undefined values\n if (value !== undefined) {\n\n // So array elements don't get treated as variables in csv\n if (Array.isArray(value)){\n value = \"\\\"[\" + value.toString() + \"]\\\"\"\n }\n\n // Append value\n ret_string += value\n }\n\n // New line on last value, comma otherwise\n if (i === headers.length - 1) {\n ret_string += \"\\n\";\n } else {\n ret_string += \",\";\n }\n }\n\n // Log CSV string\n console.log(\"ret_string:\", ret_string)\n\n return ret_string;\n }",
"function csvFormatAdjust(array) {\r\n var newArray = []\r\n for (var n = 0; n < array.length; n++) {\r\n newEntry = [\r\n array[n][0],\r\n array[n][6],\r\n array[n][2],\r\n array[n][4],\r\n array[n][5],\r\n array[n][3],\r\n array[n][5],\r\n array[n][9],\r\n array[n][19], // Renter\r\n array[n][23], // Renter\r\n array[n][24], // Renter\r\n array[n][22], // Renter\r\n array[n][14],\r\n array[n][15],\r\n array[n][16],\r\n array[n][17]\r\n ]\r\n\r\n newArray.push(newEntry)\r\n }\r\n\r\n return newArray\r\n}",
"_createCsvData() {\n const oThis = this;\n\n if (oThis.replyDetailIds.length === 0) {\n console.log('No data present for this parent video.');\n return;\n }\n\n const csvDataArray = [];\n\n const headerRow = ['user_id', 'user_name', 'name', 'reply_share_url', 'total_amount'];\n\n csvDataArray.push(headerRow);\n\n for (let ind = 0; ind < oThis.replyDetailIds.length; ind++) {\n const replyDetailId = oThis.replyDetailIds[ind],\n replyDetails = oThis.replyDetailsMap[replyDetailId],\n creatorUserId = replyDetails.creator_user_id,\n creatorUserDetails = oThis.userDetailsMap[creatorUserId],\n replyShareUrl = oThis.replyShareUrlsMap[replyDetailId];\n\n const row = [\n creatorUserDetails.id,\n creatorUserDetails.user_name,\n creatorUserDetails.name,\n replyShareUrl,\n basicHelper.convertWeiToNormal(replyDetails.total_amount)\n ];\n\n csvDataArray.push(row);\n }\n\n for (let ind = 0; ind < csvDataArray.length; ind++) {\n // Print csv data for now.\n console.log(\n `${csvDataArray[ind][0]},${csvDataArray[ind][1]},${csvDataArray[ind][2]},${csvDataArray[ind][3]},${\n csvDataArray[ind][4]\n }`\n );\n }\n }",
"function nestedArrayToCSV(nestedArray) {\n let lineArray = [];\n let header = []\n\n for (let i = 0; i < jsonQuestions.length; i++) {\n header.push(jsonQuestions[i].questionTag);\n }\n\n nestedArray.unshift(header);\n\n for (let i = 0; i < nestedArray.length; i++) {\n var line = nestedArray[i].join(\",\");\n lineArray.push(line);\n }\n\n var csvContent = lineArray.join(\"\\n\");\n console.log(`csv:\\n${csvContent}`);\n return csvContent;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The await keyword can be used to block asynchronous functionality Normally, JavaScript is nonblocking and executes the rest of the code as asynchronous code like promises are handled in the background. But the await keyword allows you to wait for the promise to resolve or reject before executing the following code | async function test() { // to use await, it must be in a function marked by the async keyword
try { // try/catch is used to handle resolved/rejected promises
const boomerangStatus = await boomerang; // this blocks the following console.log
console.log('boomerangStatus', boomerangStatus);
} catch(error) {
console.log('error', error);
}
} | [
"async function awaitTest() {\n try {\n // call async function with await, this pause the async function execution until primose resolved\n const result = await asyncOperation()\n console.log(result)\n } catch (e) {\n console.error(e)\n }\n}",
"async function awaitAsyncCall() {\n\t//\n\tlet result = await request();\n\tlet result2 = await request();\n}",
"async function ejecutarEjercicioAsyncAwait(){\n\n}",
"async function callTheFunctionUsingPromisesUsingAsyncAwait() {\n try {\n console.log(\"Just before the await\");\n var result = await callbackdoneasapromise(\"hello\");\n console.log(\"this is AFTER AWAIT \" + result);\n }\n catch(err) {\n console.log(\"looks like the promise didn't work out\" + err);\n }\n}",
"async function myFn(){\n // since this is an async function it unlocks the use of the 'await' keyword\n}",
"async function doIt() {\n await askMom4();\n}",
"async function getArticles() {\n let result = await 'test'\n return result\n}",
"async function awaitFetchData() {\n let returnedData = await fetchData();\n console.log(returnedData);\n}",
"function awaitingE1L1ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(){;}",
"async function noAwait() {\n let value = myPromise();\n console.log(value);\n}",
"async function ej3() {\n var res = await prom();\n console.log(res);\n}",
"async function funcionConPromesaYAwait(){\n let miPromesa = new Promise( resolver => {\n resolver('Promesa con await');\n });\n\n console.log( await miPromesa );\n}",
"async function getBlogPostAw() {\n //Promise CONSTRUCTOR with callback (resolve, reject)\n const promise = new Promise((resolve, reject) => {\n //mimik an API call with setTimeout:\n setTimeout(() => resolve(\"async-await blog post\"), 1000);\n });\n // await tells the function to pause until the\n //promise is resolved and then use the resolved\n //value.\n //AWAIT for promise to be resolved\n const result = await promise;\n console.log(result); //async-await blog post\n console.log(\"done with async-await\"); //done with async-await\n}",
"async function asyncFuncExample(){\n let resolvedValue = await myPromise();\n console.log(resolvedValue);\n }",
"async function cobaAsync() {\r\n try {\r\n await testAsyncAwait().then(e => console.log(e))\r\n } catch (error) {\r\n console.error(error);\r\n }\r\n}",
"async function funcionConPromesaYAwait(){\n let miPromesa=new Promise(resolver=>{\n resolver(\"Promesa con await\");\n });\n console.log(await miPromesa);\n}",
"async function task(){\n // if we call one promise without the await keyword vo baki sab ke sath parallel chahla gha\n // prmse(3,\"anita\") ye hata ke dekh samaj me aaye gha \n await prmse(3,\"aman\")\n await prmse(3,\"bablu\")\n await prmse(3,\"annu\")\n await prmse(3,\"renu\")\n await prmse(3,\"tona\")\n await prmse(3,\"banti\")\n \n}",
"async function asyncAwaitMain() {\n console.log(\"Before\");\n try {\n const user = await getUser(1);\n const repos = await getRepos(user.gitHubUsername);\n const stars = await getRepoStars(repos);\n console.log(\"stars: \", stars);\n } catch (err) {\n console.log('err: ', err.message)\n }\n\n console.log(\"After\");\n}",
"async function myAsync(){\n let myPromise = new Promise(function (myResolve, _myError) {\n setTimeout(function(){ myResolve(\"Hello Moto\")},3000);\n });\n document.getElementById(\"asyncawait\").innerHTML= await myPromise;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will retrieve our speakers list for displaying | getAllSpeakers() {
return speakers;
} | [
"async getAvailableSpeakers() {\n const headers = this.key\n ? { Authorization: `Bearer ${this.key}` }\n : undefined;\n\n try {\n const response = await axios({\n url: `${VOICERY_URL}/speakers`,\n method: \"get\",\n headers\n });\n return response.data;\n } catch (error) {\n throw new VoiceryError(error);\n }\n }",
"function retrieveSpeakers() {\n var speakersRef = firebase.database().ref().child(\"speakers\").orderByChild(\"name\");\n\n speakersRef.once('value', function (snapshot) {\n snapshot.forEach(function (childSnapshot) {\n var speaker = childSnapshot.val();\n speakers[speaker.id] = speaker;\n });\n\n retrieveSessions();\n });\n }",
"get speakers(){\n return this._lastSpeakers\n }",
"function populateVoiceList() {\n var systemVoices = speechSynthesis.getVoices();\n\n for(var i = 0; i<systemVoices.length; i++) {\n voices.push(new voiceObj(systemVoices[i].name, systemVoices[i].lang));\n }\n }",
"function getSongList(){\n\t\t\tSongSheetAPI.index(\n\t\t\t\tfunction success(data){\n\t\t\t\t\tconsole.log('success', data);\n\t\t\t\t\t$scope.songSheets = data;\n\t\t\t\t},\n\t\t\t\tfunction error(data){\n\t\t\t\t\tconsole.log('error', data);\n\t\t\t\t}\n\t\t\t);\n\t\t}",
"function getVoices() {\n voices = speechSynthesis.getVoices(); // get array of speaking voices from speechSynethesis\n voices.forEach((voice) => {\n const option = document.createElement(\"option\"); // create option element\n option.value = voice.name; // impart value to option tag\n option.innerText = `${voice.name} - ${voice.lang}`; // Add Text for Option\n voiceSelectEl.appendChild(option); // Add option to VoiceSelect Element\n });\n }",
"function getPlaylists() {\n\tconsole.log(\"getPlaylists.\");\n\taudioboxDB.getPlaylists();\n}",
"getPlaylists() {\n this.makeGETRequest('getplaylists','playlistsloaded','playlists')\n }",
"_allPersistedSpeakers() {\n return this.store.findAll('speaker').then(() => {\n return this.store.filter('speaker', function(speaker) {\n return !speaker.get('isNew');\n });\n });\n }",
"populateVoiceList () {\n const systemVoices = window.speechSynthesis.getVoices();\n systemVoices.forEach((voice) => {\n const { name, lang } = voice;\n const voiceObject = new VoiceObject({ name, lang });\n this.voices.push(voiceObject);\n });\n }",
"async function populateVoiceList(synth) {\n try {\n const voices = await synth.getVoices().sort(function (a, b) {\n const aname = a.name.toUpperCase()\n const bname = b.name.toUpperCase()\n if (aname < bname) return -1\n else if (aname === bname) return 0\n else return +1\n })\n return voices\n } catch (error) {\n throw new Error(\"Failure retrieving voices\")\n }\n}",
"function getPlaylistNames() {\n\tconsole.log(\"getPlaylistNames.\");\n\taudioboxDB.getPlaylistNames();\n}",
"retrievePublishersList() {\n return thegamesDbApi.retrievePublishersList();\n }",
"populateVoiceList() {\n this.selSpeechVoice.innerHTML = '';\n let voices = RAG.speech.browserVoices;\n // Handle empty list\n if (voices === {}) {\n let option = DOM.addOption(this.selSpeechVoice, L.ST_SPEECH_EMPTY);\n option.disabled = true;\n }\n // https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis\n else\n for (let name in voices)\n DOM.addOption(this.selSpeechVoice, `${name} (${voices[name].lang})`, name);\n }",
"function getStreamers(){\n return users;\n}",
"function getAdvertisers() {\n getAudiencesController().fetchAndOutputAdvertisers();\n}",
"function getPlaylists (response) {\n var playlistLink = 'https://api.spotify.com/v1/users/' + response.id +'/playlists';\n addPlaylist(playlistLink); //append each playlist to an unordered list\n }",
"function songsList()\n\t\t\t{\n\t\t\tMusic.call(songsList);\n\t\t\t}",
"function populateVoiceList() {\n\t// Get list of voices\n\t// The list of voices is browser dependent and we cannot expect\n\t// any single voice to exist.\n\tvoices = synth.getVoices();\n\tvar selectedIndex =\n\t\tvoiceSelect.selectedIndex < 0 ? 0 : voiceSelect.selectedIndex;\n\tvoiceSelect.innerHTML = '';\n\n\t// Populate list per option\n\tfor (i = 0; i < voices.length; i++) {\n\t\tvar option = document.createElement('option');\n\t\toption.textContent = voices[i].name + ' (' + voices[i].lang + ')';\n\n\t\tif (voices[i].default) {\n\t\t\toption.textContent += ' -- DEFAULT';\n\t\t}\n\n\t\toption.setAttribute('data-lang', voices[i].lang);\n\t\toption.setAttribute('data-name', voices[i].name);\n\t\tvoiceSelect.appendChild(option);\n\t}\n\tvoiceSelect.selectedIndex = selectedIndex;\n\n\t// tbh no idea what this does\n\tif (speechSynthesis.onvoiceschanged !== undefined) {\n\t\tspeechSynthesis.onvoiceschanged = populateVoiceList;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add new subject ID to JSON file (main file to be converted to excel) | function addSubjectIDToJSON(subjectID) {
if ($("#form-add-a-subject").length > 0) {
addTheRestSubjectEntriesToJSON();
}
} | [
"function modJson(id, newEntry) {\n json.id = newEntry\n}",
"function storeSubjectName(){\n\n\tsubjectHeader = splitURI(dbJson).split('.')[0];\n}",
"function addSentenceToJson(singleSentence, givenJson){\n var myId = givenJson.data.documents.length + 1;\n myId = myId.toString(10);\n givenJson.data.documents.push({\"language\":\"en\",\"id\":myId,\"text\":singleSentence})\n return givenJson;\n}",
"function add() {\n const json = require(jsonPath);\n const title = process.argv[3];\n const body = process.argv[4];\n\n if (findTitle(json, title) === -1) {\n const note = {\n \"title\": title,\n \"body\": body\n };\n \n json.push(note);\n fs.writeFile(jsonPath, JSON.stringify(json), (err) => {\n if (err) {\n throw err;\n }\n });\n \n console.log(`ADD : \"${title}\" : \"${body}\"`);\n } else {\n console.log(\"This note is already written\");\n }\n}",
"function addSubj() {\n\t\n\tsaveSubject(false);\n\t\n\tg_curSubject = new Object();\n\tg_curSubject.civId = uniqid(); //new subject ID:\n\t\n\tg_curIncident.subjects.push(g_curSubject); //add subject to incident.\n\t\n\tsetSubjectVals();\n\tsetSubjSelect();\n\t\n}",
"function addSubject(subjectID){\n\t// Create a new object to store the subject\n\tvar subject = {};\n\n\t// Thanks to UF's dumb registrar page, the subjectID and subjectName\n\t// are the same. Woo, go outdated technology!\n\tsubject.subjectID = subjectID;\n\t// Leave the subject name out so we don't display it twice\n\tsubject.subjectName = ' ';\n\n\t// Push the completed subject object onto the global subjects list\n\tsubjects.push(subject);\n}",
"function addContact(name, email, phone) {\n const id = uuidv4();\n fs.readFile(contactsPath, \"utf-8\", (error, data) => {\n try {\n const contactsData = JSON.parse(data);\n let changedData = [];\n\n const contactWithId = contactsData.map(contact => {\n changedData.push(contact);\n return changedData;\n });\n\n changedData.push({ id, name, email, phone });\n console.table(changedData);\n\n fs.writeFile('./db/contacts.json', JSON.stringify(changedData), (err, changedData) => {\n if (err) {\n console.log(err);\n }\n })\n } catch (error) {\n console.log('listContacts error', error)\n }\n })\n}",
"function addFileToMaster(jwt_text) {\n blockstack.getFile(UNIVERSAL_RECORD_KEEPING_FILE_NAME).then((fileContents) => {\n var parsed = JSON.parse(fileContents);\n //parse the current tracking file and add the new contents\n var arr = [];\n for (var i = 0; i<parsed.files.length; i++) {\n arr[i] = parsed.files[i];\n }\n arr.push(jwt_text);\n //reset the array to include the new value\n parsed.files = arr;\n var str = JSON.stringify(parsed);\n //write the new file\n blockstack.putFile(UNIVERSAL_RECORD_KEEPING_FILE_NAME, str).then(() => {\n location.reload();\n });\n });\n}",
"addSubject(subject, emailId){\n /** invert subject to reduce number of compare\n * operations to merge mails to threads*/\n let rsubject = subject.split('').reverse().join('');\n if(this.subjects.has(rsubject)){\n let ids = this.subjects.get(rsubject);\n ids.push(emailId);\n this.subjects.set(rsubject, ids);\n }else{\n this.subjects.set(rsubject, [emailId]);\n }\n }",
"function setTaskTitle(taskFileInJson){\r\n taskTitle = '{\"title\":' +JSON.stringify(taskFileInJson.title)+'}';\r\n \r\n}",
"function updateLocalJSON() {\n dataJsonFileStream.open(Ti.Filesystem.MODE_WRITE);\n dataJsonFileStream.write('{\"currentMaxID\":' + currentMaxID + ',\"scraps\":' + JSON.stringify(scraps) + '}');\n dataJsonFileStream.close();\n}",
"function genArticleIds() {\n const articleIds = {}\n fileNames.forEach(fileName => {\n const slug = fileName.split('_')[1]\n articleIds[slug] = fileName\n })\n const json = JSON.stringify(articleIds, undefined, 2)\n fs.writeFileSync(path.join(process.cwd(), 'gen/articleIds.json'), json)\n console.log(logColors.cyan + '[script:build]' + logColors.white + ' articleIds.json' + logColors.reset)\n}",
"writeAppointJson(){\n \n var obj = {\n appoint : []\n }\n for(let i = 0;i<this.Appoint.length;i++)\n {\n obj.appoint.push(this.Appoint[i])\n }\n \n oop_utility.data.writeFile(\"../JsonFiles/appointment.json\",obj)\n }",
"saveArticle(article, sentiment) {\n const articleDatabase = `${__dirname}/articles.json`;\n var articleJson;\n var rawText = \"\";\n\n if (fs.existsSync(articleDatabase)) {\n rawText = fs.readFileSync(articleDatabase); // read in the existing json\n }\n\n if (rawText.length > 0) {\n articleJson = JSON.parse(rawText);\n } else {\n articleJson = {articles: []};\n }\n\n var alreadyInJson = false;\n\n articleJson.articles.forEach(function(data) {\n if (data.url == article.url) {\n alreadyInJson = true; // if the article is already in the json then skip it\n }\n });\n \n if (alreadyInJson) {\n return;\n }\n\n var newArticleInfo = { // format the json for the article\n source: article.source.name,\n author: article.author,\n title: article.title,\n description: article.description,\n url: article.url,\n image: article.urlToImage,\n date: article.publishedAt,\n sentiment: sentiment\n };\n\n articleJson.articles.push(newArticleInfo); // add it to the json file\n\n var toWrite = JSON.stringify(articleJson, null, 2);\n fs.writeFileSync(articleDatabase, toWrite); // write back to the file\n\n }",
"function addQuestion(category, qu, ans, authorID) \n{\n //Open the JSON file\n fs.readFile(questionsFile, 'utf8', function read(err, data){\n if(err) {\n console.log(err)\n } \n else {\n let qFile = JSON.parse(data); //Read file into a json object\n qFile.questions.push({ //Add question to the questions array\n cat: category,\n question: qu,\n answer: ans,\n author: authorID\n });\n let qOut = JSON.stringify(qFile, null, 4); //Rewrite the file\n fs.writeFile(questionsFile, qOut, function(err){console.log(err);});\n }\n });\n}",
"function BuildSubjectList() {\n\tvar lst = new Array();\n\tvar taken = {};\n\n\tvar z = String(fs.readFileSync('recordings.htm'));\n\tz = z.split('\\n');\n\tfor (var i = 0; i < z.length; i++) {\n\t\tvar a = z[i].indexOf('\">') + 2;\n\t\tvar dash = z[i].indexOf(' - ')\n\t\tvar code = z[i].substr(a, dash - a);\n\t\tvar name = z[i].substr(dash + 3, z[i].indexOf('</a>') - dash - 3);\n\n\t\t// Check if we already have this subject:\n\t\tif (!taken[code]) {\n\t\t\tlst.push(code + ' ' + name);\n\t\t}\n\n\t\t// Stop same subject appearing twice:\n\t\ttaken[code] = true;\n\t}\n\n\tvar fin = JSON.stringify(lst);\n\n\t// Store the results:\n\tfs.writeFile('subjects.json', fin, function (err) {\n\t\tif (err) {\n\t\t\tconsole.log(err);\n\t\t}\n\t});\n}",
"saveJSON (fileName, data) {\n fs.writeFileSync(path.join(__dirname, '..', 'data', fileName), JSON.stringify(data))\n }",
"function addSubject() {\n let subjectname = $('input[name=\"subject_name\"]');\n let subject = {\n subjectname: subjectname.val()\n };\n let subref = firebase\n .database()\n .ref(\"portal_db/courses\")\n .child(_courseID)\n .child(\"subjects\");\n\n subject.subjectID = subref.push().key;\n subref.child(subject.subjectID).set(subject);\n subjectname.val(\"\");\n listSubjectList();\n}",
"function addContact(name, email, phone) {\n fs.readFile(contactsPath, 'utf-8')\n .then((data) => {\n const contacts = JSON.parse(data);\n const newContact={id: nanoid(5), name, email, phone}\n const newContactsList = [...contacts, newContact];\n fs.writeFile(contactsPath, JSON.stringify(newContactsList))\n .then(() => console.log(`contact ${name} was successfully added`))\n .catch((err)=>console.log(err.message));\n })\n .catch((err)=>console.log(err.message))\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get all core courses from programme courses | function getCoreCourses(courses) {
var core = [];
for (var i=0; i<courses.length; i++) {
if (courses[i].type === "Core") {
core.push(courses[i]);
}
}
return core;
} | [
"function returnCourses(){\n\treturn allCourses\n}",
"function courses () {\n const api = require('./api')\n\n return api.courses.getCourseNames().map(course => {\n return {\n type: TYPES.COURSE,\n path: `/course/${course}/`,\n sitemap: { priority: 1, changefreq: 'monthly', lastmod }\n }\n }).map(addSitemapLoc)\n}",
"getAllCourses() {\r\n return courses().then((courseCollection) => {\r\n return courseCollection.find({}).toArray();\r\n });\r\n }",
"function listCourses() {\n var courses = [];\n var pageToken = null;\n var optionalArgs = {\n pageToken: pageToken,\n pageSize: 100\n };\n while (true) {\n var response = Classroom.Courses.list(optionalArgs);\n var courses = response.courses;\n if (!pageToken) {\n break;\n }\n }\n if (courses.length === 0) {\n Logger.log(\"No courses found.\");\n } else {\n Logger.log(\"Courses:\");\n for (course in courses) {\n Logger.log('%s (%s)', courses[course].name, courses[course].id);\n }\n }\n}",
"async function getMajorOptionCoursesList(_dbo, _subjectArea, _majorOption){\n var coursesArr = [];\n var majorOptions = await _getCoursesForMajorOption(_dbo, _subjectArea, _majorOption);\n for(var key in majorOptions){\n var mo = majorOptions[key];\n for(var k2 in mo){\n var cat = mo[k2].categories;\n for(var k3 in cat){\n var courses = cat[k3].courses;\n for(var c in courses){\n var courseName = courses[c];\n coursesArr.push({name:courseName})\n }\n }\n\n }\n\n }\n\nreturn coursesArr;\n\n}",
"function listCourses() {\n console.log('It is hitting listCourses')\n var request = gapi.client.classroom.courses.list({\n pageSize: 10\n });\n\n request.execute(function(resp) {\n var courses = resp.courses;\n appendPre('Courses:');\n\n if (courses.length > 0) {\n for (i = 0; i < courses.length; i++) {\n var course = courses[i];\n appendPre(course.name)\n }\n } else {\n appendPre('No courses found.');\n }\n\n });\n }",
"getAllCourses() {\n return this.courses;\n }",
"async scrapeCourses() {\n\t\tlet course_array = [];\n\n\t\ttry {\n\t\t\tconst courses = await this.agent\n\t\t\t\t.get(this.get_course_url)\n\t\t\t\t.query({ courses_filter: 'learning', category_id: 8 });\n\n\t\t\tfor (const course in courses.body['courses']) {\n\t\t\t\t// console.log(courses.body['courses'][course]['slug'])\n\t\t\t\t// console.log(courses.body['courses'][course]['url'])\n\t\t\t\tcourse_array.push({\n\t\t\t\t\tid: courses.body['courses'][course]['id'],\n\t\t\t\t\tname: courses.body['courses'][course]['name'],\n\t\t\t\t\turl: courses.body['courses'][course]['url'],\n\t\t\t\t});\n\t\t\t}\n\t\t\t//console.log(course_array)\n\t\t\treturn course_array;\n\t\t} catch (err) {\n\t\t\t//console.log(err)\n\t\t\treturn null;\n\t\t}\n\t}",
"function listCourses() {\r\n\t\tgapi.client.classroom.courses.list({\r\n\t\t\tpageSize: 10\r\n\t\t}).then(function(response) {\r\n\t\t\tvar courses = response.result.courses;\r\n\t\t\tappendPre('Courses:');\r\n\t\t\tif(courses.length > 0) {\r\n\t\t\t\tfor(i = 0; i < courses.length; i++) {\r\n\t\t\t\t\tvar course = courses[i];\r\n\t\t\t\t\tappendPre(course.name)\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tappendPre('No courses found.');\r\n\t\t\t}\r\n\t\t});\r\n\t}",
"async getCourses() {\n const response = await this.api('/courses', 'GET', null);\n if (response.status === 200) {\n return response.json().then(data => {\n return data.courses;\n });\n }\n }",
"function loadCourses() {\n // Get Courses List\n $http({\n method: 'GET',\n url: '/api/v0/school/courses/list'\n }).then(function successCallback(response) {\n $scope.courses = response.data['courses'];\n return $scope.courses.map(function(course) {\n course._lowername = course.name.toLowerCase();\n course._lowertype = course._id.toLowerCase();\n return course;\n });\n }, function errorCallback(response) {});\n }",
"getAllProgramReqs() {\n\t\tvar allProgramReqs = [];\n\t\tif(this.state.program){\n\t\t\tthis.state.program.forEach(function(req){\n\t\t\t\treq.courses.forEach(function(courseSet){\n\t\t\t\t\tcourseSet.forEach(function(course){\n\t\t\t\t\t\tallProgramReqs.push(course);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\treturn allProgramReqs;\n\t}",
"function getCourses(program) {\n\n // loading\n $('#spin1').show();\n\n // mongo db MLab API query\n var query = \"{\\\"programs\\\":{\\\"$in\\\":[\\\"\" + program + \"\\\"]}}\"\n\n // get listed requirements for requested program\n $.ajax({\n // don't want to asyncronously render graph without data\n async: false,\n dataType: \"json\",\n url: \"https://api.mlab.com/api/1/databases/bluetest/collections/courses3?q=\" + query + \"&apiKey=\" + API_KEY,\n success: function(progCourses) {\n //singles = data;\n courses = progCourses;\n }\n });\n\n // get user course history\n // TODO: user minerva API\n $.ajax({\n async: false,\n global: false,\n dataType: \"json\",\n url: \"user_details/user-1.json\",\n success: function(userCourses) {\n coursesTaken = userCourses;\n }\n });\n\n}",
"async function getCourses() {\r\n // Let's make an array to store our courses\r\n let courses = [];\r\n\r\n // Request data from the url above\r\n let html = await rp(url);\r\n\r\n /* Only use if falling back to loading HTML locally - and remember to comment out line 12! */\r\n // let html = ($.load(fs.readFileSync('src/rutgers-course-catalog.html'))).html();\r\n\r\n // Iterate over all courses\r\n $(\"div.item-container\", html).map((container) =>\r\n courses.push({\r\n code: $(\".course-annotation\", container).text(),\r\n title: $(\".course-title\", container).text(),\r\n desc: $(\".course-desc\", container).text(),\r\n prereqs: $(\".course-prereq\", container).text()\r\n })\r\n );\r\n\r\n // Return our array of courses\r\n return courses;\r\n}",
"function list_all_courses_by_program(program_detail) {\n return program_detail.mandatory.concat(program_detail.optional);\n}",
"function getCourses(courses) {\n\tvar course_list = [];\n\t//iterate over all of the courses in the list of type\n\tfor (var i = 0; i < courses.length; i++) {\n\t\tif (courses[i].id == \"000004\") {\n\t\t\tcontinue;\n\t\t}\n\t\t//add its attributes to the string representation\n\t\tvar course = \"<b>Course ID:</b> \" + courses[i].id + \"<br />\";\n\t\tcourse += \"<b>Credits:</b> \" + courses[i].credits + \"<br />\";\n\t\tcourse += \"<b>Required:</b> \" + courses[i].required + \"<br />\";\n\t\tcourse += \"<b>Senior:</b> \" + courses[i].senior + \"<br />\";\n\t\tcourse += \"<b>Course Name:</b> \" + courses[i].name + \"<br />\";\n\t\tcourse += \"<b>Course Description:</b><br />\" + courses[i].desc + \"<br />\";\n\n\t\t//add all of the names of its prerequisites\n\t\tcourse += \"<b>Prerequisites:</b><br />\";\n\t\tvar prereqs = courses[i].prereqs;\n\t\t//no prerequisites\n\t\tif (prereqs.length == 0) {\n\t\t\tcourse += \" None<br />\";\n\t\t//has prerequisites\n\t\t} else {\n\t\t\t//get the course name of the prerequisite using its course id\n\t\t\tfor (var j = 0; j < prereqs.length; j++) {\n\t\t\t\tvar prereq = findCourse(courses, prereqs[j].id);\n\t\t\t\tcourse += \" \" + prereq.name + \"<br />\";\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tcourse_list.push(course);\n\t}\n\n\treturn course_list;\n}",
"function getCourses() {\n return new Promise((resolve, reject) => {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", `https://golf-courses-api.herokuapp.com/courses/`);\n xhr.onreadystatechange = function() {\n if (this.readyState === 4 && this.status === 200) {\n resolve(JSON.parse(this.responseText));\n }\n };\n xhr.setRequestHeader(\"ContentType\", \"application/json\");\n xhr.send();\n });\n}",
"function getCourses() {\n try {\n var requirements = majorCatalog[chosenMajor].major.singular;\n // If the major chosen is not found in json file, print a message\n } catch (error) {\n var warning = document.createElement(\"p\");\n var node = document.createTextNode(\n \"Missing information of major \" + chosenMajor\n );\n warning.appendChild(node);\n\n displayInfo(warning);\n return;\n }\n\n // Create the courseBlocks, and store them\n for (var i = 0; i < requirements.length; i++) {\n createCourseBlock(requirements[i], i);\n }\n\n makeDraggable();\n getPaths();\n}",
"async function get_all_courses(teacherid) {\n try {\n let res = await axios.get(`/get_classes/${teacherid}`, config);\n\n return res.data.data;\n } catch (err) {\n console.error(err);\n return [];\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update central logo position and size | function updateLogoTransforms() {
var docW = window.innerWidth;
var docH = window.innerHeight
var logoSizeRatio = 0.5;
logoWidth = Math.min(maxWidth, docW * logoSizeRatio);
var height = logoWidth / ratio;
if (height > docH * logoSizeRatio) {
height = docH * logoSizeRatio;
logoWidth = height * ratio;
}
[logoDom, armIdleDom,shoulderDom].forEach(function (img) {
img.width = logoWidth;
img.height = height;
img.style.left = (docW / 2 - logoWidth / 2) + "px";
img.style.top = (docH / 2 - height / 2) + "px";
});
} | [
"function updateLogoTransforms() {\n var docW = window.innerWidth;\n var docH = window.innerHeight\n var logoSizeRatio = 0.75;\n\n logoWidth = Math.min(maxWidth, docW * logoSizeRatio);\n var height = logoWidth / ratio;\n if (height > docH * logoSizeRatio) {\n height = docH * logoSizeRatio;\n logoWidth = height * ratio;\n }\n [logoDom, armIdleDom,shoulderDom].forEach(function (img) {\n img.width = logoWidth;\n img.height = height;\n img.style.left = (docW / 2 - logoWidth / 2) + \"px\";\n img.style.top = (docH / 2 - height / 2) + \"px\";\n });\n }",
"function renderLogoResizeLogic () {\n logoResizeDelta++;\n \n if (logoResizeDelta >= SI.res.ResourceLoader.getResources().game.properties.StartScreenLogoResizeMaxDelta) {\n logoResizeDelta = 0;\n \n if (logoProportion == 1.0 && logoProgression == -1) {\n return;\n }\n \n logoProportion += \n SI.res.ResourceLoader.getResources().game.properties.StartScreenLogoProportionDiff * logoProgression;\n \n if (logoProgression == 1) {\n if (logoCurrentWidth > logoEndWidth) {\n logoProgression = -1;\n }\n } else \n if (logoProportion < 1.0) {\n logoProportion = 1.0;\n }\n \n logoCurrentWidth = logoSpriteSheet.width * logoProportion;\n logoCurrentHeight = logoSpriteSheet.height * logoProportion;\n logoCurrentX = SI.game.Renderer.getScene().getCenterXCoord(logoCurrentWidth);\n logoCurrentY = SI.game.Renderer.getScene().getCenterYCoord(logoCurrentHeight);\n }\n }",
"function update() {\n logo.style.left = xPosition + \"px\";\n logo.style.top = yPosition + \"px\";\n //logo2.style.left = xPosition2 + \"px\";\n //logo2.style.top = yPosition2 + \"px\";\n}",
"function vCenterLogo() {\n var height = $('#logo-container > div').height();\n if (height == 0) {\n console.log('height not received');\n height = 69;\n }\n var difference = (74 - height);\n console.log(height + '|' + difference);\n if (difference > 2) {\n $('#logo').css('margin-top', (difference / 2));\n }\n }",
"function positionLogoImage(){\n\tvar html5X = 16;\n\tvar byFWDRLX = (windowW - byFWDRLImageWidth);\n\tvar logoImageX = parseInt((windowW - logoImageWidth)/2) - 3;\n\t\n\tif(byFWDRLX > mainWidth - byFWDRLImageWidth){\n\t\tbyFWDRLX = parseInt(logoImageX + logoImageWidth - byFWDRLImageWidth);\n\t}\n\t\n\tif(windowW < mainWidth){\n\t\thtml5X = 2;\n\t}else{\n\t\thtml5X = logoImageX + 14;\n\t}\n\t\n\tif(windowW < 300){\n\t\tbyFWDRL_img.style.top = \"-50px\";\n\t}else{\n\t\tbyFWDRL_img.style.top = \"120px\";\n\t}\n\t\n\tlogoImage_img.style.left = logoImageX + \"px\";\n\tbyFWDRL_img.style.left = byFWDRLX + \"px\";\n}",
"function update() {\n if (cursors.left.isDown) {\n logo.x--;\n }\n if (cursors.right.isDown) {\n logo.x++;\n }\n if (cursors.up.isDown) {\n logo.y--;\n }\n if (cursors.down.isDown) {\n logo.y++;\n }\n }",
"function positionLogoImage(){\n\tvar html5X = 16;\n\tvar byFWDRLX = (windowW - byFWDRLImageWidth);\n\tvar logoImageX = parseInt((windowW - logoImageWidth)/2) - 26;\n\t\n\tif(byFWDRLX > mainWidth - byFWDRLImageWidth){\n\t\tbyFWDRLX = parseInt(logoImageX + logoImageWidth - byFWDRLImageWidth);\n\t}\n\t\n\tif(windowW < mainWidth){\n\t\thtml5X = 2;\n\t}else{\n\t\thtml5X = logoImageX + 14;\n\t}\n\t\n\tif(windowW < 300){\n\t\tbyFWDRL_img.style.top = \"-50px\";\n\t}else{\n\t\tbyFWDRL_img.style.top = \"140px\";\n\t}\n\t\n\tlogoImage_img.style.left = logoImageX + \"px\";\n\tbyFWDRL_img.style.left = byFWDRLX + \"px\";\n}",
"function computeLogoProperties () {\n logoEndWidth = \n SI.game.Renderer.getScene().getCanvas().width + \n SI.res.ResourceLoader.getResources().game.properties.StartScreenLogoEndWidthOffset;\n }",
"function centeredLogoHeaderInit() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tif($('#header-outer[data-format=\"centered-logo-between-menu\"]').length > 0) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(!usingLogoImage) {\r\n\t\t\t\t\t\t\tcenteredLogoMargins();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if(usingLogoImage && $('#header-outer[data-format=\"centered-logo-between-menu\"]').length > 0 && $('header#top #logo img:first[src]').length > 0) {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//fadein img on load\r\n\t\t\t\t\t\t\tvar tempLogoImg = new Image();\r\n\t\t\t\t\t\t\ttempLogoImg.src = $('header#top #logo img:first').attr('src');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\ttempLogoImg.onload = function() {\r\n\t\t\t\t\t\t\t\tcenteredLogoMargins();\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Resize event.\r\n\t\t\t\t\t\t$window.on('smartresize', centeredLogoMargins);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}",
"function adjustLogoHeight() {\n var height = $('.screenshot').load().height();\n $('.gitLogo').css({\n 'height': height,\n 'width': 'auto'\n });\n }",
"function logoSizeOnSmallScreens(){\n\t\"use strict\";\n\t// 100 is height of header on small screens\n\t\n\tif((100 - 20 < logo_height)){\n\t\t$j('.q_logo a').height(100 - 20);\n\t}else{\n\t\t$j('.q_logo a').height(logo_height);\n\t}\n\t$j('.q_logo a img').css('height','100%');\n\t\n\t$j('header.page_header').removeClass('sticky_animate sticky');\n\t$j('.content').css('padding-top','0px');\n\t\n}",
"function modifyLogo() {\n storage\n .get({\n [CHOSEN_LOGO_PRIMARY_KEY]:\n DEFAULT_SETTINGS[CHOSEN_LOGO_PRIMARY_KEY],\n })\n .then((response) => {\n let newLogoUrl = {\n satoriPremium: BANNER_URL,\n tcs: TCS_LOGO_URL,\n alternative: ALT_TCS_LOGO_URL,\n }[response[CHOSEN_LOGO_PRIMARY_KEY]];\n $('img[src=\"/files/satori_banner.png\"]').attr(\n 'src',\n newLogoUrl,\n );\n });\n }",
"function normalizeMainBrandLogo() {\n brand.width(normalize(0, 300, 550, 200, doc.scrollTop()));\n }",
"function adjustLogo(i) {\n logo.style.width = sizeLogos[i][0][\"width\"];\n logo.style.height = sizeLogos[i][0][\"height\"];\n}",
"function centeredNavBottomBarReposition() {\r\n \r\n var $headerSpan9 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_9');\r\n var $headerSpan3 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_3');\r\n var $secondaryHeader = $('#header-secondary-outer');\r\n \r\n var $logoLinkClone = $headerSpan3.find('#logo').clone();\r\n if($logoLinkClone.is('[data-supplied-ml=\"true\"]')) {\r\n $logoLinkClone.find('img:not(.mobile-only-logo)').remove();\r\n }\r\n //trans\r\n $logoLinkClone.find('img.starting-logo').remove();\r\n \r\n \r\n if($secondaryHeader.length > 0) {\r\n $secondaryHeader.addClass('centered-menu-bottom-bar');\r\n } \r\n \r\n \r\n if($('#header-outer[data-condense=\"true\"]').length > 0) {\r\n $headerSpan9.prepend($logoLinkClone);\r\n } \r\n }",
"function modifyLogo() {\n storage.get({\n [CHOSEN_LOGO_PRIMARY_KEY]: DEFAULT_SETTINGS[CHOSEN_LOGO_PRIMARY_KEY]\n }).then(response => {\n const newLogoUrl = {\n satoriPremium: BANNER_URL,\n shitoriPremium: SHITORI_BANNER_URL,\n suspiciousSatoriPremium: SUSPICIOUS_SATORI_BANNER_URL,\n suspiciousShitoriPremium: SUSPICIOUS_SHITORI_BANNER_URL,\n tcs: TCS_LOGO_URL,\n tcsWhite: TCS_LOGO_WHITE_URL,\n alternative: ALT_TCS_LOGO_URL,\n alternativeWhite: ALT_TCS_WHITE_LOGO_URL,\n }[response[CHOSEN_LOGO_PRIMARY_KEY]];\n $('img[src=\"/files/satori_banner.png\"]').attr('src', newLogoUrl);\n });\n }",
"function et_define_logo_dimension() {\n var $logo = $('#logo'),\n logo_src = $logo.attr('src'),\n is_svg = logo_src.substr(-3, 3) === 'svg' ? true : false,\n $logo_wrap,\n logo_width,\n logo_height; // Append invisible wrapper at the bottom of the page\n\n $('body').append($('<div />', {\n 'id': 'et-define-logo-wrap',\n 'style': 'position: fixed; bottom: 0; opacity: 0;'\n })); // Define logo wrap\n\n $logo_wrap = $('#et-define-logo-wrap');\n\n if (is_svg) {\n $logo_wrap.addClass('svg-logo');\n } // Clone logo to invisible wrapper\n\n\n $logo_wrap.html($logo.clone().css({\n 'display': 'block'\n }).removeAttr('id')); // Get dimension\n\n logo_width = $logo_wrap.find('img').width();\n logo_height = $logo_wrap.find('img').height(); // Add data attribute to $logo\n\n $logo.attr({\n 'data-actual-width': logo_width,\n 'data-actual-height': logo_height\n }); // Destroy invisible wrapper\n\n $logo_wrap.remove(); // Init logo transition onload\n\n et_fix_logo_transition(true);\n }",
"function centeredLogoMargins() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (nectarDOMInfo.winW > 1000) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $navItemLength = $('#header-outer[data-format=\"centered-logo-between-menu\"] #top nav > .sf-menu:not(.buttons) > li').length;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($('#header-outer #social-in-menu').length > 0) {\r\n\t\t\t\t\t\t\t$navItemLength--;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $centerLogoWidth,\r\n\t\t\t\t\t\t$extraMenuSpace;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($('#header-outer #top .row .col.span_3 #logo img:visible').length == 0) {\r\n\t\t\t\t\t\t\t$centerLogoWidth = parseInt($('#header-outer #top .row .col.span_3').width());\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t$centerLogoWidth = parseInt($('#header-outer #top .row .col.span_3 img:visible').width());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($('#header-outer[data-lhe=\"animated_underline\"]').length > 0) {\r\n\t\t\t\t\t\t\t$extraMenuSpace = parseInt($('header#top nav > ul > li:first-child > a').css('margin-right'));\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t$extraMenuSpace = parseInt($('header#top nav > ul > li:first-child > a').css('padding-right'));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($extraMenuSpace > 30) {\r\n\t\t\t\t\t\t\t$extraMenuSpace += 45;\r\n\t\t\t\t\t\t} else if ($extraMenuSpace > 20) {\r\n\t\t\t\t\t\t\t$extraMenuSpace += 40;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t$extraMenuSpace += 30;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (!$body.hasClass('rtl')) {\r\n\t\t\t\t\t\t\t$('#header-outer[data-format=\"centered-logo-between-menu\"] #top nav > .sf-menu:not(.buttons) > li:nth-child(' + Math.floor($navItemLength / 2) + ')').css({\r\n\t\t\t\t\t\t\t\t'margin-right': ($centerLogoWidth + $extraMenuSpace) + 'px'\r\n\t\t\t\t\t\t\t}).addClass('menu-item-with-margin');\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t$('#header-outer[data-format=\"centered-logo-between-menu\"] #top nav > .sf-menu:not(.buttons) > li:nth-child(' + Math.floor($navItemLength / 2) + ')').css({\r\n\t\t\t\t\t\t\t\t'margin-left': ($centerLogoWidth + $extraMenuSpace) + 'px'\r\n\t\t\t\t\t\t\t}).addClass('menu-item-with-margin');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $leftMenuWidth \t= 0;\r\n\t\t\t\t\t\tvar $rightMenuWidth = 0;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$('#header-outer[data-format=\"centered-logo-between-menu\"] #top nav > .sf-menu:not(.buttons) > li:not(#social-in-menu)').each(function (i) {\r\n\t\t\t\t\t\t\tif (i + 1 <= Math.floor($navItemLength / 2)) {\r\n\t\t\t\t\t\t\t\t$leftMenuWidth += $(this).width();\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t$rightMenuWidth += $(this).width();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $menuDiff = Math.abs($rightMenuWidth - $leftMenuWidth);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($leftMenuWidth > $rightMenuWidth || ($body.hasClass('rtl') && $leftMenuWidth < $rightMenuWidth) ) {\r\n\t\t\t\t\t\t\t$('#header-outer #top .row > .col.span_9').css('padding-right', $menuDiff);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t$('#header-outer #top .row > .col.span_9').css('padding-left', $menuDiff);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$('#header-outer[data-format=\"centered-logo-between-menu\"] nav').css('visibility', 'visible');\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t} \r\n\t\t\t\t\t\r\n\t\t\t\t\telse if ($('#header-outer[data-format=\"centered-logo-between-menu\"]').length > 0 && nectarDOMInfo.winW < 1000) {\r\n\t\t\t\t\t\t$('#header-outer .row > .col.span_9').css({\r\n\t\t\t\t\t\t\t'padding-right': '0',\r\n\t\t\t\t\t\t\t'padding-left': '0'\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}",
"function centeredNavBottomBarReposition() {\n\t\t\n\t\tvar $headerSpan9 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_9');\n\t\tvar $headerSpan3 = $('#header-outer[data-format=\"centered-menu-bottom-bar\"] header#top .span_3');\n\t\tvar $secondaryHeader = $('#header-secondary-outer');\n\t\t\n\t\tvar $logoLinkClone = $headerSpan3.find('#logo').clone();\n\t\tif($logoLinkClone.is('[data-supplied-ml=\"true\"]')) {\n\t\t\t$logoLinkClone.find('img:not(.mobile-only-logo)').remove();\n\t\t}\n\t\t//trans\n\t\t$logoLinkClone.find('img.starting-logo').remove();\n\t\t\n\n\t\tif($secondaryHeader.length > 0) {\n\t\t\t$secondaryHeader.addClass('centered-menu-bottom-bar');\n\t\t} \n\t\t\n\t\t\n\t\tif($('#header-outer[data-condense=\"true\"]').length > 0) {\n\t\t\t$headerSpan9.prepend($logoLinkClone);\n\t\t} \n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets indexes 0 through 3 of masterCode.code to randomly generated numbers ranging from 0 to 9. It then converts each index into a Number class using number.js | constructor(){
this.code = [];
this.cheat = [];
for (var i = 0; i < 4; i++){
this.code[i] = getRandomIntInclusive(0, 9);
this.cheat[i] = this.code[i];
this.code[i] = new Number(this.code[i]);
}
} | [
"function newNumbers() {\n\t\tmagicNumber = Math.floor(Math.random() * 120) + 19;\n\t\tcrystal1Num = Math.ceil(Math.random() * 12);\n\t\tcrystal2Num = Math.ceil(Math.random() * 12);\n\t\tcrystal3Num = Math.ceil(Math.random() * 12);\n\t\tcrystal4Num = Math.ceil(Math.random() * 12);\n\t}",
"function loadCodes() \n{\n\tvar codeNumbers = [];\n\tfor (var compteur = 0; compteur < 10; compteur++) codeNumbers[compteur] = compteur;\n\n\tfor (compteur = 0; compteur < 4; compteur++) //In order to have no repeated numbers in the code, we remove the used one from the array. \n\t{\n\t\tvar index = Math.floor(Math.random() * codeNumbers.length);\n\t\tvar codeNumber = codeNumbers.splice(index, 1);\n\t\tcodes.push(codeNumber);\n\t}\n}",
"getRandomCode() {\r\n let min = Math.pow(10, this.Barcode_Length);\r\n let max = Math.pow(10, this.Barcode_Length + 1);\r\n let code = Math.floor(Math.random() * (max - min)) + min;\r\n let code_array = code.toString().split(\"\").map(Number);\r\n let end_code = 0;\r\n for (let i = 0; i < this.Barcode_Length; i++) {\r\n let digit = this.IDENTIFIER[i];\r\n if (digit == 0) {\r\n end_code += code_array[i] * Math.pow(10, this.Barcode_Length - i - 1);\r\n }\r\n else {\r\n end_code += digit * Math.pow(10, this.Barcode_Length - i - 1);\r\n }\r\n }\r\n return end_code;\r\n }",
"function cValueGenerator() {\r\n for (var j = 0; j <= 3; j++) {\r\n cValue[j] = Math.floor(Math.random() * 12) + 1;\r\n }\r\n }",
"function resetNums() {\n targetNumber = Math.floor(Math.random() * 102) + 19;\n amethyst = Math.floor(Math.random() * 12) + 1;\n sapphire = Math.floor(Math.random() * 12) + 1;\n opal = Math.floor(Math.random() * 12) + 1;\n peridot = Math.floor(Math.random() * 12) + 1;\n }",
"function initializeNumber(){\n pNmbrArr.push(phoneNmbr.slice(0,1) + \"32\");\n pNmbrArr.push(phoneNmbr.slice(1,4));\n pNmbrArr.push(phoneNmbr.slice(4,6));\n pNmbrArr.push(phoneNmbr.slice(6,8));\n pNmbrArr.push(phoneNmbr.slice(8,10));\n }",
"function genNumber(){\n return Math.round( Math.random() * 9 + 1 );\n }",
"function CodeMonotoneToNumber(cod)\r\n{\r\n let aReturn = 0;\r\n try\r\n {\r\n switch (cod)\r\n {\r\n case '00': aReturn = '0'; break;\r\n case '01': aReturn = '1'; break;\r\n case '02': aReturn = '2'; break;\r\n case '04': aReturn = '3'; break;\r\n case '07': aReturn = '4'; break;\r\n case '0D': aReturn = '5'; break;\r\n case '10': aReturn = '6'; break;\r\n case '11': aReturn = '7'; break;\r\n case '12': aReturn = '8'; break;\r\n case '14': aReturn = '9'; break;\r\n case '17': aReturn = '*'; break; //+\r\n case '1D': aReturn = '#'; break; //-\r\n case '20': aReturn = 'A'; break; //>>\r\n case '21': aReturn = 'B'; break; //<<\r\n case '22': aReturn = 'C'; break; //> \r\n case '24': aReturn = 'D'; break;\r\n default: aReturn = '0';\r\n }\r\n }\r\n catch(err)\r\n {\r\n DebugLog(err.message.toString());\r\n } \r\n return (aReturn);\r\n}",
"function fourNum(){\n for (let index = 0; index < 4; index++) {\n var crystInd = Math.floor(Math.random()*13);\n crystalValues.push(crystInd);\n}\n}",
"SetRandomNumber () {\n var temp = Math.floor(Math.random() * 54);\n RandomNumber = temp;\n }",
"function generateNumbers() {\n for (let i=0; i < 4; i++) {\n randomNumbers[i] = Math.floor(Math.random() * 12) + 1;\n }\n}",
"getIndexFromCode(code) {\n return parseInt(code.join(''), this.radix);\n }",
"function crystalRandNumbers() {\n\t\tfor (var i = 0; i < 4; i++) {\n\t\t\tvar num = Math.floor(Math.random() * 12) +1;\n\t\t\tcrystalNumbers.push(num);\n\t\t}\n\t}",
"function generateNumber() {\n\tgeneratedNumber = Math.floor(Math.random() * (121 - 19) + 19);\n}",
"function randomGameCode() {\n return Math.floor(10000 + Math.random() * 90000);\n }",
"function CodeGenerator(gameObject)\n{\n\t//---\n\t// nibble 0 | nibble 1 | nibble 2 | nibble 3 | nibble 4 | nibble 5 | nibble 6\n\t// -----------|-----------|-----------|-----------|-----------|-----------|----------\n\t// 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0\n\t// 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1\n\t// | | | | | |\n\t// 3 2 1 0| 7 6 5 4|11 10 9 8|15 14 13 12|19 18 17 16|23 22 21 20|27 26 25 24\n\t// | | | | | |\n\t// L0 P0 F0 S0|S1 L1 0 P1|S2 L2 P2 F1|S4 S3 P3 L3|P4 S5 L4 F2|S6 P5 F3 L5|L7 L6 0 P6\n\t// 0 = fixed bitvalue: must be zero, otherwise the code is not accepted!\n\t// Ln = level bits: L6 is most significant, L0 is least significant\n\t// Pn = previous percentage bits: P6 is most-, P0 is least significant\n\t// Sn = spurious bits: S6 is used here as most, S0 as least significant\n\t// Fn = previous number of times the level was failed Bits\n\t// nibble 7 : least significant bits of level index \n\t// nibble 8 : most significant bits of level index \n\t// nibble 9 : Checksum\n\n\n\tthis.codeBase = new Array(7);\n\tthis.codeBase[gameObject.VERSION.LEMMINGS.value] = \"AJHLDHBBCJ\";\n\tthis.codeBase[gameObject.VERSION.OHNO.value]\t = \"AHPTDHBBAD\";\n\tthis.codeBase[gameObject.VERSION.HOLIDAY93.value]= \"AJHLDHBBAD\";\n\tthis.codeBase[gameObject.VERSION.HOLIDAY94.value]= \"AJPLDHBBCD\";\n\tthis.codeBase[gameObject.VERSION.XMAS91.value]\t = this.codeBase[gameObject.VERSION.LEMMINGS.value]; //- they use the same codebase\n\tthis.codeBase[gameObject.VERSION.XMAS92.value]\t = this.codeBase[gameObject.VERSION.LEMMINGS.value];\n\n\tthis.game = gameObject;\n\n\tvar self = this;\n\n\t//- result structure\n\tfunction codeInfo()\n\t{\n\t\tthis.levelIndex = 0;\n\t\tthis.percent = 100;\n\t\tthis.lemmingsVersion = null;\n\t\tthis.failCount = 0;\n\t\tthis.suprise = 0;\n\t}\n\n\t//- return (codeInfo) from Lemmings-Code.\n\tthis.reverseCode = function(codeString)\n\t{\n\t\t//- check for all know Lemmings Versions\n\t\tfor (var versionName in gameObject.VERSION)\n\t\t{\n\t\t\tvar version = gameObject.VERSION[versionName];\n\t\t\tvar inf = self.reverseCodeSub(codeString, version);\n\t\t\tif (inf != null) return inf;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\t\n\tthis.reverseCodeSub = function(codeString, gameVersion)\n\t{\n\t\tif (codeString.length != 10) return null;\n\n\t\tvar codeBase = self.codeBase[gameVersion.value];\n\n\t\t//- CodeBase Offsets\n\t\tvar Ofc = new Array(codeBase.length);\n\t\tfor (var i = 0; i < codeBase.length; i++)\n\t\t{\n\t\t\t\tOfc[i] = codeBase.charCodeAt(i);\n\t\t}\n\n\n\t\t//- convert code to int Array\n\t\tvar code = new Array(10);\n\t\tfor (var i = 0; i < 10; i++)\n\t\t{\n\t\t\t\tcode[i] = codeString.charCodeAt(i);\n\t\t}\n\n\t\t//- calculate and check the checksum\n\t\tvar csum = 0;\n\t\tfor (var i = 0; i < 9; i++) csum += code[i];\n\n\t\tif ((Ofc[9] + (csum & 0x0F)) != code[9]) return null;\n\n\t\t//- get level Index from code\n\t\tvar l1 = (code[7] - Ofc[7]);\n\t\tvar l2 = (code[8] - Ofc[8]);\n\t\tif ((l1 < 0) || (l2 < 0) || (l1 > 0x0F) || (l2 > 0x0F)) return null;\n\n\t\tvar levelIndex = l1 | (l2 << 4);\n\n\t\t//- unrotate code\n\t\tvar codeVal = new Array(8);\n\t\tcodeVal[7] = 0;\n\t\tfor (var i = 0; i < 7; i++)\n\t\t{ \n\t\t\tvar j = (i + 8 - (levelIndex % 8)) % 7;\n\t\t\tcodeVal[i] = code[j] - Ofc[i]; \n\t\t}\n\n\t\t//- extract value by bit position\n\t\tfunction generateValue(codeValue, bitPosList)\n\t\t{\n\t\t\tvar value = 0;\n\t\t\tfor (var i = 0; i < bitPosList.length; i++)\n\t\t\t{\n\t\t\t\tvar pos = bitPosList[i];\n\t\t\t\tvar nibble = codeValue[Math.floor(pos / 4)];\n\t\t\t\tvar bit = (nibble >>> (pos % 4)) & 0x01;\n\t\t\t\n\t\t\t\tvalue = value\t| (bit << i);\n\t\t\t}\n\n\t\t\treturn value; \n\t\t}\n\n\t\t//- do extract\n\t\tvar nullValue = generateValue(codeVal, [5, 25]);\n\t\tvar levelValue = generateValue(codeVal, [3, 6, 10, 12, 17, 20, 26, 27]);\n\t\tvar persentValue = generateValue(codeVal, [2, 4, 9, 13, 19, 22, 24]);\n\t\tvar supriseValue = generateValue(codeVal, [0, 7, 11, 14, 15, 18, 23]);\n\t\tvar failValue = generateValue(codeVal, [1, 8, 16, 21]);\n\n\t\tif (nullValue != 0) return null;\n\t\tif (levelValue != levelIndex) return null;\n\n\t\tvar ret = new codeInfo();\n\n\t\tret.levelIndex = levelValue;\n\t\tret.percent = persentValue;\n\t\tret.lemmingsVersion = gameVersion;\n\t\tret.failCount = failValue;\n\t\tret.suprise = supriseValue;\n\n\t\treturn ret;\n\t}\n\n\n\tthis.createCode = function(levelIndex, percent, gameVersion)\n\t{\n\t\t//- ToDo: refactor this function using 8 bit for Lbit.\n\n\t\tif (typeof gameVersion === \"undefined\") gameVersion = self.game.VERSION.LEMMINGS;\n\t\tif (typeof percent === \"undefined\") percent = 100;\n\n\t\tvar result = new Array(9);\n\t\tvar Lbit = [3, 2, 2, 0, 1, 0, 2]; //- where to place the Level bits in result\n\t\tvar Pbit = [2, 0, 1, 1, 3, 2, 0]; //- where to place the Percentage bits in result\n\n\t\t//- CodeBase Offsets\n\t\tvar codeBase = self.codeBase[gameVersion.value];\n\t\tvar Ofc = new Array(codeBase.length);\n\t\tfor (var i = 0; i < codeBase.length; i++)\n\t\t{\n\t\t\tOfc[i] = codeBase.charCodeAt(i);\n\t\t}\n\n\t\t//- bit selector\n\t\tvar bitmask = 1;\n\n\t\tfor (var j = 0; j < 7; j++)\n\t\t{\n\t\t\t//- add level bit\n\t\t\tvar nibble = (levelIndex & bitmask) << Lbit[j];\n\t \n\t\t\t//- add percent bit\n\t\t\tnibble = nibble + ((percent & bitmask) << Pbit[j]);\n\n\t\t\t//- rotate the order\n\t\t\tvar i = (j + 8 - (levelIndex % 8)) % 7;\n\n\t\t\t//- assemble the rotated character\n\t\t\tresult[i] = Ofc[j] + (nibble >>> j);\n\n\t\t\t// next bit\n\t\t\tbitmask = bitmask << 1;\n\t\t}\n\n\n\t\t//- add level characters \n\t\tresult[7] = Ofc[7] + ((levelIndex & 0x0F));\n\t\tresult[8] = Ofc[8] + ((levelIndex & 0xF0) >>> 4);\n\n\t\t//- calculating the checksum\n\t\tvar csum = 0;\n\t\tfor (var i = 0; i < 9; i++) csum += result[i];\n\n\t\t//- add checksum\n\t\tresult[9] = Ofc[9] + (csum & 0x0F);\n\n\t\t//- combine all characters to a proper level string\n\t\tvar Levelcode = \"\";\n\t\tfor (var i = 0; i < 10; i++)\n\t\t{\n\t\t\tLevelcode += String.fromCharCode(result[i]);\n\t\t}\n\n\t\treturn Levelcode;\n\t} \n\n}",
"function crystalValueGenerator() {\n for (var j =0; j <= 3; j++) {\n crystalValue[j] = Math.floor(Math.random() * 12) + 1;\n }\n }",
"function setRandomNumber() {\n randomnumber = Math.floor(Math.random()*101+19);\n $(\"#random-number\").text(randomnumber);\n }",
"function mNumberGenerator() {\r\n for (var i = 1; i <= 10; i++) {\r\n mNumber = Math.floor(Math.random() * 120) + 1; \r\n if (mNumber >= 19) {\r\n i = 11;\r\n }\r\n } \r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array with the words from specified text | function getWords(text)
{
let startWord = -1;
let ar = [];
for(let i = 0; i <= text.length; i++)
{
let c = i < text.length ? text[i] : " ";
if (!isSeparator(c) && startWord < 0)
{
startWord = i;
}
if (isSeparator(c) && startWord >= 0)
{
let word = text.substring(startWord, i);
ar.push(word);
startWord = -1;
}
}
return ar;
} | [
"function getWordsFromText(text) {\n\t //var pattern = /[\\wА-Яа-я]+/g;\n //return text.match(pattern);\n return text.split(\" \");\n }",
"function getWords(text) {\n if (text.length > 0){\n return text.split(' ');\n } else return []\n}",
"async words(contentText) {\n //TODO\n let word_arr = contentText.split(/\\s+/).map((w) => normalize(w)).filter((w) => !this.noise_words.has(w));\n return word_arr;\n }",
"function getWords(txt) {\r\n var words = [];\r\n var word = '';\r\n if (!txt) {\r\n txt = '';\r\n }\r\n for (var i = 0; i < txt.length; ++i) {\r\n var ch = txt.charCodeAt(i);\r\n if (ch < 33 || ch > 126) {\r\n if (word) {\r\n words.push(word);\r\n word = '';\r\n }\r\n words.push(txt[i]);\r\n continue;\r\n }\r\n else {\r\n word += txt[i];\r\n }\r\n }\r\n if (word) {\r\n words.push(word);\r\n }\r\n // console.log('words',words)\r\n return words;\r\n}",
"function countWords(text)\r\n {\r\n // REPLACE THIS CODE WITH YOUR countWords() METHOD\r\n var len = text.length;\r\n var pos = 0;\r\n var inWord = false;\r\n var count = 0;\r\n var words = [];\r\n while (pos < len) {\r\n var ch = text[pos];\r\n if (isPartOfWord(ch)) {\r\n if(!inWord) {\r\n count++;\r\n inWord = true;\r\n words.push(\"\");\r\n }\r\n \r\n words[count -1] += ch;\r\n \r\n } else if (isSeparator(ch)) {\r\n inWord = false;\r\n }\r\n pos++;\r\n }\r\n return words;\r\n\t}",
"function _splitWords(text) {\n\t\t\treturn text.split(/\\s+/);\n\t\t}",
"async words(contentText) {\n //TODO\n let words = [];\n let splitWords;\n let noiseWords = [];\n await db.collection(noise_table).find({}).forEach(function (u) {\n noiseWords.push(u.word);\n });\n while (splitWords = WORD_REGEX.exec(contentText)) {\n let [word, offset] = [splitWords[0], splitWords.index];\n word = normalize(word);\n word = stem(word);\n if(!(noiseWords.indexOf(word) > -1)) {\n words.push([word, offset]);\n }\n }\n return await words;\n\n }",
"function getTextArray(text) {\r\n textArr = text.split(' ');\r\n}",
"function _splitWords(text) {\n\t\treturn text.split(/\\s+/);\n\t}",
"async words(contentText) {\n return (await this._wordsLow(contentText)).map((pair) => pair[0]);\n }",
"function countWords(text)\r\n {\r\n // REPLACE THIS CODE WITH YOUR countWords() METHOD\r\n var len=text.length;\r\n var pos=0;\r\n var word='';\r\n var words=[];\r\n while(pos<len) {\r\n var ch=text[pos];\r\n \r\n if(isPartOfWord(ch)) {\r\n word+=ch;\r\n }\r\n else if(isSeparator(ch)&&word!==\"\"){\r\n words.push(word);\r\n word=\"\";\r\n }\r\n \r\n pos+=1;\r\n }\r\n\r\n return words;\r\n\t}",
"wordsToArr(text) {\n // Splits all words, apostrophes, and hyphens together, then punctuations separately. Example:\n // Text = He's provided Dr. Bond pre-authorized payment at 12:10, what should we do?\n // text.match(regex) = [\"He's\", \"provided\", \"Dr\", \".\", \"Bond\", \"pre-authorized\", \"payment\", \"at\", \"12\", \":\", \"10\", \",\", \"what\", \"should\", \"we\", \"do\", \"?\"]\n var regex = /([\\w'-]+)|[^\\s\\w]/g; \n return text.match(regex);\n }",
"words(content) {\n const splitWords = content.match(WORD_REGEX);\n let localWords = [];\n if (null != splitWords) {\n for (let word of splitWords) {\n if (word === null)\n continue;\n const keyword = normalize(word);\n if (keyword === null)\n continue;\n if (!this.noiseWordsIndex.has(keyword)) {\n this.finalWords.add(keyword);\n localWords.push(keyword);\n }\n\n }\n\n }\n return localWords;\n }",
"getWordsFromCounterpartList(text) {\n let result = [];\n\n this.wordLists.forEach((words, index, all) => {\n const isMatch = words.some((word) => word === text);\n\n if (isMatch) {\n result = all[index ? 0 : 1];\n }\n });\n\n return result;\n }",
"function splitIntoWords(text) {\n return text.toLowerCase().split(/[^a-z0-9]/).filter(e => e);\n}",
"function get_stopwords(text) {\n\tvar words = text.split(' ');\n\tvar stopwords_in_words = [];\n\tfor(var w = 0; w < words.length; w++) {\n\t\tcheck_stop = stopwords.indexOf(words[w])\n\t\tif( check_stop > -1) {\n\t\t\tstopwords_in_words.push(stopwords[check_stop]);\n\t\t}\n\t}\n\treturn stopwords_in_words;\n}",
"async words(contentText) {\n let wordsArray;\n wordsArray = contentText.match(WORD_REGEX);\n let normalizedWordArray = [];\n\n // Fetch noise words from database\n let storedNoiseWords = await this.noiseWordsCollection.find().toArray();\n storedNoiseWords = storedNoiseWords.map(a => a._id);\n\n if(wordsArray !== null) {\n for (let word of wordsArray) {\n word = normalize(word);\n if (!storedNoiseWords.includes(word)) {\n let normalizedWord = normalize(word);\n normalizedWordArray.push(normalizedWord);\n }\n }\n }\n return normalizedWordArray;\n }",
"words (inputString) {\n let wordArray = inputString.split(' ');\n return wordArray;\n }",
"function getWords(text) {\n\t\t\tvar words = text.split(/[\\s\\.,-?!)(]/),\n\t\t\t\ti;\n\n\t\t\tfor (i = 0; i < words.length; i++) {\n\t\t\t\tif (words[i] == \"\") {\n\t\t\t\t\twords.splice(i, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn words;\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a new game and questions | function newGame(){
var create1 = new genQuestion(question1);
var create2 = new genQuestion(question2);
var create3 = new genQuestion(question3);
var create4 = new genQuestion(question4);
var create5 = new genQuestion(question5);
} | [
"function createGame() {\r\n createBoard();\r\n createCoins();\r\n createRules();\r\n}",
"function createGame(choices){\n\tmessageDisplay.textContent = \"\";\n\tcreateOptions(choices);\n\tanswerSet = generateRandomSet(choices);\n\tanswer = options[answerSet][2];\n\tquestion1.textContent = options[answerSet][0];\n\tquestion2.textContent = options[answerSet][1];\n\n\tfor (var i \t= 0; i < choices; i++){\n\t\tsquares[i].textContent = options[i][2];\n\t\tsquares[i].classList.remove(\"bigShaq\");\n\t\tsquares[i].classList.remove(\"happyBigShaq\");\n\t\treset.textContent = \"New Numbers\";\n\t} \n}",
"function createGame () {}",
"function newGame() {\n $(\"#gameCol\").show();\n $(\"#finalMessage\").empty();\n $(\"#correctAnswers\").empty();\n $(\"#incorrectAnswers\").empty();\n $(\"#unanswered\").empty();\n $(\"gif\").hide();\n $(\"#gifCaption\").hide();\n currentQuestion = 0;\n correctAnswer = 0;\n incorrectAnswer = 0;\n unanswered = 0;\n newQuestion();\n }",
"function newGame() {\n onloadscrn.style.display = \"none\";\n game.style.display = \"grid\";\n friendbtn.disabled = false;\n fifty.disabled = false;\n expertbtn.disbled = false;\n currentQuestion = 0;\n getNextQuestion();\n currentScore = 0;\n}",
"function newGame() {\n var game = JSON.parse(localStorage.getItem('game'))\n game[props.user].push({\n question_number: 0,\n score: 0,\n game_over: false\n })\n localStorage.setItem('game', JSON.stringify(game))\n props.newGame(1)\n }",
"function newGame(){\n\t$('#finalMessage').empty();\n\t$('#correctAnswers').empty();\n\t$('#incorrectAnswers').empty();\n\t$('#unanswered').empty();\n\tcurrentQuestion = 0;\n\tcorrectAnswer = 0;\n\tincorrectAnswer = 0;\n\tunanswered = 0;\n\tnewQuestion();\n}",
"function createQuestions(){\n buildButtons(quizCards[longClock].answerChoices);\n questionTitle.textContent = quizCards[longClock].question;\n\n}",
"function newGame() {\n\n\t\t$(\"#initial-input\").off();\n\t\t$(\".saver\").off();\n\t\t$(\".submitBtn\").off();\t\n\t\trenderScores();\n\t\t// Reset testItems and certain globals. \n\t\ttotalIncorrect = 0;\n\t\ttotalCorrect = 0;\n\t\ttimeRemaining = 120;\n\t\ttestItem = [\n\n\t\t\t{\n\t\t\t\tname: \"Alert in JS\",\n\t\t\t\tquestion: \"Which makes an alert box?\",\n\t\t\t\tcorrectAnswer: [\"alert();\"],\n\t\t\t\tincorrectAnswers: [\"alertBox();\", \"msg();\", \"msgBox();\", \"warning();\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Comment in JavaScript\",\n\t\t\t\tquestion: \"Which is a comment in a JavaScript?\",\n\t\t\t\tcorrectAnswer: [\"// This\", '/*This*/'],\n\t\t\t\tincorrectAnswers: [\"<!--This-->\", \"`This`\", \"#This\",\"$This\" ]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"FOR loop syntax\",\n\t\t\t\tquestion: \"Which starts a FOR loop?\",\n\t\t\t\tcorrectAnswer: [\"for\"],\n\t\t\t\tincorrectAnswers: [\"four\", \"fore!\", \"4\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"jQuery shorthand\",\n\t\t\t\tquestion: \"The 'shorthand' version of JavaScript is called ____________.\",\n\t\t\t\tcorrectAnswer: [\"jQuery\"],\n\t\t\t\tincorrectAnswers: [\"HTML\", \"miniJava\", \"jScript\", \"MochaScript\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"id syntax\",\n\t\t\t\tquestion: \"Which of these selects an element by ID?\",\n\t\t\t\tcorrectAnswer: [\"#\"],\n\t\t\t\tincorrectAnswers: [\".\", \"@\", \"$\", \"&\", \"!\", \"*\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"class syntax\",\n\t\t\t\tquestion: \"Which of these select an element by class?\",\n\t\t\t\tcorrectAnswer: [\".\"],\n\t\t\t\tincorrectAnswers: [\"#\", \"@\", \"$\", \"&\", \"!\", \"*\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Identify event listener\",\n\t\t\t\tquestion: \"Which of these can add an event listener?\",\n\t\t\t\tcorrectAnswer: [\".on()\", \".click()\"],\n\t\t\t\tincorrectAnswers: [ \".off()\", \".up()\", \".down()\", \".add()\", \".pop()\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Variable types\",\n\t\t\t\tquestion: \"Which variable type holds a value of true or false?\",\n\t\t\t\tcorrectAnswer: [\"boolean\"],\n\t\t\t\tincorrectAnswers: [\"string\", \"array\", \"integer\", \"function\", \"attribute\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"FOR loop terminology\",\n\t\t\t\tquestion: \"Which of these belong inside a FOR-loop's argument?\",\n\t\t\t\tcorrectAnswer: [\"all of these\"],\n\t\t\t\tincorrectAnswers: [\"iterator\", \"condition\", \"initializer\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Linking .js files\",\n\t\t\t\tquestion: \"Which <script> attribute links HTML to a js file?\",\n\t\t\t\tcorrectAnswer: [\"src\"],\n\t\t\t\tincorrectAnswers: [\"href\", \"rel\", \"name\", \"link\", \"value\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"DOM\",\n\t\t\t\tquestion: \"What does the 'O' in DOM stand for?\",\n\t\t\t\tcorrectAnswer: [\"Object\"],\n\t\t\t\tincorrectAnswers: [\"Olive\", \"Ocelot\", \"Octogon\", \"Ostrich\", \"Oxygen\", \"Orca\", \"Orbit\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Conditional Q\",\n\t\t\t\tquestion: \"let x = !!!true; What is the value of x?\",\n\t\t\t\tcorrectAnswer: [\"false\"],\n\t\t\t\tincorrectAnswers: [\"true\", \"null\", \"supertrue\", \"ultrafalse\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"jQuery() alias\",\n\t\t\t\tquestion: \"Which of these is an alias for jQuery?\",\n\t\t\t\tcorrectAnswer: [\"$\"],\n\t\t\t\tincorrectAnswers: [\".\", \"#\", \"@\", \"!\", \"&\", \"*\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Removing array elements\",\n\t\t\t\tquestion: \"Which of these removes elements from an array?\",\n\t\t\t\tcorrectAnswer: [\"all of these\"],\n\t\t\t\tincorrectAnswers: [\".splice()\", \".pop()\", \".shift()\", \".filter()\"]\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tname: \"Select all elements\",\n\t\t\t\tquestion: \"Which of these selects all elements?\",\n\t\t\t\tcorrectAnswer: [\"*\"],\n\t\t\t\tincorrectAnswers: [\".\", \"#\", \"@\", \"!\", \"&\", \"$\"]\n\t\t\t}\n\n\t\t];\n\n\t\ttotalQuestions = testItem.length;\n\t\t$(\"#unanswered\").remove();\n\t\t$(\".question\").text(\"Depth of Knowledge: JavaScript Edition\");\n\t\t$(\".answerBtn\").text(\"_\").addClass(\"off\").removeClass(\"on active correct incorrect smaller\");\n\t\t$(\".submitBtn\").text(\"CLICK TO BEGIN\").addClass(\"on correct\").click(startTimer).click(sounds.select).click(phaseOne);\n\t\t\n\t}",
"function addFakeQuestion() {\n Question.create({\n description: \"Interpreting a graph\",\n knowledge: \"know how to label graphs correctly\",\n test_num: \"Test 1\",\n calc: true,\n image_link: \"http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg\",\n difficulty: 1,\n type: \"Charts\",\n question_num: 7,\n category: \"Problem Solving\",\n subcategory: \"Key Features of Graphs\",\n isMC: true,\n answer: \"C\"\n });\n Question.create({\n description: \"Solving Max Flow\",\n knowledge: \"Learn to properly implement Ford Fulkerson\",\n test_num: \"Test 3\",\n calc: true,\n image_link: \"https://www.ptable.com/Images/periodic%20table.png\",\n difficulty: 4,\n type: \"Graphs\",\n question_num: 3,\n category: \"Algorithms\",\n subcategory: \"Graph Theory\",\n isMC: true,\n answer: \"D\"\n });\n Question.create({\n description: \"Divide and Conquer an Array\",\n knowledge: \"discover how to create subproblems\",\n test_num: \"Test 4\",\n calc: true,\n image_link: \"https://assets3.thrillist.com/v1/image/2754967/size/tmg-article_tall;jpeg_quality=20.jpg\",\n difficulty: 2,\n type: \"Arrays\",\n question_num: 4,\n category: \"Array Computing\",\n subcategory: \"Comp sci techniques\",\n isMC: true,\n answer: \"A\"\n });\n}",
"function addQuestions() {\n createQuestions(\"What is the incantation for unlocking a door?\", \"Wingardium Leviosa\",\n \"Sectumsempra\",\n \"Silencio\",\n \"Alohomora\");\n createQuestions(\"When affected by a Dementor what should one eat?\", \"Broccoli\",\n \"Bread\",\n \"Soup\",\n \"Chocolate\");\n createQuestions(\"What is the difference between a Werewolf and an Animagus?\",\n \"Nothing they are synonyms\",\n \"A Werewolf chooses when to transform and an Animagus does not\",\n \"A Werewolf is a version of an Animagus, they just chose a wolf\",\n \"A Werewolf is cursed and must transform, an Animagus chooses to turn into an animal\");\n createQuestions(\"If one were to drink a Unicorn’s blood what would happen?\",\n \"They would get a wish\",\n \"They would die instantly\",\n \"They would turn into a Unicorn\",\n \"They would be kept alive indefinitely but would live a cursed life\");\n createQuestions(\"Which one is an Unforgivable Curse?\",\n \"Reducto\",\n \"Stupefy\",\n \"Aguamenti\",\n \"Imperio\");\n createQuestions(\"What cures most poisons?\",\n \"Dragon’s blood\",\n \"Pixie wings\",\n \"Polyjuice Potion\",\n \"A Bezoar\");\n createQuestions(\"What is the incantation to Disarm someone?\",\n \"Expecto Patronum\",\n \"Petrificus Totalus\",\n \"Serpensortia\",\n \"Expelliarmus\");\n createQuestions(\"How long does it take to brew a Polyjuice Potion?\",\n \"6 days\",\n \"3 hours\",\n \"1 year\",\n \"1 month\");\n createQuestions(\"What is a Horcrux?\",\n \"A type of currency\",\n \"A sword used to destroy unbreakable items\",\n \"A ball used in Quidditch\",\n \"A fragment of a soul hidden in an object\");\n createQuestions(\"What should one do first before approaching a Hippogriff?\",\n \"Wave\",\n \"Sing\",\n \"Clap\",\n \"Bow\");\n }",
"function createGameView()\n\t{\n\t\t// create a default value\n\t\t_quickGameView = new GameView(_randomGameObject, gameViewLoaded);\n\t\t_quickGameView.createUI();\n\n\t\t_quickGameView.setQuestionText(currentQuestion.getText());\n\n\t\t//alert(\"current question\" + currentQuestion);\n\t\t// loads the localization data onto the screen widgets\n\t\tloadScreen();\n\t}",
"function createGame() {\n playersData.remove();\n var grid = generateRandomWeightedGrid(20,12);\n saveMap(grid);\n var newGame = {\n grid: JSON.stringify(grid), \n creatorName: getNomJoueur()\n }\n gameList.push(newGame);\n}",
"function new_game() {\n var game = {\n uid: random_uid(),\n state: GAME_IS_WAITING,\n story: random_short_story(),\n };\n\n game.parameters = starting_game_parameters_1(game);\n\n return game;\n}",
"function CreateNewGame(){\n if(typeof(newGame) == \"object\"){\n gameInstances.push(newGame);\n }\n newGame = new Hangman.game();\n// Run the logic in newGame to alter from the defaults to what should be the start.\n\tnewGame.gameWordLogic();\n newGame.gameWordUniqueLogic();\n gameStartInterfaceHelpers.makeHiddenWordField();\n console.log(\"made it after the helper.\"+newGame);\n\n var missProg = document.getElementById(\"misses\");\n\n}",
"function CreateGame() {\n\t\tvar players = Session.get(\"players\");\n\t\tvar teamSize = Session.get(\"team_size\");\n\t\tvar numOfPlayers = _.size(players);\n\t\tvar numOfTeams = (teamSize==10) ? 1 : Math.ceil(numOfPlayers/teamSize);\n\n\t\tplayers = randomizeArray(players); //randomize players array\n\n\t\t// If use selected 10+ players then create one team \n\t\t// Otherwise even out the teams and create them\n\t\tvar teams;\n\t\tif (numOfTeams == 1) {\n\t\t\tteams = CreateOneTeam(players);\n\t\t}\n\t\telse {\n\t\t\tplayers = EvenOutTeams(numOfPlayers, teamSize, players); //Even out the teams\n\t\t\tteams = CreateMultipleTeams(players, numOfTeams, teamSize);\n\t\t}\n\n\t\tSession.set(\"teams\", teams);\n\t}",
"function createNewQuiz() {\n\n\tvar roomID = generateCode(codeArr);\n\tcodeArr.push(roomID);\n\tconsole.log(\"room created \" + roomID);\n\n\tthis.emit('quizCreated', {roomId: roomID, mySocketId: this.id});\n\tthis.join(roomID);\n}",
"function createNewGame(canvasid, title) {\n console.log(\"createNewGame(): Now Running\");\n var newgame = new NewGame(canvasid, title);\n newgame.startGame(canvasid);\n}",
"function newGame() {\n\t\tif (gameSet === false) {\n\t\t\tcardsFlipped = 0;\n\t\t\tgameContainer.textContent = '';\n\t\t\tyourScore = 0;\n\t\t\tscore.textContent = 0;\n\t\t\tlet placeholder;\n\t\t\tcopyCARDS = [ ...CARDS ];\n\t\t\tcopyCARDS.length = challengeCount.value / 2;\n\t\t\tgameplayCARDS = [];\n\t\t\tfor (let card of copyCARDS) {\n\t\t\t\tgameplayCARDS.push(card);\n\t\t\t\tgameplayCARDS.push(card);\n\t\t\t}\n\t\t\tlet shuffledCards = shuffle(gameplayCARDS);\n\t\t\tcreateDivsForCards(shuffledCards);\n\t\t\tgameSet = true;\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc. You need to return the highest scoring word as a string. If two words score the same, return the word that appears earliest in the original string. All letters will be lowercase and all inputs will be valid. | function high(x){
let result = '';
let bestScore = 0;
let arrayWord = x.split(' ');
for (let p = 0 ; p < arrayWord.length ; p++ ){
let wordScore = 0;
for (let k = 0; k < arrayWord[p].length; k++){
let code = arrayWord[p].toUpperCase().charCodeAt(k)
if (code > 64 && code < 91 ) wordScore += (code - 64);
}
bestScore < wordScore ? ( bestScore = wordScore, result = arrayWord[p]) : null;
}
return result;
} | [
"function highestScoringWord(string) {\n const alphabet = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\n const scoreMapper = string\n .split(\" \")\n .reduce((result, word) => {\n const score = word.split(\"\").reduce((res, letter) => res + alphabet.indexOf(letter), 0);\n return { ...result, [word]: score }\n }, {});\n\n return Object.keys(scoreMapper)\n .reduce((acc, word) => scoreMapper[word] > (scoreMapper[acc] || 0) ? word : acc, \"\")\n}",
"function high(str){\n const alphabet = {\n 'a': 1,\n 'b': 2,\n 'c': 3,\n 'd': 4,\n 'e': 5,\n 'f': 6,\n 'g': 7,\n 'h': 8,\n 'i': 9,\n 'j': 10,\n 'k': 11,\n 'l': 12,\n 'm': 13,\n 'n': 14,\n 'o': 15,\n 'p': 16,\n 'q': 17,\n 'r': 18,\n 's': 19,\n 't': 20,\n 'u': 21,\n 'v': 22,\n 'w': 23,\n 'x': 24,\n 'y': 25,\n 'z': 26\n };\n const splitStr = str.split(' ');\n let highestWord = '';\n let scoreCount = 0;\n for (let word of splitStr) {\n let currentScore = 0;\n for(let i = 0; i < word.length; i++) {\n currentScore += alphabet[word[i]];\n }\n if (currentScore > scoreCount) {\n highestWord = word;\n scoreCount = currentScore;\n }\n }\n return highestWord;\n}",
"function high (str) {\n const alphabet = \" abcdefghijklmnopqrstuvwxz\";\n // word is split into an array of letters, reduce will add the index of each letter for a total score\n const score = word => word.split(\"\").reduce((a,c) => a + alphabet.indexOf(c), 0);\n\n let highestWord = \"\";\n let highestCount = 0;\n\n str.split(\" \").forEach(w => {\n const scoreCheck = score(w);\n if (scoreCheck > highestCount) {\n highestWord = w;\n highestCount = scoreCheck;\n }\n })\n return highestWord;\n}",
"function highestScoringWord(str) {\n\n\tlet words = str.split(' '),\n\t\twordScores = [],\n\t\tscore;\n\n\twords.forEach(word => {\n\n\t\tscore = 0;\n\n\t\tfor (let i = 0; i < word.length; i++) {\n\t\t\tscore += word.charCodeAt(i) - 96; // char code of 'a' = 97\n\t\t}\n\n\t\twordScores.push(score);\n\t});\n\n\treturn words[wordScores.indexOf(Math.max(...wordScores))];\n}",
"function high(x){\n let highestScore = 0;\n let highestWord = '';\n const words = x.split(' ');\n for (let i = words.length - 1; i >= 0; i--) {\n const word = words[i];\n let wordScoreCounter = 0;\n word.split('').forEach(letter => {\n // a: 97 - 96 = 1\n wordScoreCounter = wordScoreCounter + (letter.charCodeAt(0) - 96);\n });\n console.log(word, wordScoreCounter);\n \n if(wordScoreCounter >= highestScore) {\n highestScore = wordScoreCounter;\n highestWord = word;\n }\n }\n return highestWord;\n}",
"function high(x){\n let alpha = 'abcdefghijklmnopqrstuvwxyz'\n let highest = ''\n \n x.split(' ').forEach((word)=>{\n let total = 0\n let highestTotal = 0\n for(let i=0; i<word.length; i++){\n total += alpha.indexOf(word[i]) + 1\n }\n for(let i=0; i<highest.length; i++){\n highestTotal += alpha.indexOf(highest[i]) + 1\n }\n if(total > highestTotal){\n highest = word\n }\n })\n \n return highest\n }",
"function wordRank(str) {\n const strArr = str.split(\" \");\n let word;\n let num = 0;\n strArr.map(function (item) {\n let newNum = 0;\n let lowerCaseItem = item.toLowerCase();\n let newItem;\n if (\n lowerCaseItem[item.length - 1].charCodeAt() < 97 ||\n lowerCaseItem[item.length - 1].charCodeAt() > 122\n ) {\n newItem = lowerCaseItem.slice(0, -1);\n } else {\n newItem = lowerCaseItem;\n }\n //\n for (let i = 0; i < item.length; i++) {\n newNum += newItem.charCodeAt(i);\n if (newNum > num) {\n num = newNum;\n word = item;\n }\n }\n });\n\n if (\n word[word.length - 1].charCodeAt() < 97 ||\n (word[word.length - 1].charCodeAt() > 122 &&\n word[word.length - 1].charCodeAt() < 65) ||\n word[word.length - 1].charCodeAt() > 90\n ) {\n word = word.slice(0, -1);\n }\n\n console.log(word);\n}",
"function highScoreWord(str) {\n // split the words in the provided string apart\n var words = str.split(\" \");\n let wordValueArray = [];\n // sum the total of each word\n for (let i = 0; i < words.length; i++) {\n let currentWord = words[i];\n let counter = 0;\n let currentWordTally = 0;\n\n while (counter < currentWord.length) {\n let character = currentWord.charAt(counter).toLowerCase();\n currentWordTally += letters.indexOf(character) + 1;\n counter++;\n }\n wordValueArray.push(currentWordTally);\n }\n // compare to find highest word value\n console.log(wordValueArray);\n let highBid = Math.max.apply(null, wordValueArray);\n console.log(highBid);\n console.log(str);\n let index = wordValueArray.indexOf(highBid);\n // returns word with matching index\n console.log(words[index]);\n}",
"function mostFrequentLetter(string){\n\n}",
"function high(string){\n const letterConversion = {\n a:1,\n b:2,\n c:3,\n d:4,\n e:5,\n f:6,\n g:7,\n h:8,\n i:9,\n j:10,\n k:11,\n l:12,\n m:13,\n n:14,\n o:15,\n p:16,\n q:17,\n r:18,\n s:19,\n t:20,\n u:21,\n v:22,\n w:23,\n x:24,\n y:25,\n z:26\n }\n let highestSum = 0;\n let highestIndex = null;\n\n string.split(' ').forEach((word,index)=>{\n let sum = word.split('').map((letter)=>{\n return letterConversion[letter];\n }).reduce((a,b)=>{\n return a+b;\n },0)\n\n if ( sum > highestSum ) {\n highestSum = sum\n highestIndex = index;\n }\n })\n\n //if highest exists, return highest. else return \"\";\n return string.split(' ')[highestIndex] ? string.split(' ')[highestIndex] : \"\"\n}",
"function scrabbleScorer(word) {\n word = word.toUpperCase();\n let letterPoints = 0;\n for (let i=0; i<word.length; i++) {\n letterPoints += Number(newPointStructure[word[i]]);\n }\n return letterPoints;\n}",
"static scoreWord(word) {\n //create letterScore\n const letterScore = {\n 'A' : 1,\n 'N' : 1,\n 'B' : 3,\n 'O' : 1,\n 'C' : 3,\n 'P' : 3,\n 'D' : 2,\n 'Q' : 10,\n 'E' : 1,\n 'R' : 1,\n 'F' : 4,\n 'S' : 1,\n 'G' : 2,\n 'T' : 1,\n 'H' : 4,\n 'U' : 1,\n 'I' : 1,\n 'V' : 4,\n 'J' : 8,\n 'W' : 4,\n 'K' : 5,\n 'X' : 8,\n 'L' : 1,\n 'Y' : 4,\n 'M' : 3,\n 'Z' : 10\n };\n\n //initialize total\n let total = 0;\n //parse word into array of letters\n let letters = word.toUpperCase().split('');\n //if array of letters ===7,8,9,10\n if (letters.length >= 7 && letters.length <= 10) {\n //additional 8 points\n total += 8;\n }\n //loop through array of letters to find assigned value for that letter\n for (let i = 0; i < letters.length; i++) {\n //add values\n total = total + letterScore[letters[i]];\n }\n // return score that is integer\n return total; \n }",
"function high(x){\n let alphabet = 'abcdefghijklmnopqrstuvwxyz';\n let wordArr = x.split(' ');\n let biggest = { word: wordArr[0], total: wordArr[0].split('').reduce((acc, cur) => acc + alphabet.indexOf(cur) + 1, 0) };\n x\n .split(' ')\n .map(word => {\n let next = { word: word, total: word.split('').reduce((acc, cur) => acc + alphabet.indexOf(cur) + 1, 0) };\n if(next.total > biggest.total){\n biggest.total = next.total;\n biggest.word = next.word;\n }\n });\n return biggest.word;\n}",
"static scoreWord(word) {\n const letterValues = { \"A\": 1, \"B\": 3, \"C\": 3, \"D\": 2, \"E\": 1, \"F\": 4, \"G\": 2,\n \"H\": 4, \"I\": 1, \"J\": 8, \"K\": 5, \"L\": 1, \"M\": 3, \"N\": 1,\n \"O\": 1, \"P\": 3, \"Q\": 10, \"R\": 1, \"S\": 1, \"T\": 1, \"U\": 1,\n \"V\": 4, \"W\": 4, \"X\": 8, \"Y\": 4, \"Z\": 10 };\n const upperCaseWord = word.toUpperCase();\n // Loop thru the word and add the value for each letter\n let score = 0;\n for(let i = 0; i < upperCaseWord.length; i++) {\n score += letterValues[upperCaseWord[i]]; \n }\n if (upperCaseWord.length > 6) {\n score += 8;\n } \n return score;\n }",
"scoreWord(word) {\n //create letterScore\n const letterScore = {\n 'A' : 1,\n 'N' : 1,\n 'B' : 3,\n 'O' : 1,\n 'C' : 3,\n 'P' : 3,\n 'D' : 2,\n 'Q' : 10,\n 'E' : 1,\n 'R' : 1,\n 'F' : 4,\n 'S' : 1,\n 'G' : 2,\n 'T' : 1,\n 'H' : 4,\n 'U' : 1,\n 'I' : 1,\n 'V' : 4,\n 'J' : 8,\n 'W' : 4,\n 'K' : 5,\n 'X' : 8,\n 'L' : 1,\n 'Y' : 4,\n 'M' : 3,\n 'Z' : 10\n };\n\n //initialize total\n let total = 0;\n //parse word into array of letters\n let letters = word.toUpperCase().split('');\n //if array of letters ===7,8,9,10\n if (letters.length >= 7 && letters.length <= 10) {\n //additional 8 points\n total += 8;\n }\n //loop through array of letters to find assigned value for that letter\n for (let i = 0; i < letters.length; i++) {\n //add values\n total = total + letterScore[letters[i]];\n }\n // return score that is integer\n return total; \n }",
"function oldScrabbleScorer(word) {\n\tword = word.toUpperCase();\n\tlet letterPoints = \"\";\n \n\tfor (let i = 0; i < word.length; i++) {\n \n\t for (const pointValue in oldPointStructure) {\n \n\t\t if (oldPointStructure[pointValue].includes(word[i])) {\n\t\t\tletterPoints += `Points for '${word[i]}': ${pointValue}\\n`\n\t\t }\n \n\t }\n\t}\n\treturn letterPoints;\n }",
"function oldScrabbleScorer(word) {\n\tword = word.toUpperCase();\n\tlet letterPoints = \"\";\n\n\tfor (let i = 0; i < word.length; i++) {\n\n\t for (const pointValue in oldPointStructure) {\n\n\t\t if (oldPointStructure[pointValue].includes(word[i])) {\n\t\t\tletterPoints += `${pointValue}\\n`\n\t\t }\n\n\t }\n\t}\n\treturn letterPoints;\n }",
"function mostWanted(string) {\n let str = string.toLowerCase();\n let evalObj = {};\n let finalLetter = \"\";\n let counter = -Infinity\n let alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];\n\n for (let value of str) {\n alphabet.indexOf(value) !== -1 ? (evalObj[value] === undefined ? evalObj[value] = 1 : evalObj[value] += 1) : null;\n }\n console.log(evalObj);\n\n for (let key in evalObj) {\n evalObj[key] > counter ? (finalLetter = key, counter = evalObj[key]) : null;\n evalObj[key] === counter && alphabet.indexOf(finalLetter) > alphabet.indexOf(key) ? finalLetter = key : null;\n }\n return finalLetter;\n}",
"function greatestLetter(s) {\n const charMap = {};\n let highestChar = \"\";\n\n s.split(\"\").forEach((el) => {\n charMap[el] = true;\n\n if (\n upperAndLowerExistInTarget(el, charMap) &&\n charIsGreater(el, highestChar)\n ) {\n const char = el.toUpperCase();\n highestChar = char;\n }\n });\n\n return highestChar;\n\n function upperAndLowerExistInTarget(el, targetMap) {\n if (targetMap[el.toLowerCase()] && targetMap[el.toUpperCase()]) return true;\n return false;\n }\n\n function charIsGreater(el, highestChar) {\n if (el.toUpperCase() > highestChar) return true;\n return false;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert an LatLngBounds (Leaflet) to extent (ArcGIS) | function boundsToExtent (bounds) {
bounds = leaflet.latLngBounds(bounds);
return {
'xmin': bounds.getSouthWest().lng,
'ymin': bounds.getSouthWest().lat,
'xmax': bounds.getNorthEast().lng,
'ymax': bounds.getNorthEast().lat,
'spatialReference': {
'wkid': 4326
}
};
} | [
"function boundsToExtent (bounds) {\n\t bounds = leaflet.latLngBounds(bounds);\n\t return {\n\t 'xmin': bounds.getSouthWest().lng,\n\t 'ymin': bounds.getSouthWest().lat,\n\t 'xmax': bounds.getNorthEast().lng,\n\t 'ymax': bounds.getNorthEast().lat,\n\t 'spatialReference': {\n\t 'wkid': 4326\n\t }\n\t };\n\t}",
"function boundsToExtent(bounds) {\n bounds = leaflet.latLngBounds(bounds);\n return {\n 'xmin': bounds.getSouthWest().lng,\n 'ymin': bounds.getSouthWest().lat,\n 'xmax': bounds.getNorthEast().lng,\n 'ymax': bounds.getNorthEast().lat,\n 'spatialReference': {\n 'wkid': 4326\n }\n };\n }",
"function boundsToExtent (bounds) {\r\n bounds = Object(leaflet__WEBPACK_IMPORTED_MODULE_0__[\"latLngBounds\"])(bounds);\r\n return {\r\n 'xmin': bounds.getSouthWest().lng,\r\n 'ymin': bounds.getSouthWest().lat,\r\n 'xmax': bounds.getNorthEast().lng,\r\n 'ymax': bounds.getNorthEast().lat,\r\n 'spatialReference': {\r\n 'wkid': 4326\r\n }\r\n };\r\n}",
"function boundsToExtent(bounds) {\n bounds = L.latLngBounds(bounds);\n return {\n 'xmin': bounds.getSouthWest().lng,\n 'ymin': bounds.getSouthWest().lat,\n 'xmax': bounds.getNorthEast().lng,\n 'ymax': bounds.getNorthEast().lat,\n 'spatialReference': {\n 'wkid': 4326\n }\n };\n}",
"function boundsToExtent(bounds) {\n bounds = leaflet.latLngBounds(bounds);\n return {\n xmin: bounds.getSouthWest().lng,\n ymin: bounds.getSouthWest().lat,\n xmax: bounds.getNorthEast().lng,\n ymax: bounds.getNorthEast().lat,\n spatialReference: {\n wkid: 4326\n }\n };\n}",
"function extentToBounds (extent) {\r\n // \"NaN\" coordinates from ArcGIS Server indicate a null geometry\r\n if (extent.xmin !== 'NaN' && extent.ymin !== 'NaN' && extent.xmax !== 'NaN' && extent.ymax !== 'NaN') {\r\n var sw = Object(leaflet__WEBPACK_IMPORTED_MODULE_0__[\"latLng\"])(extent.ymin, extent.xmin);\r\n var ne = Object(leaflet__WEBPACK_IMPORTED_MODULE_0__[\"latLng\"])(extent.ymax, extent.xmax);\r\n return Object(leaflet__WEBPACK_IMPORTED_MODULE_0__[\"latLngBounds\"])(sw, ne);\r\n } else {\r\n return null;\r\n }\r\n}",
"function extentToBounds(extent){\n var southWest = new L.LatLng(extent.ymin, extent.xmin);\n var northEast = new L.LatLng(extent.ymax, extent.xmax);\n return new L.LatLngBounds(southWest, northEast);\n }",
"function markerBounds() {\n if (hasAnyFeatures()) {\n return markers.getBounds();\n } else {\n return [[90, 180], [-90, -180]];\n }\n }",
"function getMapExtent ()\n {\n\tvar extent = map.getView().calculateExtent(map.getSize());\n\treturn ol.proj.transformExtent(extent, 'EPSG:3857', 'EPSG:4326');\n }",
"function webMercatorBoundsToGeographic ({\n north,\n west,\n width,\n height,\n zoom\n}: {\n north: number,\n west: number,\n height: number,\n width: number,\n zoom: number\n}) {\n const nw = LeafletMap.prototype.unproject([west + 1, north], zoom)\n const se = LeafletMap.prototype.unproject(\n [west + width + 1, north + height],\n zoom\n )\n return {\n north: nw.lat,\n south: se.lat,\n east: se.lng,\n west: nw.lng\n }\n}",
"function SetMapExtent() {\n\tmap.getExtent();\n\tvar curBounds = map.getExtent();\n\tbounds = curBounds.transform(googleMercator, wgs84);\n\t//console.log(bounds);\n}",
"function convertBounds(bounds){\n\t return [\n\t llToGeoJsonArray(bounds.getNorthEast()),\n\t llToGeoJsonArray(bounds.getNorthWest()),\n\t llToGeoJsonArray(bounds.getSouthWest()),\n\t llToGeoJsonArray(bounds.getSouthEast()),\n\t llToGeoJsonArray(bounds.getNorthEast())\n\t ];\n\t}",
"getBoundsZoomLevel(bounds, mapDim) {\n var WORLD_DIM = { height: 256, width: 256 };\n var ZOOM_MAX = 21;\n \n function latRad(lat) {\n var sin = Math.sin(lat * Math.PI / 180);\n var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;\n return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;\n } \n function zoom(mapPx, worldPx, fraction) {\n return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);\n } \n var ne = bounds.getNorthEast();\n var sw = bounds.getSouthWest();\n \n var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI; \n var lngDiff = ne.lng() - sw.lng();\n var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;\n var latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);\n var lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);\n return Math.min(latZoom, lngZoom, ZOOM_MAX);\n }",
"function mapBounds() {\n if (options.initialview) {\n return options.initialview;\n } else {\n return markerBounds();\n }\n }",
"getLatLngBounds () {\n\t\tif (!this.options.data || !this._map) return null;\n\t\treturn L.latLngBounds(this.options.data.map((d) => { return [d.properties.lat, d.properties.lon]; }));\n\t}",
"getExtendedBounds(bounds) {\r\n const projection = this.getProjection();\r\n // Turn the bounds into latlng.\r\n const tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng());\r\n const bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng());\r\n // Convert the points to pixels and the extend out by the grid size.\r\n const trPix = projection.fromLatLngToDivPixel(tr);\r\n trPix.x += this.gridSize_;\r\n trPix.y -= this.gridSize_;\r\n const blPix = projection.fromLatLngToDivPixel(bl);\r\n blPix.x -= this.gridSize_;\r\n blPix.y += this.gridSize_;\r\n // Convert the pixel points back to LatLng\r\n const ne = projection.fromDivPixelToLatLng(trPix);\r\n const sw = projection.fromDivPixelToLatLng(blPix);\r\n // Extend the bounds to contain the new bounds.\r\n bounds.extend(ne);\r\n bounds.extend(sw);\r\n return bounds;\r\n }",
"_calculateFullExtent(data) {\n if (!data || data.length < 1) {\n throw new Error(\"no data in parameters\");\n }\n let full_extent = new L.latLngBounds(data[0].latlng, data[0].latlng);\n data.forEach((item) => {\n if (!full_extent.contains(item.latlng)) {\n full_extent.extend(item.latlng);\n }\n });\n return full_extent;\n }",
"function calcZoomForBounds(bounds, width, height) {\n\tvar WORLD_DIM = {width: 256, height: 256};\n\tvar ZOOM_MAX = 21;\n\t\n\tvar ne = {lon: bounds[2], lat: bounds[3]};\n\tvar sw = {lon: bounds[0], lat: bounds[1]};\n\t\n\tvar latFraction = (_latRad(ne.lat) - _latRad(sw.lat)) / Math.PI;\n\tvar lonDiff = ne.lon - sw.lon;\n\tvar lonFraction = ((lonDiff < 0) ? (lonDiff + 360) : lonDiff) / 360;\n\t\n\tvar latZoom = _zoom(height, WORLD_DIM.height, latFraction);\n\tvar lonZoom = _zoom(width, WORLD_DIM.width, lonFraction);\n\t\n\treturn Math.min(latZoom, lonZoom, ZOOM_MAX);\n}",
"fitBounds(longLat0, longAccessor, latAccessor) {\n let longLat = longLat0.slice();\n if (longAccessor && latAccessor) {\n longLat = longLat.map(d => [longAccessor(d), latAccessor(d)]);\n }\n let bound = new google.maps.LatLngBounds();\n longLat.forEach(d => {\n let long = d[0];\n let lat = d[1];\n bound.extend(new google.maps.LatLng(lat, long));\n });\n //Fit\n this.map.fitBounds(bound);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open wine section when url have wine | function hrefWine() {
const href = window.location.href;
if (href.slice(-4) == "wine") {
setTimeout(() => {
document.querySelector(".tab-title").click();
setTimeout(() => {
let headerHeight = document.querySelector('header').clientHeight;
const rect = document.querySelector("#wine").getBoundingClientRect(),
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const top = rect.top + scrollTop - headerHeight + 20;
jQuery('body, html').animate({scrollTop: top}, 1000);
}, 3000);
}, 1000);
}
} | [
"function openSpecificRestaurantWindo() {\n\t\t\t\twindow.open(\"resturantPage.html\");\n\t\t\t}",
"function openHTMLInOxygen() {\r\n helper.open(window.location.href)\r\n}",
"function goToLink(e, obj){\n var link = obj.part.data.link;\n if(link != '#'){\n window.open(link, '_blank');\n }\n }",
"function ShowUrl1(xiUrl, xiCaption, xiWidth, xiHeight, xiAllowScroll)\r\n{ \r\n window.location.href= xiUrl;\r\n}",
"function r2oWebviewOpen(){\n\t\t\treturn {\n\t\t\t\trestrict : \"A\",\n\t\t\t\tlink: function(scope, element, attrs){\n\t\t\t\t\t\telement.on('click', function(){\n\t\t\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\t\t\twindow.shopWebViewOverlay.goToPage(attrs.url);\n\t\t\t\t\t\t\t}, 200);\n\t\t });\n\t \t}\n\t\t\t};\n\t\t}",
"function GoToJellyfin() {\n window.open(\"https://snkstream.com/jellyfin\");\n}",
"function wikipedia (){\r\n window.open(wiki_link, \"_blank\")\r\n}",
"function open_page(url, where)\n{\n proto = \"http://\";\n\n if(url.substring(0, proto.length) == proto)\n window.open(url, \"new_window\");\n else\n $(where).load(url);\n}",
"openInSharePoint(){\n if(this.docPathURL != null){\n window.open(this.docPathURL);\n }\n }",
"function ToHopePage() {\n Linking.openURL('https://www.hopeokanagan.com');\n }",
"function openlink(upperCase){\n clickAnchor(upperCase,getItem(\"link\"));\n}",
"function openElpha(){\n window.open(\"https://elpha.com/\", \"_blank\");\n }",
"function openpageload() {\n\tpageload.show()\n}",
"function openWikipedia(url){\n\t\tvar wikiWin = Titanium.UI.createWindow({ \n\t\t title:'Wikipedia',\n\t\t url:'ui/WikipediaWindow.js',\n\t\t borderRadius: 0,\n\t\t barColor: '#4B5B60',\n\t\t navBarHidden: false,\n\t\t pageUrl: url\n\t\t});\n\t\t\n\t\twikiWin.open({modal:true, animate:true});\t\t\t\n\t}",
"goToWebsite(){\n this.openWebsite(this.mapPoint.website);\n }",
"function redirectHelp()\n {\n $window.open('https://12thdoor.zendesk.com/hc/en-us', '_blank');\n }",
"function showOpenPlaceWebsiteButton() {\r\n if (item) {\r\n var openPlaceWebsiteURL = item.attributes.url;\r\n if (openPlaceWebsiteURL && openPlaceWebsiteURL.replace(/[^A-Za-z0-9]/g,'').length > 2) {\r\n if ($('#WMEPHurl').length === 0 ) {\r\n strButt1 = '<input class=\"btn btn-success btn-xs\" id=\"WMEPHurl\" title=\"Open place URL\" type=\"button\" value=\"Open Website\" style=\"margin-left:3px;\">';\r\n $(\"#runWMEPH\" + devVersStr).after(strButt1);\r\n btn = document.getElementById(\"WMEPHurl\");\r\n if (btn !== null) {\r\n btn.onclick = function() {\r\n var item = W.selectionManager.selectedItems[0];\r\n if (item && item.model && item.model.attributes) {\r\n openPlaceWebsiteURL = item.model.attributes.url;\r\n if (openPlaceWebsiteURL.match(/^http/i) === null) {\r\n openPlaceWebsiteURL = 'http:\\/\\/'+openPlaceWebsiteURL;\r\n }\r\n if ( $(\"#WMEPH-WebSearchNewTab\" + devVersStr).prop('checked') ) {\r\n window.open(openPlaceWebsiteURL);\r\n } else {\r\n window.open(openPlaceWebsiteURL, searchResultsWindowName, searchResultsWindowSpecs);\r\n }\r\n }\r\n };\r\n } else {\r\n setTimeout(bootstrapRunButton,100);\r\n }\r\n }\r\n }\r\n }\r\n }",
"open() {\n browser.url(this.url);\n }",
"function ouvre_yamj3 ()\n\t\t{\n\t\tconsole.log(\"detail ouvre_yamj3\");\n\t\twindow.open(\"/yamj3/\", \"_blank\",\"\");\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the fragment shader according to type (fShader is global) | function setFragmentShader( type ) {
if ( type == CONSTANTS.STRIPE )
fShader = $('#shader-fs-stripes');
else if ( type == CONSTANTS.BRICK )
fShader = $('#shader-fs-bricks');
else
fShader = $('#shader-fs-checkers');
} | [
"setFragmentShader(shader) {\n\n // Bind the fragment shader\n this.fragmentShader = shader;\n\n // Generate the program again\n this.generate();\n }",
"set fragmentShaderSource(newValue) {\n this._fragmentShaderSource = newValue;\n this.initializeWebGL(); // redo initialization with new renderer\n }",
"function ShaderFragment() {\n}",
"create(id, vShader, fShader) {\n let shader = new Shader(vShader, fShader);\n this.shaders.set(id, shader);\n }",
"setShader(_shaderType) {\n this.shaderType = _shaderType;\n let coat = this.createCoatMatchingShader();\n coat.mutate(this.coat.getMutator());\n this.setCoat(coat);\n }",
"createShader (gl, shaderScript, type) {\n const shader = gl.createShader(type)\n\n gl.shaderSource(shader, shaderScript)\n gl.compileShader(shader)\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))\n this.error(gl.getShaderInfoLog(shader))\n\n return shader\n }",
"SetGlobalShaderProperty() {}",
"fragmentShaderSource() {\n return `\n precision mediump float;\n\t\t\tvarying vec3 vPosition;\n\t\t\tvarying vec3 vNormal;\n\t\t\tvarying vec3 vColor;\n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = vec4(vColor, 1.0);\n\t\t\t}`;\n }",
"function _handleShader(contents, shadertype) {\n\tvar newScript = document.createElement('script');\n\tnewScript.type = 'text/x-glsl';\n\tnewScript.id = shadertype;\n\tnewScript.text = contents;\n\tdocument.getElementsByTagName('body')[0].appendChild(newScript);\n}",
"setVertexShader(shader) {\n\n // Bind the vertex shader\n this.vertexShader = shader;\n\n // Generate the program again\n this.generate();\n }",
"setShader(vShaderCode,fShaderCode,uniforms) {\n var newShader = new PIXI.AbstractFilter(vShaderCode,fShaderCode,uniforms);\n this.setState({\n shader: [newShader]\n }, ()=>{this.stage._app.render()});\n this.processStack = [this.state.shader];\n }",
"function setupShaders() {\n __shaders.vertexShader_normal = document.getElementById(\"vertexShader_normal\").text;\n __shaders.fragmentShader_normal = document.getElementById(\"fragmentShader_normal\").text;\n}",
"function addShader(name) {\n\tvar shaderTag;\n\n\tshaderTag = document.createElement('script');\n\tshaderTag.setAttribute(\"data-src\",\"brdf/\"+name+\".glslv\");\n\tshaderTag.setAttribute(\"data-name\",name);\n\tshaderTag.setAttribute(\"type\",\"x-shader/x-vertex\");\n\tdocument.getElementsByTagName('head')[0].appendChild(shaderTag);\n\n\tshaderTag = document.createElement('script');\n\tshaderTag.setAttribute(\"data-src\",\"brdf/\"+name+\".glslf\");\n\tshaderTag.setAttribute(\"data-name\",name);\n\tshaderTag.setAttribute(\"type\",\"x-shader/x-fragment\");\n\tdocument.getElementsByTagName('head')[0].appendChild(shaderTag);\n\n\tvar select = document.getElementById(\"shaderSelector\").options;\n\tselect[select.length] = new Option(name);\n}",
"function createShader(gl, str, type)\n{\n let shader;\n\n // Checking the type of shader\n if (type == \"fragment\") {\n shader = gl.createShader(gl.FRAGMENT_SHADER);\n } else if (type == \"vertex\") {\n shader = gl.createShader(gl.VERTEX_SHADER);\n } else {\n return null;\n }\n\n gl.shaderSource(shader, str);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(gl.getShaderInfoLog(shader));\n return null;\n }\n\n return shader;\n}",
"function compileShader() {\n\tshaders[currentShader].vertex = document.getElementById('editor_vshader').value;\n\tshaders[currentShader].fragment = document.getElementById('editor_fshader').value;\n\t\n\tvar shader = shaders[currentShader].program;\n\n\t// disable all enabled vertex array objects before switching to the new shader\n\tif(shader) {\n\t\tif (shader.vertexPositionAttribute >= 0)\n\t\t\tgl.disableVertexAttribArray(shader.vertexPositionAttribute);\n\t\tif (shader.vertexNormalAttribute >= 0)\n\t\t\tgl.disableVertexAttribArray(shader.vertexNormalAttribute);\n\t\tif (shader.textureCoordAttribute >= 0)\n\t\t\tgl.disableVertexAttribArray(shader.textureCoordAttribute);\n\t}\n\n\tshaders[currentShader].program = createProgram(shadersList[currentShader], shaders[currentShader].vertex, shaders[currentShader].fragment);\n\tshader = shaders[currentShader].program;\n\t\n\tif(shaders[currentShader].program) {\n\t\tgl.useProgram(shaders[currentShader].program);\n\n\t\t// enable vertex array objects that are used by the new shader\n\t\tif (shader.vertexPositionAttribute >= 0)\n\t\t\tgl.enableVertexAttribArray(shader.vertexPositionAttribute);\n\t\tif (shader.vertexNormalAttribute >= 0)\n\t\t\tgl.enableVertexAttribArray(shader.vertexNormalAttribute);\n\t\tif (shader.textureCoordAttribute >= 0)\n\t\t\tgl.enableVertexAttribArray(shader.textureCoordAttribute);\n\t}\n\n\t// reset slide bars\n\t// better read off the current values from the controls and set them to the uniforms\n\tupdateOptionControls();\n}",
"function create_shader_from_script(gl, script, type) {\n if (!script) {\n throw \"Unknown script element “%0”\".fmt(id);\n }\n if (!type) {\n if (script.type == \"x-shader/x-vertex\") {\n type = gl.VERTEX_SHADER;\n } else if (script.type == \"x-shader/x-fragment\") {\n type = gl.FRAGMENT_SHADER;\n } else if (type != gl.VERTEX_SHADER && type != gl.FRAGMENT_SHADER) {\n throw \"Unknown shader type\";\n }\n }\n return compile_shader(gl, script.textContent, type);\n}",
"createShader() {\n //........................................\n var vShader = '#version 300 es\\n' +\n 'layout(location=0) in vec3 a_position;' +\n 'uniform mat4 uPMatrix;' +\n 'uniform mat4 uCameraMatrix;' +\n 'out highp vec3 texCoord;' +\n 'void main(void){' +\n 'texCoord = a_position.xyz;' +\n 'gl_Position = uPMatrix * uCameraMatrix * vec4(a_position.xyz, 1.0);' +\n '}';\n //........................................\n //Build Fragment Shader Based on if there is a Night Texture.\n var fShader = '#version 300 es\\n' +\n 'precision mediump float;' +\n 'out vec4 finalColor;' +\n 'in highp vec3 texCoord;' +\n 'uniform samplerCube uDayTex;';\n if (this.mNightTex == -1)\n fShader += 'void main(void){ finalColor = texture(uDayTex, texCoord); }';\n else\n fShader += 'uniform samplerCube uNightTex; uniform float uTime;' +\n 'void main(void){ finalColor = mix( texture(uDayTex, texCoord), texture(uNightTex, texCoord), uTime ); }';\n //........................................\n this.mShader = C_ShaderUtil.createProgramFromText(this.gl, skyShader[0], skyShader[1], true);\n this.mUniProj = this.gl.getUniformLocation(this.mShader, \"uPMatrix\");\n this.mUniCamera = this.gl.getUniformLocation(this.mShader, \"uCameraMatrix\");\n this.mUniDayTex = this.gl.getUniformLocation(this.mShader, \"uDayTex\");\n if (this.mNightTex != -1) {\n this.mUniNightTex = this.gl.getUniformLocation(this.mShader, \"uNightTex\");\n this.mUniTime = this.gl.getUniformLocation(this.mShader, \"uTime\");\n }\n }",
"function changeFragColor(r, g, b, a, gl){\r\n gl.uniform4f(u_FragColor, r, g, b, a);\r\n }",
"useNewShaders() {\n this.vertexShader = this.createShader(this.vsCode, this.gl.VERTEX_SHADER);\n this.fragmentShader = this.createShader(this.fsCode, this.gl.FRAGMENT_SHADER);\n\n if(!this.vertexShader || !this.fragmentShader) {\n if(!this.renderer.production) throwWarning(this.type + \": Unable to find or compile the vertex or fragment shader\");\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
shows or hides Paymentfilter edits | function switchPaymentFilter(flag) {
var trId = "trPaymentFilter";
Element[flag ? 'show' : 'hide'](trId);
} | [
"function showEditButtons () {\n $element.parent().find('.edit-button').css('visibility', 'visible');\n }",
"function _controlFilterVisibility(){\n\t\t\tlet visibility = _properties.hasFilter ? \"block\" : \"none\";\n\t\t\t_$filter.css(\"display\", visibility);\n\t\t\t_$filter.attr(\"placeholder\", _properties.filterPlaceholder);\n\t\t}",
"function showEditAccounts(){\n\t\t$(\"#editAccounts\").show();\n\t\t$(\".accountDetails\").hide();\n\t}",
"function modeFilter()\n{\n $('#filters').show();\n updateFilter();\n}",
"function toggleFilter() {\n vm.showFilter = !vm.showFilter;\n }",
"function showEdit(){\n\t$('#sbe-side-title, #sbe-side-content').hide();\n\t$('.sbe-side-label, #sbe-title-edit, #sbe-content-edit, #sbe-img-edit, #sbe-category-edit, #ip-open-btn, #sbe-active').show();\n}",
"function esf_show_filter_ui(element_id) {\n\t\t\t$('#'+element_id+'_tree').find('.esf-remove-filters').removeClass('hidden').attr('aria-hidden', 'false');\n\t\t}",
"function toggleCustomFilterTextBox(){\n\t\t$('#ocqlFilterInputTextParent').css(\"display\",\"block\");\n}",
"function filterView() {\n\tif (filter == \"all\") {\n\t\t$(\"#entryList div.panel\").removeClass(\"hidden\");\n\t}else {\n\t\t$(\"#entryList div.panel\").addClass(\"hidden\");\n if (filter == \"starred\") $(\"#entryList input[value='starred']\").parent().parent().removeClass(\"hidden\");\n\t\telse $(\"#entryList input[value='\" + filter + \"']\").parent().parent().parent().removeClass(\"hidden\");\n\t\tif (filter == \"unread\") $(\"#entryList input[value='new']\").parent().parent().parent().removeClass(\"hidden\");\n\t\t$(\"#entryList #more\").removeClass(\"hidden\");\n\t\t$(\"#entryList #last\").removeClass(\"hidden\");\n }\n \t// set first visible entry to be activea\n makeFirstEntryActive();\n\t\n}",
"function hideFilterPanel(){\n\t\tif ($filterRow.hasClass('hidden')) {\n\t\t\t$resultRow.addClass('hidden');\n\t\t\t$filterRow.removeClass('hidden');\n\t\t}else{\n\t\t\t$filterRow.addClass('hidden');\n\t\t\t$resultRow.removeClass('hidden');\n\t\t}\n\t}",
"function showEnsFilters() {\t\r\n\r\n}",
"function showEditCard() {\n setShowEdit((showEdit) => !showEdit)\n }",
"toggleFilter() {\n if (this.showFilters) {\n this.showFilters = false;\n\n this.resetFilters();\n } else {\n this.showFilters = true;\n }\n }",
"function hideWorkflowEditButton()\n {\n $.PercDataList.enableButtons(container);\n $(\"#perc-wf-update-editor\").hide();\n $(\"#perc-wf-name-wrapper\").hide();\n dirtyController.setDirty(false);\n }",
"function editOtherInfo(){\n $(\"#edit_other_info_show_hide\").show();\n $(\"#other_info_show_hide\").hide();\n $(\"#btn-cancel\").on(\"click\", function() {\n $(\"#edit_other_info_show_hide\").hide();\n $(\"#other_info_show_hide\").show();\n });\n}",
"showEditView() {\n this.state = FIELD_STATE.EDIT;\n this.update();\n }",
"function toggleFilter() {\n buttonText = isVisible ? 'Show Filter' : 'Hide Filter';\n $buttonHideFilter.text(buttonText);\n $filters.toggle();\n isVisible = !isVisible;\n}",
"function showAsEditForm() {\n syllabusIdField.parent().removeClass('hidden');\n syllabusStateField.removeClass('hidden');\n }",
"function showEdit(){\n\t$('#ne-side-title, #ne-side-article').hide();\n\t$('.ne-side-label, #ne-title-edit, #ne-intro-edit, #ne-article-edit, #ne-img-edit, #ne-sdate-edit, #ne-edate-edit, #ne-img-edit').show();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
writeCellCode(rowID, dateCode, thisDay, thisMonth) | function writeCellCode(rowID, dateCode, thisDay, thisMonth, thisYear) {
/** Using the details provided append the correct row with the cell
code. **/
var l1 = '<td><ul id="'+dateCode+'">';
var l2 = '<li class="liBold">'+thisDay+' <span class="month">';
var l3 = monthName[thisMonth]+' '+thisYear+'</span></li></ul></td>';
$(rowID).append(l1+l2+l3);
} | [
"function writeNextMonth(){\n\t//create an array of month names to reference. note: january starts at array element position 0, not 1.\n\tvar monthName = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\t\n\t//update month global variable with the array position of the next month\n\tmonth = month + 1;\n\tif (month == 12){\n\t\tmonth = 0;\n\t\tyear++;\n\t}\n\t\n\t//change month name in title\n\tdocument.getElementById(\"calendar_head\").innerHTML = monthName[month] + \" \" + year;\n\n\t//clear the contents of the cells in the calendar table\n\tclearCalendarDays();\n\t//change the class name of the highlighted cell to calendar_dates\n\tdocument.getElementById(todayCell).className = \"calendar_dates\";\n\t//write the events and dates of the next month\n\twriteNextCalDays();\n\t\n}",
"function creatCells() {\n\t\t\tstartOfWeek();\n\t\t\tvar thisDate = targetSundayDate;\n\t\t\t// var tempArray = [];\n\t\t\tfor (n=0;n<numRows;n++) {\n\t\t\t\t/** For each row of the table... **/\n\t\t\t\tfor (b=0;b<7;b++) {\n\t\t\t\t\t/** Repeat seven times:\n\t\t\t\t\t\tCreate the dateCode, which will be used as the cell ID.\n\t\t\t\t\t\tCreate and write the code for the cell.\n\t\t\t\t\t\tChange the date to tomorrow in prep for next cell. **/\n\t\t\t\t\tvar monthPlusOne = thisDate[1]+1;\n\t\t\t\t\tvar dateCode = thisDate[0].toString()+'x'+monthPlusOne.toString()+'x'+thisDate[2].toString();\n\t\t\t\t\twriteCellCode('#row'+n,dateCode,thisDate[2],thisDate[1],thisDate[0]);\n\t\t\t\t\t// tempArray.push(dateCode);\n\t\t\t\t\tthisDate = tomorrow(thisDate);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// console.log('createCells :: tempArray.length :: '+tempArray.length);\n\t\t}",
"function writeCode() {}",
"function day_cell(n) {\r\n return get_element('calendar_day_'+n);\r\n}",
"generateWeekRowDayCellText(day){\n\n let calendarDate = new Date()\n , currentMonthDay = calendarDate.getDate()\n , currentMonthDayTime = calendarDate.getTime()\n , dayOffset = (currentMonthDay - day)\n\n calendarDate.setDate(currentMonthDay - dayOffset)\n\n let dayOfMonth = calendarDate.getDate()\n , dayTextTime = calendarDate.getTime()\n , dayTextWithStyle = this.applyHighlightStyle(dayOfMonth, dayTextTime, currentMonthDayTime)\n\n /***OUTPUT TO TABLECELL***/\n return dayTextWithStyle\n\n }",
"function dateWriter(year, month, day) {\n return month+\"/\"+day+\"/\"+year;\n}",
"function addDateToCalendar(row, day, dateValueOf){\n\t\n\tvar dataCol = $('<td>');\n\trow.append(dataCol);\n\n\tvar innerElem = $('<div>');\n\tdataCol.append(innerElem);\n\t\n\tinnerElem.append('<span class=\"celldate-number\">' + (day) +'</span>');\n\tinnerElem.data('itemdata', dateValueOf);\n\tinnerElem.addClass('celldate-container');\n}",
"function locationToCode(row, col) {\n return (String.fromCharCode(col + 97)) + (row + 1);\n}",
"function writeCalDays() {\n\t//find today's date\n\tvar calendarDay = new Date();\n\t//create the first day of the month\n\tvar day = new Date(calendarDay.getFullYear(), calendarDay.getMonth(), 1);\n\t//find the weekday the month starts on (0-6)\n\tvar weekDay = day.getDay();\n\tvar cellCount = 1;\n\t\n\t//set global month and year variables\n\tsetMonthYear();\n\t\n\t//copy the events array for the current month from the appropriate month event array\n\tswitch(month){\n\t\tcase 0:\n\t\t\tvar currentMonthEvents = JanuaryDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tvar currentMonthEvents = FebruaryDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvar currentMonthEvents = MarchDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvar currentMonthEvents = AprilDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tvar currentMonthEvents = MayDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tvar currentMonthEvents = JuneDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\tvar currentMonthEvents = JulyDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\tvar currentMonthEvents = AugustDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tvar currentMonthEvents = SeptemberDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 9:\n\t\t\tvar currentMonthEvents = OctoberDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\tvar currentMonthEvents = NovemberDayEvent.slice(0);\n\t\t\tbreak;\n\t\tcase 11:\n\t\t\tvar currentMonthEvents = DecemberDayEvent.slice(0);\n\t\t\tbreak;\n\t}\n\n\t//print a blank cell for all days preceding the monthly start date\n\tif (weekDay > 0){\n\t\tfor (var i = 1; i <= weekDay; i++) {\n\t\t\tdocument.getElementById(\"Cell\" + i).innerHTML = \"\";\n\t\t\tcellCount++;\n\t\t}\n\t}\n\n\t//print the date and events for each cell in the table\n\tfor (var i = 1; i < daysInMonth() + 1; i++) {\n\t\tdocument.getElementById(\"Cell\" + cellCount).innerHTML = i + currentMonthEvents[i];\n\t\t\n\t\tif (i == calendarDay.getDate()){\n\t\t\tdocument.getElementById(\"Cell\" + cellCount).className = \"calendar_today\";\n\t\t\ttodayCell = \"Cell\" + cellCount;\n\t\t}\n\t\t\n\t\tcellCount++;\n\t}\n\t\n\t\n}",
"_buildShiftCountCells(row,shiftCountData,itoId)\n\t{\n\t\tvar cell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_totalHour\";\n\t\tcell.textContent=shiftCountData[\"totalHour\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_actualHour\";\n\t\tcell.textContent=shiftCountData[\"actualHour\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_lastMonthBalance\";\n\t\tcell.textContent=shiftCountData[\"lastMonthBalance\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_thisMonthHourTotal\";\n\t\tcell.textContent=shiftCountData[\"thisMonthHourTotal\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_thisMonthBalance\";\n\t\tcell.textContent=shiftCountData[\"thisMonthBalance\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_aShiftCount\";\n\t\tcell.textContent=shiftCountData[\"aShiftCount\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_bxShiftCount\";\n\t\tcell.textContent=shiftCountData[\"bxShiftCount\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_cShiftCount\";\n\t\tcell.textContent=shiftCountData[\"cShiftCount\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_dxShiftCount\";\n\t\tcell.textContent=shiftCountData[\"dxShiftCount\"];\n\t\trow.appendChild(cell);\n\n\t\tcell=SimpleCellFactory.BorderedAlignCenterCell;\n\t\tcell.id=itoId+\"_noOfWoringDay\";\n\t\tcell.textContent=shiftCountData[\"noOfWorkingDay\"];\n\t\trow.appendChild(cell);\n\t}",
"function addDates() {\n var i = cellStart;\n // get day to start month's dates from\n var date = 1;\n while (i < cellEnd) {\n // iterate through array of cells\n cellArray[i].innerText = date;\n // add date into cell\n if (date === currentDate.getUTCDate()) {\n // change colour and font of current date cell\n cellArray[i].style.background = \"rgb(21, 117, 124)\";\n cellArray[i].style.color = \"rgb(255, 255, 255)\";\n }\n i += 1;\n date += 1;\n }\n}",
"function insert_cell(rowObject,cell_number,cell_data){\n var cell_id = rowObject.insertCell(cell_number);\n cell_id.innerHTML = cell_data;\n}",
"function getCellId(row, col){\r\n return 'cell_row' + row + '_col' + col;\r\n}",
"function dateWriter(year, month, day) {\n return month + '/' + day + '/' + year;\n}",
"codeToDate(dateCode) {\n const baseDate = new Date(1997, 9, 7)\n const date = new Date(baseDate.getTime() + (parseInt(dateCode) + 1)\n * 86400000)\n return [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/')\n }",
"function onCreateCell(cell, cellData, rowData, rowIndex, colIndex){\r\n\t\t\tjQuery(cell).attr('data-fieldname', columns[colIndex].name);\t\t\t\t\r\n\t\t}",
"function getDateCell(eventDate){\n var ymd = new Date(eventDate +\"T12:00:00Z\");\n var wkday = ymd.getDay();\n var wk = null;\n var weeks = currentMonth.getWeeks();\n \n for(var w in weeks){\n var days = weeks[w].getDates();\n if(days[wkday].getDate() == ymd.getDate() && days[wkday].getMonth() == ymd.getMonth()){\n wk = w;\n break;\n }\n }\n if(wk != null){\n return document.getElementById('colbottom' + wk + wkday);\n }\n else{\n return null;\n }\n}",
"function setTimeStamp(numRow, numCol) {\n\n // get cell\n var cell = SHEET.getRange(numRow, numCol);\n \n var d = new Date();\n \n // set date\n cell.setValue(d);\n\n\n}",
"function handleCellClick(dayNum) {\n if (dayNum !== \"X\") {\n // create dateString and pass to parent function cellClick, which gives default date to AddCompleted component\n let dateString = `${monthYear.slice(0, 3)}-${dayNum}-${monthYear.slice(3)}`;\n props.cellClick( dayjs(dateString).format('YYYY-MM-DD') );\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tracks a request promise, starting and then ending the request (triggering new slots). | trackRequestPromise(handle, promise) {
this.startRequest(handle);
promise.then(() => this.endRequest(handle)).catch(() => this.endRequest(handle));
} | [
"finishRequest(aRequest) {\n let requestIndex = this._requestQueue.indexOf(aRequest);\n if (requestIndex >= 0)\n this._requestQueue.splice(requestIndex, 1);\n // signal the queue to fire any pending requests\n this.queueRequest(null);\n }",
"_makeNextRequest() {\n this._waiting = true;\n this._testem.emit(this._request, this._browserId);\n }",
"onRequestStarted() {\n this.startedRequestCount++;\n\n const activeCount = this.activeRequestCount();\n log.verbose('NetworkRecorder', `Request started. ${activeCount} requests in progress` +\n ` (${this.startedRequestCount} started and ${this.finishedRequestCount} finished).`);\n\n // If only one request in progress, emit event that we've transitioned from\n // idle to busy.\n if (activeCount === 1) {\n this.emit('networkbusy');\n }\n }",
"onRequestStarted(request) {\n this.startedRequestCount++;\n this._records.push(request.data);\n\n const activeCount = this.activeRequestCount();\n log.verbose('NetworkRecorder', `Request started. ${activeCount} requests in progress` +\n ` (${this.startedRequestCount} started and ${this.finishedRequestCount} finished).`);\n\n // If only one request in progress, emit event that we've transitioned from\n // idle to busy.\n if (activeCount === 1) {\n this.emit('networkbusy');\n }\n\n // If exactly three requests in progress, we've transitioned from 2-idle to 2-busy.\n if (activeCount === 3) {\n this.emit('network-2-busy');\n }\n }",
"run () {\n let request = this.requestQueue.shift()\n // resolve all cancelled requests\n while (!isNil(request) && request.cancelled) {\n request.reject()\n request = this.requestQueue.shift()\n }\n if (!isNil(request)) {\n request.resolve()\n this.lastExecutionTime = Date.now()\n }\n this.idle = true\n this.wakeUp()\n }",
"startRequest(handle) {\n this.activeRequestCount++;\n }",
"request() {\n this.requestId = requestIdleCallback(idleDeadline => {\n this.requestId = null\n this.continue(idleDeadline)\n })\n }",
"resume() {\n // 处理等待队列的请求\n while (this.canRequest()\n && this.waitQueue.length > 0) {\n const { url, resolve, reject } = this.waitQueue.shift();\n this.get(url).then(resolve).catch(reject);\n }\n }",
"function finish() {\n if (pendingRequests > 0) {\n pendingRequests -= 1;\n if (pendingRequests < 1 && notifyFinish) {\n $rootScope.$broadcast(APP_EVENTS.END_REQUEST);\n notifyFinish = false;\n }\n }\n }",
"trackRequest (request) {\n\t\tthis.trackedRequests[request.id] = request;\n\t}",
"async _finishRequest() {\n const response = await this._worker.postMessage('finish');\n\n this.hasEvents = false;\n\n return response;\n }",
"async _requestHandler(route, initiate, req, res) {\n let taskId = req.body.id,\n promise\n\n function isChanged(task, timestamp) { return (!task || task.completed || (task.timestamp > timestamp)) }\n\n if (!taskId) { // initial request\n let task\n try {\n task = await initiate(req)\n task.route = route\n await task.save()\n }\n catch (e) {\n this.log.error('queued-task _requestHandler ', e)\n }\n promise = Promise.resolve(this._packageTask(task))\n }\n else {\n let task = await this.getTask(taskId)\n if (route !== task.route) {\n this.log.error('queued-task _requestHandler route mismatch')\n promise = Promise.resolve()\n res.status(400)\n }\n else {\n let timestamp = req.body.timestamp || 0\n task = this._packageTask(task)\n if (isChanged(task, timestamp))\n promise = Promise.resolve(task)\n else {\n let timerId,\n progressListener,\n timer = new Promise((resolve, reject) => {\n timerId = setTimeout(() => {\n resolve(task)\n timerId = undefined\n }, taskProgressLimit)\n }),\n checker = new Promise((resolve, reject) => {\n progressListener = (task) => {\n if (task.id === taskId) {\n task = this._packageTask(task)\n if (isChanged(task, timestamp)) resolve(task)\n }\n }\n queuedTask.on('queued-task-progress', progressListener)\n })\n promise = Promise.race([checker, timer])\n .finally(() => {\n if (timerId) clearTimeout(timerId)\n queuedTask.removeListener('queued-task-progress', progressListener)\n })\n }\n }\n }\n\n return promise.then((task) => {\n res.json({task})\n })\n }",
"handleDeferredRequests() {\n this.requests.forEach((entry) => {\n const { deferred, request: { name, serial } } = entry;\n // Stop processing When the current request isn't deferred, or still has running dependencies.\n if (!deferred || this.hasRunningDependencies(name)) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n entry.deferred = false;\n this.sendRequest(serial);\n });\n }",
"_next() {\n\t\twhile (this._running < this._parallel && this._requests.length !== 0) {\n\t\t\tthis._completed = false; // We have a new request about to start so we are not completed.\n\t\t\tthis._running++;\n\t\t\trequest(this._requests.shift())\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._running--;\n\t\t\t\t\tthis.emit(EVENTS.RESOLVED, res);\n\t\t\t\t\tthis._wait().then(() => this._next());\n\t\t\t\t})\n\t\t\t\t.catch(err => {\n\t\t\t\t\tthis._running--;\n\t\t\t\t\tthis.emit(EVENTS.REJECTED, err);\n\t\t\t\t\tthis._wait().then(() => this._next());\n\t\t\t\t});\n\t\t}\n\t\tthis._emitIfCompleted();\n\t}",
"async do_request_processing() {\n try {\n await this.emit_start()\n let rsp = await this.send_request()\n let data = this.parse_response_data(rsp)\n rsp = null\n await this.emit_data(data)\n data = null\n } catch (err) {\n if (this._check_ignore_errors(err)) await this.emit_error_ignored(err)\n else this.emit_error(err)\n } finally {\n await this.emit_complete()\n }\n }",
"addOpenRequest(id, promise) {\n logger.log('addOpenRequest', this.name, `adding request ${id} and waiting for answer`);\n this.openRequests.set(id, promise);\n }",
"_sendNextRequest () {\n const ticket = this._nextTicketInLine\n let { request, requestSent } = this._requestMap.get(ticket)\n if (requestSent) {\n // A request was sent and is waiting its response.\n // Wait for the full respones before sending another request.\n return\n } else {\n requestSent = true\n this._requestMap.set(ticket, { request, requestSent })\n }\n console.assert(request != null, { ticket, request })\n const jsonRequest = JSON.stringify(request)\n const requestMap = this._requestMap\n console.debug('PeerFetch: Sending request to remote peer',\n { requestMap, ticket, request })\n try {\n this._dataConnection.send(jsonRequest)\n console.debug('PeerFetch: Request sent to remote peer: ', jsonRequest)\n } catch (error) {\n console.error('PeerFetch: Error sending message via Peer DataConnection', { error })\n }\n }",
"add(request) {\n request.requestCount = 0;\n request.id = uuid.v4();\n request.requests = [];\n if (!request.repeat) {\n request.repeat = 1;\n }\n this.pending.push(request);\n return request;\n }",
"untrackRequest (request) {\n\t\tdelete this.trackedRequests[request.id];\n\t\tif (Object.keys(this.trackedRequests).length === 0) {\n\t\t\tthis.api.noMoreRequests();\n\t\t}\n\t\telse if (this.api.waitingToShutdown()) {\n\t\t\tthis.api.waitingForRequests(Object.keys(this.trackedRequests), request.id);\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Permutes the dependencies into topological order | function topoSort (deps) {
// Build reversed adjacency list
var adj = {}
var inDegree = {}
var index = {}
deps.forEach(function (dep) {
var v = dep.id
var nbhd = Object.keys(dep.deps)
index[dep.id] = dep
inDegree[v] = nbhd.length
nbhd.forEach(function (filename) {
var u = dep.deps[filename]
if (adj[u]) {
adj[u].push(v)
} else {
adj[u] = [v]
}
})
})
// Initialize toVisit queue
var result = []
var inverse = {}
deps.forEach(function (dep) {
var v = dep.id
if (!adj[v]) {
adj[v] = []
}
if (inDegree[v] === 0) {
inverse[v] = result.length
result.push(v)
}
})
// Run BFS
for (var ptr = 0; ptr < result.length; ptr++) {
var v = result[ptr]
adj[v].forEach(function (u) {
if (--inDegree[u] === 0) {
inverse[u] = result.length
result.push(u)
}
})
}
if (result.length !== deps.length) {
throw new Error('cyclic dependency')
}
// Relabel dependencies
return result.map(function (v) {
var dep = index[v]
var deps = dep.deps
var ndeps = {}
Object.keys(deps).forEach(function (filename) {
ndeps[filename] = inverse[deps[filename]] | 0
})
return {
id: inverse[v] | 0,
deps: ndeps,
file: dep.file,
source: dep.source,
entry: dep.entry
}
})
} | [
"function topoSort (deps) {\r\n // Build reversed adjacency list\r\n var adj = {}\r\n var inDegree = {}\r\n var index = {}\r\n deps.forEach(function (dep) {\r\n var v = dep.id\r\n var nbhd = Object.keys(dep.deps)\r\n index[dep.id] = dep\r\n inDegree[v] = nbhd.length\r\n nbhd.forEach(function (filename) {\r\n var u = dep.deps[filename]\r\n if (adj[u]) {\r\n adj[u].push(v)\r\n } else {\r\n adj[u] = [v]\r\n }\r\n })\r\n })\r\n\r\n // Initialize toVisit queue\r\n var result = []\r\n var inverse = {}\r\n deps.forEach(function (dep) {\r\n var v = dep.id\r\n if (!adj[v]) {\r\n adj[v] = []\r\n }\r\n if (inDegree[v] === 0) {\r\n inverse[v] = result.length\r\n result.push(v)\r\n }\r\n })\r\n\r\n // Run BFS\r\n for (var ptr = 0; ptr < result.length; ptr++) {\r\n var v = result[ptr]\r\n adj[v].forEach(function (u) {\r\n if (--inDegree[u] === 0) {\r\n inverse[u] = result.length\r\n result.push(u)\r\n }\r\n })\r\n }\r\n\r\n if (result.length !== deps.length) {\r\n throw new Error('cyclic dependency')\r\n }\r\n\r\n // Relabel dependencies\r\n return result.map(function (v) {\r\n var dep = index[v]\r\n var deps = dep.deps\r\n var ndeps = {}\r\n Object.keys(deps).forEach(function (filename) {\r\n ndeps[filename] = inverse[deps[filename]] | 0\r\n })\r\n return {\r\n id: inverse[v] | 0,\r\n deps: ndeps,\r\n file: dep.file,\r\n source: dep.source,\r\n entry: dep.entry\r\n }\r\n })\r\n}",
"toDependencyGraph() {\n return _.map(\n // FIND MAX UNIQUE VERSION FIRST\n _.groupBy(this.allDependencies,\"name\"), versionGroup =>\n versionGroup.reduce((maxVersion, version) =>\n !maxVersion || getValue(() =>\n SemVer.gt(SemVer.coerce(version.version),SemVer.coerce(maxVersion.version)),\n version.version <= maxVersion.version\n ) ?\n version :\n maxVersion\n , null))\n \n // SORT BY INTER-DEPENDENCY\n .sort((depA,depB) => {\n const\n depADependencies = this.collectDependencies(depA.project),\n depBDependencies = this.collectDependencies(depB.project),\n depARequiresB = depADependencies.includes(depB.name),\n depBRequiresA = depBDependencies.includes(depA.name)\n \n if (depARequiresB && depBRequiresA)\n throw `Dependency circular requirement: ${depA.name} <~> ${depB.name}`\n \n return (!depARequiresB && !depARequiresB) ? 0 : depARequiresB ? 1 : -1\n })\n \n \n }",
"order () {\n /* determine all graph nodes */\n const nodes = {}\n this._elements.forEach((element) => {\n if (nodes[element.name])\n throw new Error(`element named \"${element.name}\" occurs multiple times (has to be unique)`)\n nodes[element.name] = true\n })\n\n /* internal helper data structures */\n const DAG = {}\n const TAG = {}\n const GRP = {}\n const BEFORE = {}\n const AFTER = {}\n\n /* pre-fill all groups with sentinel elements to ensure that\n a group dependency always has at least one element it can be\n expanded to */\n this._groups.forEach((group) => {\n if (GRP[group])\n throw new Error(`group named \"${group}\" occurs multiple times (has to be unique)`)\n GRP[group] = [ `@@@${group}` ]\n nodes[`@@@${group}`] = true\n })\n\n /* helper function for taking zero or more strings out of a field */\n const takeField = (field) => {\n if (typeof field === \"object\" && field instanceof Array)\n return field\n else if (typeof field === \"string\")\n return [ field ]\n else\n return []\n }\n\n /* pass 1: iterate over all elements and pre-process information */\n this._elements.forEach((element) => {\n /* take information of element */\n const name = element.name\n const tag = takeField(element.tag)\n const before = takeField(element.before)\n const after = takeField(element.after)\n const group = element.group\n\n /* remember (a mutable copy of) after/before information */\n BEFORE[name] = [].concat(before)\n AFTER[name] = [].concat(after)\n\n /* remember mapping of tag to element */\n tag.forEach((tag) => {\n if (this._groups.indexOf(tag) > -1)\n throw new Error(`element \"${element.name}\" has invalid tag \"${tag}\" ` +\n \"(tag cannot have same name as existing group)\")\n if (TAG[tag] === undefined)\n TAG[tag] = []\n TAG[tag].push(name)\n })\n\n /* remember group of module */\n if (group !== undefined) {\n const idx = this._groups.indexOf(group)\n if (idx === -1)\n throw new Error(`element \"${element.name}\" has invalid group \"${group}\" ` +\n \"(group has to be explicitly defined)\")\n GRP[group].push(name)\n\n /* add implicit before/after for elements of intermediate groups */\n if (idx < this._groups.length - 1)\n BEFORE[name].push(this._groups[idx + 1])\n if (idx > 0)\n AFTER[name].push(this._groups[idx - 1])\n }\n })\n\n /* helper function: insert edge into DAG */\n const insertDAG = (name, list, order) => {\n list.forEach((element) => {\n let elements\n let via\n if (TAG[element] !== undefined) {\n elements = TAG[element]\n via = \"tag-based\"\n }\n else if (GRP[element] !== undefined) {\n elements = GRP[element]\n via = \"group-based\"\n }\n else {\n elements = [ element ]\n via = \"direct\"\n }\n elements.forEach((element) => {\n const [ before, after ] = order(name, element)\n if (nodes[before] === undefined)\n throw new Error(`element \"${name}\" has invalid ${via} before-reference ` +\n `to unknown element \"${before}\"`)\n if (nodes[after] === undefined)\n throw new Error(`element \"${name}\" has invalid ${via} after-reference ` +\n `to unknown element \"${after}\"`)\n if (DAG[before] === undefined)\n DAG[before] = {}\n DAG[before][after] = true\n })\n })\n }\n\n /* pass 2: iterate over all elements and process \"after\" and \"before\" information */\n this._elements.forEach((element) => {\n /* take information of module */\n const name = element.name\n const before = BEFORE[name]\n const after = AFTER[name]\n\n /* insert all \"after\" dependencies into DAG\n (as standard \"after\" dependencies) */\n insertDAG(name, after, (name, element) => [ element, name ])\n\n /* insert all \"before\" dependencies into DAG\n (as inverse \"after\" dependencies) */\n insertDAG(name, before, (name, element) => [ name, element ])\n })\n\n /* determine resulting graph edges */\n const edges = []\n Object.keys(DAG).forEach((before) => {\n Object.keys(DAG[before]).forEach((after) => {\n edges.push([ before, after ])\n })\n })\n\n /* perform a topological sorting of the graph */\n let elements = toposort.array(Object.keys(nodes), edges)\n\n /* remove group sentinel values again */\n elements = elements.filter((element) => !element.match(/^@@@.+/))\n\n /* return the final ordered list of elements */\n return elements\n }",
"reorderForDependencies() {\n if (this.dependencyLinks.size > 0) {\n const actorsAfter = [];\n // Temporarily remove all actors that have dependencies\n for (const actorAfter of this.dependencyLinks.keys()) {\n const dependentPos = this.actors.indexOf(actorAfter);\n if (dependentPos >= 0) {\n this.actors.splice(dependentPos, 1);\n actorsAfter.push(actorAfter);\n }\n }\n // Iteratively append actors based on the first dependency link\n // that has all of its dependencies available in the array\n while (actorsAfter.length > 0) {\n // Find the first actor that has all of its dependencies available.\n let activeActorAfterId = -1;\n for (let i = 0; i < actorsAfter.length; i++) {\n let validLink = true;\n for (const dependency of this.dependencyLinks.get(actorsAfter[i])) {\n if (this.actors.indexOf(dependency) < 0 && actorsAfter.indexOf(dependency) >= 0) {\n validLink = false;\n break;\n }\n }\n if (validLink) {\n activeActorAfterId = i;\n break;\n }\n }\n // If none of the pending links are possible, there must be a cyclic dependency\n if (activeActorAfterId < 0) {\n throw new Error('Cyclic dependency links detected in bus ' + this.name);\n }\n // The dependent may not be available (yet), so we don't add it to the array (yet).\n const activeActorAfter = actorsAfter.splice(activeActorAfterId, 1)[0];\n this.actors.push(activeActorAfter);\n }\n }\n }",
"reorderForDependencies() {\n if (this.dependencyLinks.size > 0) {\n const actorsAfter = [];\n // Temporarily remove all actors that have dependencies\n for (const actorAfter of this.dependencyLinks.keys()) {\n const dependentPos = this.actors.indexOf(actorAfter);\n if (dependentPos >= 0) {\n this.actors.splice(dependentPos, 1);\n actorsAfter.push(actorAfter);\n }\n }\n // Iteratively append actors based on the first dependency link\n // that has all of its dependencies available in the array\n while (actorsAfter.length > 0) {\n // Find the first actor that has all of its dependencies available.\n let activeActorAfterId = -1;\n for (let i = 0; i < actorsAfter.length; i++) {\n let validLink = true;\n for (const dependency of this.dependencyLinks.get(actorsAfter[i])) {\n if (!this.actors.includes(dependency) && actorsAfter.includes(dependency)) {\n validLink = false;\n break;\n }\n }\n if (validLink) {\n activeActorAfterId = i;\n break;\n }\n }\n // If none of the pending links are possible, there must be a cyclic dependency\n if (activeActorAfterId < 0) {\n throw new Error(`Cyclic dependency links detected in bus ${this.name}`);\n }\n // The dependent may not be available (yet), so we don't add it to the array (yet).\n const activeActorAfter = actorsAfter.splice(activeActorAfterId, 1)[0];\n this.actors.push(activeActorAfter);\n }\n }\n }",
"function topologicalSort(libs) {\n const libsObject = libs.split('\\n').reduce((acc, item) => {\n const libsArray = item.split(' ').filter(i => i !== '');\n acc[libsArray[0]] = libsArray.slice(1).filter(i => i !== libsArray[0]);\n return acc;\n }, {});\n\n const visited = {};\n const libsStack = {};\n const result = [];\n\n function traverse(lib) {\n if (visited[lib]) return;\n\n visited[lib] = true;\n\n if (typeof libsObject[lib] === 'undefined') return result.push(lib);\n\n libsStack[lib] = true;\n\n for (const item of libsObject[lib]) {\n if (libsStack[item]) console.log(`Un-orderable dependency: ${Object.keys(libsStack)}`);\n if (!visited[item]) traverse(item);\n }\n\n delete libsStack[lib];\n result.push(lib);\n }\n\n for (const lib of Object.keys(libsObject)) {\n traverse(lib);\n }\n\n return result;\n}",
"function topoSort (vertices) {\n var hshDependents = {};\n var queue = [];\n for (var i = 0; i < vertices.length; i++) {\n var vertex = vertices[i];\n hshDependents[vertex.value] = vertex.inEdges.length;\n if (hshDependents[vertex.value] === 0) {\n queue.push(vertex);\n }\n }\n var results = [];\n while (queue.length > 0) {\n var current = queue.shift();\n results.push(current);\n for (var i = 0; i < current.outEdges.length; i++) {\n var edge = current.outEdges[i];\n hshDependents[edge.toVertex.value] -= 1;\n if (hshDependents[edge.toVertex.value] === 0) {\n queue.push(edge.toVertex);\n }\n }\n }\n}",
"getTopologicalSort() {\n let list = new LinkedList();\n let visited = new Set();\n for (let node of this.getNodes()) {\n if (!visited.has(node)) {\n this.getTopologicalDependents(node, visited, list);\n }\n }\n return list;\n }",
"function topoSort(map) {\n var arr = [];\n for (key in map) {\n if (map[key].count == 0) {\n arr.push(key);\n }\n }\n for (var low = 0; low < arr.length; low++) {\n var node = map[arr[low]];\n for (var i = 0; i < node.link.length; i++) {\n map[node.link[i]].count--;\n if (map[node.link[i]].count === 0) {\n arr.push(node.link[i]);\n }\n }\n }\n for (var key in map) {\n if (map[key].count !== 0) {\n throw \"Cycling dependencies occured:\" + key;\n }\n }\n return arr.reverse();\n }",
"async populateFlattenedDependencies() {\n _logger().default.debug(`populateFlattenedDependencies starts with ${this.components.length} components`);\n\n this.createGraphs(this.components);\n await this.importExternalDependenciesInBulk();\n await (0, _pMapSeries().default)(this.components, async component => {\n component.flattenedDependencies = await this.getFlattened(component.id);\n });\n }",
"resolveDependencies () {\n\t\tlet sorted;\n\t\ttry {\n\t\t\t// we use the toposort module to figure this out...\n\t\t\tsorted = TopoSort.array(\n\t\t\t\tthis.moduleNames,\n\t\t\t\tthis.moduleDependencies\n\t\t\t);\n\t\t}\n\t\tcatch(error) {\n\t\t\tif (error) {\n\t\t\t\tthrow `Error resolving module dependencies: ${error}`;\n\t\t\t}\n\t\t}\n\t\t// the result of the TopoSort is an array of module names, where those\n\t\t// dependent on others come first ... we need to reverse this so those\n\t\t// dependent on others are registered later\n\t\tthis.modules = sorted.map(moduleName => this.modulesByName[moduleName]);\n\t\tthis.modules.reverse();\n\t}",
"sortedChildren() {\n // Project dependencies to current children\n const nodes = this.nodes;\n const projectedDependencies = projectDependencies(this.deepDependencies(), (node) => {\n while (!nodes.has(node) && node.parentGraph) {\n node = node.parentGraph;\n }\n return nodes.has(node) ? [node] : [];\n });\n return toposort_1.topoSort(nodes, projectedDependencies);\n }",
"mapDependencies() {\n if (this.mapped) {\n return;\n }\n this.mapped = true;\n this.packages.forEach((pkg) => {\n Object.keys(Object.assign(Object.assign({}, pkg.dependencies), pkg.peerDependencies)).forEach((depName) => {\n this.mapDependency(pkg.name, depName);\n });\n });\n }",
"function reorderGraph(graph) {\n const orderedDependencies = new Map();\n\n graph.entryPoints.forEach(entryPoint => {\n const mainModule = graph.dependencies.get(entryPoint);\n\n if (!mainModule) {\n throw new ReferenceError(\"Module not registered in graph: \" + entryPoint);\n }\n\n reorderDependencies(graph, mainModule, orderedDependencies);\n });\n\n graph.dependencies = orderedDependencies;\n}",
"function sortByDependencies(unsorted, sorted = []) {\n const [head, ...tail] = unsorted;\n if (tail.length < 1) return [...sorted, head];\n const [idA, reqA] = head;\n const aDependsOn = []; const dependsOnA = []; const independent = [];\n tail.forEach(([idB, reqB]) => {\n if (isDependent(reqA, idB)) {\n aDependsOn.push([idB, reqB]);\n } else if (isDependent(reqB, idA)) {\n dependsOnA.push([idB, reqB]);\n } else {\n independent.push([idB, reqB]);\n }\n });\n const circularDependency = !aDependsOn.every(([i]) => dependsOnA.every(([j]) => i !== j));\n if (circularDependency) throw new Error('Circular dependency detected!');\n if (aDependsOn.length === 0) {\n return sortByDependencies(tail, [...sorted, head]);\n }\n const resorted = [...independent, ...aDependsOn, head, ...dependsOnA];\n return sortByDependencies(resorted, sorted);\n }",
"sortByDependedOn(nodes) {\n return Array.from(nodes).sort((a, b) => {\n const diff = b.dependents.size - a.dependents.size;\n if (diff === 0) {\n return a.name > b.name ? 1 : -1;\n }\n return diff;\n });\n }",
"buildDependencyList(deps) {\n\t\tlet allFlat = [];\n\t\t_.forEach(deps, (dep) => {\n\t\t\tallFlat = _.union(allFlat, dep.flat);\n\t\t});\n\n\t\treturn Array.sort(allFlat);\n\t}",
"get allDeps() {\n var _a, _b;\n const fromParent = (_b = (_a = this.parentGraph) === null || _a === void 0 ? void 0 : _a.allDeps) !== null && _b !== void 0 ? _b : [];\n return [...this.dependencies, ...fromParent];\n }",
"_mergeDependencies(dependencyMap,newDependencies,dependenciesToClear){if(dependenciesToClear.size>0){// Use the reverseLookup index to remove the dependencies.\n const dependenciesToClearArray=Array.from(dependenciesToClear);for(let i=0,length=dependenciesToClearArray.length;i<length;++i){const dependencyToClear=dependenciesToClearArray[i];const reverseLookupEntry=dependencyMap.dependenciesReverseLookup[dependencyToClear];if(reverseLookupEntry){const reverseLookupEntryArray=Array.from(reverseLookupEntry);for(let k=0,reverseLookupEntryArrayLength=reverseLookupEntryArray.length;k<reverseLookupEntryArrayLength;++k){const reverseLookupKey=reverseLookupEntryArray[k];const dependenciesEntryForReverseLookupKey=dependencyMap.dependencies[reverseLookupKey];if(dependenciesEntryForReverseLookupKey){dependenciesEntryForReverseLookupKey.delete(dependencyToClear);if(dependenciesEntryForReverseLookupKey.size===0){delete dependencyMap.dependencies[reverseLookupKey];}}}// Remove the entry.\n delete dependencyMap.dependenciesReverseLookup[dependencyToClear];}}}// Loop through new dependencies and shove them in.\n const newDependenciesKeys=Object.keys(newDependencies);for(let len=newDependenciesKeys.length,n=0;n<len;n++){const newDependenciesKeyString=newDependenciesKeys[n];if(!dependencyMap.dependencies[newDependenciesKeyString]){// Completely new entry.\n dependencyMap.dependencies[newDependenciesKeyString]=new Map(newDependencies[newDependenciesKeyString]);}else{// Existing entry, so merge.\n newDependencies[newDependenciesKeyString].forEach((value,key)=>{dependencyMap.dependencies[newDependenciesKeyString].set(key,value);});}if(dependencyMap.dependencies[newDependenciesKeyString].size>0){// Update the reverse lookup index.\n dependencyMap.dependencies[newDependenciesKeyString].forEach((_dependency,reverseLookupKey)=>{let reverseLookupEntry=dependencyMap.dependenciesReverseLookup[reverseLookupKey];if(!reverseLookupEntry){reverseLookupEntry=new Set();reverseLookupEntry.add(newDependenciesKeyString);dependencyMap.dependenciesReverseLookup[reverseLookupKey]=reverseLookupEntry;}else{reverseLookupEntry.add(newDependenciesKeyString);}});}}}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create group of Stars | createStars() {
const stars = this.physics.add.group({
key: STAR_KEY,
// Create a star and add/clone 11 more + (create 1 + clone 11 = 12 stars)
repeat: 11,
// Place them on the X horizontal axis 14 pixels from the left
// Place them on the Y vertical axis 0 pixels from the top
// Distance between the stars should be 70px
setXY: { x: 14, y: 0, stepX: 70 },
});
// iterate() - apply some method to all elements in a group - (such as map())
stars.children.iterate((child) => {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8)); // random Y axis bounce value between 0.4 and 0.8
});
return stars;
} | [
"createStars(space){\n for(var x = 100; x < space.starFieldWidth; x+= 150 )\n for(var y = 100; y < space.starFieldHeight; y += 150)\n space.stars.push(new Star(x, y));\n }",
"function generateStars() {\n let nostars = [];\n for (let i = 0; i < props.numberOfStars; i++) {\n nostars.push(\n <span key={i}>\n <i key={i} className=\"fa fa-star\" />\n </span>\n );\n }\n return nostars;\n }",
"function createStars(sc) { \r\n starCount=sc;\r\n starArray=[];\r\n\r\n // Create an array of stars\r\n for (var i = 0; i < starCount; i++) {\r\n // this assigns each element in the array all the information for the star by \r\n // using the 'star' class, pass the starting x,y locations \r\n // and speeds into the array.\r\n if (i<starCount/2){\r\n\r\n \r\n starArray.push(star.create(20,i+50,Math.random()*5,Math.random()*5)); \r\n }\r\n else {starArray.push(star.create(w-20,i+50,-Math.random()*5,Math.random()*5));}\r\n }\r\n }",
"function makeManyStars() {\n\n\tfor (var i = 0; i < starCap; i++) {\n\n\t\trandoTop = Math.floor(Math.random() * 100),\n\t\trandoLeft = Math.floor(Math.random() * 100),\n\t\trandoColor = colors[Math.floor(Math.random() * colors.length)];\n\n\t\t$(star).appendTo(starField)\n\t\t\t .css({\n\t\t\t\t\t'top': randoTop + '%',\n\t\t\t\t\t'left': randoLeft + '%',\n\t\t\t\t\t'background': randoColor,\n\t\t\t\t\t'-moz-box-shadow': '0 0 10px 3px ' + randoColor,\n\t\t\t\t\t'-webkit-box-shadow': '0 0 10px 3px ' + randoColor,\n\t\t\t\t\t'box-shadow': '0 0 10px 3px ' + randoColor\n\t\t\t }),\n\n\t\tstarCrawl(); // set each star into motion\n\n\t}\n}",
"createStars(...args) {\n if (args.length) {\n return new Stars(...args, this);\n }\n // No arguments supplied\n return new Stars({}, this);\n }",
"function createStars(averageRating) {\n var goodreadsStars = $(\"<span>\", {class: \"gfc-stars\"});\n if (CurrentStore === SupportedStores.GOOGLE_PLAY) goodreadsStars.attr(\"title\", averageRating);\n\n\tvar fullStarCount = Math.floor(averageRating);\n\tvar partialStarValue = averageRating - fullStarCount;\n\tvar emptyStarCount = TOTAL_STARS - fullStarCount - Math.ceil(partialStarValue);\n\n\tappendFullStars(goodreadsStars, fullStarCount, \"gfc-p10\");\n\tif (partialStarValue > 0) appendPartialStar(goodreadsStars, partialStarValue);\n\tappendFullStars(goodreadsStars, emptyStarCount, \"gfc-p0\");\n\n return goodreadsStars;\n}",
"function createStars(n) {\n let stars = [];\n for (let i = 0; i < n; i++) {\n stars.push({\n x: Math.random() * width,\n y: Math.random() * height,\n r: Math.random() * (STAR_RADIUS[1] - STAR_RADIUS[0])\n + STAR_RADIUS[0],\n n: map(Math.floor(Math.random() * 9),\n 0, 9,\n STAR_POINTS[0], STAR_POINTS[1])\n });\n }\n this.stars = stars;\n}",
"function createStars(num) {\n for(var i = 0; i < num; i++) {\n stars.push({\n x: windowWidth * Math.random(),\n y: windowHeight * Math.random() - windowHeight,\n speed: Math.random()\n });\n }\n}",
"createStars(...args) {\n if (args.length) {\n return new Stars(...args, this);\n }\n // No arguments supplied\n return new Stars({}, this);\n }",
"returnStarsGroup() {\n let rateStars = [];\n\n for(var i = 1; i <= this.props.maxRate; i++) {\n rateStars.push(\n <RateStar \n key={i} \n index={i} \n filled={i<=this.state.score} \n onClick={this.setSelectedStar.bind(this, i)} \n starSize={this.props.starSize}\n />\n );\n }\n return rateStars;\n }",
"function createStars() {\n\n const star1 = new Star(20, 20);\n const star2 = new Star(90, 20);\n const star3 = new Star(160, 20);\n\n if (win === 1) {\n allStars.push(star1);\n const bug9 = new Enemy(80, 100);\n const bug10 = new Enemy(200, 410);\n const bug11= new Enemy(320, 190);\n const bug12= new Enemy(80, 260);\n\n allEnemies.push(bug9, bug10, bug11, bug12);\n\n\n } else if (win === 2) {\n allStars.push(star2);\n const bug13 = new Enemy(160, 340);\n const bug14 = new Enemy(400, 190);\n const bug15= new Enemy(600, 260);\n const bug16= new Enemy(660, 190);\n allEnemies.push(bug13, bug14, bug15, bug16);\n\n } else if (win === 3) {\n allStars.push(star3);\n\n player.win();\n\n allEnemies=[];\n\n\n }\n}",
"shatter() {\n this.radius -=3\n\n for (let i = 0; i< 8; i++) {\n miniStars.push(new miniStar(this.x, this.y, 2))\n }\n }",
"function generateStars() {\r\n\r\n generateStars.generatedStars = [];\r\n\r\n // Generate a random number of stars between 400 - 1000 stars.\r\n let numStars = Math.random() * 600 + 400;\r\n\r\n // Paint that many stars.\r\n for (let i = 0; i < numStars + 1; i ++) {\r\n\r\n // Choose a random location.\r\n let starX = Math.random() * width;\r\n let starY = Math.random() * screenHeight - 5;\r\n\r\n // Save generated stars for repainting in this game instance.\r\n generateStars.generatedStars.push([starX, starY]);\r\n\r\n }\r\n\r\n}",
"function initializeStars(numberOfStars) {\r\n for(var i = 0; i < numberOfStars; i++) {\r\n starXCoords.push(random(17, width - 17));\r\n starYCoords.push(random(17, (height/3)));\r\n sizeOfStar.push(random(0.35, 0.5));\r\n }\r\n}",
"function paintStars(nStars){\n for (i=1; i<= nStars; i++) {\n var elt = $('#star' + i.toString());\n if(!elt.hasClass('starred')){\n elt.addClass('starred');\n }\n };\n for (i=nStars + 1; i<=5; i++) {\n var elt = $('#star' + i.toString());\n if(elt.hasClass('starred')){\n elt.removeClass('starred');\n }\n };\n}",
"function createStars(solidRating, fadedRating) {\n let rating = [];\n\n for (let i = 0; i < solidRating; i++) {\n rating.push(<StarIcon style={{ color: \"#64b5f6\" }} />);\n }\n\n for (let i = 0; i < fadedRating; i++) {\n rating.push(<StarTwoToneIcon style={{ color: \"#90caf9\" }} />);\n }\n\n while (rating.length < 5) {\n rating.push(<StarBorderIcon />);\n }\n\n return <div>{rating}</div>;\n}",
"initShapes() {\n var star = new Star({\n id: 'star-1'\n });\n this.group.docElementNS.appendChild(star.docElementNS);\n this.shapes.push(star);\n }",
"function drawStars () {\n\t\tfor(var i=0; i<noOfStar; i++) {\n\t\t\tctx.fillRect(stars[i].x,stars[i].y,stars[i].size,stars[i].size);\n\t\t}\n\t}",
"function initStars(num,parent){\n for (let i = 0; i < num; i++){\n const star = document.createElement('img');\n star.classList.add('inline');\n star.src = \"img/star.png\";\n parent.appendChild(star);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds expected state of contract using custom variables specified in test. | async function expectedState(token, stateChanges, accounts, name) {
let state = {}
switch (name) {
case 'BearBucks':
state = {
'totalSupply': 0,
'balanceOf': {
'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'a5': 0, 'a6': 0, 'a7': 0
},
'allowance': {
'a0': {
'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'cb': 0},
'a1': {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'cb': 0},
'a2': {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'cb': 0},
'a3': {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'cb': 0},
'a4': {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'cb': 0},
},
'betSum': {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0},
'minter': zero40
}
break
case 'CryptoBears':
state = {
'balanceOf': {
'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'a5': 0, 'a6': 0, 'a7': 0
},
'ownerOf': {'b0': zero40, 'b1': zero40, 'b2': zero40, 'b3': zero40, 'b4': zero40},
'getApproved': {'b0': zero40, 'b1': zero40, 'b2': zero40, 'b3': zero40, 'b4': zero40},
'isApprovedForAll': {
'a0': {'a0': false, 'a1': false, 'a2': false, 'a3': false, 'a4': false},
'a1': {'a0': false, 'a1': false, 'a2': false, 'a3': false, 'a4': false},
'a2': {'a0': false, 'a1': false, 'a2': false, 'a3': false, 'a4': false},
'a3': {'a0': false, 'a1': false, 'a2': false, 'a3': false, 'a4': false},
'a4': {'a0': false, 'a1': false, 'a2': false, 'a3': false, 'a4': false},
},
'bets': {
'b0': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b1': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b2': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b3': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b4': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
},
'commitments': {
'b0': {'b0': zero64, 'b1': zero64, 'b2': zero64, 'b3': zero64, 'b4': zero64},
'b1': {'b0': zero64, 'b1': zero64, 'b2': zero64, 'b3': zero64, 'b4': zero64},
'b2': {'b0': zero64, 'b1': zero64, 'b2': zero64, 'b3': zero64, 'b4': zero64},
'b3': {'b0': zero64, 'b1': zero64, 'b2': zero64, 'b3': zero64, 'b4': zero64},
'b4': {'b0': zero64, 'b1': zero64, 'b2': zero64, 'b3': zero64, 'b4': zero64},
},
'committed': {
'b0': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b1': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b2': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b3': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b4': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
},
'secrets': {
'b0': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b1': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b2': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b3': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
'b4': {'b0': 0, 'b1': 0, 'b2': 0, 'b3': 0, 'b4': 0},
},
'revealed': {
'b0': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b1': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b2': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b3': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
'b4': {'b0': false, 'b1': false, 'b2': false, 'b3': false, 'b4': false},
},
'timeLastFed': {
'b0': await getTimeOfBirthOrZero(token, 0),
'b1': await getTimeOfBirthOrZero(token, 1),
'b2': await getTimeOfBirthOrZero(token, 2),
'b3': await getTimeOfBirthOrZero(token, 3),
'b4': await getTimeOfBirthOrZero(token, 4),
},
'minter': accounts[5],
}
break
case 'BearCrowdsale':
state = {
'weiRaised': 0,
'wei_balance': accountBalances,
}
break
default:
throw new Error('Contract name not recognized ' + name)
}
for (let i = 0; i < stateChanges.length; ++i) {
let variable = stateChanges[i].var
if (_.has(state, variable)) {
let defaultVal = state[variable]
let change = stateChanges[i].expect
if (defaultVal == change) {
throw new Error("Default value specified for variable " + variable)
} else {
_.set(state, variable, change)
}
} else {
throw new Error("variable " + variable + " not found in state")
}
}
return state
} | [
"function buildExpectedPartialState(\n emptyState,\n customState,\n ignoreExtraCustomVars\n) {\n // for each item in customVars, set the item in expectedState\n const expectedState = clone(emptyState);\n\n for (const variableName in customState) {\n // do I ignore extra values\n if (Object.prototype.hasOwnProperty.call(expectedState, variableName)) {\n const variableValue = customState[variableName];\n if (isLiteral(variableValue)) {\n expectedState[variableName] = variableValue;\n } else {\n // assume variableValue is a mapping evaluated on 1 or more accounts\n for (const accountName in variableValue) {\n expectedState[variableName][accountName] = variableValue[accountName];\n }\n }\n } else if (!ignoreExtraCustomVars) {\n throw new Error(\n \"variable \" + variableName + \" not found in expectedState\"\n );\n }\n }\n return expectedState;\n}",
"async test13(stub, args) {\n const signer = new ChaincodeCrypto(stub);\n const signature = signer.sign(Buffer.from(args[1]));\n const state = {\n signature: signature,\n value: args[1]\n };\n\n await stub.putState(args[0], Buffer.from(JSON.stringify(state)));\n }",
"function MockTransactionConstructor() {\n this.date = new Date;\n this.balanceSoFar = '100';\n this.balanceChange = '200';\n }",
"function buildContract(input) {\n // Split input and keep brackets.\n input = input.split(/(\\(|\\)|->|\\{|\\}|\\?|[a-zA-Z0-9]*)/);\n input = input.filter(function(s) { return s.trim() != '' });\n\n // Check for typedefs and replace with strings, recursively calls\n // build contract to check for more typedefs\n for (var i = 0; i < input.length; i++) {\n if (typedefs[input[i]]) {\n input[i] = typedefs[input[i]];\n return buildContract(input.join(\" \"));\n }\n }\n\n var pos = 0;\n\n function parse() {\n var result = undefined;\n\n function parseKeyVal() {\n var name = input[pos++];\n pos += 1;\n var val = parse();\n return {name: name, contract: val};\n }\n\n function parseHead() {\n if (input[pos] == \"Int\") {\n pos += 1;\n out = IntegerContractFactory();\n } else if (input[pos] == \"Num\") {\n pos += 1;\n out = NumberContractFactory();\n } else if (input[pos] == \"String\") {\n pos += 1;\n out = StringContractFactory();\n } else if (input[pos] == \"Bool\") {\n pos += 1;\n out = BooleanContractFactory();\n } else if (input[pos] == \"Unit\") {\n pos += 1;\n out = UnitContractFactory();\n } else if (input[pos] == \"0\") {\n pos += 1;\n out = EmptyContractFactory();\n pos += 1; // ->\n range = parse();\n if (!range) {\n throw \"Can't use empty contract outside the context of a function\";\n }\n out = FunctionContractFactory(EmptyContractFactory(), range);\n } else if (input[pos] == \"(\") {\n pos += 1;\n out = parse();\n } else if (input[pos] == \"[\") {\n pos += 1;\n var inner = parse();\n out = ListContractFactory(inner);\n } else if (input[pos] == \"<\") {\n pos += 1;\n var key = StringContractFactory();\n var value = parse();\n out = MapContractFactory(key, value);\n } else if (input[pos] == \"{\") {\n // Parses and returns one ObjectContractFactory\n var parseObject = function () {\n var record = [];\n // Allow empty record contract\n if (input[pos+1] != \"}\") {\n while (input[pos] != \"}\") {\n pos += 1;\n record.push(parseKeyVal());\n }\n }\n pos += 1;\n var name = undefined;\n if (input[pos] == \"@\") {\n pos += 1;\n name = input[pos];\n pos += 1;\n }\n return ObjectContractFactory(name, record);\n }\n out = parseObject();\n // Checks for union operator and performs a merge operation if\n // present and does so until there are no more merges necessary.\n while (input[pos] == \"U\" && input[pos+1] == \"{\") {\n pos += 1;\n out = ObjectContractFactoryMerge(out, parseObject());\n }\n } else if (input[pos] == \"forall\") {\n pos += 1;\n var vars = [];\n while (input[pos] != \".\") {\n vars.push(input[pos]);\n pos += 1;\n }\n pos += 1;\n var out = parseHead();\n // Inserting a forall for each variable.\n vars.reverse().forEach(function(v) {\n var typeFunc = \"function(\" + v + \") { return \" + out.repr() + \"}\"\n var typeFunc = eval(\"typeFunc = \" + typeFunc);\n out = ForAllContractFactory(typeFunc);\n });\n return out;\n } else if (adts[input[pos]] != null) {\n out = adts[input[pos++]];\n } else {\n out = VariableContractFactoryPlaceholder(input[pos]);\n pos += 1;\n }\n\n if (input[pos] == \"?\") {\n pos += 1;\n out = MaybeContractFactory(out);\n }\n\n if (input[pos] == \"->\") {\n pos += 1;\n var range = parseHead();\n return FunctionContractFactory(out, range);\n }\n\n return out;\n }\n\n while (pos < input.length) {\n if (input[pos] == \")\" || input[pos] == \"]\" || input[pos] == \">\") {\n pos += 1;\n return result;\n }\n if (input[pos] == \",\" || input[pos] == \"}\") {\n return result;\n }\n result = parseHead();\n }\n return result;\n }\n\n return parse();\n\n}",
"async function buildMockResponse(customerState)\n{\n try\n {\n var accountMockData = \n {\n // TODO add more example accounts mapping to various response scenarios\n '10682365': {\n Success: true,\n AccountInternalId: 16170525,\n ActiveDate: '2021-05-05T00:00:00',\n AccountExternalId: 16170525,\n AccountExternalIdType: 1,\n AccountStatus: -1,\n AccountStatusDt: '2021-05-05T20:59:08',\n AccountType: 1,\n AcctSegId: 1,\n BillAddress1: '15 STATION STREET',\n BillCity: 'CAMBERWELL',\n BillFname: 'AR HD',\n BillLname: 'IVR SMS',\n BillNamePre: 'Mr',\n BillPeriod: 'TBA',\n BillSequenceNum: 0,\n BillState: 'VIC',\n BillZip: 3124,\n BillingFrequency: 3,\n ChargeThreshold: 0,\n CollectionIndicator: 0,\n CollectionStatus: 0,\n Converted:0,\n CreditRating: 0,\n CustPhone1: 0321050502,\n CyclicalThreshol: 0,\n DateActive: '2021-05-05T00:00:00',\n DateCreated: '2021-05-05T20:59:08',\n ExrateClass: 1,\n LanguageCode: 1,\n MktCode: 1,\n NextBillDate: '2021-06-15T00:00:00',\n NoBill: false,\n AccountRateClass: 1000,\n VipCode: 0,\n PaymentProfileId: 32263900003,\n EasyPaySetup: false,\n EasyPayMethod: 1,\n ExtendedData : {\n ExtendedDataParam: [{\n ParamId: 9146,\n ParamValue: false,\n ParamName: 'WAIVE_PAPER_BILL_FEE'\n },\n {\n ParamId: 9136,\n ParamValue: 3,\n ParamName: 'Usage_Notification'\n },\n {\n ParamId: 10027,\n ParamValue: 1,\n ParamName: 'DISCLOSURE_PARAMID'\n },\n {\n ParamId: 9119,\n ParamValue: 0,\n ParamName: 'BUSINESS_UNIT_PARAMID'\n },\n {\n ParamId: 9121,\n ParamValue: 0,\n ParamName: 'COMPANY_NUMBER_PARAMID'\n },\n {\n ParamId: 9122,\n ParamValue: 0,\n ParamName: 'CONTACT_FAMILY_NAME_PARAMID'\n },\n {\n ParamId: 9123,\n ParamValue: 0,\n ParamName: 'CONTACT_GIVEN_NAME_PARAMID'\n },\n {\n ParamId: 9124,\n ParamValue: 0,\n ParamName: 'CONTACT_TITLE_PARAMID'\n },\n {\n ParamId: 9125,\n ParamValue: 0,\n ParamName: 'CONTACT_DOB_PARAMID'\n },\n {\n ParamId: 9126,\n ParamValue: 0,\n ParamName: 'CONTACT_PHONE_NUMBER_PARAMID'\n },\n {\n ParamId: 9117,\n ParamValue: false,\n ParamName: 'calc_monthlyrate'\n },\n {\n ParamId: 9112,\n ParamValue: 1,\n ParamName: 'MARKETING_PARAMID'\n },\n {\n ParamId: 9113,\n ParamValue: 4,\n ParamName: 'IDENTIFIER_QUESTION_PARAMID'\n },\n {\n ParamId: 9114,\n ParamValue: NA,\n ParamName: 'IDENTIFIER_ANSWER_PARAMID'\n },\n {\n ParamId: 9115,\n ParamValue: false,\n ParamName: 'PROSPECT_FLAG_PARAMID'\n },\n {\n ParamId: 10018,\n ParamValue: 0,\n ParamName: 'TENURE'\n },\n {\n ParamId: 9138,\n ParamValue: 0,\n ParamName: 'BUSINESS_CODE_PARAMID'\n }\n ]\n },\n Delay: 1000,\n Template: 'KenanSearchCustomerResponseSuccess'\n },\n '10682367': \n {\n Success: false,\n Delay: 3000,\n Template: 'KenanSearchCustomerResponseError'\n }\n };\n\n var selectedAccount = accountMockData[customerState.Customer.AccountNumber];\n\n if (selectedAccount === undefined)\n {\n selectedAccount = accountMockData['10682365'];\n }\n\n await sleep(selectedAccount.Delay);\n\n customerState.Mock = selectedAccount;\n var responseTemplate = getTemplate(selectedAccount.Template);\n\n console.log('[INFO] got template raw: ' + responseTemplate);\n\n var templateResult = handlebarsUtils.template(responseTemplate, customerState);\n\n console.log('[INFO] got templated result: ' + templateResult);\n\n return templateResult;\n }\n catch (error)\n {\n console.log('[ERROR] failed to load response template for customer: ' + customerState.Customer.AccountNumber);\n throw error;\n }\n}",
"async test12(stub, args) {\n\t\t// construct the decrypter, the stub is required to contain a transient map\n\t\t// with a key \"encKey\", which will be used to decrypt the values\n const decrypter = new ChaincodeCrypto(stub);\n const ciphertext = await stub.getState(args[0]);\n const value = decrypter.decrypt(ciphertext).toString();\n value.should.equal(args[1], 'Test state value decryption with the ChaincodeCrypto library');\n }",
"function buildTestContractsArray(contractsInput) {\n const testContracts = [];\n const contracts = Object.assign({}, contractsInput);\n\n // contracts\n for (var contractName in contracts) { // eslint-disable-line\n const contractInterface = JSON.parse(contracts[contractName].interface);\n if (contractName !== 'Test' &&\n contractInterface.some(includesSomeAssertLogEvent)) {\n contracts[contractName].name = contractName;\n testContracts.push(contracts[contractName]);\n }\n }\n\n // output test contracts array\n return testContracts;\n}",
"async function resetContractTestEnv() {\n //deploy contract\n const latestBlock = await web3.eth.getBlock('latest');\n startTime = latestBlock.timestamp;\n icoContract = await DelphyICOMock.new(wallet, startTime);\n tokenContract = DelphyTokenContract.at(await icoContract.delphyToken());\n\n endTime = startTime + totalDuring;\n }",
"function deliveryStateTestCase(assert, sRequiredDate, sShippedDate, fExpectedResult){\n\t\t//var sRequiredDateTime = new Date(sRequiredDate).getTime();\n\t\t//var sShippedDateTime = new Date(sShippedDate).getTime();\n\t\t//var fResult = formatter.deliveryState(sRequiredDateTime, sShippedDateTime);\n\t\tvar fResult = formatter.deliveryState(sRequiredDate, sShippedDate);\n\t\tassert.strictEqual(fResult, fExpectedResult, \"The calculation of delivery state was correct\");\n\t}",
"async test11(stub, args) {\n\t\t// construct the encrypter, the stub is required to contain a transient map\n\t\t// with a key \"encrypt-key\", which will be used to encrypt the values\n const encrypter = new ChaincodeCrypto(stub);\n const ciphertext = encrypter.encrypt(Buffer.from(args[1])); // 2nd arg has the new value to encrypt\n await stub.putState(args[0], ciphertext); // 1st arg has the key\n }",
"async function buildMockResponse(customerState)\n{\n try\n {\n\n var customerScenario = '0';\n\n if (customerState.CustomerScenario !== undefined)\n {\n customerScenario = customerState.CustomerScenario;\n }\n\n var accountMockData =\n {\n // No direct debit - TODO confirm this scenario\n '0': {\n Success: true,\n OngoingFlag: false,\n Delay: 0,\n Template: 'IntegrationRetrievePaymentProfileNoneResponseSuccess'\n },\n // Bank account number\n '1': {\n Success: true,\n OngoingFlag: true,\n PaymentProfileId: '32539430000',\n BankAccountNumber: '10682365',\n BSBNumber: '064000',\n Delay: 0,\n Template: 'IntegrationRetrievePaymentProfileBankAccountResponseSuccess'\n },\n // Credit card\n '2': {\n Success: true,\n OngoingFlag: true,\n PaymentProfileId: '32539430001',\n CardNumber: '4673647364763746376', // Tokenised card number?\n MaskedCardNumber: '4534112...342', // TODO is this the card token?\n CardExpiryDate: '1223',\n CardType: 'MSC',\n Delay: 0,\n Template: 'IntegrationRetrievePaymentProfileCreditCardResponseSuccess'\n },\n // No direct debit - TODO confirm this scenario\n '3': {\n Success: true,\n OngoingFlag: false,\n Delay: 2000,\n Template: 'IntegrationRetrievePaymentProfileNoneResponseSuccess'\n },\n // Bank account number\n '4': {\n Success: true,\n OngoingFlag: true,\n PaymentProfileId: '32539430000',\n BankAccountNumber: '10682365',\n BSBNumber: '064000',\n Delay: 3000,\n Template: 'IntegrationRetrievePaymentProfileBankAccountResponseSuccess'\n },\n // Credit card\n '5': {\n Success: true,\n OngoingFlag: true,\n PaymentProfileId: '32539430001',\n CardNumber: '4673647364763746376', // Tokenised card number?\n MaskedCardNumber: '4534112...342', // TODO is this the card token?\n CardExpiryDate: '1223',\n CardType: 'MSC',\n Delay: 5000,\n Template: 'IntegrationRetrievePaymentProfileCreditCardResponseSuccess'\n },\n // No direct debit - TODO confirm this scenario\n '6': {\n Success: true,\n OngoingFlag: false,\n Delay: 1000,\n Template: 'IntegrationRetrievePaymentProfileNoneResponseSuccess'\n },\n // Bank account number\n '7': {\n Success: true,\n OngoingFlag: true,\n PaymentProfileId: '32539430000',\n BankAccountNumber: '10682365',\n BSBNumber: '064000',\n Delay: 3000,\n Template: 'IntegrationRetrievePaymentProfileBankAccountResponseSuccess'\n },\n // Timeout response\n '8': {\n Success: true,\n OngoingFlag: true,\n PaymentProfileId: '32539430001',\n CardNumber: '4673647364763746376', // Tokenised card number?\n MaskedCardNumber: '4534112...342', // TODO is this the card token?\n CardExpiryDate: '1223',\n CardType: 'MSC',\n Delay: 16000,\n Template: 'IntegrationRetrievePaymentProfileCreditCardResponseSuccess'\n },\n // Error response\n '9': {\n Success: false,\n Delay: 5000,\n Template: 'IntegrationRetrievePaymentProfileResponseError'\n }\n };\n\n var selectedAccount = accountMockData[customerState.CustomerScenario];\n\n if (selectedAccount === undefined)\n {\n selectedAccount = accountMockData['0'];\n }\n\n await sleep(selectedAccount.Delay);\n\n customerState.Mock = selectedAccount;\n var responseTemplate = getTemplate(selectedAccount.Template);\n\n console.log('[INFO] got template raw: ' + responseTemplate);\n\n var templateResult = handlebarsUtils.template(responseTemplate, customerState);\n\n console.log('[INFO] got templated result: ' + templateResult);\n\n return templateResult;\n }\n catch (error)\n {\n console.log('[ERROR] failed to template mock response', error);\n throw error;\n }\n}",
"function testContract(address) {\n // Reference to the deployed contract\n const token = contract.at(address);\n // Destination account for test\n const dest_account = '0x002D61B362ead60A632c0e6B43fCff4A7a259285';\n\n // Assert initial account balance, should be 100000\n const balance1 = token.balances.call(web3.eth.coinbase);\n console.log(balance1 == 1000000);\n\n // Call the transfer function\n token.transfer(dest_account, 100, {from: web3.eth.coinbase}, (err, res) => {\n // Log transaction, in case you want to explore\n console.log('tx: ' + res);\n // Assert destination account balance, should be 100 \n const balance2 = token.balances.call(dest_account);\n console.log(balance2 == 100);\n });\n}",
"function createTest( param ) {\n \n QUnit.test( param.name, async function( assert ){\n\n // async test, so get the callback\n const done = assert.async();\n\n try {\n\n // parse formula to AST\n const formula = await parseFormula( parseConstants.IN_STRING, parseConstants.OUT_AST, param.formula );\n \n // resolve bindings by Unit objects\n const boundUnits = Object.keys( param.binding )\n .reduce( (all,key) => {\n all[ key ] = replaceUnit( param.binding[ key ] );\n return all;\n }, {} );\n\n // run unit estimation\n const res = await estimateUnit( formula, boundUnits );\n\n // get resulting units\n const resUnits = await res.resolve();\n\n // check total number of results\n if( param.resultCount ) {\n assert.equal( resUnits.length, param.resultCount, `result has exactly ${param.resultCount} options` );\n }\n\n // check individual results\n for( const expectedRes of param.results ) {\n \n // resolve target unit\n const targetUnit = replaceUnit( expectedRes.unit );\n\n // find in result set\n const resUnit = resUnits.find( (el) => el.unit == targetUnit );\n assert.ok( !!resUnit, `one result should be in ${expectedRes.unit}` );\n if( !resUnit ) { continue; }\n\n // compare properties\n assert.equal( resUnit.conv, expectedRes.conv, `result in ${expectedRes.unit} should need ${expectedRes.conv} conversion(s)`)\n if( 'factor' in param ) {\n assert.equal( resUnit.factor.toString(), param.factor, `check result factor for ${expectedRes.unit}` ); \n }\n assert.yavaa_astEqual( await res.getAst( targetUnit ), expectedRes.ast, `check AST for ${expectedRes.unit}` );\n \n }\n\n // check additional results (AST only)\n if( 'addResults' in param ) {\n for( let expectedRes of param.addResults ) {\n\n // resolve target unit\n const targetUnit = replaceUnit( expectedRes.unit );\n \n // compare AST\n assert.yavaa_astEqual( await res.getAst( targetUnit ), expectedRes.ast, `check AST for ${expectedRes.unit}` );\n \n } \n } \n\n } catch(e) {\n\n // internal error\n assert.ok( false, e + \"\\n\" + e.stack );\n\n }\n\n // finished\n done();\n\n });\n\n }",
"function testAdvanceTournamentCase (testCase) {\n var beforeState = JSON.parse(testCase.before)\n var afterState = JSON.parse(testCase.after)\n var advancedState = tourneyNerd.advanceTournament(beforeState)\n\n it(testCase.description, function () {\n assert.deepStrictEqual(advancedState, afterState)\n })\n}",
"function testInvokeContract (callback, tx) {\n const assetType = tx.type === ASSETS_LABELS.NEO ? ASSETS.NEO : ASSETS.GAS\n console.log('test invoking contract')\n var gasCost = 0.001\n var operation = tx.operation\n // var args = [{'type': 7, 'value': tx.args}]\n var args = []\n tx.args.forEach((arg) => {\n if (arg !== '') args.push({'type': 7, 'value': arg})\n })\n\n console.log('invoke wif: ' +state.wif)\n console.log('invoke network: ' +state.network)\n console.log('invoke scriptHash: ' +tx.scriptHash)\n console.log('invoke operation: ' +operation)\n console.log('args: '+util.inspect(args,{depth:null}))\n\n neon.testInvokeContract(state.network, operation, args, tx.scriptHash)\n .then((response) => {\n if (response.result.stack[0].type === 'ByteArray' && response.result.stack[0].value) {\n var endian = response.result.stack[0].value\n\n var r = parseInt('0x'+endian.match(/../g).reverse().join(''));\n console.log('price result: '+r)\n\n callback(null, 'SC Return Value: ' + r + ' Transaction result: '+\n 'state: ' + response.result.state +\n ' gas_consumed: ' + response.result.gas_consumed +\n ' stack: ' + util.inspect(response.result, {depth: null}))\n console.log('bg test invoke succeeded: '+ util.inspect(response.result, {depth: null}))\n } else {\n callback(null, 'Transaction result: '+\n 'state: ' + response.result.state +\n ' gas_consumed: ' + response.result.gas_consumed +\n ' stack: ' + util.inspect(response.result, {depth: null}))\n console.log('bg test invoke failed: '+ util.inspect(response.result, {depth: null}))\n }\n }).catch((e) => {\n console.log('bg test invoke caught exception: '+e)\n // console.log('error: '+util.inspect(e, {depth: null}))\n callback(''+e) // throw e\n })\n}",
"buildTransaction() {\n const transaction = {\n date: this.state.date,\n description: this.state.description,\n charge: this.state.charge,\n payment: this.state.payment,\n amount: this.state.amount,\n }\n return transaction\n }",
"test_calculate(test) {\n const attrs_without_ma = test_args.parsed_request.raw_attributes.filter(a => a[0] != radius.attr_name_to_id('Message-Authenticator'));\n\n const encoded = radius.encode({\n code: test_args.parsed_request.code,\n identifier: test_args.parsed_request.identifier,\n authenticator: test_args.parsed_request.authenticator,\n attributes: attrs_without_ma,\n secret,\n });\n\n test.equal(encoded.toString('hex'), test_args.raw_request.toString('hex'));\n\n test.done();\n }",
"async function fetchAndBuild(testDataAll, outputAddress) {\n\t// check if the outputAddress provided is for mainnet or testnet\n\tif (bitboxMainnet.Address.isMainnetAddress(outputAddress)) {\n\t\tnetwork = \"mainnet\";\n\t\tbitbox = bitboxMainnet;\n\t} else if (bitboxMainnet.Address.isTestnetAddress(outputAddress)) {\n\t\tnetwork = \"testnet\";\n\t\tbitbox = bitboxTestnet;\n\t}\n\t\n\t// use the appropriate data from the full testing dataset\n\tlet testData = testDataAll[network];\n\t\n\t// placeholder for address details fetching function\n\tvar addressesToFetch = [];\n\ttestData[\"child_nodes\"].forEach(function (childNode) {\n\t\taddressesToFetch.push(childNode[\"cashAddress\"]);\n\t});\n\t\n\t// fetch the details of all addresses in the dataset\n\tlet details = await bitbox.Address.details(addressesToFetch);\n\t\n\t// placeholder for cumulative balance on all testing addresses\n\tvar totalBalance = 0;\n\t\n\t// placeholder for a list of all addresses with balances to fetch utxos of\n\tvar utxosToFetch = [];\n\t\n\t// go through all the details of the testing child nodes and find out if they have balance\n\tfor (var i = 0; i < testData[\"child_nodes\"].length; i++) {\n\t\tif (testData[\"child_nodes\"][i][\"cashAddress\"] == details[i][\"cashAddress\"]) {\n\t\t\ttestData[\"child_nodes\"][i][\"balance\"] = details[i][\"balanceSat\"];\n\t\t\ttotalBalance += details[i][\"balanceSat\"];\n\t\t\t\n\t\t\tif (details[i][\"balanceSat\"] > 0) {\n\t\t\t\tutxosToFetch.push(details[i][\"cashAddress\"]);\n\t\t\t}\n\t\t}\n\t}\n\n\t// if there is a balance at any of the addresses, get their details to compile a testing transaction\n\tif (totalBalance > 0) {\n\t\t// get an account node from the testing account master private key\n\t\tlet accountNode = bitbox.HDNode.fromXPriv(testData[\"account_xpriv\"]);\n\t\t\n\t\t// get utxo details based on the list compiled above\n\t\tlet utxos = await bitbox.Address.utxo(utxosToFetch);\n\t\t\n\t\t// create a transaction builder for the appropriate network\n\t\tlet builder = new bitbox.TransactionBuilder(network);\n\t\t\n\t\t// placeholder for input signatures\n\t\tvar signatures = [];\n\t\t\n\t\t// go through all the utxo details to get the input and signature data\n\t\tfor (var i = 0; i < utxos.length; i++) {\n\t\t\t// first add utxos to the test data under the respective child node\n\t\t\tfor (var index = 0; index < testData[\"child_nodes\"].length; index++) {\n\t\t\t\tif (testData[\"child_nodes\"][index][\"cashAddress\"] == utxos[i][\"cashAddress\"]) {\n\t\t\t\t\ttestData[\"child_nodes\"][index][\"utxos\"] = utxos[i][\"utxos\"];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// go through the list of utxos for this address to add them into inputs and signatures\n\t\t\tutxos[i][\"utxos\"].forEach(function (utxo) {\n\t\t\t\t// add input to the transaction\n\t\t\t\tbuilder.addInput(utxo[\"txid\"], utxo[\"vout\"]);\n\t\t\t\t\n\t\t\t\t// add signature. Use private key derived from the account node\n\t\t\t\tsignatures.push({\n\t\t\t\t\t\"vin\" : signatures.length,\n\t\t\t\t\t\"keyPair\" : bitbox.HDNode.toKeyPair(accountNode.derive(i)),\n\t\t\t\t\t\"originalAmount\" : utxo[\"satoshis\"]\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\t\t\n\t\t// calculate fee for the transaction (signatures array length equals numbers of inputs)\n\t\tlet byteCount = bitbox.BitcoinCash.getByteCount({ P2PKH: signatures.length }, { P2PKH: 1 });\n\t\t\n\t\t// substract the fee from total balance on the addresses\n\t\tlet sendAmount = totalBalance - byteCount;\n\t\t\n\t\t// add output from the output address provided in the console and calculated amount after the fee\n\t\tbuilder.addOutput(outputAddress, sendAmount);\n \n\t\t// sign all inputs\n\t\tsignatures.forEach(function (signature) {\n\t\t\tbuilder.sign(signature[\"vin\"], signature[\"keyPair\"], undefined, builder.hashTypes.SIGHASH_ALL, signature[\"originalAmount\"]);\n\t\t});\n\t\t\n\t\t// build the transaction\n\t\tlet tx = builder.build();\n\t\t\n\t\t// store the output address and testing transaction String\n\t\ttestData[\"output_address\"] = outputAddress;\n\t\ttestData[\"testing_tx_hex\"] = tx.toHex();\n\t}\n\t\n\t// save all the details into the testing data for the appropriate network\n\ttestDataAll[network] = testData;\n\t\n\t// return the data (this function doesn't decide when to write them into the testing file\n\treturn testDataAll;\n}",
"async initStateFromContract() {\n // Clear the reload timeout if it's still set.\n clearTimeout(this.reloadStateTimeout);\n\n this.setState({\n contractLoadOpen: false\n });\n\n try {\n var holder = await getHolder(this.props.contract, this.props.address);\n var counterParty = await getCounterParty(this.props.contract, this.props.address);\n var concluded = await getConcluded(this.props.contract, this.props.address);\n var orChoices = await getOrChoices(this.props.contract, this.props.address);\n var obsEntries = await getObsEntries(this.props.contract, this.props.address);\n var acquisitionTimes = await getAcquisitionTimes(this.props.contract, this.props.address);\n var holderBalance = await getBalance(this.props.contract, this.props.address, true);\n var counterPartyBalance = await getBalance(this.props.contract, this.props.address, false);\n var combinatorContract = await getCombinatorContract(this.props.contract, this.props.address);\n var useGas = await getUseGas(this.props.contract, this.props.address);\n var lastUpdated = await getLastUpdated(this.props.contract, this.props.address);\n\n this.setState({\n holder: holder,\n counterParty: counterParty,\n concluded: concluded,\n orChoices: orChoices,\n obsEntries: obsEntries,\n acquisitionTimes: acquisitionTimes,\n holderBalance: holderBalance,\n counterPartyBalance: counterPartyBalance,\n combinatorContract: combinatorContract,\n useGas: useGas,\n lastUpdated: lastUpdated\n }, () => {\n this.reloadStateTimeout = setTimeout(() => this.initStateFromContract(), Monitoring.RELOAD_PERIOD);\n });\n } catch(err) {\n this.setState({\n contractInteractionError: \"Contract functions not found. Please check that the contract address is correct.\",\n contractInteractionErrorDetails: err.toString()\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Goal: Build a molecular structure from a local pdbfile | function ReadPDBfile(file,callback)
{
var self = this;
var name= PDButil.stripName(file.name);
//Assigning Properties by reading the file
var pdbfileReader = new FileReader();
//Reads the file
pdbfileReader.readAsText(file);
//When file is read, this function is called
pdbfileReader.onload = loadStructureHandler;
pdbfileReader.onerror = errorStructureHandler;
function loadStructureHandler(event)
{
var content = event.target.result.split("\n");
//console.log(content[1]);
BuildStructure(name,content,callback, new ProgressDialog("Assimilating PDB file "+name+"..."));
};
function errorStructureHandler(event)
{
console.log("Error while reading the file");
};
} | [
"function readPDBfile(lines) {\n // Declare local variables\n var i, j;\n var x, y, z;\n var bond1, bond2;\n var A, symbol, line;\n var Qtitle = new Array();\n var molecule = Mol();\n var atomnum_limit = 2000;\n\n // Write file information to information window\n var molname = lines[0].split(/\\s+/)[1];\n\n // Reset molecule object and contents\n delMolecule();\n\n // Read data\n for(i = 2; i < lines.length; i++) {\n if(lines[i].substring(0, 6) == \"HETATM\" || lines[i].substring(0, 4) == \"ATOM\") {\n symbol = lines[i].substring(12, 16);\n symbol = symbol.replace(/\\s+/, \"\");\n A = lookupSymbol(symbol.trim());\n x = parseFloat(lines[i].substring(30, 38));\n y = parseFloat(lines[i].substring(38, 46));\n z = parseFloat(lines[i].substring(46, 54));\n addAtom(A, x, y, z, 0);\n }\n if(lines[i].substring(0, 6) == \"CONECT\") {\n bond1 = parseFloat(lines[i].substr(6, 5));\n for(j = 11; j < lines[i].length; j = j + 5) {\n var bonds = BondMatrix();\n bond2 = parseFloat(lines[i].substr(j, 5));\n bonds[bond1][0]++;\n bonds[bond1][bond2] = 1;\n }\n }\n }\n \n formula();\n }",
"function pdb(text) {\n console.time('pdb'); \n var structure = new Mol();\n var currChain = null;\n var currRes = null;\n var currAtom = null;\n \n var helices = [];\n var sheets = [];\n \n function parseAndAddAtom(line, hetatm) {\n var alt_loc = line[16];\n if (alt_loc !== ' ' && alt_loc !== 'A') {\n return;\n }\n var chainName = line[21];\n var res_name = line.substr(17, 3);\n var atomName = line.substr(12, 4).trim();\n var rnumNum = parseInt(line.substr(22, 4), 10);\n var ins_code = line[26];\n var updateResidue = false;\n var updateChain = false;\n if (!currChain || currChain.name() !== chainName) {\n updateChain = true;\n updateResidue = true;\n }\n if (!currRes || currRes.num() !== rnumNum) {\n updateResidue = true;\n }\n if (updateChain) {\n // residues of one chain might appear interspersed with residues from\n // other chains.\n currChain = structure.chain(chainName) || structure.addChain(chainName);\n }\n if (updateResidue) {\n currRes = currChain.addResidue(res_name, rnumNum,\n currChain.residues().length);\n }\n var pos = vec3.create();\n for (var i=0;i<3;++i) {\n pos[i] = (parseFloat(line.substr(30+i*8, 8)));\n }\n currRes.addAtom(atomName, pos, line.substr(76, 2).trim());\n }\n var lines = text.split(/\\r\\n|\\r|\\n/g);\n var i = 0;\n for (i = 0; i < lines.length; i++) {\n var line = lines[i];\n var recordName = line.substr(0, 6);\n\n if (recordName === 'ATOM ') {\n parseAndAddAtom(line, false);\n continue;\n }\n if (recordName === 'HETATM') {\n parseAndAddAtom(line, true);\n continue;\n }\n if (recordName === 'HELIX ') {\n helices.push(parseHelixRecord(line));\n continue;\n }\n if (recordName === 'SHEET ') {\n sheets.push(parseSheetRecord(line));\n continue;\n }\n if (recordName === 'END') {\n break;\n }\n }\n var chain = null;\n for (i = 0; i < sheets.length; ++i) {\n var sheet = sheets[i];\n chain = structure.chain(sheet.chainName);\n if (chain) {\n chain.assign_ss(sheet.first, sheet.last, 'E');\n }\n }\n for (i = 0; i < helices.length; ++i) {\n var helix = helices[i];\n chain = structure.chain(helix.chainName);\n if (chain) {\n chain.assign_ss(helix.first, helix.last, 'H');\n }\n }\n structure.deriveConnectivity();\n console.log('imported', structure.chains().length, 'chain(s),',\n structure.residueCount(), 'residue(s)');\n console.timeEnd('pdb');\n\n return structure;\n}",
"function loadPDB(name, callback) {\n console.log(\"Loading \" + name + \" ...\");\n jQuery.get('http://www.adcworks.com/api/pdb/' + name, function(data) {\n\n var lines = data.split(\"\\n\");\n if (lines.length > 0) {\n pdb = lines.join(\"<br>\");\n var mol = new Molecule();\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n var recordName = line.substring(1 - 1, 6).trim();\n if (recordName === \"ATOM\" || recordName === \"HETATM\") {\n\n var symbol = line.substring(77 - 1, 78).trim().toUpperCase();\n symbol = symbol.replace(/[^A-Z]/g, '');\n if (symbol.length === 0) {\n var name = line.substring(13 - 1, 15).trim().toUpperCase();\n name = name.replace(/[^A-Z]/g, '');\n symbol = symByPDBName(name);\n }\n\n var x = parseFloat(line.substring(31 - 1, 38).trim());\n var y = parseFloat(line.substring(39 - 1, 46).trim());\n var z = parseFloat(line.substring(47 - 1, 54).trim());\n var ref = refElement(symbol);\n mol.add(new Atom(i, symbol, x, y, z, ref.r));\n }\n }\n\n mol.finalise();\n callback(pdb, mol);\n }\n }, 'text');\n}",
"function pdb(text) {\n console.time('pdb'); \n var reader = new PDBReader();\n var lines = text.split(/\\r\\n|\\r|\\n/g);\n var i = 0;\n for (i = 0; i < lines.length; i++) {\n if (!reader.processLine(lines[i])) {\n break;\n }\n }\n var structure = reader.finish();\n console.timeEnd('pdb');\n return structure;\n}",
"function loadPDB(pdb,rotate) {\n\t\t\t\t\t\tconsole.log('loadPDB');\n\t\t\t\t\t\tvar structure = pv.io.pdb(pdb);\n\t\t\t\t\t\tvar ligand = structure.select({rnames : ['UNL']});\n\t\t\t\t\t\t//Attach protein viewer to element\n\t\t\t\t\t\tvar viewer = pv.Viewer(document.getElementById(scope.ngid), { quality : 'high', width: 'auto', height : 'auto', antialias : true, outline : false, });\n\t\t\t\t\t\tviewer.on('viewerReady', function() {\n\t\t\t\t\t\t\tviewer.clear();\n\t\t\t\t\t\t\tviewer.ballsAndSticks('ligand', ligand);\n\t\t\t\t\t\t\tviewer.centerOn(ligand);\n\t\t\t\t\t\t\tviewer.autoZoom();\n\t\t\t\t\t\t\t//viewer.fitParent();\n\t\t\t\t\t\t\tviewer.spin(rotate);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}",
"function makeSciForm(mol) {\n var lines = mol.split(\"\\n\");\n var nodes = [];\n var bonds = [];\n var ncount = 0;\n var bcount = 0;\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n if (i == 3) {\n ncount = line.substring(0, 3).trim() - 0;\n bcount = line.substring(4, 7).trim() - 0;\n }\n if (i > 3 && i <= ncount + 3) {\n var node = {};\n node.id = \"cdj\" + (i - 3);\n node.pos = {};\n node.pos.x = line.substring(0, 10).trim() - 0;\n node.pos.y = -1 * (line.substring(11, 20).trim() - 0);\n //node.z=line.substring(0,10).trim()-0;\n node.sym = line.substring(31, 34).trim();\n node.type = \"ring_or_chain\";\n node.nodeNumber = (i - 3);\n nodes.push(node);\n }\n if (i > ncount + 3 && i <= ncount + 3 + bcount) {\n var b1 = line.substring(0, 3).trim() - 0;\n var b2 = line.substring(3, 6).trim() - 0;\n var or = line.substring(6, 9).trim() - 0;\n var bond = {};\n bond.id = \"cdj\" + (i - 3);\n bond.fromId = \"cdj\" + b1;\n bond.toId = \"cdj\" + b2;\n if (or == 1) {\n bond.order = \"single\";\n } else if (or == 2) {\n bond.order = \"double\";\n } else if (or == 3) {\n bond.order = \"triple\";\n }\n bond.type = \"ring_or_chain\";\n bond.locked = false;\n bonds.push(bond);\n\n }\n }\n return {\n nodes: nodes,\n bonds: bonds\n };\n }",
"function LM_getUrlStructure(anode,pdbname){\r\n pdbname = pdbname.toLowerCase();\r\n if (pdbname.length === 4) {\r\n if (anode.data.surface)\r\n {\r\n if (anode.data.opm === 1){\r\n //replace purl\r\n return opm_url+ pdbname +\".pdb\";//cellpack_repo+\"opm/\" + pdbname + \".mmtf\";\r\n }\r\n else if (anode.data.opm === 0)\r\n {\r\n //check if exists\r\n var search_url = cellpack_repo+\"opm/\"+pdbname+ \".mmtf\";\r\n var results = syncCall(search_url);\r\n if (results !==\"\")\r\n {\r\n purl = cellpack_repo+\"opm/\" + pdbname + \".mmtf\";\r\n anode.data.opm = 1;\r\n return purl;\r\n }\r\n else {\r\n anode.data.opm = -1;\r\n }\r\n //check if exist in opm..doesnt work\r\n //var search_url = \"http://opm.phar.umich.edu/protein.php?search=\"+aname//1l7v\r\n //var results = syncCall(search_url);\r\n //var parser = new DOMParser();\r\n //var hdoc = parser.parseFromString(results,\"text/xml\");\r\n //console.log(hdoc);\r\n }\r\n }\r\n return \"https://files.rcsb.org/download/\" + pdbname + \".cif\";\r\n //return \"https://www.ebi.ac.uk/pdbe/static/entry/\" + pdbname + \".cif\";\r\n }\r\n else\r\n {\r\n var ext = pdbname.slice(-4, pdbname.length);\r\n if (pdbname.startsWith(\"EMD\") || pdbname.startsWith(\"EMDB\") || pdbname.slice(-4, pdbname.length) === \".map\") {\r\n var params = {\r\n defaultRepresentation: false\r\n };\r\n //this is async!\r\n console.log(\"try to load \", pdbname, ext);\r\n if (ext !== \".map\") pdbname = pdbname + \".map\";\r\n if (folder_elem && folder_elem.files.length != \"\")\r\n {\r\n return pathList_[pdbname];\r\n }\r\n else\r\n {\r\n return cellpack_repo+\"other/\" + pdbname;\r\n }\r\n }\r\n else\r\n {\r\n //what about emdb\r\n if (folder_elem && folder_elem.files.length != \"\") {\r\n //alert(pathList_[d.data.source]),\r\n return pathList_[pdbname];\r\n }\r\n else\r\n {\r\n return cellpack_repo+\"other/\" + pdbname;\r\n }\r\n }\r\n }\r\n return \"\";\r\n}",
"function readSDFfile(sdffile,lines) {\n // Declare local variables\n var i, j;\n var x, y, z;\n var bond1, bond2;\n var A, symbol;\n var Qtitle = new Array();\n var molecule = Mol();\n var atomnum_limit = 2000;\n\n // Write file information to information window\n var molname = escape(sdffile.name);\n InfoWin(\"File Name = \"+sdfname,1);\n InfoWin(\"\\nFile Type = \"+sdffile.type);\n InfoWin(\"\\nFile Size = \"+sdffile.size);\n\n // Reset molecule object and contents\n delMolecule();\n\n // Read data\n Qtitle = lines[0];\n Qtitle = Qtitle.replace(/\\s+$/,\"\");\n var molAtoms = parseFloat(lines[3].substr(0,3));\n var molBonds = parseFloat(lines[3].substr(3,3));\n InfoWin(\"\\n\\n\"+Qtitle);\n InfoWin(\"\\n\"+molAtoms+\" atoms and \"+molBonds+\" bonds.\");\n\n if (molAtoms > atomnum_limit){\n InfoWin(\"Error: Numbers Of Atoms Exceed Limit.\");\n return;\n }\n // Read coordinates\n j = molAtoms+4;\n for (i=4; i < j; i++) {\n x = parseFloat(lines[i].substr(0,10));\n y = parseFloat(lines[i].substr(10,10));\n z = parseFloat(lines[i].substr(20,10));\n symbol = lines[i].substr(31,3);\n symbol = symbol.replace(/\\s+/,\"\");\n A = lookupSymbol(symbol);\n InfoWin(\"\\n \"+symbol+\"(\"+A+\") \"+x+\", \"+y+\", \"+z);\n addAtom(A, x, y, z, 0);\n }\n j = 4 + molAtoms + molBonds;\n for (i = 4+molAtoms; i < j; i++) {\n bond1 = parseFloat(lines[i].substr(0,3));\n bond2 = parseFloat(lines[i].substr(3,3));\n bond3 = parseFloat(lines[i].substr(6,3));\n InfoWin(\"\\n Bond from \"+bond1+\" to \"+bond2);\n var bondtype = \"single\";\n if(bond3==2){\n bondtype = \"double\";\n }\n if(bond3==3){\n bondtype = \"triple\";\n }\n addBond(bond1,bond2,bondtype);\n }\n // Finished\n formula();\n }",
"function pdb(id = '4glf') {\n // const data = posturi('https://files.rcsb.org/download/' + id.toUpperCase() + '.pdb');\n const url = 'https://files.rcsb.org/download/' + id.toUpperCase() + '.pdb';\n CSynth.handlefileset( {eventParms: [{ canonpath: url}] })\n}",
"function readMOLfile(molfile,lines) {\n // Declare local variables\n var i, j;\n var x, y, z;\n var bond1, bond2;\n var A, symbol;\n var Qtitle = new Array();\n var molecule = Mol();\n var atomnum_limit = 2000;\n\n // Write file information to information window\n var molname = escape(molfile.name);\n InfoWin(\"File Name = \"+molname,1);\n InfoWin(\"\\nFile Type = \"+molfile.type);\n InfoWin(\"\\nFile Size = \"+molfile.size);\n\n // Reset molecule object and contents\n delMolecule();\n\n // Read data\n Qtitle = lines[0];\n Qtitle = Qtitle.replace(/\\s+$/,\"\");\n var molAtoms = parseFloat(lines[3].substr(0,3));\n var molBonds = parseFloat(lines[3].substr(3,3));\n InfoWin(\"\\n\\n\"+Qtitle);\n InfoWin(\"\\n\"+molAtoms+\" atoms and \"+molBonds+\" bonds.\");\n\n if (molAtoms > atomnum_limit){\n InfoWin(\"Error: Numbers Of Atoms Exceed Limit.\");\n return;\n }\n // Read coordinates\n j = molAtoms+4;\n for (i=4; i < j; i++) {\n x = parseFloat(lines[i].substr(0,10));\n y = parseFloat(lines[i].substr(10,10));\n z = parseFloat(lines[i].substr(20,10));\n symbol = lines[i].substr(31,3);\n symbol = symbol.replace(/\\s+/,\"\");\n A = lookupSymbol(symbol);\n InfoWin(\"\\n \"+symbol+\"(\"+A+\") \"+x+\", \"+y+\", \"+z);\n addAtom(A, x, y, z, 0);\n }\n j = 4 + molAtoms + molBonds;\n for (i = 4+molAtoms; i < j; i++) {\n bond1 = parseFloat(lines[i].substr(0,3));\n bond2 = parseFloat(lines[i].substr(3,3));\n bond3 = parseFloat(lines[i].substr(6,3));\n InfoWin(\"\\n Bond from \"+bond1+\" to \"+bond2);\n var bondtype = \"single\";\n if(bond3 == 2){\n bondtype = \"double\";\n }\n if(bond3 == 3){\n bondtype = \"triple\";\n }\n addBond(bond1,bond2,bondtype);\n }\n // Finished\n formula();\n }",
"function ReadPDBurl(URL,callback)\r\n{\r\n\tvar name = PDButil.stripName(URL);\r\n\tvar request = new XMLHttpRequest();\r\n\trequest.open('GET', URL, true);\r\n\trequest.onload = function() {\r\n\t\t var text = request.responseText;\r\n\t\t loadStructureHandler(text);\r\n\t};\r\n\trequest.send();\r\n\t\r\n\t//When file is read, this function is called\r\n\tfunction loadStructureHandler(text)\r\n\t{\r\n\t var content = text.split(\"\\n\");\r\n\t //console.log(content[1]);\r\n\t BuildStructure(name,content,callback, new ProgressDialog(\"Assimilating PDB file \"+name+\"...\"));\r\n\t};\r\n\r\n\tfunction errorStructureHandler(event)\r\n\t{\r\n\t console.log(\"Error while reading the file\");\r\n\t}; \r\n}",
"parse( text ) {\n\n\t\tfunction trim( text ) {\n\n\t\t\treturn text.replace( /^\\s\\s*/, '' ).replace( /\\s\\s*$/, '' );\n\n\t\t}\n\n\t\tfunction capitalize( text ) {\n\n\t\t\treturn text.charAt( 0 ).toUpperCase() + text.slice( 1 ).toLowerCase();\n\n\t\t}\n\n\t\tfunction hash( s, e ) {\n\n\t\t\treturn 's' + Math.min( s, e ) + 'e' + Math.max( s, e );\n\n\t\t}\n\n\t\tfunction parseBond( start, length, satom, i ) {\n\n\t\t\tconst eatom = parseInt( lines[ i ].slice( start, start + length ) );\n\n\t\t\tif ( eatom ) {\n\n\t\t\t\tconst h = hash( satom, eatom );\n\n\t\t\t\tif ( _bhash[ h ] === undefined ) {\n\n\t\t\t\t\t_bonds.push( [ satom - 1, eatom - 1, 1 ] );\n\t\t\t\t\t_bhash[ h ] = _bonds.length - 1;\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// doesn't really work as almost all PDBs\n\t\t\t\t\t// have just normal bonds appearing multiple\n\t\t\t\t\t// times instead of being double/triple bonds\n\t\t\t\t\t// bonds[bhash[h]][2] += 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfunction buildGeometry() {\n\n\t\t\tconst build = {\n\t\t\t\tgeometryAtoms: new BufferGeometry(),\n\t\t\t\tgeometryBonds: new BufferGeometry(),\n\t\t\t\tjson: {\n\t\t\t\t\tatoms: atoms\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst geometryAtoms = build.geometryAtoms;\n\t\t\tconst geometryBonds = build.geometryBonds;\n\n\t\t\tconst verticesAtoms = [];\n\t\t\tconst colorsAtoms = [];\n\t\t\tconst verticesBonds = [];\n\n\t\t\t// atoms\n\n\t\t\tconst c = new Color();\n\n\t\t\tfor ( let i = 0, l = atoms.length; i < l; i ++ ) {\n\n\t\t\t\tconst atom = atoms[ i ];\n\n\t\t\t\tconst x = atom[ 0 ];\n\t\t\t\tconst y = atom[ 1 ];\n\t\t\t\tconst z = atom[ 2 ];\n\n\t\t\t\tverticesAtoms.push( x, y, z );\n\n\t\t\t\tconst r = atom[ 3 ][ 0 ] / 255;\n\t\t\t\tconst g = atom[ 3 ][ 1 ] / 255;\n\t\t\t\tconst b = atom[ 3 ][ 2 ] / 255;\n\n\t\t\t\tc.set( r, g, b ).convertSRGBToLinear();\n\n\t\t\t\tcolorsAtoms.push( c.r, c.g, c.b );\n\n\t\t\t}\n\n\t\t\t// bonds\n\n\t\t\tfor ( let i = 0, l = _bonds.length; i < l; i ++ ) {\n\n\t\t\t\tconst bond = _bonds[ i ];\n\n\t\t\t\tconst start = bond[ 0 ];\n\t\t\t\tconst end = bond[ 1 ];\n\n\t\t\t\tconst startAtom = _atomMap[ start ];\n\t\t\t\tconst endAtom = _atomMap[ end ];\n\n\t\t\t\tlet x = startAtom[ 0 ];\n\t\t\t\tlet y = startAtom[ 1 ];\n\t\t\t\tlet z = startAtom[ 2 ];\n\n\t\t\t\tverticesBonds.push( x, y, z );\n\n\t\t\t\tx = endAtom[ 0 ];\n\t\t\t\ty = endAtom[ 1 ];\n\t\t\t\tz = endAtom[ 2 ];\n\n\t\t\t\tverticesBonds.push( x, y, z );\n\n\t\t\t}\n\n\t\t\t// build geometry\n\n\t\t\tgeometryAtoms.setAttribute( 'position', new Float32BufferAttribute( verticesAtoms, 3 ) );\n\t\t\tgeometryAtoms.setAttribute( 'color', new Float32BufferAttribute( colorsAtoms, 3 ) );\n\n\t\t\tgeometryBonds.setAttribute( 'position', new Float32BufferAttribute( verticesBonds, 3 ) );\n\n\t\t\treturn build;\n\n\t\t}\n\n\t\tconst CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], be: [ 194, 255, 0 ], b: [ 255, 181, 181 ], c: [ 144, 144, 144 ], n: [ 48, 80, 248 ], o: [ 255, 13, 13 ], f: [ 144, 224, 80 ], ne: [ 179, 227, 245 ], na: [ 171, 92, 242 ], mg: [ 138, 255, 0 ], al: [ 191, 166, 166 ], si: [ 240, 200, 160 ], p: [ 255, 128, 0 ], s: [ 255, 255, 48 ], cl: [ 31, 240, 31 ], ar: [ 128, 209, 227 ], k: [ 143, 64, 212 ], ca: [ 61, 255, 0 ], sc: [ 230, 230, 230 ], ti: [ 191, 194, 199 ], v: [ 166, 166, 171 ], cr: [ 138, 153, 199 ], mn: [ 156, 122, 199 ], fe: [ 224, 102, 51 ], co: [ 240, 144, 160 ], ni: [ 80, 208, 80 ], cu: [ 200, 128, 51 ], zn: [ 125, 128, 176 ], ga: [ 194, 143, 143 ], ge: [ 102, 143, 143 ], as: [ 189, 128, 227 ], se: [ 255, 161, 0 ], br: [ 166, 41, 41 ], kr: [ 92, 184, 209 ], rb: [ 112, 46, 176 ], sr: [ 0, 255, 0 ], y: [ 148, 255, 255 ], zr: [ 148, 224, 224 ], nb: [ 115, 194, 201 ], mo: [ 84, 181, 181 ], tc: [ 59, 158, 158 ], ru: [ 36, 143, 143 ], rh: [ 10, 125, 140 ], pd: [ 0, 105, 133 ], ag: [ 192, 192, 192 ], cd: [ 255, 217, 143 ], in: [ 166, 117, 115 ], sn: [ 102, 128, 128 ], sb: [ 158, 99, 181 ], te: [ 212, 122, 0 ], i: [ 148, 0, 148 ], xe: [ 66, 158, 176 ], cs: [ 87, 23, 143 ], ba: [ 0, 201, 0 ], la: [ 112, 212, 255 ], ce: [ 255, 255, 199 ], pr: [ 217, 255, 199 ], nd: [ 199, 255, 199 ], pm: [ 163, 255, 199 ], sm: [ 143, 255, 199 ], eu: [ 97, 255, 199 ], gd: [ 69, 255, 199 ], tb: [ 48, 255, 199 ], dy: [ 31, 255, 199 ], ho: [ 0, 255, 156 ], er: [ 0, 230, 117 ], tm: [ 0, 212, 82 ], yb: [ 0, 191, 56 ], lu: [ 0, 171, 36 ], hf: [ 77, 194, 255 ], ta: [ 77, 166, 255 ], w: [ 33, 148, 214 ], re: [ 38, 125, 171 ], os: [ 38, 102, 150 ], ir: [ 23, 84, 135 ], pt: [ 208, 208, 224 ], au: [ 255, 209, 35 ], hg: [ 184, 184, 208 ], tl: [ 166, 84, 77 ], pb: [ 87, 89, 97 ], bi: [ 158, 79, 181 ], po: [ 171, 92, 0 ], at: [ 117, 79, 69 ], rn: [ 66, 130, 150 ], fr: [ 66, 0, 102 ], ra: [ 0, 125, 0 ], ac: [ 112, 171, 250 ], th: [ 0, 186, 255 ], pa: [ 0, 161, 255 ], u: [ 0, 143, 255 ], np: [ 0, 128, 255 ], pu: [ 0, 107, 255 ], am: [ 84, 92, 242 ], cm: [ 120, 92, 227 ], bk: [ 138, 79, 227 ], cf: [ 161, 54, 212 ], es: [ 179, 31, 212 ], fm: [ 179, 31, 186 ], md: [ 179, 13, 166 ], no: [ 189, 13, 135 ], lr: [ 199, 0, 102 ], rf: [ 204, 0, 89 ], db: [ 209, 0, 79 ], sg: [ 217, 0, 69 ], bh: [ 224, 0, 56 ], hs: [ 230, 0, 46 ], mt: [ 235, 0, 38 ], ds: [ 235, 0, 38 ], rg: [ 235, 0, 38 ], cn: [ 235, 0, 38 ], uut: [ 235, 0, 38 ], uuq: [ 235, 0, 38 ], uup: [ 235, 0, 38 ], uuh: [ 235, 0, 38 ], uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] };\n\n\t\tconst atoms = [];\n\n\t\tconst _bonds = [];\n\t\tconst _bhash = {};\n\t\tconst _atomMap = {};\n\n\t\t// parse\n\n\t\tconst lines = text.split( '\\n' );\n\n\t\tfor ( let i = 0, l = lines.length; i < l; i ++ ) {\n\n\t\t\tif ( lines[ i ].slice( 0, 4 ) === 'ATOM' || lines[ i ].slice( 0, 6 ) === 'HETATM' ) {\n\n\t\t\t\tconst x = parseFloat( lines[ i ].slice( 30, 37 ) );\n\t\t\t\tconst y = parseFloat( lines[ i ].slice( 38, 45 ) );\n\t\t\t\tconst z = parseFloat( lines[ i ].slice( 46, 53 ) );\n\t\t\t\tconst index = parseInt( lines[ i ].slice( 6, 11 ) ) - 1;\n\n\t\t\t\tlet e = trim( lines[ i ].slice( 76, 78 ) ).toLowerCase();\n\n\t\t\t\tif ( e === '' ) {\n\n\t\t\t\t\te = trim( lines[ i ].slice( 12, 14 ) ).toLowerCase();\n\n\t\t\t\t}\n\n\t\t\t\tconst atomData = [ x, y, z, CPK[ e ], capitalize( e ) ];\n\n\t\t\t\tatoms.push( atomData );\n\t\t\t\t_atomMap[ index ] = atomData;\n\n\t\t\t} else if ( lines[ i ].slice( 0, 6 ) === 'CONECT' ) {\n\n\t\t\t\tconst satom = parseInt( lines[ i ].slice( 6, 11 ) );\n\n\t\t\t\tparseBond( 11, 5, satom, i );\n\t\t\t\tparseBond( 16, 5, satom, i );\n\t\t\t\tparseBond( 21, 5, satom, i );\n\t\t\t\tparseBond( 26, 5, satom, i );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// build and return geometry\n\n\t\treturn buildGeometry();\n\n\t}",
"function buildContract (name, path){\n var fileName = name;\n var filePath = path;\n var source = fs.readFileSync();\n\n\n}",
"function makeDB(dbfn) {\n const db = sqlite3(dbfn);\n db.exec(`PRAGMA journal_mode=WAL`);\n // these tables hold the snapshot contents more-or-less verbatim\n db.exec(`CREATE TABLE chunk (chunk BLOB)`);\n db.exec(\n `CREATE TABLE chunks (chunkIndex INTEGER, offset INTEGER, chunk BLOB, PRIMARY KEY (offset))`,\n );\n db.exec(\n `CREATE TABLE slots (slotID INTEGER, kind STRING, flag INTEGER, id INTEGER, next INTEGER, ` +\n `fieldsJSON STRING, slotFieldsJSON STRING, chunkFieldsJSON STRING, ` +\n `PRIMARY KEY (slotID))`,\n );\n db.exec(`CREATE INDEX slots_kind ON slots (kind, slotID)`);\n db.exec(`CREATE INDEX slots_next ON slots (next)`);\n db.exec(`CREATE INDEX slots_id ON slots (id)`);\n db.exec(\n `CREATE TABLE stack (stackID INTEGER, slotID INTEGER, PRIMARY KEY (stackID))`,\n );\n db.exec(\n `CREATE TABLE keys (keyID INTEGER, slotID INTEGER, isSymbol BOOL, string STRING, PRIMARY KEY (keyID))`,\n );\n db.exec(\n `CREATE TABLE nameBuckets (hash INTEGER, slotID INTEGER, PRIMARY KEY (hash))`,\n );\n db.exec(\n `CREATE TABLE symbolBuckets (hash INTEGER, slotID INTEGER, PRIMARY KEY (hash))`,\n );\n // these tables hold parsed results, for easier lookup\n db.exec(\n `CREATE TABLE strings (slotID INTEGER, string STRING, PRIMARY KEY (slotID))`,\n );\n db.exec(`CREATE INDEX strings_string ON strings (string)`);\n db.exec(`CREATE TABLE refs (slotID INTEGER, refID INTEGER)`);\n db.exec(`CREATE INDEX refs_slotID ON refs (slotID)`);\n db.exec(`CREATE INDEX refs_refID ON refs (refID)`);\n\n // comment this out to preserve a partial DB if the ingest process\n // throws an error, but it runs much more slowly because it will\n // auto-commit after every statement\n db.prepare('BEGIN IMMEDIATE TRANSACTION').run();\n\n const sql = { db };\n sql.sqlAddChunk = db.prepare(\n 'INSERT INTO chunks (chunkIndex, offset, chunk) VALUES (?,?,?)',\n );\n sql.sqlGetChunk = db.prepare('SELECT chunk FROM chunks WHERE offset=?');\n sql.sqlGetChunk.pluck(true);\n sql.getStringChunk = chunkOffset => {\n const chunkData = sql.sqlGetChunk.get(chunkOffset);\n const stripped = chunkData.slice(0, chunkData.indexOf(0));\n const string = Buffer.from(stripped).toString('utf-8');\n return string;\n };\n sql.sqlAddSlot = db.prepare(\n 'INSERT INTO slots ' +\n '(slotID, kind, flag, id, next,' +\n ' fieldsJSON, slotFieldsJSON, chunkFieldsJSON)' +\n ' VALUES (?,?,?,?,?,?,?,?)',\n );\n sql.sqlGetSlot = db.prepare('SELECT * FROM slots WHERE slotID=?'); // no pluck\n sql.sqlAddStack = db.prepare(\n 'INSERT INTO stack (stackID, slotID) VALUES (?,?)',\n );\n sql.sqlAddKey = db.prepare(\n 'INSERT INTO keys (keyID, slotID, isSymbol, string) VALUES (?,?,?,?)',\n );\n sql.sqlAddNameBucket = db.prepare(\n 'INSERT INTO nameBuckets (hash, slotID) VALUES (?,?)',\n );\n sql.sqlAddSymbolBucket = db.prepare(\n 'INSERT INTO symbolBuckets (hash, slotID) VALUES (?,?)',\n );\n\n sql.sqlAddString = db.prepare(\n 'INSERT INTO strings (slotID, string) VALUES (?,?)',\n );\n sql.sqlGetString = db.prepare('SELECT `string` FROM strings WHERE slotID=?');\n sql.sqlGetString.pluck(true);\n sql.sqlAddReference = db.prepare(\n 'INSERT INTO refs (slotID, refID) VALUES (?,?)',\n );\n\n return { db, sql };\n}",
"function readXYZfile(lines) {\n // Declare local variables\n var i, j, numatoms;\n var A, x, y, z;\n var dx, dy, dz, r;\n var bond;\n var mystr;\n var current = new Array();\n var Qtitle = new Array();\n var molecule = Mol();\n var atomnum_limit = 2000;\n\n // Reset molecule object and contents\n delMolecule();\n\n // Read data\n InfoWin(\"\",1);\n numatoms = parseInt(lines[0].replace(/\\s+/,\"\"));\n if ( isNaN(numatoms) ) {\n InfoWin(\"*** ERROR Reading XYZ file. ***\\n\");\n return;\n }\n if (numatoms > atomnum_limit){\n InfoWin(\"Error: Numbers Of Atoms Exceed Limit\");\n return;\n }\n Qtitle = lines[1];\n Qtitle = Qtitle.replace(/\\s+$/,\"\");\n InfoWin(Qtitle+\"\\n\");\n InfoWin(\"Looking for \"+numatoms+\" atoms.\\n\");\n\n // Read coordinates\n for (i=2; i < (numatoms+2); i++) {\n current = lines[i].replace(/\\s+/g,\" \").replace(/^\\s+/,\"\").split(' ');\n A = lookupSymbol(current[0]);\n if ( (A<1) || (A>118) ) {\n InfoWin(\"*** ERROR Reading XYZ file. ***\\n\");\n return;\n }\n x = parseFloat(current[1]);\n y = parseFloat(current[2]);\n z = parseFloat(current[3]);\n addAtom(A, x, y, z, 0);\n InfoWin(\" \"+current[0]+\"(\"+A+\") \"+x+\", \"+y+\", \"+z+\"\\n\");\n }\n\n // Create bonds\n for (i=1; i < numatoms; i++) {\n for (j=i+1; j <= numatoms; j++) {\n bond = 1.2 * (element(molecule[i].atomicnumber,\"radius\") + element(molecule[j].atomicnumber,\"radius\"));\n dx = molecule[i].x - molecule[j].x;\n dy = molecule[i].y - molecule[j].y;\n dz = molecule[i].z - molecule[j].z;\n r = Math.sqrt(dx*dx+dy*dy+dz*dz);\n if (r <= bond)\n addBond(i,j,\"single\");\n }\n }\n\n // Finished with readXYZfile routine\n formula();\n InfoWin(\"Finished reading XYZ input file.\\n\");\n }",
"loadPdbData(data, pdbid, bOpm, bAppend) {\n let ic = this.icn3d,\n me = ic.icn3dui\n ic.loadPDBCls.loadPDB(data, pdbid, bOpm, undefined, undefined, bAppend) // defined in the core library\n\n if (me.cfg.opmid === undefined) ic.ParserUtilsCls.transformToOpmOri(pdbid)\n\n if (ic.biomtMatrices !== undefined && ic.biomtMatrices.length > 1) {\n $('#' + ic.pre + 'assemblyWrapper').show()\n\n ic.asuCnt = ic.biomtMatrices.length\n } else {\n $('#' + ic.pre + 'assemblyWrapper').hide()\n }\n\n if (ic.emd !== undefined) {\n $('#' + ic.pre + 'mapWrapper1').hide()\n $('#' + ic.pre + 'mapWrapper2').hide()\n $('#' + ic.pre + 'mapWrapper3').hide()\n } else {\n $('#' + ic.pre + 'emmapWrapper1').hide()\n $('#' + ic.pre + 'emmapWrapper2').hide()\n $('#' + ic.pre + 'emmapWrapper3').hide()\n }\n\n // calculate secondary structures if not available\n // DSSP only works for structures with all atoms. The Calpha only strucutres didn't work\n //if(!ic.bSecondaryStructure && !bCalphaOnly) {\n\n if (!ic.bSecondaryStructure && Object.keys(ic.proteins).length > 0) {\n ic.deferredSecondary = $.Deferred(function () {\n let bCalphaOnly = me.utilsCls.isCalphaPhosOnly(me.hashUtilsCls.hash2Atoms(ic.proteins, ic.atoms)) //, 'CA');\n ic.dsspCls.applyDssp(bCalphaOnly)\n }) // end of me.deferred = $.Deferred(function() {\n\n return ic.deferredSecondary.promise()\n } else {\n this.loadPdbDataRender()\n }\n }",
"function loadMolecule() {\n\n // Add atomic coordinates to molecule array\n addAtom(6, 0.000, 0.000, 0.000);\n addAtom(1, 0.874, 0.618, 0.000);\n addAtom(1, -0.874, 0.618, 0.000);\n addAtom(1, 0.000, -0.618, 0.874);\n addAtom(1, 0.000, -0.618, -0.874);\n // Add bonds to bond array\n addBond(1, 2, \"single\");\n addBond(1, 3, \"single\");\n addBond(1, 4, \"single\");\n addBond(1, 5, \"single\");\n }",
"function createBitfieldFile(torrent, paths){\n let bitfieldPath = config.DOWNLOAD_DIR;\n let bitfield, bfFile;\n if(torrent.files){\n bitfieldPath = bitfieldPath + torrent.filename + '/';\n if(!fs.existsSync(bitfieldPath)){\n fs.mkdirSync(bitfieldPath);\n }\n }\n \n bitfieldPath = bitfieldPath + torrent.md5 + '.bfd'\n\n if(fs.existsSync(bitfieldPath)){\n bitfield= Bitfield.fromBuffer(fs.readFileSync(bitfieldPath),torrent.pieceCount);\n }else{\n bitfield= new Bitfield(torrent.pieceCount);\n fs.writeFileSync(bitfieldPath,bitfield.buffer);\n }\n\n bfFile=openOverwrite(bitfieldPath);\n paths.push(bitfieldPath);\n\n return [bitfield, bfFile];\n}",
"function read_dab_entry(f)\n{\n // These sbl.dab magic numbers come from sbldefs.h (now deprecated)\n var i;\n var total;\n var obj = { name: '', entry:{}, sysop:[], service:[], terminal:{}, network:[], description:[], total:{} };\n\n obj.name = truncsp(f.read(26));\n if(f.eof)\n return null;\n obj.entry.created = { on:null, by:truncsp(f.read(26)) };\n obj.software = truncsp(f.read(16));\n total = f.readBin(1);\n for(i=0;i<sbl_defs.MAX_SYSOPS;i++)\n obj.sysop[i] = { name: truncsp(f.read(26)) };\n obj.sysop.length = total;\n total_numbers = f.readBin(1);\n total = f.readBin(1);\n for(i=0;i<sbl_defs.MAX_NETS;i++) {\n obj.network[i] = {};\n obj.network[i].name = truncsp(f.read(16));\n }\n for(i=0;i<sbl_defs.MAX_NETS;i++)\n obj.network[i].address = truncsp(f.read(26));\n obj.network.length = total;\n total = f.readBin(1);\n obj.terminal.types = [];\n for(i=0;i<sbl_defs.MAX_TERMS;i++)\n obj.terminal.types[i] = truncsp(f.read(16));\n obj.terminal.types.length = total;\n for(i=0;i<sbl_defs.DESC_LINES;i++)\n obj.description.push(truncsp(f.read(51)));\n for(i=0;i<sbl_defs.DESC_LINES;i++)\n if(obj.description[i].length == 0)\n break;\n\tobj.description.length=i;\t// terminate description at first blank line\n obj.terminal.nodes = f.readBin(2);\n obj.total.users = f.readBin(2);\n obj.total.subs = f.readBin(2);\n obj.total.dirs = f.readBin(2);\n obj.total.doors = f.readBin(2);\n obj.entry.created.on = new Date(f.readBin(4)*1000).toISOString();\n var updated = f.readBin(4);\n if(updated)\n obj.entry.updated = { on: new Date(updated*1000).toISOString() };\n var first_online = f.readBin(4);\n if(first_online)\n obj.first_online = new Date(first_online*1000).toISOString();\n obj.total.storage = f.readBin(4)*1024*1024;\n obj.total.msgs = f.readBin(4);\n obj.total.files = f.readBin(4);\n obj.imported = Boolean(f.readBin(4));\n for(i=0;i<sbl_defs.MAX_NUMBERS;i++) {\n var service = { address: truncsp(f.read(13)), description: truncsp(f.read(16)), protocol: 'modem' };\n var location = truncsp(f.read(31));\n var min_rate = f.readBin(2)\n var port = f.readBin(2);\n if(min_rate==0xffff) {\n\t\t\tservice.address = service.address + service.description;\n\t\t\tservice.description = undefined;\n\t\t\tservice.protocol = 'telnet';\n\t\t\tvar uri=service.address.match(/^(\\S+)\\:\\/\\/(\\S+)/);\n\t\t\tif(uri) {\n\t\t\t\tservice.protocol = uri[1].toLowerCase();\n\t\t\t\tservice.address = uri[2];\n\t\t\t}\n service.port = port;\n } else {\n\t\t\t// Only the first 12 chars of the modem \"address\" (number) are valid\n\t\t\t//service.address = service.address.substr(0, 12);\n service.min_rate = min_rate;\n service.max_rate = port;\n }\n if(obj.service.indexOf(service) < 0)\n obj.service.push(service);\n if(obj.location==undefined || obj.location.length==0)\n obj.location=location;\n }\n obj.service.length = total_numbers;\n var updated_by = truncsp(f.read(26));\n if(obj.entry.updated)\n obj.entry.updated.by = updated_by;\n var verified_date = f.readBin(4);\n var verified_by = f.read(26);\n if(verified_date)\n obj.entry.verified = { on: new Date(verified_date*1000).toISOString(), by: truncsp(verified_by), count: 1 };\n obj.web_site = truncsp(f.read(61));\n var sysop_email = truncsp(f.read(61));\n if(obj.sysop.length)\n obj.sysop[0].email = sysop_email;\n f.readBin(4); // 'exported' not used, always zero\n obj.entry.autoverify = { successes: f.readBin(4), attempts: f.readBin(4) };\n f.read(310); // unused padding\n\n return obj;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Agregar diagnostico en el caso que no se aya registrado anterioemente | function agregarDiagnostico(diag, cie, idc, callback){
token=$('#token').val()
$.ajax({
url: '../AgregarDiagnostico',
type: 'POST',
headers: {'X-CSRF-TOKEN': token},
data: {
diag: diag,
cie: cie,
idc: idc,
},
success: function (respuesta){
callback(respuesta)
},
error: function (){
alertify.error('Ocurrio un error')
}
});
} | [
"function Registra(){\n if(attivo == 0)\n {\n attivo = 1; //disalbilito il pulsante se la registrazione è già partita\n registrazione.record(suono); //fa partire la registrazione\n }\n}",
"function Agregar_movimiento(){\r\n\t\tvar msg = \"Desea Agregar un NUEVO REGISTRO?.. \";\r\n\t\tif(confirm(msg)) Form_movimiento('', 'agregar');\r\n\t}",
"function agregarPersona(){\r\n /* Recuperamos el objeto del formulario */\r\n const forma = document.forms['forma'];\r\n /* Recuperamos el campo de nombre del objeto del formulario */\r\n const nombre = forma['nombre'];\r\n /* Recuperamos el campo de apellido del objeto del formulario */\r\n const apellido = forma['apellido'];\r\n /* Hacemos una validacion, solo si ambos inputs no estan vacios se agregara la nueva persona */\r\n if(nombre.value != '' && apellido.value != ''){\r\n /* Creamos una persona mediante el constructor que se declaro y la guardamos en la variable\r\n persona */\r\n const persona = new Persona(nombre.value, apellido.value);\r\n console.log(persona);\r\n /* Añadimos la nueva persona al arreglo mediate el push */\r\n personas.push(persona);\r\n /* Una vez agregada la nueva persona se vuelve a mostrar todo el arreglo mandando a llamar\r\n la funcion de mostrarPersonas*/\r\n mostrarPersonas();\r\n }\r\n else{\r\n console.log('No hay información que agregar');\r\n }\r\n}",
"function agregarRegistro() {\n // Creacion de un objeto base con info del formulario que representa el registro\n let usuario = {\n tipoDocumento: document.getElementById(\"tipo-documento\").value,\n numeroDocumento: document.getElementById(\"numero-documento\").value,\n correo: document.getElementById(\"correo\").value,\n contrasena: document.getElementById(\"contrasena\").value\n }\n\n // Agregar el objeto (registro) al arreglo\n registros.push(usuario);\n\n // Constancia de informacion\n console.log(\"Se esta agregando la siguiente info \\n\")\n console.log(`Tipo: ${usuario.tipoDocumento}\n Numero: ${usuario.numeroDocumento}\n Correo: ${usuario.correo}\n Contraseña: ${usuario.contrasena}`)\n}",
"mostrarFormularioDespidoPersonal() {\n \n crearFormulario([\"Nombre\"], \"despidoPersonal\", () => this.despidoPersonal(this.hospital));\n\n }",
"function agregarPersona() {\n //conectamos el html form con el objeto forms\n const forma = document.forms[\"forma\"];\n\n //del mismo obtenemos el atributo del nombre\n const nombre = forma[\"nombre\"];\n\n //y tambien del apellido\n const apellido = forma[\"apellido\"];\n\n //validamos cadenas vacias\n if (nombre.value != \"\" && nombre.value != \"\") {\n //creamos un objeto de la clase persona y le pasamos los atributos a la clase persona\n const persona = new Persona(nombre.value, apellido.value);\n\n console.log(persona);\n\n //agregamos la constante persona en el arreglo\n personas.push(persona);\n\n //llamamos a llamar a la funcion de mostrarPersonas\n mostrarPersonas();\n } else {\n alert(\"No hay informacion\");\n }\n}",
"function formularioDeRegistroUsuarioAnfitrion() {\n\n let tipoUsuario = \"anfitrion\" // El anfitrion lo registra el Administrador\n let nombre = document.querySelector(\"#txtNombreAnfi\").value;\n let apellido = document.querySelector(\"#txtApellidoAnfi\").value;\n let correo = document.querySelector(\"#txtCorreoAnfi\").value;\n let celular = document.querySelector(\"#txtCelularAnfi\").value;\n let contrasena = document.querySelector(\"#txtContrasenaAnfi\").value;\n let contrasena2 = document.querySelector(\"#txtContrasena2Anfi\").value;\n\n logicaNegocioAgregarPersona(esPrecarga = false, tipoUsuario, nombre, apellido, correo, celular, contrasena, contrasena2);\n}",
"function noExisteUsuario(){\n\tdojo.byId('existeUsuario').innerHTML = \"No existe usuario con el n\\u00FAmero y tipo de documento ingresados\";\n\t\n\tmostrarCargaDeUsuario();\n\tadmin_pacNuevo.validarFormulario();\n}",
"function ajouterEnfant() {\n\t\t\n\t\tStrutsLayout.addDatagridLine(datagridName);\n\t\t\n\t\t// parametre la ligne :\n\t\tEnfants_setRequired(Enfants_getCountLines()-1); // Mets la ligne ajoute en isRequired\n\t\t\n\t\tsetDtgEnfant_Visibility()\n\t\t\n\t}",
"mostrarFormularioIngresoPaciente() {\n let datosPersonal = this.hospital.nombresPersonal;\n let clase = \"ingresoPaciente\";\n let funcion = () => { this.ingresarDatos(Paciente.name, clase) };\n crearFormulario([\"nombre\", \"apellidos\", \"edad\", \"enfermedad\"], clase, funcion);\n let botonAltaForm = document.getElementById(\"confirmacion\");\n addSelect(botonAltaForm, datosPersonal, clase);\n }",
"function addErrorLexico(tipo,fila,columna,descripcion){\n listaErroresLexicos.push({Tipo:tipo,Fila:fila,Columna:columna,Descripcion:descripcion});\n }",
"function RegistrarDatos(){\n //validacion de datos\n \n //capturando valores\n var nom=txtNom.value;\n var ape=txtApe.value;\n var cor=txtCor.value;\n //llamamos al procedimiento registrar\n Registrar(nom,ape,cor);\n //llamamos al procedimiento para mostrar\n MostrarRegistro();\n}",
"addRespuesta(pregunta){\n pregunta.get('respuestas').createRecord()\n }",
"function creaMessaggioErrore() {\n\n //Creo un messaggio di errore con un titolo e un paragrafo\n $(\"#cliente #page #content\").append(\"<h3>Errore!</h3>\");\n $(\"#cliente #page #content h3\").attr(\"id\", \"titleError\");\n $(\"#cliente #page #content\").append(\"<p>Nessun oggetto trovato, inserisci dei nuovi parametri di ricerca!</p>\");\n $(\"#cliente #page #content p\").attr(\"id\", \"paragraphError\");\n }",
"function creaFormularioFirma(nombre,div){\n let form = document.createElement(\"form\");\n form.setAttribute('id',nombre);\n form.setAttribute('action',\"\");\n // Creo el label y la entrada de texto para investigador\n let texto=\"Introduzca nombre del investigador:\";\n creaEntradaFormulario(\"Nombre\",form,texto);\n // Creo el label y la entrada de texto para numero de investigador\n texto=\"Introduzca numero del investigador:\";\n creaEntradaFormulario(\"Numero\",form,texto);\n // Creo el label y la entrada de texto para la firma del virus\n texto=\"Introduzca Id de la firma del virus:\";\n creaEntradaFormulario(\"idFirma\",form,texto);\n // Creo el label y la entrada de texto para la firma del virus\n texto=\"Introduzca la firma del virus:\";\n creaEntradaFormulario(\"firma\",form,texto);\n // Creo el botón de submit\n let enviar = document.createElement(\"input\");\n enviar.setAttribute('type',\"submit\");\n enviar.setAttribute('value',\"Submit\");\n enviar.setAttribute('id',\"enviar\");\n enviar.addEventListener(\"click\",hacerSubmitFirma,false);\n form.appendChild(enviar);\n document.getElementById(div).appendChild(form); \n // Cuando hago foco añado el texto\n document.getElementById(\"entradafirma\").addEventListener(\"focus\",addTexto,false);\n}",
"mostrarFormularioAltaPersonal() {\n let clase = \"altaPersonal\";\n let funcion = () => { this.ingresarDatos(Personal.name, clase) };\n crearFormulario([\"Nombre\", \"Apellidos\", \"Edad\"], clase, funcion);\n let botonAltaForm = document.getElementById(\"confirmacion\");\n\n addRadioGroup(botonAltaForm, Personal.tiposEspecialidad(), clase);\n }",
"function adicionarServicio(apl){\n\t\t\tif (regServPresta.getForm().isValid()){\n\t\t\t\tregServPresta.getForm().submit({\n\t\t\t\t url:'insertarservicio',\t\t\t\t\t\t\t\t\t\n\t\t\t\t\twaitMsg:perfil.etiquetas.lbMsgEsperaRegServ,\n\t\t\t\t\tparams:{idsistema:arbolServ.getSelectionModel().getSelectedNode().attributes.id},\t\t\t\t\n\t\t\t\t\tfailure: function(form, action){\n\t\t\t\t\t\t\tif(action.result.codMsg != 3){\n\t\t\t\t\t\t\t\tmostrarMensaje(action.result.codMsg, action.result.mensaje); \n\t\t\t\t\t\t\t\tregServPresta.getForm().reset(); \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(!apl)\t\t\t\t\t\n\t\t\t\t\t\t\t\t\twinIns.hide();\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstGpServicio.reload();\n\t\t\t\t\t\t\t\tsm.clearSelections();\n\t\t\t\t\t\t\t\tbtnModificar.disable();\n\t\t\t\t\t\t\t\tbtnEliminar.disable();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tif(action.result.codMsg == 3) mostrarMensaje(action.result.codMsg, action.result.mensaje);\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n else\n mostrarMensaje(3,perfil.etiquetas.lbMsgErrorEnCamops); \n\t}",
"function RegistrarDatos (){ \r\n//validacion de datos \r\n// capturando valores \r\nvar nom=txtNom.value; \r\nvar ape=txtApe.value; \r\nvar cor=txtCor.value; \r\n//llamamos al procedimiento registrar \r\nRegistrar(nom, ape,cor); \r\n//llamamos al procedimiento para mostrar \r\nMostrarRegistro(); \r\n}",
"function pacienteExistente(){\n\tdocument.getElementById('existeUsuario').innerHTML = \"\";\n\tdocument.getElementById('existeUsuario').appendChild(document.createTextNode('Ya existe el paciente .'));\n\tdocument.getElementById('existeUsuario').appendChild(document.createElement(\"BR\"));\n\t\n\tvar labelPaciente = elem_paciente.getLabel();\n\tdocument.getElementById('existeUsuario').appendChild(document.createTextNode(labelPaciente));\n\t\n\tvar boton = crearBoton(elem_paciente, labelPaciente);\n\tdocument.getElementById('existeUsuario').appendChild(boton);\n\t\n\tdocument.getElementById('datosUsario').style.display = 'none';\n\tdojo.byId('accionesPacienteNuevo').style.display = 'none';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
inputType : val description pressed : mouse button pressed (0 = left, 1 = right, 2 = middle, ..) doublepressed : mouse button pressed wheeled : scroll wheel used (1 = scroll up, 1 = scroll down) note: using the scroll wheel will trigger both pressed and wheeled inputTypes. For me scroll wheel is key 5 and 6 Click Behaviors 0 = no behavior (clicked anywhere in viewport except for the HUD) 1 = clicked in viewport (this could be an move/attack command) 2 = a click (attack key was pressed before the moused click) 3 = cast ability or item (if an ability hotkey was pressed before the click) returning true will prevent the default functionality of the mouse input | function mouseInputFilter(inputType, val)
{
var pos = GameUI.GetScreenWorldPosition();
var behavior = GameUI.GetClickBehaviors();
//add custom targeting here e.g. vector targeting
//scroll functionality
if( inputType === "wheeled" ||
(inputType === "pressed" && (val == 5 || val == 6))){
if(ENABLE_SCROLL_ROTATE == true && inputType === "wheeled"){
var yawChange = val*5;
currentCameraSettings.yaw += yawChange;
GameUI.SetCameraYaw(currentCameraSettings.yaw);
}
return DISBALE_CAMERA_ZOOM;
}
} | [
"function Input(e)\n {\n\n\t\t\t if(!DataIntf.Enabled) \n\t\t\t { \n\t\t\t Mouse.getXYPosition(e);\n\t\t\t ccl.Mouse.getXYPosition(e);\n\t\t\t //ROOMS\n \t\t\t switch(Room.Index)\n\t\t\t {\n\t\t\t case 0://menu principal\n\t\t\t\t Intf.Input();\n\t\t\t\t break;\n\t\t\t\t \n\t\t\t case 1:\n\t\t\t \t Intf2.Input();\n\t\t\t\t break;\n\t\t\t case 2://el juego seleccionado\n\t\t\t Games.Input();\n\t\t\t\t break;\n\t\t\t\t \n\t\t\t }\n \t\t\t Mouse.Click=false;\n }\n }",
"handleInput(e) {\n\t\tif (this.canScroll) {\n\n\t\t\tlet wheelData;\n\n\t\t\tif(Veams.detections.mobile && Veams.detections.touch) {\n\t\t\t\t// stop if just tapped or touchend is on exact same position\n\t\t\t\tif(this.touchStartY === this.touchEndY || this.touchEndY === 0) return;\n\n\t\t\t\t// normalize touch event data\n\t\t\t\twheelData = this.touchStartY < this.touchEndY ? 1 : -1;\n\n\t\t\t\t// reset\n\t\t\t\tthis.touchEndY = 0;\n\t\t\t} else {\n\t\t\t\t// normalize wheel event data\n\t\t\t\twheelData = e.originalEvent.wheelDelta ? e.originalEvent.wheelDelta : e.originalEvent.detail * -1;\n\t\t\t}\n\n\t\t\tif ((wheelData && wheelData < 0) || e.keyCode === 40) {\n\t\t\t\t//scroll down or down key\n\t\t\t\tthis.activateNextSection();\n\t\t\t} else if ((wheelData && wheelData > 0) || e.keyCode === 38) {\n\t\t\t\t//scroll up ur up key\n\t\t\t\tthis.activatePrevSection();\n\t\t\t}\n\t\t}\n\t}",
"function onClick()\n{\n if (inputs.option == \"direct\" || inputs.option == \"wheelControl\")\n {\n inputs.option = \"none\";\n }\n}",
"function MouseInput() {\n \n this.buttons = []; // Array of buttons. Set to true if pressed.\n this.buttonBinds = []; // Array of buttonBinds objects.\n\n this.moveBind = null;\n this.pointerBind = null;\n this.wheelBind = null;\n \n this.pointerLock = false;\n this.pointerLockElement = null;\n\n this.disableContextMenu = false;\n \n this.sensitivity = 1;\n \n}",
"function getInput(e) {\n // If the key code of the event is in our key codes array.\n if (KEY_CODES[e.keyCode]) {\n // Prevent the default so that the page does not scroll or lose focus.\n e.preventDefault();\n // Convert from the key code to the control and set the state based on whether the type of the even was keydown.\n if (e.type === \"keydown\") {\n gameManager.CONTROLS_STATE[KEY_CODES[e.keyCode]] = true;\n }\n // Else if the key even was a keyup\n else if (e.type === \"keyup\") {\n // Reset both the control state and held states to false\n gameManager.CONTROLS_STATE[KEY_CODES[e.keyCode]] = false;\n gameManager.CONTROLS_HELD[KEY_CODES[e.keyCode]] = false;\n }\n }\n}",
"isMouseEvent() {\n return this.type >= Message.Type.MOUSE_DOWN && this.type <= Message.Type.MOUSE_CLICK;\n }",
"isMouseEvent() {\n return (\n this.type >= Message.Type.MOUSE_DOWN &&\n this.type <= Message.Type.MOUSE_CLICK\n );\n }",
"scrollInteraction(e) {\n if(!this.blockInput) {\n this.blockInput = true;\n this.currentAnimationStep = 0;\n if(e.deltaY > 0 && this.valueHandler(this.gotoIndex - 1) != null) {\n this.gotoIndex--;\n this.updateView();\n } else if(e.deltaY < 0 && this.valueHandler(this.gotoIndex + 1) != null){\n this.gotoIndex++;\n this.updateView();\n } else {\n this.blockInput = false;\n }\n }\n if(!\"ne\" in e) {\n e.preventDefault();\n }\n }",
"function handleInput() {\n // Zoom\n if (Gamepad.buttons.leftShoulder) {\n startZoom(-0.04);\n } else if (Gamepad.buttons.rightShoulder) {\n startZoom(+0.04);\n } else if (!Gamepad.buttons.leftShoulder || !Gamepad.buttons.rightShoulder) {\n stopZoom();\n }\n\n // Move horizontally\n if (Gamepad.axes.leftStickX) {\n deltaX = -Gamepad.axes.leftStickX * 10;\n startPan();\n } else {\n deltaX = 0;\n }\n\n // Move vertically\n if (Gamepad.axes.leftStickY) {\n deltaY = -Gamepad.axes.leftStickY * 10;\n startPan();\n } else {\n deltaY = 0;\n }\n\n // Click link -> Y\n if (Gamepad.buttons.primary) {\n clickElement(currentElement);\n }\n\n if (deltaX === 0 && deltaY === 0) {\n stopPan();\n }\n}",
"function keyTyped() {\n //Hotkey values: Analog devices increase or decrease the separation, alignment, and cohesion values here\n if (c < 5000 && key === 'q') {\n cohesion = cohesion + 20;\n }\n if (c > -1 && key === \"a\") {\n cohesion = cohesion - 20;\n }\n if (a < 360 && key === \"e\") {\n alignment = alignment + 1;\n }\n if (a > -1 && key === \"d\") {\n alignment = alignment - 1;\n }\n}",
"isInput() {\r\n return this.type === 'INPUT';\r\n }",
"function EnableMouseBehaviour(h) {\n var lastX = 0;\n var lastY = 0;\n\n h.on(\"drag\", function (e) {\n var g = e.gesture;\n g.preventDefault()\n\n var deltaX = Math.round(g.deltaX);\n var deltaY = Math.round(g.deltaY);\n console.log(e.type + \" \" + deltaX + \",\" + deltaY);\n if (deltaX != lastX || deltaY != lastY) {\n console.log(\"Mouse move \" + (deltaX-lastX) + \",\" + (deltaY-lastY));\n MouseMove((deltaX - lastX), (deltaY - lastY))\n lastX = deltaX;\n lastY = deltaY;\n }\n })\n\n h.on(\"release\", function (e) {\n var g = e.gesture;\n g.preventDefault()\n\n console.log(e.type);\n lastX = 0;\n lastY = 0;\n })\n\n h.on(\"tap\", function (e) {\n var g = e.gesture;\n g.preventDefault()\n\n console.log(e.type);\n console.log(\"Mouse click\");\n MouseClick(false);\n })\n}",
"keyInput(e) { /* 轉移至 this._keyInputHander 作為替代方案 */ }",
"function input_init(args){\n args = args || {};\n args['keybinds'] = args['keybinds'] || false;\n args['mousebinds'] = args['mousebinds'] || false;\n\n if(args['keybinds'] !== false){\n input_keybinds_update({\n 'clear': true,\n 'keybinds': args['keybinds'],\n });\n\n window.onkeydown = input_handle_keydown;\n window.onkeyup = input_handle_keyup;\n }\n\n input_mouse = {\n 'down': false,\n 'down-x': 0,\n 'down-y': 0,\n 'movement-x': 0,\n 'movement-y': 0,\n 'pointerlock-id': 'canvas',\n 'pointerlock-state': false,\n 'todo': {},\n 'x': 0,\n 'y': 0,\n };\n if(args['mousebinds'] !== false){\n input_mousebinds_update({\n 'clear': true,\n 'mousebinds': args['mousebinds'],\n });\n\n document.onpointerlockchange = input_handle_onpointerlockchange;\n document.onmozpointerlockchange = input_handle_onpointerlockchange;\n window.onmousedown = input_handle_mousedown;\n window.onmousemove = input_handle_mousemove;\n window.onmouseup = input_handle_mouseup;\n window.ontouchend = input_handle_mouseup;\n window.ontouchmove = input_handle_mousemove;\n window.ontouchstart = input_handle_mousedown;\n\n if('onmousewheel' in window){\n window.onmousewheel = input_handle_mousewheel;\n\n }else{\n document.addEventListener(\n 'DOMMouseScroll',\n input_handle_mousewheel,\n false\n );\n }\n }\n\n window.ongamepadconnected = input_handle_gamepadconnected;\n window.ongamepaddisconnected = input_handle_gamepaddisconnected;\n}",
"_inputWheelHandler(event) {\n const that = this,\n activeElement = that.shadowRoot ? (that.shadowRoot.activeElement || document.activeElement) : document.activeElement;\n\n if (that.$.input === activeElement && that.enableMouseWheelAction && that._isIncrementOrDecrementAllowed()) {\n event.stopPropagation();\n event.preventDefault();\n if (event.wheelDelta > 0) {\n that._incrementOrDecrement('add');\n }\n else {\n that._incrementOrDecrement('subtract');\n }\n }\n }",
"isConnectedInput() { return (this.type == 'input'); }",
"getInput() {\n\t\tif (data1.left) {\n\t\t\tthis.xDirection = -1;\n\t\t}\n\t\telse if (data1.right) {\n\t\t\tthis.xDirection = 1;\n\t\t}\n\t\telse {\n\t\t\tthis.xDirection = 0;\n\t\t}\n\n\t\tif (data1.up) {\n\t\t\tthis.yDirection = -1;\n\t\t}\n\t\telse if (data1.down) {\n\t\t\tthis.yDirection = 1;\n\t\t}\n\t\telse {\n\t\t\tthis.yDirection = 0;\n\t\t}\n\t\tif (data1.jump) {\n\t\t\tthis.jjump = 1;\n\t\t}\n\t\telse { this.jjump = 0; }\n\n\t\tif (data1.hit) {\n\t\t\tthis.powerHit = 1;\n\t\t}\n\t\telse {\n\t\t\tthis.powerHit = 0;\n\t\t}\n\t}",
"function Input()\n{\n //*************\n // Data members\n //*************\n var canvas = document.getElementById(\"canvas\");\n \n var m_Keys = {};\n \n var m_CurrentMousePos = [0,0];\n \n //****************\n // Input interface\n //****************\n \n \n this.start = function()\n {\n initKeyHandlers();\n initMouseHandler();\n \n };\n \n this.update = function()\n {\n mouseUpdate();\n \n };\n \n this.getKeys = function()\n {\n return m_Keys;\n \n };\n \n this.getMouseDelta = function()\n {\n return m_CurrentMousePos;\n \n };\n \n //****************\n // Private methods\n //****************\n mouselock = function()\n {\n canvas.requestPointerLock();\n \n if (\n document.pointerLockElement === canvas || //Cross browser call (future proofing)\n document.mozPointerLockElement === canvas || //ff\n document.webkitPointerLockElement === canvas //chrome\n ) {}\n //document.removeEventListener(\"mousemove\", mouseMove, false);\n else \n document.addEventListener(\"mousemove\", mouseMove, false);\n\n \n };\n \n initKeyHandlers = function()\n {\n document.onkeydown = keyDown;\n document.onkeyup = keyUp;\n \n };\n \n initMouseHandler = function()\n {\n \n canvas.onclick = mouselock;\n \n var check_pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;\n\n if(check_pointerLock)\n { canvas.requestPointerLock = \n canvas.requestPointerLock ||\n canvas.mozRequestPointerLock ||\n canvas.webkitRequestPointerLock;\n canvas.requestPointerLock(); \n \n }\n \n };\n \n keyDown = function (event)\n {\n m_Keys[event.keyCode] = true;\n \n };\n\n keyUp = function (event)\n {\n m_Keys[event.keyCode] = false;\n \n };\n \n mouseUpdate = function()\n {\n m_CurrentMousePos = [0,0];\n \n if (m_Keys[27])\n document.removeEventListener(\"mousemove\", mouseMove, false);\n \n };\n \n mouseMove = function (e)\n {\n //Retrieve movement across browsers\n var movementX = e.movementX ||\n e.mozMovementX ||\n e.webkitMovementX ||\n 0,\n movementY = e.movementY ||\n e.mozMovementY ||\n e.webkitMovementY ||\n 0;\n \n m_CurrentMousePos = [movementX ,movementY];\n \n };\n \n}",
"function ui_keyStateDown(key)\n{\n for (var j = 0; j < ui_piano_key_section.component.component_list.length; j++)\n {\n var component = ui_piano_key_section.component.component_list[j];\n\n if (component instanceof UI_Piano_Key)\n {\n if (key == component.key)\n {\n component.button_component.is_pressed = true;\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Service implementation If not specified, maxItems assumed unlimited | function ShoppingListService(maxItems) {
var service = this;
// List of shopping items
var items = [];
// Servie method for adding item
service.addItem = function (itemName, quantity) {
console.log('inside additem');
if ((maxItems === undefined) || (maxItems !== undefined) && (items.length < maxItems)) {
var item = {
name: itemName,
quantity: quantity
};
items.push(item);
}else{
throw new Error("Max Items (" + maxItems +") reached.");
}
};
// Servie method to remove items from list
service.removeItem = function (itemIndex) {
console.log('inside removeitem: ', itemIndex);
items.splice(itemIndex, 1);
}
// Servie method to get items
service.getItems = function () {
console.log('inside getitems: ', items);
return items;
};
} | [
"setMaxItems(value) {\n if (value === 0) value = null; //reset to unlimited items.\n\n this.settings.maxItems = value;\n this.refreshState();\n }",
"setMaxItems(value) {\n\t if (value === 0) value = null; //reset to unlimited items.\n\n\t this.settings.maxItems = value;\n\t this.refreshState();\n\t }",
"maxItems(maxItems) {\n super.set(\"maxItems\", maxItems);\n return this;\n }",
"function getMaxItems() {\n return internal.maxItems;\n }",
"function TodoListService(maxTodos) {\n var service = this;\n\n // List of todos\n var todos = [];\n\n // Pre-populate a todo list\n todos.push({\n title: \"Init\",\n plannedEffort: \"15 min\",\n details: \"Call Marcus for a team meeting appointment\",\n dueDate: 20170519\n });\n todos.push({\n title: \"meeting X\",\n plannedEffort: \"2 hours\",\n details: \"talk about the strategy\",\n dueDate: 20170530\n });\n todos.push({\n title: \"first version\",\n plannedEffort: \"5 days\",\n details: \"show simple todo list\",\n dueDate: 20170630\n });\n\n service.addItem = function (pTitle, pPlannedEff, pDetails, pDueDate) {\n if ((maxTodos === undefined) ||\n (maxTodos !== undefined) && (todos.length < maxTodos)) {\n var newTodo = {\n title: pTitle,\n plannedEffort: pPlannedEff,\n details: pDetails,\n dueDate: pDueDate\n };\n todos.push(newTodo);\n }\n else {\n throw new Error(\"Max todos (\" + maxTodos + \") reached.\");\n }\n };\n\n // service.addItem = function (itemName, itemQuantity) {\n // if ((maxTodos === undefined) ||\n // (maxTodos !== undefined) && (todos.length < maxTodos)) {\n // var item = {\n // name: itemName,\n // quantity: itemQuantity\n // };\n // todos.push(item);\n // }\n // else {\n // throw new Error(\"Max todos (\" + maxTodos + \") reached.\");\n // }\n // };\n\n service.removeItem = function (itemIndex) {\n todos.splice(itemIndex, 1);\n };\n\n service.getTodos = function () {\n return todos;\n };\n}",
"function ServiceLimit() {\n _classCallCheck$m(this, ServiceLimit);\n }",
"get max() {\n return this.items.length;\n }",
"loadMoreItemsFromApi () {\n const paginationOptions = this.getNextPagePaginationOptions(this.state.paginationState)\n this.loadItemsFromApi(paginationOptions, false)\n .then((httpResponse) => {\n this.updateStateFromLoadItemsApiSuccessResponse(\n httpResponse, paginationOptions, false)\n })\n .catch((error) => {\n if (!error.isCancelled) {\n this.handleGetListItemsFromApiRequestError(error)\n }\n })\n }",
"function maxAllowed() {\n if (!ctrl.servicePack) return\n var selectedServices = ctrl.servicePack.userServices || []\n if (selectedServices.length === 0) return unlimited\n if (_.every(selectedServices, { quantity: -1 })) return unlimited\n\n const min = _.minBy(selectedServices, function(service) {\n if (service.quantity === -1) return unlimited\n return service.quantity - service.allocated\n })\n return min.quantity - min.allocated\n }",
"loadMoreItems(vec) {\n const { typeFilter, user, useUserAsContext } = this.props;\n const offset = 0;\n let queryUser = null;\n if (useUserAsContext && __WEBPACK_IMPORTED_MODULE_11_reducers_user__[\"a\" /* isUserEmbedded */](user)) {\n queryUser = user;\n }\n this.throttleApi.fetch(() => {\n return __WEBPACK_IMPORTED_MODULE_5_api_query__[\"f\" /* queryGraphItemsAround */](vec.toArray(), typeFilter, ITEMS_PER_REQUEST, offset, queryUser);\n }, this.renderItems);\n }",
"function ShoppingListFactory() {\n var factory = function (maxItems) {\n return new ShoppingListService(maxItems);\n };\n return factory;\n }",
"function setMaxItems(slider){\n\tslider.vars.maxItems = getMaxItems();\n}",
"items() {\n if(this.cache){\n return Promise.resolve(this.cache);\n }\n return this.formQueryAndSend('get').then(response => {\n let instances = [];\n let data = response.data.results;\n let prefetch_fields = this._getPrefetchFields();\n\n for(let item in data){\n instances.push(\n this.model.getInstance(data[item], this.clone())\n );\n }\n\n // if prefetch fields exist, loads prefetch data.\n if(prefetch_fields && prefetch_fields.length > 0) {\n return this._loadPrefetchData(prefetch_fields, instances).then(() => {\n this.api_count = response.data.count;\n this.cache = instances;\n return instances;\n });\n }\n\n // otherwise returns instances.\n this.api_count = response.data.count;\n this.cache = instances;\n return instances;\n }).catch(error => {\n debugger;\n throw error;\n })\n }",
"static get PAGE_ITEMS() {\n return 10;\n }",
"getSuccessfulItems(id, limit, pageToken) {\n let url_ = this.baseUrl + \"/v1/BusinessProcesses/{id}/items/successful?\";\n if (id === undefined || id === null)\n throw new Error(\"The parameter 'id' must be defined.\");\n url_ = url_.replace(\"{id}\", encodeURIComponent(\"\" + id));\n if (limit === undefined || limit === null)\n throw new Error(\"The parameter 'limit' must be defined and cannot be null.\");\n else\n url_ += \"limit=\" + encodeURIComponent(\"\" + limit) + \"&\";\n if (pageToken !== undefined && pageToken !== null)\n url_ += \"pageToken=\" + encodeURIComponent(\"\" + pageToken) + \"&\";\n url_ = url_.replace(/[?&]$/, \"\");\n let options_ = {\n method: \"GET\",\n headers: {\n \"Accept\": \"application/json\"\n }\n };\n return this.transformOptions(options_).then(transformedOptions_ => {\n return this.http.fetch(url_, transformedOptions_);\n }).then((_response) => {\n return this.processGetSuccessfulItems(_response);\n });\n }",
"static get PAGE_ITEMS() {\n return 50;\n }",
"constructor(maxSize = 10) {\n this.storage = {};\n this.quantity = 0;\n this.maxSize = maxSize;\n }",
"chunk(max) {\n let chunked = new Collection([]);\n let chunk = new Collection([], this.primary_key);\n for(let i=0; i < this.count(); ++i) {\n chunk.push(this.items[i]);\n if(chunk.count() == max || i == (this.count()-1)) {\n chunked.push(chunk);\n chunk = new Collection([], this.primary_key);\n }\n }\n return chunked;\n }",
"async function listWithLimits() {\n const client = makeStorageClient()\n\n // get today's date and subtract 1 day\n const d = new Date()\n d.setDate(d.getDate() - 1)\n\n // the list method's before parameter accepts an ISO formatted string\n const before = d.toISOString()\n\n // limit to ten results\n const maxResults = 10\n\n for await (const upload of client.list({ before, maxResults })) {\n console.log(upload)\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calcIslamic Update from Islamic calendar | function calcIslamic()
{
setJulian(islamic_to_jd((new Number(document.islamic.year.value)),
document.islamic.month.selectedIndex + 1,
(new Number(document.islamic.day.value))));
} | [
"function calcIslamic()\n{\n setJulian(islamic_to_jd((new Number(document.islamic.year.value)),\n document.islamic.month.selectedIndex + 1,\n (new Number(document.islamic.day.value))));\n}",
"function calcGregorian()\n{\n updateFromGregorian();\n}",
"function updateFromGregorian()\n {\n var j, year, mon, mday, hour, min, sec,\n\t weekday, julcal, hebcal, islcal, hmindex, utime, isoweek,\n\t may_countcal, mayhaabcal, maytzolkincal, bahcal, frrcal,\n\t indcal, isoday, xgregcal;\n\n year = new Number(document.gregorian.year.value);\n mon = document.gregorian.month.selectedIndex;\n mday = new Number(document.gregorian.day.value);\n hour = min = sec = 0;\n hour = new Number(document.gregorian.hour.value);\n min = new Number(document.gregorian.min.value);\n sec = new Number(document.gregorian.sec.value);\n\n // Update Julian day\n\n j = gregorian_to_jd(year, mon + 1, mday) +\n\t (Math.floor(sec + 60 * (min + 60 * hour) + 0.5) / 86400.0);\n\n document.julianday.day.value = j;\n document.modifiedjulianday.day.value = j - JMJD;\n\n // Update day of week in Gregorian box\n\n weekday = jwday(j);\n document.gregorian.wday.value = Weekdays[weekday];\n\n // Update leap year status in Gregorian box\n\n document.gregorian.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0];\n\n // Update Julian Calendar\n\n julcal = jd_to_julian(j);\n document.juliancalendar.year.value = julcal[0];\n document.juliancalendar.month.selectedIndex = julcal[1] - 1;\n document.juliancalendar.day.value = julcal[2];\n document.juliancalendar.leap.value = NormLeap[leap_julian(julcal[0]) ? 1 : 0];\n weekday = jwday(j);\n document.juliancalendar.wday.value = Weekdays[weekday];\n\n // Update Hebrew Calendar\n\n hebcal = jd_to_hebrew(j);\n if (hebrew_leap(hebcal[0])) {\n\t document.hebrew.month.options.length = 13;\n\t document.hebrew.month.options[11] = new Option(\"Adar I\");\n\t document.hebrew.month.options[12] = new Option(\"Veadar\");\n } else {\n\t document.hebrew.month.options.length = 12;\n\t document.hebrew.month.options[11] = new Option(\"Adar\");\n }\n document.hebrew.year.value = hebcal[0];\n document.hebrew.month.selectedIndex = hebcal[1] - 1;\n document.hebrew.day.value = hebcal[2];\n hmindex = hebcal[1];\n if (hmindex == 12 && !hebrew_leap(hebcal[0])) {\n\t hmindex = 14;\n }\n document.hebrew.hebmonth.src = \"figures/hebrew_month_\" +\n\t hmindex + \".gif\";\n switch (hebrew_year_days(hebcal[0])) {\n\t case 353:\n\t document.hebrew.leap.value = \"Common deficient (353 days)\";\n\t break;\n\n\t case 354:\n\t document.hebrew.leap.value = \"Common regular (354 days)\";\n\t break;\n\n\t case 355:\n\t document.hebrew.leap.value = \"Common complete (355 days)\";\n\t break;\n\n\t case 383:\n\t document.hebrew.leap.value = \"Embolismic deficient (383 days)\";\n\t break;\n\n\t case 384:\n\t document.hebrew.leap.value = \"Embolismic regular (384 days)\";\n\t break;\n\n\t case 385:\n\t document.hebrew.leap.value = \"Embolismic complete (385 days)\";\n\t break;\n\n\t default:\n\t document.hebrew.leap.value = \"Invalid year length: \" +\n\t\t hebrew_year_days(hebcal[0]) + \" days.\";\n\t break;\n }\n\n // Update Islamic Calendar\n\n islcal = jd_to_islamic(j);\n document.islamic.year.value = islcal[0];\n document.islamic.month.selectedIndex = islcal[1] - 1;\n document.islamic.day.value = islcal[2];\n document.islamic.wday.value = \"yawm \" + ISLAMIC_WEEKDAYS[weekday];\n document.islamic.leap.value = NormLeap[leap_islamic(islcal[0]) ? 1 : 0];\n\n // Update Persian Calendar\n\n perscal = jd_to_persian(j);\n document.persian.year.value = perscal[0];\n document.persian.month.selectedIndex = perscal[1] - 1;\n document.persian.day.value = perscal[2];\n document.persian.wday.value = PERSIAN_WEEKDAYS[weekday];\n document.persian.leap.value = NormLeap[leap_persian(perscal[0]) ? 1 : 0];\n\n // Update Persian Astronomical Calendar\n\n perscal = jd_to_persiana(j);\n document.persiana.year.value = perscal[0];\n document.persiana.month.selectedIndex = perscal[1] - 1;\n document.persiana.day.value = perscal[2];\n document.persiana.wday.value = PERSIAN_WEEKDAYS[weekday];\n document.persiana.leap.value = NormLeap[leap_persiana(perscal[0]) ? 1 : 0];\n\n // Update Mayan Calendars\n\n may_countcal = jd_to_mayan_count(j);\n document.mayancount.baktun.value = may_countcal[0];\n document.mayancount.katun.value = may_countcal[1];\n document.mayancount.tun.value = may_countcal[2];\n document.mayancount.uinal.value = may_countcal[3];\n document.mayancount.kin.value = may_countcal[4];\n mayhaabcal = jd_to_mayan_haab(j);\n document.mayancount.haab.value = \"\" + mayhaabcal[1] + \" \" + MAYAN_HAAB_MONTHS[mayhaabcal[0] - 1];\n maytzolkincal = jd_to_mayan_tzolkin(j);\n document.mayancount.tzolkin.value = \"\" + maytzolkincal[1] + \" \" + MAYAN_TZOLKIN_MONTHS[maytzolkincal[0] - 1];\n\n // Update Bahai Calendar\n\n bahcal = jd_to_bahai(j);\n document.bahai.kull_i_shay.value = bahcal[0];\n document.bahai.vahid.value = bahcal[1];\n document.bahai.year.selectedIndex = bahcal[2] - 1;\n document.bahai.month.selectedIndex = bahcal[3] - 1;\n document.bahai.day.selectedIndex = bahcal[4] - 1;\n document.bahai.weekday.value = BAHAI_WEEKDAYS[weekday];\n document.bahai.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0]; // Bahai uses same leap rule as Gregorian\n\n // Update Indian Civil Calendar\n\n indcal = jd_to_indian_civil(j);\n document.indiancivilcalendar.year.value = indcal[0];\n document.indiancivilcalendar.month.selectedIndex = indcal[1] - 1;\n document.indiancivilcalendar.day.value = indcal[2];\n document.indiancivilcalendar.weekday.value = INDIAN_CIVIL_WEEKDAYS[weekday];\n document.indiancivilcalendar.leap.value = NormLeap[leap_gregorian(indcal[0] + 78) ? 1 : 0];\n\n // Update French Republican Calendar\n\n frrcal = jd_to_french_revolutionary(j);\n document.french.an.value = frrcal[0];\n document.french.mois.selectedIndex = frrcal[1] - 1;\n document.french.decade.selectedIndex = frrcal[2] - 1;\n document.french.jour.selectedIndex = ((frrcal[1] <= 12) ? frrcal[3] : (frrcal[3] + 11)) - 1;\n\n // Update Gregorian serial number\n\n if (document.gregserial != null) {\n\t document.gregserial.day.value = j - J0000;\n }\n\n // Update Excel 1900 and 1904 day serial numbers\n\n document.excelserial1900.day.value = (j - J1900) + 1 +\n\t /* Microsoft marching morons thought 1900 was a leap year.\n\t\t Adjust dates after 1900-02-28 to compensate for their\n\t\t idiocy. */\n\t ((j > 2415078.5) ? 1 : 0)\n\t ;\n document.excelserial1904.day.value = j - J1904;\n\n // Update Unix time()\n\n utime = (j - J1970) * (60 * 60 * 24 * 1000);\n document.unixtime.time.value = Math.round(utime / 1000);\n\n // Update ISO Week\n\n isoweek = jd_to_iso(j);\n document.isoweek.year.value = isoweek[0];\n document.isoweek.week.value = isoweek[1];\n document.isoweek.day.value = isoweek[2];\n\n // Update ISO Day\n\n isoday = jd_to_iso_day(j);\n document.isoday.year.value = isoday[0];\n document.isoday.day.value = isoday[1];\n }",
"function updateFromGregorian()\n{\n var j, year, mon, mday, hour, min, sec,\n weekday, julcal, hebcal, islcal, hmindex, utime, isoweek,\n may_countcal, mayhaabcal, maytzolkincal, bahcal, frrcal,\n indcal, isoday, xgregcal;\n\n year = new Number(document.gregorian.year.value);\n mon = document.gregorian.month.selectedIndex;\n mday = new Number(document.gregorian.day.value);\n hour = min = sec = 0;\n hour = new Number(document.gregorian.hour.value);\n min = new Number(document.gregorian.min.value);\n sec = new Number(document.gregorian.sec.value);\n\n // Update Julian day\n\n j = gregorian_to_jd(year, mon + 1, mday) +\n (Math.floor(sec + 60 * (min + 60 * hour) + 0.5) / 86400.0);\n\n document.julianday.day.value = j;\n document.modifiedjulianday.day.value = j - JMJD;\n\n // Update day of week in Gregorian box\n\n weekday = jwday(j);\n document.gregorian.wday.value = Weekdays[weekday];\n\n // Update leap year status in Gregorian box\n\n document.gregorian.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0];\n\n // Update Julian Calendar\n\n julcal = jd_to_julian(j);\n document.juliancalendar.year.value = julcal[0];\n document.juliancalendar.month.selectedIndex = julcal[1] - 1;\n document.juliancalendar.day.value = julcal[2];\n document.juliancalendar.leap.value = NormLeap[leap_julian(julcal[0]) ? 1 : 0];\n weekday = jwday(j);\n document.juliancalendar.wday.value = Weekdays[weekday];\n\n // Update Hebrew Calendar\n\n hebcal = jd_to_hebrew(j);\n if (hebrew_leap(hebcal[0])) {\n document.hebrew.month.options.length = 13;\n document.hebrew.month.options[11] = new Option(\"Adar I\");\n document.hebrew.month.options[12] = new Option(\"Veadar\");\n } else {\n document.hebrew.month.options.length = 12;\n document.hebrew.month.options[11] = new Option(\"Adar\");\n }\n document.hebrew.year.value = hebcal[0];\n document.hebrew.month.selectedIndex = hebcal[1] - 1;\n document.hebrew.day.value = hebcal[2];\n hmindex = hebcal[1];\n if (hmindex == 12 && !hebrew_leap(hebcal[0])) {\n hmindex = 14;\n }\n document.hebrew.hebmonth.src = \"/img/hebrew/hebrew_month_\" +\n hmindex + \".gif\";\n switch (hebrew_year_days(hebcal[0])) {\n case 353:\n document.hebrew.leap.value = \"Common deficient (353 days)\";\n break;\n\n case 354:\n document.hebrew.leap.value = \"Common regular (354 days)\";\n break;\n\n case 355:\n document.hebrew.leap.value = \"Common complete (355 days)\";\n break;\n\n case 383:\n document.hebrew.leap.value = \"Embolismic deficient (383 days)\";\n break;\n\n case 384:\n document.hebrew.leap.value = \"Embolismic regular (384 days)\";\n break;\n\n case 385:\n document.hebrew.leap.value = \"Embolismic complete (385 days)\";\n break;\n\n default:\n document.hebrew.leap.value = \"Invalid year length: \" +\n hebrew_year_days(hebcal[0]) + \" days.\";\n break;\n }\n\n // Update Islamic Calendar\n\n islcal = jd_to_islamic(j);\n document.islamic.year.value = islcal[0];\n document.islamic.month.selectedIndex = islcal[1] - 1;\n document.islamic.day.value = islcal[2];\n document.islamic.wday.value = \"yawm \" + ISLAMIC_WEEKDAYS[weekday];\n document.islamic.leap.value = NormLeap[leap_islamic(islcal[0]) ? 1 : 0];\n\n // Update Persian Calendar\n\n perscal = jd_to_persian(j);\n document.persian.year.value = perscal[0];\n document.persian.month.selectedIndex = perscal[1] - 1;\n document.persian.day.value = perscal[2];\n document.persian.wday.value = PERSIAN_WEEKDAYS[weekday];\n document.persian.leap.value = NormLeap[leap_persian(perscal[0]) ? 1 : 0];\n\n // Update Mayan Calendars\n\n may_countcal = jd_to_mayan_count(j);\n document.mayancount.baktun.value = may_countcal[0];\n document.mayancount.katun.value = may_countcal[1];\n document.mayancount.tun.value = may_countcal[2];\n document.mayancount.uinal.value = may_countcal[3];\n document.mayancount.kin.value = may_countcal[4];\n mayhaabcal = jd_to_mayan_haab(j);\n document.mayancount.haab.value = \"\" + mayhaabcal[1] + \" \" + MAYAN_HAAB_MONTHS[mayhaabcal[0] - 1];\n maytzolkincal = jd_to_mayan_tzolkin(j);\n document.mayancount.tzolkin.value = \"\" + maytzolkincal[1] + \" \" + MAYAN_TZOLKIN_MONTHS[maytzolkincal[0] - 1];\n\n // Update Bahai Calendar\n\n bahcal = jd_to_bahai(j);\n document.bahai.kull_i_shay.value = bahcal[0];\n document.bahai.vahid.value = bahcal[1];\n document.bahai.year.selectedIndex = bahcal[2] - 1;\n document.bahai.month.selectedIndex = bahcal[3] - 1;\n document.bahai.day.selectedIndex = bahcal[4] - 1;\n document.bahai.weekday.value = BAHAI_WEEKDAYS[weekday];\n document.bahai.leap.value = NormLeap[leap_gregorian(year) ? 1 : 0]; // Bahai uses same leap rule as Gregorian\n\n // Update Indian Civil Calendar\n\n indcal = jd_to_indian_civil(j);\n document.indiancivilcalendar.year.value = indcal[0];\n document.indiancivilcalendar.month.selectedIndex = indcal[1] - 1;\n document.indiancivilcalendar.day.value = indcal[2];\n document.indiancivilcalendar.weekday.value = INDIAN_CIVIL_WEEKDAYS[weekday];\n document.indiancivilcalendar.leap.value = NormLeap[leap_gregorian(indcal[0] + 78) ? 1 : 0];\n\n // Update French Republican Calendar\n\n frrcal = jd_to_french_revolutionary(j);\n document.french.an.value = frrcal[0];\n document.french.mois.selectedIndex = frrcal[1] - 1;\n document.french.decade.selectedIndex = frrcal[2] - 1;\n document.french.jour.selectedIndex = ((frrcal[1] <= 12) ? frrcal[3] : (frrcal[3] + 11)) - 1;\n\n // Update Gregorian serial number\n\n if (document.gregserial != null) {\n document.gregserial.day.value = j - J0000;\n }\n\n // Update Excel 1900 and 1904 day serial numbers\n\n document.excelserial1900.day.value = (j - J1900) + 1 +\n /* Microsoft marching morons thought 1900 was a leap year.\n Adjust dates after 1900-02-28 to compensate for their\n idiocy. */\n ((j > 2415078.5) ? 1 : 0)\n ;\n document.excelserial1904.day.value = j - J1904;\n\n // Update Unix time()\n\n utime = (j - J1970) * (60 * 60 * 24 * 1000);\n document.unixtime.time.value = Math.round(utime / 1000);\n\n // Update ISO Week\n\n isoweek = jd_to_iso(j);\n document.isoweek.year.value = isoweek[0];\n document.isoweek.week.value = isoweek[1];\n document.isoweek.day.value = isoweek[2];\n\n // Update ISO Day\n\n isoday = jd_to_iso_day(j);\n document.isoday.year.value = isoday[0];\n document.isoday.day.value = isoday[1];\n}",
"function calcGregorian() { updateFromGregorian(); }",
"function calcGregorian()\n {\n updateFromGregorian();\n }",
"function calcIndianCivilCalendar()\n {\n setJulian(indian_civil_to_jd(\n\t\t\t (new Number(document.indiancivilcalendar.year.value)),\n\t\t\t document.indiancivilcalendar.month.selectedIndex + 1,\n\t\t\t (new Number(document.indiancivilcalendar.day.value))));\n }",
"function updateMonth() {\n updateCal(30);\n}",
"function calcIndianCivilCalendar()\n{\n setJulian(indian_civil_to_jd(\n (new Number(document.indiancivilcalendar.year.value)),\n document.indiancivilcalendar.month.selectedIndex + 1,\n (new Number(document.indiancivilcalendar.day.value))));\n}",
"function updateCalendars() {\n initCalendars(currentMetric(), currentDate().year, currentDate().month);\n }",
"CalculateEvents(loc,nYear,nMonth) {\n //GCSunData sun = new GCSunData();\n //DstTypeChange ndst = DstTypeChange.DstOff;\n var nData;\n this.Clear();\n this.EarthLocation = loc;\n this.Year = nYear;\n var vcStart = GregorianDateTime.fromComponents(this.Year - 1, 12, 29);\n var vcEnd = GregorianDateTime.fromComponents(this.Year + 1, 1, 2);\n if (nMonth != undefined) {\n vcStart = GregorianDateTime.fromComponents(nYear, nMonth, 1);\n vcEnd = GregorianDateTime.fromComponents(nYear, nMonth, GregorianDateTime.GetMonthMaxDays(nYear,nMonth));\n }\n\n var vc = GregorianDateTime.fromDate(vcStart).setOffset(loc.OffsetUtcHours);\n var vcAdd = GregorianDateTime.fromDate(vc).InitWeekDay();\n var vcNext = new GregorianDateTime();\n var earth = loc.GetEarthData();\n\n /*while (vcAdd.IsBeforeThis(vcEnd))\n {\n ndst = loc.TimeZone.DetermineDaylightChange(vcAdd);\n vcAdd.NextDay();\n }*/\n\n\n if (this.Full || gds.getValue(GCDS.COREEVENTS_TITHI) != 0)\n {\n vcAdd.Set(vc);\n vcAdd.shour = 0.0;\n while (vcAdd.IsBeforeThis(vcEnd))\n {\n [nData, vcNext] = GCTithi.GetNextTithiStart(earth, vcAdd);\n if (vcNext.GetDayInteger() < vcEnd.GetDayInteger())\n {\n //vcNext.InitWeekDay();\n //ndst = loc.TimeZone.DetermineDaylightChange(vcNext);\n this.AddEvent(vcNext, CoreEventType.CCTYPE_TITHI, nData);\n }\n else\n {\n break;\n }\n vcAdd.Set(vcNext);\n vcAdd.shour += 0.2;\n if (vcAdd.shour >= 1.0)\n {\n vcAdd.shour -= 1.0;\n vcAdd.NextDay();\n }\n }\n }\n\n if (this.Full || gds.getValue(GCDS.COREEVENTS_NAKSATRA) != 0)\n {\n vcAdd.Set(vc);\n vcAdd.shour = 0.0;\n while (vcAdd.IsBeforeThis(vcEnd))\n {\n [nData,vcNext] = GCNaksatra.GetNextNaksatra(earth, vcAdd);\n if (vcNext.GetDayInteger() < vcEnd.GetDayInteger())\n {\n //vcNext.InitWeekDay();\n //ndst = loc.TimeZone.DetermineDaylightChange(vcNext);\n this.AddEvent(vcNext, CoreEventType.CCTYPE_NAKS, nData);\n }\n else\n {\n break;\n }\n vcAdd.Set(vcNext);\n vcAdd.shour += 0.2;\n if (vcAdd.shour >= 1.0)\n {\n vcAdd.shour -= 1.0;\n vcAdd.NextDay();\n }\n }\n }\n\n if (this.Full || gds.getValue(GCDS.COREEVENTS_YOGA) != 0)\n {\n vcAdd.Set(vc);\n vcAdd.shour = 0.0;\n while (vcAdd.IsBeforeThis(vcEnd))\n {\n [nData,vcNext] = GCYoga.GetNextYogaStart(earth, vcAdd);\n if (vcNext.GetDayInteger() < vcEnd.GetDayInteger())\n {\n //vcNext.InitWeekDay();\n //ndst = loc.TimeZone.DetermineDaylightChange(vcNext);\n this.AddEvent(vcNext, CoreEventType.CCTYPE_YOGA, nData);\n }\n else\n {\n break;\n }\n vcAdd.Set(vcNext);\n vcAdd.shour += 0.2;\n if (vcAdd.shour >= 1.0)\n {\n vcAdd.shour -= 1.0;\n vcAdd.NextDay();\n }\n }\n }\n\n if (this.Full || gds.getValue(GCDS.COREEVENTS_SANKRANTI) != 0)\n {\n vcNext = new GregorianDateTime();\n vcAdd.Set(vc);\n vcAdd.shour = 0.0;\n var nSan;\n while (vcAdd.IsBeforeThis(vcEnd))\n {\n [nSan,nData] = GCSankranti.GetNextSankranti(vcAdd, earth);\n vcNext.Set(nSan);\n if (vcNext.GetDayInteger() < vcEnd.GetDayInteger())\n {\n //vcNext.InitWeekDay();\n //ndst = loc.TimeZone.DetermineDaylightChange(vcNext);\n this.AddEvent(vcNext, CoreEventType.CCTYPE_SANK, nData);\n }\n else\n {\n break;\n }\n vcAdd.Set(vcNext);\n vcAdd.NextDay();\n }\n }\n\n if (this.Full || gds.getValue(GCDS.COREEVENTS_MOONRASI) != 0)\n {\n vcAdd.Set(vc);\n vcAdd.shour = 0.0;\n var vmr;\n while (vcAdd.IsBeforeThis(vcEnd))\n {\n [nData, vmr] = GCMoonData.GetNextMoonRasi(earth, vcAdd);\n vcNext.Set(vmr);\n if (vcNext.GetDayInteger() < vcEnd.GetDayInteger())\n {\n //vcNext.InitWeekDay();\n //ndst = loc.TimeZone.DetermineDaylightChange(vcNext);\n this.AddEvent(vcNext, CoreEventType.CCTYPE_M_RASI, nData);\n }\n else\n {\n break;\n }\n vcAdd.Set(vcNext);\n vcAdd.shour += 0.5;\n vcAdd.NormalizeValues();\n }\n\n }\n if (this.Full || gds.getValue(GCDS.COREEVENTS_CONJUNCTION) != 0)\n {\n var dlong;\n vcAdd.Set(vc);\n vcAdd.shour = 0.0;\n while (vcAdd.IsBeforeThis(vcEnd))\n {\n [dlong,vcNext] = GCConjunction.GetNextConjunction(vcAdd, true, earth);\n if (vcNext.GetDayInteger() < vcEnd.GetDayInteger())\n {\n vcNext.InitWeekDay();\n //ndst = loc.TimeZone.DetermineDaylightChange(vcNext);\n this.AddEvent(vcNext, CoreEventType.CCTYPE_CONJ, GCRasi.GetRasi(dlong, GCAyanamsha.GetAyanamsa(vcNext.GetJulianComplete())));\n }\n else\n {\n break;\n }\n vcAdd.Set(vcNext);\n vcAdd.NextDay();\n }\n }\n\n this.Sort();\n }",
"updateCalendar() {\n /*\n get the correct month\n number the calendar\n get future events\n * show the events\n highlight current date\n */\n\n this.updateMonth();\n this.updateYear();\n this.numberCalendar();\n this.highlightToday();\n this.updateEvents();\n }",
"function update() {\n\t// setupIntialValues();\n\tlet values = getCurrentUIValues();\n\t// console.log(values);\n\tupdateMonthly(calculateMonthlyPayment(values));\n}",
"function jalCal(jy){// Jalaali years starting the 33-year rule.\nvar breaks=[-61,9,38,199,426,686,756,818,1111,1181,1210,1635,2060,2097,2192,2262,2324,2394,2456,3178],bl=breaks.length,gy=jy+621,leapJ=-14,jp=breaks[0],jm,jump,leap,leapG,march,n,i;if(jy<jp||jy>=breaks[bl-1])throw new Error('Invalid Jalaali year '+jy);// Find the limiting years for the Jalaali year jy.\nfor(i=1;i<bl;i+=1){jm=breaks[i];jump=jm-jp;if(jy<jm)break;leapJ=leapJ+div(jump,33)*8+div(mod(jump,33),4);jp=jm;}n=jy-jp;// Find the number of leap years from AD 621 to the beginning\n// of the current Jalaali year in the Persian calendar.\nleapJ=leapJ+div(n,33)*8+div(mod(n,33)+3,4);if(mod(jump,33)===4&&jump-n===4)leapJ+=1;// And the same in the Gregorian calendar (until the year gy).\nleapG=div(gy,4)-div((div(gy,100)+1)*3,4)-150;// Determine the Gregorian date of Farvardin the 1st.\nmarch=20+leapJ-leapG;// Find how many years have passed since the last leap year.\nif(jump-n<6)n=n-jump+div(jump+4,33)*33;leap=mod(mod(n+1,33)-1,4);if(leap===-1){leap=4;}return{leap:leap,gy:gy,march:march};}",
"calculateAppDay(location,eventDate) {\n //MOONDATA moon;\n //SUNDATA sun;\n var d = this.details = new GCAstroData();\n var vc = new GregorianDateTime();\n var vcsun = new GregorianDateTime();\n var m_earth = location.GetEarthData();\n\n vc.Set(eventDate);\n vcsun.Set(eventDate);\n\n this.b_adhika = false;\n this.eventTime = GregorianDateTime.NewWithDate(eventDate);\n this.Location = location;\n\n //d.nTithi = GetPrevTithiStart(m_earth, vc, dprev);\n //GetNextTithiStart(m_earth, vc, dnext);\n vcsun.shour -= vcsun.TimezoneHours / 24.0;\n vcsun.NormalizeValues();\n vcsun.TimezoneHours = 0.0;\n d.sunRise = new GCHourTime();\n d.sunRise.TotalDays = vc.shour;\n d.sunRise.longitude = GCCoreAstronomy.GetSunLongitude(vcsun, m_earth);\n d.sunRise.longitudeMoon = GCCoreAstronomy.GetMoonLongitude(vcsun, m_earth);\n d.Ayanamsa = GCAyanamsha.GetAyanamsa(vc.GetJulianComplete());\n d.sunRise.Ayanamsa = d.Ayanamsa;\n\n // tithi\n\n\n d.Masa = d.MasaCalc(vc, m_earth);\n if (d.Masa == MasaId.ADHIKA_MASA)\n {\n d.Masa = d.sunRise.RasiOfSun;\n this.b_adhika = true;\n }\n\n vc.Today();\n vc.TimezoneHours = m_earth.OffsetUtcHours;\n var m = 0;\n var i;\n var va = new GaurabdaDate();\n var vctemp;\n\n va.tithi = d.sunRise.Tithi;\n va.masa = d.Masa;\n va.gyear = GCCalendar.GetGaurabdaYear(vc, m_earth);\n if (va.gyear < d.GaurabdaYear)\n va.gyear = d.GaurabdaYear;\n\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(7), eventDate.ToString()));\n MainInfo.push(AppDayBase.NewEmptyLine());\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(8), eventDate.ShortTimeString()));\n MainInfo.push(AppDayBase.NewEmptyLine());\n MainInfo.push(AppDayBase.NewEmptyLine());\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(9), location.Title));\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(10), location.GetLatitudeString()));\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(11), location.GetLongitudeString()));\n MainInfo.push(AppDayBase.NewValue(\"Timezone\", location.TimeZoneName));\n MainInfo.push(AppDayBase.NewValue(\"DST\", \"N/A\"));\n MainInfo.push(AppDayBase.NewEmptyLine());\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(13), GCTithi.GetName(d.sunRise.Tithi)));\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(14), GCStrings.Format(\"{0:00.000}%\", d.sunRise.TithiElapse)));\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(15), GCNaksatra.GetName(d.sunRise.Naksatra)));\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(16), GCStrings.Format(\"{0:00.000}% ({1} pada)\", d.sunRise.NaksatraElapse, GCStrings.getString(811 + d.sunRise.NaksatraPada))));\n MainInfo.push(AppDayBase.NewValue(\"Moon Rasi\", GCRasi.GetName(d.sunRise.RasiOfMoon)));\n MainInfo.push(AppDayBase.NewValue(\"Sun Rasi\", GCRasi.GetName(d.sunRise.RasiOfSun)));\n MainInfo.push(AppDayBase.NewValue(GCStrings.getString(20), GCPaksa.GetName(d.sunRise.Paksa)));\n\n if (b_adhika == true)\n {\n MainInfo.Add(AppDayBase.NewValue(GCStrings.getString(22), GCMasa.GetName(d.Masa) + GCStrings.getString(21)));\n }\n else\n MainInfo.Add(AppDayBase.NewValue(GCStrings.getString(22), GCMasa.GetName(d.Masa)));\n MainInfo.Add(AppDayBase.NewValue(GCStrings.getString(23), d.GaurabdaYear.ToString()));\n\n if (gds.getValue(48) == 1)\n {\n MainInfo.Add(AppDayBase.NewLineCond(GCDS.APP_CHILDNAMES));\n MainInfo.Add(AppDayBase.NewSeparator(GCStrings.getString(17)));\n MainInfo.Add(AppDayBase.NewLineCond(GCDS.APP_CHILDNAMES));\n\n MainInfo.Add(AppDayBase.NewValue(GCDS.APP_CHILDNAMES, GCStrings.getString(18), GCStrings.GetNaksatraChildSylable(d.sunRise.Naksatra, d.sunRise.NaksatraPada) + \"...\"));\n MainInfo.Add(AppDayBase.NewValue(GCDS.APP_CHILDNAMES, GCStrings.getString(19), GCStrings.GetRasiChildSylable(d.sunRise.RasiOfMoon) + \"...\"));\n }\n\n MainInfo.Add(AppDayBase.NewEmptyLine());\n MainInfo.Add(AppDayBase.NewSeparator(GCStrings.getString(24)));\n MainInfo.Add(AppDayBase.NewEmptyLine());\n\n\n celeb_date = [];\n celeb_gy = [];\n\n for (i = 0; i < TRESULT_APP_CELEBS + 3; i++)\n {\n vctemp = GCCalendar.VATIMEtoVCTIME(va, m_earth);\n if (va.gyear > d.GaurabdaYear)\n {\n if (this.celeb_gy.length < TRESULT_APP_CELEBS)\n {\n MainInfo.Add(AppDayBase.NewValue(\"Gaurabda \" + va.gyear.toString(), vctemp.ToString()));\n this.celeb_date.push(GregorianDateTime.NewWithDate(vctemp));\n this.celeb_gy.push(va.gyear);\n m++;\n }\n }\n va.gyear++;\n }\n }",
"function update() {\n const currentValuesUI = getCurrentUIValues();\n updateMonthly(calculateMonthlyPayment(currentValuesUI)); \n\n}",
"static cal_watat(my) {//get data for respective era\t\r\n\tvar SY=1577917828.0/4320000.0; //solar year (365.2587565)\r\n\tvar LM=1577917828.0/53433336.0; //lunar month (29.53058795)\r\n\tvar MO=1954168.050623; //beginning of 0 ME for MMT\r\n\tvar c=ceMmDateTime.GetMyConst(my); // get constants for the corresponding calendar era\r\n\tvar TA=(SY/12-LM)*(12-c.NM); //threshold to adjust\r\n\tvar ed=(SY*(my+3739))%LM; // excess day\r\n\tif(ed < TA) ed+=LM;//adjust excess days\r\n\tvar fm=Math.round(SY*my+MO-ed+4.5*LM+c.WO);//full moon day of 2nd Waso\r\n\tvar TW=0,watat=0;//find watat\r\n\tif (c.EI >= 2) {//if 2nd era or later find watat based on excess days\r\n\t\tTW=LM-(SY/12-LM)*c.NM;\r\n\t\tif(ed >= TW) watat=1;\r\n\t}\r\n\telse {//if 1st era,find watat by 19 years metonic cycle\r\n\t//Myanmar year is divided by 19 and there is intercalary month\r\n\t//if the remainder is 2,5,7,10,13,15,18\r\n\t//https://github.com/kanasimi/CeJS/blob/master/data/date/calendar.js#L2330\r\n\t\twatat=(my*7+2)%19; if (watat < 0) watat+=19;\r\n\t\twatat=Math.floor(watat/12);\r\n\t}\r\n\twatat^=c.EW;//correct watat exceptions\t\r\n\treturn {fm:fm,watat:watat};\r\n}",
"function update() {\n updateMonthly(calculateMonthlyPayment(getCurrentUIValues()));\n}",
"function update() {\n currentVal = getCurrentUIValues();\n let monPayment = calculateMonthlyPayment(currentVal);\n updateMonthly(monPayment);\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A utility function to display the nth image or video in the specified frame Used in showFile(), nextFile() and previousFile(). | function setupFrameContent(n, frame) {
// Make sure n is in range
if (n < 0 || n >= files.length) {
frame.clear();
return;
}
var fileinfo = files[n];
if (fileinfo.metadata.video) {
videodb.getFile(fileinfo.name, function(file) {
frame.displayVideo(file,
fileinfo.metadata.width,
fileinfo.metadata.height,
fileinfo.metadata.rotation || 0);
});
}
else {
photodb.getFile(fileinfo.name, function(file) {
frame.displayImage(file,
fileinfo.metadata.width,
fileinfo.metadata.height,
fileinfo.metadata.preview);
});
}
} | [
"function setupFrameContent(n, frame) {\n // Make sure n is in range\n if (n < 0 || n >= files.length) {\n frame.clear();\n delete frame.filename;\n return;\n }\n\n var fileinfo = files[n];\n\n // If we're already displaying this file in this frame, then do nothing\n if (fileinfo.name === frame.filename)\n return;\n\n // Remember what file we're going to display\n frame.filename = fileinfo.name;\n\n photodb.getFile(fileinfo.name, function(imagefile) {\n if (fileinfo.metadata.video) {\n // If this is a video, then the file we just got is the poster image\n // and we still have to fetch the actual video\n getVideoFile(fileinfo.metadata.video, function(videofile) {\n frame.displayVideo(videofile, imagefile,\n fileinfo.metadata.width,\n fileinfo.metadata.height,\n fileinfo.metadata.rotation || 0);\n });\n }\n else {\n // Otherwise, just display the image\n frame.displayImage(\n imagefile,\n fileinfo.metadata.width,\n fileinfo.metadata.height,\n fileinfo.metadata.preview,\n fileinfo.metadata.rotation,\n fileinfo.metadata.mirrored);\n }\n });\n}",
"function displayNthIndexImage(n) {\r\n var slideWindow = document.querySelector(\".slideShow--slide\");\r\n var images = getSlideAbleImages();\r\n\r\n if (n >= 0 && n <= images.length) {\r\n slideWindow.firstElementChild.setAttribute(\"src\", images[n].getAttribute(\"src\"));\r\n currentSlideIndex = n;\r\n //change the displayed slide number\r\n document.querySelector(\".slideshow__index\").innerHTML = currentSlideIndex + 1 + \"/\" + images.length;\r\n //change the displayed caption\r\n document.querySelector(\".slideshow__caption\").innerHTML = images[n].getAttribute(\"alt\");\r\n }\r\n}",
"function showPhoto(n) {\n if (thumbnailsDisplayed) {\n thumbnails.classList.add('hidden');\n header.classList.add('hidden');\n photos.classList.remove('hidden');\n playerControls.classList.remove('hidden');\n thumbnailsDisplayed = false;\n }\n\n displayImageInFrame(photoURL(n - 1), previousPhotoFrame);\n displayImageInFrame(photoURL(n), currentPhotoFrame);\n displayImageInFrame(photoURL(n + 1), nextPhotoFrame);\n currentPhotoIndex = n;\n}",
"function showImage(index) {\r\n\r\n\tif(!indexExistsIn(imgs, index))\r\n\t\tthrow \"showImage(index): Index out of bounds error: \" + index + \".\";\r\n\r\n\tcurrentImage = index;\r\n\r\n\t$(\"#image-previewer\").attr(\"src\", \"get/imgs/\" + imgs[index]);\r\n\t$(\"#current-image\").html(currentImage);\r\n\r\n\tupdateCounters();\r\n\r\n}",
"function nextFile(time) {\n // If already displaying the last one, do nothing.\n if (currentFileIndex === files.length - 1)\n return;\n\n // If the current frame is using a <video> element instead of just\n // displaying a poster image, reset it back to just the image\n if (currentFrame.displayingVideo && currentFrame.video.playerShowing)\n currentFrame.video.init();\n\n // Set a flag to ignore pan and zoom gestures during the transition.\n transitioning = true;\n setTimeout(function() { transitioning = false; }, time);\n\n // Set transitions for the visible frames\n var transition = 'transform ' + time + 'ms ease';\n currentFrame.container.style.transition = transition;\n nextFrame.container.style.transition = transition;\n\n // Cycle the three frames so next becomes current,\n // current becomes previous, and previous becomes next.\n var tmp = previousFrame;\n previousFrame = currentFrame;\n currentFrame = nextFrame;\n nextFrame = tmp;\n\n updateFocusThumbnail(currentFileIndex + 1);\n // Move (transition) the frames to their new position\n resetFramesPosition();\n\n // Update the frame for the new next item\n setupFrameContent(currentFileIndex + 1, nextFrame);\n\n // When the transition is done, cleanup\n currentFrame.container.addEventListener('transitionend', function done(e) {\n this.removeEventListener('transitionend', done);\n\n // Reposition the item that just transitioned off the screen\n // to reset any zooming and panning\n previousFrame.reset();\n });\n\n // Disable the edit button if this is a video or\n // mediaDB is scanning, enable otherwise\n if (currentFrame.displayingVideo || photodb.scanning)\n fullscreenButtons.edit.classList.add('disabled');\n else\n fullscreenButtons.edit.classList.remove('disabled');\n}",
"function nextFile(time) {\n // If already displaying the last one, do nothing.\n if (currentFileIndex === files.length - 1)\n return;\n\n // Don't pan a playing video!\n if (currentFrame.displayingVideo && !currentFrame.video.player.paused)\n currentFrame.video.pause();\n\n // Set a flag to ignore pan and zoom gestures during the transition.\n transitioning = true;\n setTimeout(function() { transitioning = false; }, time);\n\n // Set transitions for the visible frames\n var transition = 'transform ' + time + 'ms ease';\n currentFrame.container.style.transition = transition;\n nextFrame.container.style.transition = transition;\n\n // Cycle the three frames so next becomes current,\n // current becomes previous, and previous becomes next.\n var tmp = previousFrame;\n previousFrame = currentFrame;\n currentFrame = nextFrame;\n nextFrame = tmp;\n currentFileIndex++;\n\n // Move (transition) the frames to their new position\n resetFramesPosition();\n\n // Update the frame for the new next item\n setupFrameContent(currentFileIndex + 1, nextFrame);\n\n // When the transition is done, cleanup\n currentFrame.container.addEventListener('transitionend', function done(e) {\n this.removeEventListener('transitionend', done);\n\n // Reposition the item that just transitioned off the screen\n // to reset any zooming and panning\n previousFrame.reset();\n });\n\n // Disable the edit button if we're now viewing a video, and enable otherwise\n if (currentFrame.displayingVideo)\n $('fullscreen-edit-button').classList.add('disabled');\n else\n $('fullscreen-edit-button').classList.remove('disabled');\n}",
"function showNewImage() {\n displayNode.compute();\n frameCount++;\n}",
"function plusImgs(n) {\n showImages((imageIndex += n));\n}",
"function currentImg(n) {\n showImgs(slideIndex = n);\n}",
"_nextImg() {\n this._index = (this._index + 1) % this._imgs.length\n this._showImg()\n }",
"showFrame(_index) {\n let spriteFrame = this.animation.frames[_index];\n this.cmpMesh.pivot = spriteFrame.mtxPivot;\n this.cmpMaterial.pivot = spriteFrame.mtxTexture;\n this.cmpMaterial.material.setCoat(this.animation.spritesheet);\n this.frameCurrent = _index;\n this.timer = ƒ.Time.game.setTimer(spriteFrame.timeScale * 1000 / this.framerate, 1, this.showFrameNext);\n }",
"function FrameViewer(\n\t\tcanvas, \n\t\tbtn_prev_frame, \n\t\tbtn_prev_second, \n\t\tbtn_next_frame, \n\t\tbtn_next_second) {\n \n\t// Private instance variables //\n var IMG_WIDTH \t\t= 192;\n var IMG_HEIGHT \t\t= 144;\n var ROWS_TO_SHOW \t= 3;\n var curr_row \t\t= 0;\n var data \t\t\t= null;\n \n \n // Private methods //\n \n // Caches image objects and stores directly in data //\n function load_images() {\n data.each(function(frame) {\n var imgs = []\n frame.images.each(function(imgstr) {\n var img = new Image(IMG_WIDTH, IMG_HEIGHT);\n img.src = \"/img/\" + imgstr;\n img.style.float = \"left\";\n imgs.push(img); \n });\n frame['imageobjs'] = imgs;\n }) \n }\n \n // use DOM to draw the viewer HTML on canvas //\n function draw_viewer() {\n canvas.innerHTML = \"\";\n var n = curr_row;\n while(n < data.length && \n n < (curr_row + ROWS_TO_SHOW)) {\n var div = document.createElement(\"div\");\n div.style.width = 8 * IMG_WIDTH + \"px\";\n var h3 = document.createElement(\"span\");\n h3.innerHTML = data[n].timestamp.replace('T', ' ');\n div.appendChild(h3);\n div.appendChild(document.createElement(\"br\"));\n data[n].imageobjs.each(function(imageobj) {\n imageobj.addEventListener(\"click\", function() {\n window.open(imageobj.src);\n }, false);\n div.appendChild(imageobj);\n });\n canvas.appendChild(div); \n n++;\n } \n }\n \n // Called from ajax callback //\n function update(d) {\n data = d;\n load_images();\n draw_viewer();\n }\n \n \n // Privileged method (public) //\n // Makes ajax request to get data based on params //\n this.loadData = function(params) {\n var url = \"/images\";\n var pstrs = [];\n if (params.starttime && params.starttime.length != 0) {\n pstrs.push(\"starttime=\" + params.starttime);\n if (params.endtime && params.endtime.length != 0) \n pstrs.push(\"endtime=\" + params.endtime);\n if (params.duration && params.duration.length !=0)\n pstrs.push(\"duration=\" + params.duration);\n if (params.jump && params.jump.length != 0)\n pstrs.push(\"jump=\" + params.jump);\n }\n if (params.count && params.count.length !=0)\n pstrs.push(\"count=\" + params.count);\n\n url += \"?\" + pstrs.join(\"&\");\n\n //reset \n canvas.innerHTML = \"Loading...\";\n\n new Ajax.Request(url, {\n method: 'get',\n onSuccess: function(transport, json) {\n var response = transport.responseText || \"[]\";\n var data = eval(\"(\" + response + \")\");\n update(data);\n }\n });\n }\n \n \n // Set Up Button Listeners //\n \n var parent = this;\n btn_prev_frame.addEventListener(\"click\", \n function() {\n if (curr_row == 0) { \n return;\n }\n curr_row -= 1;\n draw_viewer();\n }, false);\n \n btn_prev_second.addEventListener(\"click\", \n function() {\n ts = data[curr_row].timestamp;\n curr_row = 0;\n parent.loadData({'starttime': ts, 'jump': -1});\n }, false);\n\n btn_next_frame.addEventListener(\"click\", \n function() {\n if (curr_row >= data.length - ROWS_TO_SHOW) {\n ts = data[curr_row+1].timestamp;\n curr_row = 0;\n parent.loadData( {'starttime': ts});\n return;\n }\n curr_row += 1;\n draw_viewer();\n }, false);\n\n btn_next_second.addEventListener(\"click\", \n function() {\n ts = data[curr_row].timestamp;\n curr_row = 0;\n parent.loadData( {'starttime': ts, 'jump': 1});\n }, false); \n}",
"function showPic(n) {\r\n // Handle wrapping past end of slideshow\r\n if (n > slideshowElems.length) {slideIndex = 1}\r\n\r\n // Handle wrapping before beginning of slideshow\r\n if (n < 1) {slideIndex = slideshowElems.length}\r\n\r\n // Set all slides to hidden\r\n var i;\r\n for (i = 0; i < slideshowElems.length; i++) {\r\n slideshowElems[i].style.display = \"none\";\r\n }\r\n\r\n // Set current slide to visible\r\n slideshowElems[slideIndex-1].style.display = \"block\";\r\n\r\n // Set slide description\r\n document.getElementById(\"slideName\").innerHTML = getDescription(slideshowElems[slideIndex-1].src);\r\n}",
"function displayPosition(idx) {\n $(\"#pos-info\").html(`<p>Image ${idx + 1} of ${IMAGES.length}</p>`);\n }",
"function displayFrame(frames) {\n\t\tdocument.getElementById(\"text-area\").value =\n\t\t\tframes[frameCounter % frames.length];\n\t\tframeCounter += 1;\n\t}",
"function show_img_index(index) {\n\tvar numIndex = parseInt(index);\n\ttry {\n\t\tfor (var a = 0; a <= listNameOfImg.length - 1; a++) {\n\t\t\tif (a == numIndex) {\n\t\t\t\timgNew.setAttribute(\"src\", listImg[a]);\n\t\t\t\timgNew.setAttribute(\"alt\", listNameOfImg[a]);\n\t\t\t\tslide();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthrow \"Image error!\";\n\t} catch (err) {\n\t\twindow.alert(err);\n\t}\n}",
"function displayframe()\n{\n\tcurrentframe = currentframe % frames.length;\n\tdocument.getElementById(\"txtArea\").value = frames[currentframe];\n\tcurrentframe = currentframe + 1;\n}",
"function renderImages(frames){\n //If somehow, the array \"frames\" has more than 4 elements, return...\n if(frames.length != imagesPerFrame){\n return;\n }\n\n //clear the contents of photox cells..\n $(\"#photo0\").html(\"\");$(\"#photo1\").html(\"\");$(\"#photo2\").html(\"\");$(\"#photo3\").html(\"\");\n\n //render images\n var cnt = 0;\n frames.forEach(function(image){\n $(\"#photo\" + cnt).html(\"<img src=\" + image\n + \" alt=\" + image + \" height=\\\"250\\\" width=\\\"250\\\"/>\");\n cnt++;\n });\n }",
"function nextPicturePreview() {\r\n\r\n //Incrementing image tracker\r\n imageIndex++;\r\n\r\n //Updating buttons\r\n updateButtonStatus();\r\n\r\n //Loading currently selected image\r\n loadImage();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns string with list of files in VCFiles of VCFilters collection files source VCFiles or VCFilters collection delim delimiter | function combFiles(files, delim)
{
var ret = "";
for (var i = 1; i <= files.Count; ++i)
{
if (ret != "")
ret += delim;
ret += files.Item(i).RelativePath;
}
return ret;
} | [
"function filterCreateVCFilter(parent)\r\n{\r\n var VCFilter;\r\n if (null == this.Name)\r\n VCFilter = parent;\r\n else\r\n {\r\n VCFilter = parent.AddFilter(this.Name);\r\n if (null != this.Id)\r\n VCFilter.UniqueIdentifier = this.Id;\r\n if (null != this.Filter)\r\n VCFilter.Filter = this.Filter;\r\n }\r\n\r\n if (null != this.Folder)\r\n this.Folder = ReplaceMacros(this.Folder, cmnMacros);\r\n \r\n if (0 < this.Files.length)\r\n {\r\n // add specified files\r\n for (var i = 0; i < this.Files.length; ++i)\r\n {\r\n var filename = this.Files[i];\r\n if (null != this.Folder && this.Folder.length > 0)\r\n filename = this.Folder + \"\\\\\" + filename;\r\n \r\n try\r\n {\r\n fso.GetFile(filename);\r\n }\r\n catch (e)\r\n {\r\n WScript.Echo(\"File \" + filename + \" does not exist\");\r\n WScript.Quit(3);\r\n }\r\n \r\n AddFilterFile(VCFilter, filename, this.Type, this.Exclude);\r\n }\r\n }\r\n else\r\n {\r\n // add files from folder\r\n\r\n // create regexp from extensions\r\n var extArray = this.Filter.replace(/\\./g, \"\\\\.\").split(\";\");\r\n var rxText = \"^\";\r\n if (extArray.length != 0)\r\n {\r\n rxText += \"(?:\" + extArray[0];\r\n for (i = 1; i < extArray.length; ++i)\r\n rxText += \"|\" + extArray[i];\r\n rxText += \")\";\r\n }\r\n rxText += \"$\";\r\n \r\n var rxExts = new RegExp(rxText, \"i\");\r\n \r\n var folder;\r\n \r\n try\r\n {\r\n folder = fso.GetFolder(this.Folder);\r\n }\r\n catch (e)\r\n {\r\n WScript.Echo(\"Folder \" + this.Folder + \" does not exist\");\r\n WScript.Quit(3);\r\n }\r\n \r\n // add subfolders as own filters\r\n var enumSubFolders = new Enumerator(folder.SubFolders);\r\n for (; !enumSubFolders.atEnd(); enumSubFolders.moveNext())\r\n {\r\n var subFolder = enumSubFolders.item();\r\n if (null == this.exclFolders || !this.exclFolders.test(subFolder.Name))\r\n {\r\n var filterDef = new FilterDef(subFolder.Name, this.Id,\r\n this.Filter, this.Type, this.Exclude);\r\n filterDef.Folder = subFolder.Path;\r\n filterDef.exclFolders = this.exclFolders;\r\n filterDef.exclFiles = this.exclFiles;\r\n filterDef.createVCFilter(VCFilter);\r\n }\r\n }\r\n \r\n // add files\r\n var nfiles = 0;\r\n var enumFiles = new Enumerator(folder.Files);\r\n for (; !enumFiles.atEnd(); enumFiles.moveNext())\r\n {\r\n var file = enumFiles.item();\r\n var fileext = getExtension(file.Name);\r\n if (rxExts.test(fileext) && (null == this.exclFiles || !this.exclFiles.test(file.Name)))\r\n {\r\n ++nfiles;\r\n AddFilterFile(VCFilter, file.Path, this.Type, this.Exclude);\r\n }\r\n }\r\n \r\n // remove filter if it is empty\r\n if (0 == nfiles)\r\n parent.RemoveFilter(VCFilter);\r\n }\r\n for (var i = 0; i < this.FilterDefs.length; ++i)\r\n this.FilterDefs[i].createVCFilter(VCFilter);\r\n}",
"function combFilter(filter, delim)\r\n{\r\n var ret = combFiles(filter.Files, delim);\r\n if (ret != \"\")\r\n ret += delim;\r\n ret += combFilters(filter.Filters, delim);\r\n return ret;\r\n}",
"getStepDefinitionFiles(){\n\t\tlet stepDefFileContent = '<select id=\"stepDefinitionFiles\">';\n\t\tstepDefFileContent += '<option value=\"No\" selected> Do not filter by Step Definition File </option>';\n\t\tlet stepDefFileExists = nodedir.files('./step_definitions', {sync:true});\n\t\tstepDefFileExists.forEach(function(filename){\n\t\t\tstepDefFileContent += '<option value=\"' + filename + '\">' + filename + '</option>';\n\t\t});\n\t\tstepDefFileContent += '</select>';\n\t\treturn stepDefFileContent;\n\t}",
"function getSourceFileList(){\n var next = arguments[0];\n var args = Array.prototype.slice.call(arguments, 1);\n getFilesOnCondition(sPath, false, function(filesList){\n args.unshift(filesList)\n next.apply(null, args);\n });\n}",
"function getSelectedFiles() {\n\tvar selected = $('.selected.file');\n\tvar nameFields = selected.map((i, el) => $(el).find('.name')).get();\n\tvar names = nameFields.map(field => field.text());\n\treturn names.map(name => currentFolder.files[name]);\n}",
"function getFiles() {\n return fileList;\n}",
"function buildCfcStrings(){\n for(let cfcFile of cfcFiles){\n cfcStrings.push(fs.readFileSync(cfcFile, 'utf8'));\n }\n}",
"function combFilters(filters, delim)\r\n{\r\n var ret = \"\";\r\n for (var i = 1; i <= filters.Count; ++i)\r\n {\r\n if (ret != \"\")\r\n ret += delim;\r\n ret += combFilter(filters.Item(i), delim);\r\n }\r\n return ret;\r\n}",
"function filterFiles() {\n for (var i = 0; i < content.length; i++) {\n if (path.extname(content[i]) === ext_name) {\n console.log(content[i]);\n }\n }\n}",
"getOutputFilesNames() {\n return null;\n }",
"function getWatchFiles(doc) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n let cwd, files;\r\n if (vscode.workspace.rootPath) {\r\n let detectList = yield vscode.window.showInputBox({\r\n placeHolder: \"e.g. app/*.html|app/*.css\",\r\n prompt: \"Enter relative path of files to root folder separated by | to watch multiple locations\",\r\n });\r\n if (detectList) {\r\n cwd = vscode.workspace.rootPath;\r\n files = detectList.split(\"|\");\r\n }\r\n else {\r\n cwd = path.dirname(doc.uri.fsPath);\r\n let thisType = \"*\" + path.extname(doc.uri.fsPath);\r\n files = [thisType];\r\n }\r\n }\r\n else {\r\n cwd = path.dirname(doc.uri.fsPath);\r\n let thisType = \"*\" + path.extname(doc.uri.fsPath);\r\n files = [thisType];\r\n }\r\n return files.map(p => path.join(cwd, p));\r\n });\r\n}",
"function filterFor(workflowName, vcfType, inArr)\n{\n\tvar arr = [];\n\tfor (var i = 0; i < inArr.length; i++)\n\t{\n\t\tif (typeof(inArr[i]) == \"string\") //(\"class\" in inArr[i] && inArr[i].class == \"File\")\n\t\t{\n\t\t\tif (inArr[i].indexOf(workflowName) >= 0 && inArr[i].indexOf(vcfType) >= 0)\n\t\t\t{\n\t\t\t\tarr.push(inArr[i])\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (\"class\" in inArr[i] && inArr[i].class == \"File\")\n\t\t\t{\n\t\t\t\tif (inArr[i].basename.indexOf(workflowName) >= 0 && inArr[i].basename.indexOf(vcfType) >= 0)\n\t\t\t\t{\n\t\t\t\t\tarr.push(inArr[i])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn arr;\n}",
"_formatFiles(files) {\n let fileList = [];\n if (files && files.length > 0) {\n for (let i = 0; i < files.length; i++) {\n let file = files[i];\n\n if (!file.tags || file.tags.indexOf('attachment') == -1) {\n fileList[i] = {\n name: file.name.replace(/%2F/g, '/').replace(/%20/g, ' '),\n webkitRelativePath: file.name.replace(/%2F/g, '/').replace(/%20/g, ' '),\n size: file.size\n };\n }\n }\n }\n let fileTree = fileUtils.generateTree(fileList);\n return fileTree;\n }",
"_formatFiles(files) {\n let fileList = []\n if (files && files.length > 0) {\n for (let i = 0; i < files.length; i++) {\n let file = files[i]\n\n if (!file.tags || file.tags.indexOf('attachment') == -1) {\n fileList[i] = {\n name: file.filename.replace(/%2F/g, '/').replace(/%20/g, ' '),\n webkitRelativePath: file.filename\n .replace(/%2F/g, '/')\n .replace(/%20/g, ' '),\n size: file.size,\n }\n }\n }\n }\n let fileTree = fileUtils.generateTree(fileList)\n return fileTree\n }",
"function getJsonPresetFileNames(){\n result = new Array();\n folderPath = getPresetsFolder();\n\n // Get files from folder\n // https://stackoverflow.com/questions/28017561/need-extendscript-to-open-a-file-without-knowing-the-full-file-name\n var fileName = Folder(folderPath).getFiles(); //Array of File objects\n // return array of files from folder\n // https://www.ps-scripts.com/viewtopic.php?t=23407\n var fileList = []; // Array of Strings\n for (var i = 0; i < fileName.length; i++) {\n // alert(decodeURI(fileName[i].toString()))\n // fileList.push(File.decode(fileName.name));\n\n // adds complete path address \n // var s = decodeURI(fileName[i].toString());\n\n // https://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript\n // strp pathaddress from file\n var s = fileName[i].toString().replace(/^.*[\\\\\\/]/, '').replace(\".json\",'');\n s = s.replace(/^file:\\/\\//, \"\");\n if ($.os.match(/^Windows.*/))\t// Pull off \":\" from drive letter\n s = s.replace(/^\\/(.):\\//, \"/$1/\");\n fileList.push(s); \n }\n\n return fileList\n}",
"findFilePathStrings() {\n //look for any string containing `pkg:/`\n const regexp = /\"(pkg:\\/[^\"]+)\"/gi;\n let match;\n while (match = regexp.exec(this.bscFile.fileContents)) {\n this.fileReferences.push({\n //+1 to step past opening quote\n offset: match.index + 1,\n path: match[1]\n });\n }\n }",
"function getSplitFileTypes(allFileTypes) {\n\tvar defaultFileTypes = [];\n\tvar otherFileTypes = [];\n var predefinedFileTypes = [];\n\tif (mainWidget.softwareCompetition.projectHeader.projectCategory.id > 0) {\n\t\tfor (var i = 0; i < fileTypes.length; i++) {\n\t\t\tif (fileTypes[i].id == mainWidget.softwareCompetition.projectHeader.projectCategory.id) {\n predefinedFileTypes = fileTypes[i].fileFormats;\n for (var k = 0; k < allFileTypes.length; k++) {\n var matched = false;\n for (var j = 0; j < fileTypes[i].fileFormats.length; j++) {\n if(fileTypes[i].fileFormats[j].description == allFileTypes[k] || fileTypes[i].fileFormats[j].value == allFileTypes[k]) {\n defaultFileTypes.push(fileTypes[i].fileFormats[j]);\n matched = true;\n break;\n }\n }\n if (!matched) {\n otherFileTypes.push(allFileTypes[k]);\n\t }\n\t\t }\n break;\n }\n\t\t}\n\t}\n\treturn [defaultFileTypes, otherFileTypes, predefinedFileTypes];\n}",
"function buildServerFilterListFromDir(aDir)\n{\n var ispHeaderList = document.getElementById('useServerFilterList');\n\n // now iterate over each file in the directory looking for .sfd files\n var entries = aDir.directoryEntries.QueryInterface(Components.interfaces.nsIDirectoryEnumerator);\n\n while (entries.hasMoreElements())\n {\n var entry = entries.nextFile;\n if (entry.isFile())\n {\n // we only care about files that end in .sfd\n if (entry.isFile() && /\\.sfd$/.test(entry.leafName))\n {\n var fileName = RegExp.leftContext;\n // if we've already added an item with this name, then don't add it again.\n if (ispHeaderList.getElementsByAttribute(\"value\", fileName).item(0))\n continue;\n ispHeaderList.appendItem(fileName, fileName);\n }\n }\n }\n}",
"getFileNames(dir){\n IpcRequester.send(FILES_GET, {dir});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Size of the queue, filtered by the given options. For example, this can be used to find the number of items remaining in the queue with a specific priority level. | sizeBy(options) {
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
return this._queue.filter(options).length;
} | [
"sizeBy(options) {\n return this._queue.filter(options).length;\n }",
"sizeBy(options) {\n return this._queue.filter(options).length;\n }",
"get queue_size() {\n // NOTE: _queue is the internal reference to pending commands\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return this.pipeline._queue.length;\n }",
"get size() {\n return this._queue.size;\n }",
"get size() {\n return this._queue.size;\n }",
"function getSize(){\n return queue.length;\n }",
"function size(){\n return queue.length;\n }",
"function size() {\r\n var counter = 0;\r\n for (var i = 0; i < this.PriorityQueueContents.length; i++) {\r\n counter += this.PriorityQueueContents[i].ids.length;\r\n }\r\n return counter;\r\n }",
"size() {\n return this.queue_size;\n }",
"function size(){\n \treturn pQueue.length;\n }",
"size() {\n return this.queue.size();\n }",
"_estimateSize(options) {\n let ret = 0;\n const { actionEstimate, arnEstimate } = options;\n ret += `\"Effect\": \"${this.effect}\",`.length;\n count('Action', this.actions, actionEstimate);\n count('NotAction', this.notActions, actionEstimate);\n count('Resource', this.resources, arnEstimate);\n count('NotResource', this.notResources, arnEstimate);\n ret += this.principals.length * arnEstimate;\n ret += this.notPrincipals.length * arnEstimate;\n ret += JSON.stringify(this.conditions).length;\n return ret;\n function count(key, values, tokenSize) {\n if (values.length > 0) {\n ret += key.length + 5 /* quotes, colon, brackets */ +\n (0, util_1.sum)(values.map(v => (cdk.Token.isUnresolved(v) ? tokenSize : v.length) + 3 /* quotes, separator */));\n }\n }\n }",
"queueLength() {\n return this._messages.length;\n }",
"queueLength() {\n return this._messages.length;\n }",
"TotalItemsInQueue(){\n return this._length;\n }",
"function getOptionsWidth(args) {\n return args.options.reduce((max, opt) => {\n if (!operand.isOperand(opt) && opt.signature) {\n const len = getOptionWidth(opt);\n if (len > max) {\n return len;\n }\n }\n return max;\n }, 0);\n}",
"getLength() {\n return queue.length;\n }",
"get length() {\n //* A `length` getter that returns the number of items in the queue.\n \n return this.size\n }",
"get requestQueueSize() {\n return this.m_workerRequestQueue.length;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Booking View Full details | function bookingViewFullDetails(bookid){
//alert('Mani'); return false;
//myPopupWindowOpen('#bookingViewFullDetailsPop','#maska');
//Form
$('#bookingFullDetailsList').html('<div class="addtocartloading" ><span class="image"><img src="'+jssitebaseUrl +'/theme/default/images/loader.gif" border="0" alt="Loading" /></span><span>Please wait...</span></div>').show();
$("#bookingFullDetailsList").load(jssitebaseUrl+"/ajaxActionRestaurant.php?action=bookingFullDetails&id="+bookid);
} | [
"function showBooking(d) {\n\t\t\n\t\t//calculate total price and add the room info to main data\n\t\tdata.total_price = d.price * parseInt(d.quantity);\n\t\tdata.room_types = [{\n\t\t\tid: d.room_id,\n\t\t\trate_plan_id: d.rate_id,\n\t\t\tquantity: d.quantity,\n\t\t\ttotal_price: data.total_price,\n\t\t\tcurrency: data.currency,\n\t\t\tservices: [],\n\t\t}];\n\t\t\n\t\t$booking = `\n<div class=\"imemento-book\">\n\t<form class=\"pure-form pure-form-stacked\">\n\t\t<div class=\"pure-g\">\n <div class=\"pure-u-1 pure-u-md-12-24 imemento-col-left\">\n <label>Prenume *</label>\n <input class=\"pure-u-1\" type=\"text\" name=\"first_name\" required>\n </div>\n <div class=\"pure-u-1 pure-u-md-12-24 imemento-col-right\">\n <label>Nume *</label>\n <input class=\"pure-u-1\" type=\"text\" name=\"last_name\" required>\n </div>\n <div class=\"pure-u-1 pure-u-md-12-24 imemento-col-left\">\n <label>Email *</label>\n <input class=\"pure-u-1\" type=\"email\" name=\"email\" required>\n </div>\n <div class=\"pure-u-1 pure-u-md-12-24 imemento-col-right\">\n <label>Telefon</label>\n <input class=\"pure-u-1\" type=\"text\" name=\"phone\">\n </div>\n <div class=\"pure-u-1 pure-u-md-12-24 imemento-col-left\">\n <label>Adresa</label>\n <input class=\"pure-u-1\" type=\"text\" name=\"address\" required>\n </div>\n <div class=\"pure-u-1 pure-u-md-12-24 imemento-col-right\">\n <label>Localitate</label>\n <input class=\"pure-u-1\" type=\"text\" name=\"location\" required>\n </div>\n <div class=\"pure-u-1\">\n <label>Observatii</label>\n <textarea class=\"pure-u-1\" name=\"observations\"></textarea>\n </div>\n\t\t</div>\n\t\t\n\t\t<div class=\"imemento-total imemento-text-right\">\n\t\t\t<strong class=\"imemento-block\">Nopti: ${daysBetween(o.arrival, o.departure)}</strong>\n\t\t\t<strong class=\"imemento-block\">Pret total: ${data.total_price} ${data.currency}</strong>\n\t\t</div>\n\t\t\n\t\t<div class=\"imemento-actions\">\n\t\t\t<a class=\"pure-button pure-button imemento-back-button\">Inapoi</a>\n\t\t\t<button type=\"submit\" class=\"pure-button pure-button-success imemento-confirm-button imemento-pull-right\">Rezerva</button>\n\t\t</div>\n\t</form>\n</div>\n\t\t`;\n\t\t\n\t\t$elem_inner.html($booking);\n\t\t\n\t\t//show selected room and rate\n\t\tshowRooms(true, parseInt(d.room_id), parseInt(d.rate_id), parseInt(d.quantity));\n\t}",
"function viewBookings(req, res) {\n Arena.findOne({name:req.params.arenaName}, function (err, foundArena) {\n if (err) {\n res.json({ err: err });\n }\n else if (!foundArena) {\n res.json({ err: \"Sorry Broken Link, this arena may have been deleted, removed or is no longer existant\" });\n }\n else {\n ServiceProvider.findById(foundArena.service_provider, function (errSp, serviceProvider) {\n if (errSp) {\n res.json({ err: \"Internal server Error, Sorry for the inconvenience !\" });\n }\n else if (serviceProvider) {\n if (serviceProvider.username == req.user.username) {\n //find all pending requests where the request time is greater than today, the arena is the current arena and have not been accepted\n Booking.find({ accepted: false, arena: foundArena.name })\n .$where('(new Date(new Date().getFullYear(),this.bookMonth,this.bookDay,Math.floor(this.start_index/2),((this.start_index%2)*30),0,0))>(new Date())')\n .exec(function (err, bookingArr) {\n //TODO: render a view (will be done in Sprint 2 ISA)\n if (err) {\n res.json({ err: \"Error finding pending requests\" });\n }\n else {\n res.json({\n bookings : bookingArr\n });\n }\n })\n }\n else {\n res.json({ err: \"sorry not your arena\" });\n }\n }\n else {\n res.json({ err: \"Internal Server Error sorry 😢\" });\n };\n })\n\n }\n });\n}",
"function presentBookedTable(booking) {\n console.log(\"Table has been booked from \" + booking.table.from + \" to \" + booking.table.to)\n}",
"function showPendingBookings() {\n var pendingBookings = Cookie.get(\"hotelBooking\");\n if (pendingBookings) {\n pendingBookings = JSON.parse(pendingBookings);\n var output = \"<h2>Pending Bookings</h2><dl>\";\n $(pendingBookings).each(function () {\n this.checkin = new Date(this.checkin);// make new date objects to sort out time zone problems\n this.checkout = new Date(this.checkout);//associated with JSON.stringifying Date() objects\n output += \"<dt>\" + this.roomNum +\n \"</dt><dd>Name: \" + this.guestName +\n \". <br>Checkin: \" + this.checkin +\n \". <br>Checkout: \" + this.checkout +\n \".</dd>\";\n });\n output += \"</dl>\";\n\n $(\"#pendingBookings\").empty().html(output);\n }\n }",
"tablePrepBooking(){\n return {\n Navn: this.name,\n Beskrivelse: this.description,\n Adresse: this.address.getAddress(),\n Siddepladser: this.seats,\n //This returns the current restaurant-instance\n Book: this\n }\n }",
"function viewDetails(appointment_id) {\n console.log('view details clicked ', appointment_id);\n $http.get('/appointments/' + appointment_id).then(function(response) {\n appointment.selected = response.data;\n console.log('Apt & Client details back from db: ', appointment.selected);\n });\n }",
"getHotelBookings() {\n return this.hotelBooking;\n }",
"function getBookingList() {\n return $http.get('data/bookingData.json',{\n transformResponse: transformBookingList\n })\n .then(sendResponseData)\n .catch(sendGetBookingError);\n }",
"function loadHotelBookingDetails(refNum){\n \t $.loadingPageAnimation('show','myAccount');\n \tvar $tripListContainer = $('.review-dis');\n \tvar $tripDetailsContainer = $('._tripDetails');\n \t$.get('/common/themes/'+window.templatePath+'/tmpl/myAccount/myTripsHotelDetails.ejs?v=nd-v0102',{},function(template){\n \t//set the EJS template to myProfileMobile.dynamicTemplate\n \tmyProfileMobile.dynamicTemplate = template;\t\t\n \t\tmyProfileMobile.render(false,function(renderedData){\n \t\t\tvar response=renderedData.response;\n \t\t\tvar filterRes;\n \t\t\tfor(var i in response.bookingDetails.bookings){\n \t\t\t\tif(response.bookingDetails.bookings[i].entityDetails.hotelDetails !== null){\n \t\t\t\t\tvar index=response.bookingDetails.bookings[i].entityDetails.hotelDetails.hotel.referenceNo;\n \t \t\t\t\tif(index == refNum){\t\t\t\t\t\n \t \t\t\t\t\tfilterRes=response.bookingDetails.bookings[i];\n \t \t\t\t\t\tbreak;\n \t \t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\t//set the data for UI\n \t\t\t var tripData = {\n \t\t\t\t\t response:filterRes,\n \t\t\t\t\t maps:myProfileMobile.hashmap,\n \t\t\t\t\t lang:lang\n \t\t\t }\n \t\t\t//Render the template\n \t\t\t myProfileMobile.loadTemplate('hotel-trips-view',tripData,$('._tripDetails'));\n \t\t\t myProfileMobile.hash = window.location.hash.substring(1);\n \t\t\t //hide the list view\n \t\t\t $tripListContainer.hide();\n \t\t\t //show the detail view\n \t\t\t $tripDetailsContainer.show();\n \t\t\t window.history.pushState('forward', null, '#'+refNum);\n \t\t\t $.loadingPageAnimation();\n\t\t\t//pricetagConvert.init();\n \t\t});\t\t\t\n \t});\t\n }",
"displayDetails() {\n const id = $(this)[0].id;\n const trip = new Trip({id: id});\n $('#list-wrapper').addClass('large-5');\n $('#reservation-form').show();\n $('#details').css('padding', '20px');\n trip.fetch({}).done(() => {\n $('#details').html(tripTemplate(trip));\n $('#price').html(`$${trip.attributes.cost.toFixed(2)} - Reserve!`);\n });\n $('#reservation-form').children('form').attr('id', id);\n }",
"function getAndDisplayAllbookes() {\n refreshBookList();\n}",
"render(){\r\n\t\treturn(\r\n\t\t\t!this.props.bookings.length\r\n\t\t\t? <Alert color=\"info\"> No booking found </Alert>:\r\n\t\t\t<Table>\r\n\t\t\t\t<thead>\r\n\t\t\t\t\t<tr>\r\n <th>Booking ID</th>\r\n <th>Bookings</th>\r\n <th>Room Id </th>\r\n <th>Check-in Date</th> \r\n <th>Check-out Date</th> \r\n <th>Total Price</th>\r\n <th>Action</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</thead>\r\n\t\t\t\t<tbody>\r\n\t\t\t\t\t{this.props.bookings}\r\n\t\t\t\t</tbody>\r\n\t\t\t </Table>\r\n\t\t);\r\n\t}",
"display() {\n\t\tif (sessionStorage.getItem(\"station\")) {\n\t\t\t$('#station_booked').text(`${sessionStorage.getItem(\"station\")}`);\n\t\t\t$('#station_booked').text(`${sessionStorage.getItem(\"station\")}`);\n\t\t\t$('#name_booker').text(`${localStorage.getItem(\"lastname\")} ${localStorage.getItem(\"firstName\")}`);\n\t\t\t$(\"#booking-details\").show();\n\t\t}\n\t}",
"function getBookingItem(){\n bookingAdminDataService.getBookingItem($stateParams.id)\n .then(getBookingItemSuccess)\n .catch(errorCallback);\n }",
"function getBookings (bookingDetails) {\n var deferred = $q.defer();\n\n $http.get('/api/booking', { params: bookingDetails })\n .then (\n function (bookingsRes) {\n var bookings = bookingsRes.data;\n deferred.resolve(bookings);\n }, \n function (err) {\n // Trigger Error\n console.log('Error while getting bookings', err, null, 2);\n deferred.reject(err);\n });\n\n return deferred.promise;\n }",
"getSpaBookings() {\n return this.spaBooking;\n }",
"static getAllBookings() {\n BookingService.fetchAllBookings().then((b) => {\n BookingStore.bookings = b;\n });\n }",
"get avaiableForBooking(){\n let userData = this.store.peekAll('user-detail');\n console.log(userData);\n if (userData.length == 0) {\n this.transitionToRoute('index');\n } \n else {\n this.transitionToRoute('/ticket-booking-page/:'+this.model.id);\n } \n }",
"function refreshBookings() {\n // make api call to get all manager's bookings\n apiCall.pullManagerReservations(managerId).success(function(data) {\n if (data.message === 'No new booking') {\n $scope.showBookings = false;\n $scope.noBookingMessage = data.message;\n } else {\n $scope.managerBookings = data;\n $scope.showBookings = true;\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert from a bitArray to an array of bytes. | fromBits(arr) {
const bl = bitArray.bitLength(arr);
const byteLength = bl / 8;
const out = new Uint8Array(byteLength);
let tmp2;
for (let i = 0; i < byteLength; i++) {
if ((i & 3) === 0) {
tmp2 = arr[i / 4];
}
out[i] = tmp2 >>> 24;
tmp2 <<= 8;
}
return out;
} | [
"function bitsArrayToBytesArray(array) {\n\n for (x = 0; x < 4; x++) { // Boucle 4 fois pour les 4 bytes de 8 bits\n\n var pre_array = [];\n for (y = 0; y < 8; y++) { // Boucle 8 fois pour les 8 bits\n pre_array.push(array[0]); // On ajoute la première valeur\n array.shift(); // On supprime la première valeur\n }\n\n array.push(pre_array.join(\"\"));\n }\n\n return array;\n }",
"function convertBinary(array) {\n let binaryArray = [];\n array.forEach(function(element) {\n binaryArray.push(element.toString(2));\n });\n return binaryArray;\n}",
"fromBits(arr) {\n\t\t\tconst bl = bitArray.bitLength(arr);\n\t\t\tconst byteLength = bl / 8;\n\t\t\tconst out = new Uint8Array(byteLength);\n\t\t\tlet tmp;\n\t\t\tfor (let i = 0; i < byteLength; i++) {\n\t\t\t\tif ((i & 3) === 0) {\n\t\t\t\t\ttmp = arr[i / 4];\n\t\t\t\t}\n\t\t\t\tout[i] = tmp >>> 24;\n\t\t\t\ttmp <<= 8;\n\t\t\t}\n\t\t\treturn out;\n\t\t}",
"function packBits(array) {\n let flatArr = array.flat();\n const returnArr = [];\n\n while (flatArr.length > 0) {\n // Grab the first 8 entries (bits) and join them into a string \n // Then pad the end with zeros if it's less than 8 entries\n const bitsStr = flatArr.slice(0, 8).join('').padEnd(8, 0);\n const byte = parseInt(bitsStr, 2); // convert from binary to decimal\n returnArr.push(byte);\n\n flatArr = flatArr.slice(8);\n }\n\n return returnArr;\n}",
"fromBits(arr) {\n\t\t\t\tconst bl = bitArray.bitLength(arr);\n\t\t\t\tconst byteLength = bl / 8;\n\t\t\t\tconst out = new Uint8Array(byteLength);\n\t\t\t\tlet tmp;\n\t\t\t\tfor (let i = 0; i < byteLength; i++) {\n\t\t\t\t\tif ((i & 3) === 0) {\n\t\t\t\t\t\ttmp = arr[i / 4];\n\t\t\t\t\t}\n\t\t\t\t\tout[i] = tmp >>> 24;\n\t\t\t\t\ttmp <<= 8;\n\t\t\t\t}\n\t\t\t\treturn out;\n\t\t\t}",
"function uint8ArrayToBitArray(a) {\n return sjcl.codec.base64.toBits(nacl.util.encodeBase64(a));\n}",
"function bitArrayToUint8Array(a) {\n // TODO I'm sure there's a more efficient way to do this.\n return nacl.util.decodeBase64(sjcl.codec.base64.fromBits(a));\n }",
"function uint8ArrayToBitArray(a) {\n return sjcl.codec.base64.toBits(nacl.util.encodeBase64(a));\n }",
"function bitArrayToUint8Array(a) {\n // TODO I'm sure there's a more efficient way to do this.\n return nacl.util.decodeBase64(sjcl.codec.base64.fromBits(a));\n}",
"toBits(bytes) {\n\t\t\tconst out = [];\n\t\t\tlet i;\n\t\t\tlet tmp = 0;\n\t\t\tfor (i = 0; i < bytes.length; i++) {\n\t\t\t\ttmp = tmp << 8 | bytes[i];\n\t\t\t\tif ((i & 3) === 3) {\n\t\t\t\t\tout.push(tmp);\n\t\t\t\t\ttmp = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i & 3) {\n\t\t\t\tout.push(bitArray.partial(8 * (i & 3), tmp));\n\t\t\t}\n\t\t\treturn out;\n\t\t}",
"function toBitArrayCodec(bytes) {\n var out = [], i, tmp=0;\n for (i=0; i<bytes.length; i++) {\n tmp = tmp << 8 | bytes[i];\n if ((i&3) === 3) {\n out.push(tmp);\n tmp = 0;\n }\n }\n if (i&3) {\n out.push(sjcl.bitArray.partial(8*(i&3), tmp));\n }\n return out;\n}",
"function wordArrayToByteArray(wordArray) {\n var len = wordArray.words.length;\n if (len == 0) {\n return new Array(0);\n }\n var byteArray = new Array(wordArray.sigBytes);\n var offset = 0, word, i;\n for (i = 0; i < len - 1; i++) {\n word = wordArray.words[i];\n byteArray[offset++] = word >> 24;\n byteArray[offset++] = (word >> 16) & 0xff;\n byteArray[offset++] = (word >> 8) & 0xff;\n byteArray[offset++] = word & 0xff;\n }\n word = wordArray.words[len - 1];\n byteArray[offset++] = word >> 24;\n if (wordArray.sigBytes % 4 == 0) {\n byteArray[offset++] = (word >> 16) & 0xff;\n byteArray[offset++] = (word >> 8) & 0xff;\n byteArray[offset++] = word & 0xff;\n }\n if (wordArray.sigBytes % 4 > 1) {\n byteArray[offset++] = (word >> 16) & 0xff;\n }\n if (wordArray.sigBytes % 4 > 2) {\n byteArray[offset++] = (word >> 8) & 0xff;\n }\n return byteArray;\n}",
"function binaryStringFromUint8Array(array) {\n var binaryString = '';\n for (var i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}",
"asBinary () {\n return new Uint8Array(msgpack.encode(this.bks))\n }",
"function bnToByteArray(){var i=this.t,r=new Array;r[0]=this.s;var d,p=this.DB-i*this.DB%8,k=0;if(i-- >0)for(p<this.DB&&(d=this[i]>>p)!=(this.s&this.DM)>>p&&(r[k++]=d|this.s<<this.DB-p);i>=0;)p<8?(d=(this[i]&(1<<p)-1)<<8-p,d|=this[--i]>>(p+=this.DB-8)):(d=this[i]>>(p-=8)&255,p<=0&&(p+=this.DB,--i)),0!=(128&d)&&(d|=-256),0==k&&(128&this.s)!=(128&d)&&++k,(k>0||d!=this.s)&&(r[k++]=d);return r}",
"bytes(arr) {\n if (typeof arr === \"string\") {\n // Hex string - convert to array\n const str = arr.replace(/[\\s_:.]/g, \"\"); // Remove potential separators\n assert(str.length % 2 === 0);\n arr = [];\n for (let i = 0; i < str.length - 1; i += 2) {\n arr.push(parseInt(str.slice(i, i + 2), 16));\n }\n }\n\n const bytes = utils.backend.allocBytes(arr.length);\n bytes.set(arr);\n return utils.backend.bytesToResult(bytes, bytes.length);\n }",
"static bytesToBinary(bytes) {\r\n\t const b = [];\r\n\t for (let i = 0; i < bytes.length; i++) {\r\n\t b.push(bytes[i].toString(2).padStart(8, \"0\"));\r\n\t }\r\n\t return b.join(\"\");\r\n\t }",
"static bytesToBinary(bytes) {\r\n const b = [];\r\n for (let i = 0; i < bytes.length; i++) {\r\n b.push(bytes[i].toString(2).padStart(8, \"0\"));\r\n }\r\n return b.join(\"\");\r\n }",
"function bnToByteArray(){var i=this.t,r=new Array;r[0]=this.s;var p=this.DB-i*this.DB%8,d,k=0;if(i-- >0){if(p<this.DB&&(d=this[i]>>p)!=(this.s&this.DM)>>p)r[k++]=d|this.s<<this.DB-p;while(i>=0){if(p<8){d=(this[i]&(1<<p)-1)<<8-p;d|=this[--i]>>(p+=this.DB-8)}else{d=this[i]>>(p-=8)&255;if(p<=0){p+=this.DB;--i}}if((d&128)!=0)d|=-256;if(k==0&&(this.s&128)!=(d&128))++k;if(k>0||d!=this.s)r[k++]=d}}return r}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new break point object and add it to the list of break points. | function MakeBreakPoint(source_position, opt_script_break_point) {
var break_point = new BreakPoint(source_position, opt_script_break_point);
break_points.push(break_point);
return break_point;
} | [
"addBreak(label)\n {\n this.elements.push({\n type: \"break\",\n label: label\n });\n }",
"addPoint(point){\n\t\tthis.pointsList.push(point)\n\t}",
"function setBreakPoint(newBP) {\n\tthisBreakPoint = newBP;\n}",
"function Breakpoints() {\n this._onEditorBreakpointAdd = this._onEditorBreakpointAdd.bind(this);\n this._onEditorBreakpointRemove = this._onEditorBreakpointRemove.bind(this);\n this.addBreakpoint = this.addBreakpoint.bind(this);\n this.removeBreakpoint = this.removeBreakpoint.bind(this);\n}",
"function add_breakpoint(label){\n label = parseInt(label);\n var i = breaks.indexOf(label);\n if(i > -1){\n breaks.splice(i, 1);\n send_to_debugger({'cmd': 'rmbreak', 'ip': label});\n d3.select('#code_'+label).classed(\"break\", false);\n } else {\n breaks.push(label);\n send_to_debugger({'cmd': 'break', 'ip': label});\n d3.select('#code_'+label).classed(\"break\", true);\n }\n}",
"function addBreak() {\n setBreakTime(prevTime => prevTime < 15 ? prevTime + 1 : prevTime);\n }",
"add(minValue, data) {\n if (minValue === Number.NEGATIVE_INFINITY) this.skipSentinel = false;\n const breakpoint = this.find(minValue, false, true);\n if (breakpoint.minValue === minValue) {\n breakpoint.data = data;\n } else {\n breakpoint.append(new Breakpoint(minValue, data));\n }\n }",
"function addBreak(element) {\n var breakNode = document.createElement(\"br\");\n element.appendChild(breakNode);\n}",
"addSpawnPoint(from_, x_, y_) {\n this.spawnPoints.push({\n from: from_,\n x: x_,\n y: y_\n });\n }",
"function CreateBreakerLine() //this function makes p tag with lines of slashes \n{\n i++;\n document.querySelector('main').appendChild(window['breakerLine'+i] = document.createElement('p'));\n window['breakerLine'+i].appendChild(window['breakerTxt'+i] = document.createTextNode(\"//////////////////////////////////////\"));\n}",
"function addBreak() {\n weatherContainer.appendChild(\n document.createElement('br')\n )\n }",
"addPoint() {\n this.score++;\n SoundManager.playPickUp();\n let idx = this.gameObjects.indexOf(this.currentPoint);\n document.getElementById(\"score\").innerText = this.score.toString();\n\n this.gameObjects.splice(idx, 1);\n this.currentPoint = new PointSpawner(this.canvas.width, this.canvas.height).spawnNewPoint(this.gameObjects);\n this.gameObjects.push(this.currentPoint);\n }",
"function addBreak(el) {\n var brNode = document.createElement(\"br\");\n el.appendChild(brNode);\n}",
"addNew() {\n this.polylines.push({\n borderSize: 0,\n borderColor: '#000',\n points: [[]]\n });\n }",
"function createPoint() {\n var newPoint = new MassPoint(mouseX, mouseY);\n if (options.fixedPointCreationActivated) {\n newPoint.isFixed = true;\n }\n points.push(newPoint);\n}",
"function addToListOfPoints(point){\n var listItem = document.createElement(\"li\");\n\n listItem.className = \"list-group-item list-group-item-action point \" + point.id;\n listItem.setAttribute = (\"data-point-id\", point.id)\n listItem.innerHTML = \"<i class='fa fa-map-marker' aria-hidden='true'></i>\" + point.title;\n\n document.getElementById(\"points\").append(listItem);\n}",
"function addGoal(x, y, w, h)\n{\n var obj = new Goal(x, y, w, h);\n entlist.push(obj);\n return obj;\n}",
"function createBreak(parent) {\n\tparent.appendChild(document.createElement(\"br\"));\n}",
"addBullet() {\n // Calculate starting locations\n let bulletPos = this.pos.copy().add(this.velocity.copy().mult(10));\n\n // Add to list\n this.bullets.push(new Bullet(this.p, bulletPos, this.velocity.copy().normalize(), this.p.getBounceMode()));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create list of events at the point of a time with count of entered and left cars | function createEventList (eventsTimeline) {
return eventsTimeline.reduce(function(allEvents, event) {
// If time does not exist in array add this time with initial value 0
if (!allEvents[event.time]) {
allEvents[event.time] = 0;
}
// Counting of events at time
if (event.type === DriveOptions.ENTER_TO_PARKING) {
allEvents[event.time] += 1;
} else if (event.type === DriveOptions.LEAVE_PARKING) {
allEvents[event.time] -= 1;
}
return allEvents;
}, {});
} | [
"numberOfEvents(){\n let upComing = 0;\n let expired = 0;\n for (const [key, value] of Object.entries(this._schedule)){\n if (value[0] > new Date().getTime()){\n upComing++;\n }else {\n expired++;\n }\n }\n return [upComing, expired];\n }",
"function getCollisions(events) {\r\n //initialize 2D storage to track the count of events for every 30 mins slot and fill the values with 0.\r\n collisions = [...new Array(24)].map((_) => new Array(events.length).fill(0));\r\n\r\n events.forEach((event, id) => {\r\n let end = event.end;\r\n let start = event.start;\r\n let order = 1;\r\n\r\n while (start < end) {\r\n timeIndex = Math.floor(start / 30);\r\n while (order < events.length) {\r\n if (collisions[timeIndex].indexOf(order) === -1) {\r\n break;\r\n }\r\n order++;\r\n }\r\n\r\n collisions[timeIndex][id] = order;\r\n start = start + 30;\r\n }\r\n\r\n collisions[Math.floor((end - 1) / 30)][id] = order;\r\n });\r\n}",
"function getCollisions (events) {\n\n //resets storage\n collisions = [];\n\n for (var i = 0; i < 36; i ++) {\n var time = [];\n for (var j = 0; j < events.length; j++) {\n time.push(0);\n }\n collisions.push(time);\n }\n\n events.forEach((event, id) => {\n let end = event.end;\n let start = event.start;\n let order = 1;\n\n while (start < end) {\n timeIndex = Math.floor(start/30);\n // console.log(timeIndex);\n // console.log(\"collisions\" + collisions.length)\n while (order < events.length) {\n if (collisions[timeIndex].indexOf(order) === -1) {\n break;\n }\n order ++;\n }\n\n collisions[timeIndex][id] = order;\n start = start + 30;\n }\n\n collisions[Math.floor((end-1)/30)][id] = order;\n });\n}",
"function createEvents() {\n var tempEvents = [];\n for(var i = 0; i < Math.floor(numberGenerated * 0.5); i++) {\n tempEvents[i] = createChessEvent();\n }\n return tempEvents;\n }",
"function addPropertiesToEvents(eventList) {\n let count = 0;\n return eventList.slice().sort((a, b) => a.start - b.start).map((element) => {\n element.id = count;\n element.neighbors = 0;\n element.leftIndent = -1;\n count += 1;\n return element;\n });\n}",
"function TrackEvents( parent ) {\n this.parent = parent;\n\n this.byStart = [{\n start: -1,\n end: -1\n }];\n\n this.byEnd = [{\n start: -1,\n end: -1\n }];\n this.animating = [];\n this.startIndex = 0;\n this.endIndex = 0;\n this.previousUpdateTime = -1;\n\n Object.defineProperty( this, \"count\", {\n get: function() {\n return this.byStart.length;\n }\n });\n }",
"function CreateEventStack(events){\n var eventStack = [];\n var index = 0;\n\n events.forEach(e=>{\n eventStack.push(\n {\n event:e,\n index:index\n }\n\n );\n index += 1; \n });\n\n\n return eventStack\n}",
"function findTenFree(eventTimes, currentEventObj) {\n var tenFreeTimes = []\n var eventCounter = 0\n var dayCounter = 0\n var aDay = 86400000;\n var now = new Date().getTime();\n var time = now - now%aDay + aDay;\n var halfHour = aDay/48;\n var startTime = currentEventObj.end + 1800000\n while (dayCounter < 3) {\n eventTimes.map((eventObj) => {\n var eventTimeObject = convertMilli(eventObj)\n if(!checkConflict(eventTimeObject, {'start': startTime, 'end': startTime + halfHour})) {\n console.log('THIS IS THE event counter: ', eventCounter);\n tenFreeTimes.push(startTime)\n console.log('This is the array of shit', tenFreeTimes);\n if (eventCounter === 10) {\n console.log('THIS SHOULD BE 10: ', eventCounter);\n dayCounter = 4\n }\n eventCounter ++\n if (dayCounter === 2) {\n dayCounter = 0\n startTime = startTime - startTime%aDay + aDay + aDay/3\n }\n else {\n dayCounter++\n }\n }\n })\n }\n return tenFreeTimes\n}",
"function createEvents(array,n){\n\tconsole.log('donnees recue par la fonction');\n\tconsole.log(array);\n\tevents=[];\n\tfor(let i=0;i<n;i++){\n\t\tlet event={\n\t\t\tid:array[i].id,\n\t\t\tname:array[i].name,\n\t\t\tdistance:Math.floor(array[i].distance),\n\t\t\tstatus:array[i].status,\n\t\t\tgroup: array[i].group.name,\n\t\t\turl: array[i].event_url,\n\t\t\tdate: array[i].time,\n\t\t\tfees: array[i].fee?array[i].fee.amount.toPrecision(3):'',\n\t\t\tcurrency: array[i].fee?array[i].fee.currency:''\n\t\t};\n\t\tevents.push(event);\n\t}\n\n\t//For smartphones screens\n\tif (window.innerWidth <= 767){\n\t\tgetEventsNearMeSmallScreens(events,n);\n\t\tsortResults();\n\t}\n\t//For screens larger than 767px\n\tif (window.innerWidth > 767){\n\t\tgetEventsNearMeLargeScreens(events,n);\n\t\tsortResults();\n\t}\n\n}",
"function updateAndSortLunchEvents(events) {\r\n let meObj = {};\r\n events.map((value, index) => {\r\n if (index === 0) {\r\n // store the first object which is 'Me' object\r\n meObj = value;\r\n // set the title and default for 'Me' event object\r\n meObj[\"title\"] = NIKKI_LUNCH_EVENT_TITLE;\r\n meObj[\"color\"] = \"Black\";\r\n } else {\r\n // set the title and default for other event object\r\n value[\"title\"] = OTHERS_LUNCH_EVENT_TITLE;\r\n value[\"color\"] = \"#3c5ecb\"; //blue\r\n if (value.start - meObj.start < 0 && value.end > 255) {\r\n //overlapping by atleast 30 minutes\r\n //set the color green and push to target\r\n meObj[\"color\"] = \"#388b60\"; //green\r\n value[\"color\"] = \"#388b60\"; //green\r\n }\r\n }\r\n });\r\n //sort events based on start time\r\n events.sort((a, b) => {\r\n return a.start - b.start;\r\n });\r\n}",
"function make_events(events_array){\n \n //sort by start time, id's are unimportant really\n events_array.sort(sort_by_start_time);\n \n //loop over each object in the input array\n var counter = 1;\n $.each(events_array, function(){\n //Set additional attributes\n this.title = \"Sample Event \" + counter;\n this.location = \"Event Location \" + counter;\n this.duration = this.end - this.start;\n this.top_position = this.start;\n this.width = 0;\n this.left;\n this.collision_members = new Array();\n counter++; //just convenience here for display purposes\n });\n \n // set the left position and width of each event\n $.each(events_array, function(){set_position(this, events_array);});\n \n return events_array;\n } //end make_events() function",
"function TrackEvents( parent ) {\n this.parent = parent;\n\n this.byStart = [{\n start: -1,\n end: -1\n }];\n\n this.byEnd = [{\n start: -1,\n end: -1\n }];\n this.animating = [];\n this.startIndex = 0;\n this.endIndex = 0;\n this.previousUpdateTime = -1;\n\n this.count = 1;\n }",
"function putEvents() {\r\n var eventName = document.getElementById(\"eventName\").value;\r\n var start = document.getElementById(\"start_time\").value;\r\n var end = document.getElementById(\"end_time\").value;\r\n var days = [];\r\n document.querySelectorAll('input[type=\"checkbox\"]:checked').forEach(function (element) {\r\n days.push(element.value);\r\n });\r\n addEvents(eventName, start, end, days, false);\r\n}",
"function getCollisions (events) {\n\n //resets storage\n collisions = [];\n\n for (var i = 0; i < 24; i ++) {\n var time = [];\n for (var j = 0; j < events.length; j++) {\n time.push(0);\n }\n collisions.push(time);\n }\n\n events.forEach((event, id) => {\n let end = event.end;\n let start = event.start;\n let order = 1;\n\n while (start < end) {\n timeIndex = Math.floor(start/30);\n\n while (order < events.length) {\n if (collisions[timeIndex].indexOf(order) === -1) {\n break;\n }\n order ++;\n }\n\n collisions[timeIndex][id] = order;\n start = start + 30;\n }\n\n collisions[Math.floor((end-1)/30)][id] = order;\n });\n}",
"function splitRoomEvent(event) {\n var events = [];\n\n var start = moment(event.start);\n var end = momentTime(event.start, closingTimeStr);\n\n while (!start.isSame(event.end, \"day\")) {\n events.push(_.extend({}, event, {\n start: start,\n end: end\n }));\n start = momentTime(start, openingTimeStr).add(1, \"day\");\n end = moment(end).add(1, \"day\");\n }\n events.push(_.extend({}, event, {\n start: start,\n end: event.end\n }));\n\n return events;\n }",
"function createTimeCards(){\n let events = $('.event');\n events.each(function(){\n let eventColor = $(this).find('.info').css('background-color'),\n eventId = $(this).find('.info').data('id'),\n eventTime = $(this).find('.event-time').attr('placeholder'),\n countBoxTime = timeConversation(eventTime);\n createTimeCardsFromOneEvent(eventColor, eventId, countBoxTime);\n });\n}",
"initializeTimeEvents() {\n let l = this.system.timeEvents.length;\n this.timeEventsEllapsed = new Array(l);\n for (let i = 0; i < l; i++) {\n this.timeEventsEllapsed[i] = [this.system.timeEvents[i], new Date()\n .getTime()];\n }\n }",
"calcEvents () {\n this.calcVars()\n\n this.events.length = 0\n\n for (let [from, to, varKey] of this.varEvents) {\n let val = this.var[varKey] * this.compartment[from]\n this.events.push([from, to, val])\n }\n\n for (let [from, to, paramKey] of this.paramEvents) {\n let val = this.param[paramKey] * this.compartment[from]\n this.events.push([from, to, val])\n }\n }",
"function layOutDay(events)\n{\n\t//turn times into pixels\n\tvar start_time = 9;\n\tvar end_time = 21;\n\tfor(var x = 0;x<events.length;x++)\n\t{\n\t\tvar start_hour = parseInt(events[x]['start'].split(\":\")[0]);\n\t\tvar start_minutes = parseInt(events[x]['start'].split(\":\")[1]);\n\n\t\tvar end_hour = parseInt(events[x]['end'].split(\":\")[0]);\n\t\tvar end_minutes = parseInt(events[x]['end'].split(\":\")[1]);\n\n\t\tevents[x]['start'] = ((start_hour-start_time)*60)+start_minutes;\n\t\tevents[x]['end'] = ((end_hour-start_time)*60)+end_minutes;\n\t}\n\t\n\n\tvar iterate_list = events //list to iterate through\n\tvar aligned_list = new Array(); //already aligned\n\tvar unaligned_list = new Array(); //still to align\n\n\titerate_list.sort(function(a,b) { return a.start - b.start }); //sort based on start time\n\n\tdegree = 1; //all events start out as if they are the only one in that timeslot.\n\n\t//iterate through events until all of them have been aligned\n\twhile(iterate_list.length > 0)\n\t{\t\n\t\t//go through sorted events based on start time\n\t\tfor(var i=0;i<iterate_list.length;i++)\n\t\t{\n\t\t\tfor(var j=i;j<iterate_list.length;j++) //iterate onwards\n\t\t\t{\n\t\t\t\t//if already in the unaligned list, don't check.\n\t\t\t\tif(unaligned_list.indexOf(iterate_list[j])!=-1)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\tFirst event on that degree/level will always have a left-most position because it has been sorted on start time.(i==j)\n\t\t\t\tfind the first event that has a start time great than initial end time\n\t\t\t\t*/\n\t\t\t\tif(iterate_list[j]['start'] > iterate_list[i]['end'] || i==j) \n\t\t\t\t{\n\t\t\t\t\tif(aligned_list.indexOf(iterate_list[j])==-1)\n\t\t\t\t\t{\n\t\t\t\t\t\t//add event to aligned list.\t\n\t\t\t\t\t\titerate_list[j]['degree'] = degree;\n\t\t\t\t\t\titerate_list[j]['position'] = degree;\n\n\t\t\t\t\t\t//iterate through aligned list to determine whether to increase the degree of the already aligned events.\n\t\t\t\t\t\tfor(var a = 0;a<aligned_list.length;a++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(iterate_list[j]['start'] <= aligned_list[a]['end'] && iterate_list[j]['end'] >= aligned_list[a]['start'])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\taligned_list[a]['degree'] = degree;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\taligned_list.push(iterate_list[j]);\n\t\t\t\t\t\t\n\t\t\t\t\t\t//now continue checking onwards from this event.\n\t\t\t\t\t\ti=j-1\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//add event to unaligned list.\n\t\t\t\t\tunaligned_list.push(iterate_list[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\titerate_list = unaligned_list;\n\t\tunaligned_list = new Array();\n\t\tdegree++; //now start iterating on the level.\n\t}\n\n\t/*\n\tFinal recalibration.\n\tSome degrees are not properly calibrated because not all events overlap directly.\n\tLook back at the previous element and if it collides, change degree to match.\n\t*/\n\taligned_list.sort(function(a,b) { return a.start - b.start});\n\tfor(var i=1;i<aligned_list.length;i++)\n\t{\n\t\tif(aligned_list[i]['start'] <= aligned_list[i-1]['end'])\n\t\t{\n\t\t\tif(aligned_list[i]['degree'] < aligned_list[i-1]['degree'])\n\t\t\t{\n\t\t\t\taligned_list[i]['degree'] = aligned_list[i-1]['degree'];\n\t\t\t}\n\t\t\telse if(aligned_list[i]['degree'] > aligned_list[i-1]['degree'])\n\t\t\t{\n\t\t\t\taligned_list[i-1]['degree'] = aligned_list[i]['degree'];\n\t\t\t}\n\t\t}\n\t}\n\n\tvar c_width = 600; //calendar width\n\t//iterate through events and add width/left top positions.\n\tfor(var i in aligned_list)\n\t{\n\t\tevents[i]['top'] = aligned_list[i]['start']; //top pixel is the start time\n\t\tevents[i]['left'] = c_width/aligned_list[i]['degree']*(aligned_list[i]['position']-1); //Left most pixel\n\t\tevents[i]['width'] = c_width/aligned_list[i]['degree']-1;\n\t}\n\n\treturn events;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To select Originator for the launched form. Arguments: None Sample Call: SP_SelectOriginatorLaunched(); Note: To use this function following keywords fields are necessary: SELECT field with name "mastercontrol.task.originator" and INPUT field with name "mastercontrol.form.currentuser" | function SP_SelectOriginatorLaunched()
{
var oListOriginator = document.getElementById("mastercontrol.task.originator");
var sCurrentUser = document.getElementById("mastercontrol.form.currentuser").value.toLowerCase();
var i;
var sItemValue = "";
for (i=0; i<oListOriginator.length;i++)
{
sItemValue = oListOriginator[i].value;
if (sItemValue.toLowerCase() === sCurrentUser)
{
oListOriginator.selectedIndex = i;
break;
}
}
} | [
"function SP_SetTaskCreator()\n{\n\tvar creatorName = document.getElementById(\"mastercontrol.form.creatorname\").value;\n\tvar creatorId = document.getElementById(\"mastercontrol.form.creator\").value;\n\tvar creator = document.getElementById(arguments[0]);\n\tcreator.value = creatorName+\" (\"+creatorId+\")\";\t\n}",
"function setRequestorInfo(){\n\t\n\tvar requestPanel = View.panels.get(\"requestPanel\");\n\tvar requestorValue = requestPanel.getFieldValue(\"activity_log.requestor\");\n\t\n\t\n\ttry {\n\t\tvar result = Workflow.callMethod('AbBldgOpsHelpDesk-RequestsService-getRequestorInformation', requestorValue);\n\t}catch(e){\n\t\tWorkflow.handleError(e);\n\t}\n\t\n\tif(result.code == 'executed'){\n\t\tvar res = eval('('+result.jsonExpression+')');\n\t\tif(res != null){\n\t\t\t\n\t\t\t\n\t\t\t//KB3043720 - clear phone number before select new requestor\n\t\t\trequestPanel.setFieldValue(\"activity_log.phone_requestor\",'');\n\t\t\trequestPanel.setFieldValue(\"activity_log.dv_id\",'');\n\t\t\trequestPanel.setFieldValue(\"activity_log.dp_id\",'');\n\t\t\t\n\t\t\tif(res.phone != undefined)\n\t\t\t\trequestPanel.setFieldValue(\"activity_log.phone_requestor\",res.phone);\n\t\t\t\n\t\t\tif(res.dv_id != undefined)\n\t\t\t\trequestPanel.setFieldValue(\"activity_log.dv_id\",res.dv_id);\n\t\t\t\t\n\t\t\tif(res.dp_id != undefined)\n\t\t\t\trequestPanel.setFieldValue(\"activity_log.dp_id\",res.dp_id);\n\t\t}\n\t} else {\n\t\tWorkflow.handleError(result);\n\t}\n}",
"get originator()\n {\n if( \"originator\" in this.callinfo )\n {\n return true == this.callinfo.originator\n }\n return false\n }",
"function selectCraftsperson(){\n var workTeamId = ondemandPanel.getFieldValue(\"helpdesk_sla_response.work_team_id\");\n var supervisor = ondemandPanel.getFieldValue(\"helpdesk_sla_response.supervisor\");\n var sql = \"cf.assign_work = 1\";\n if (workTeamId) {\n sql += \" AND cf.work_team_id='\" + workTeamId + \"'\";\n }\n else \n if (supervisor) {\n sql += \" AND cf.work_team_id = (SELECT work_team_id FROM cf WHERE email = (SELECT email FROM em WHERE em_id = '\" + supervisor + \"'))\";\n }\n View.selectValue('panel_ondemand_response', getMessage('craftsperson'), ['helpdesk_sla_response.cf_id'], 'cf', ['cf.cf_id'], ['cf.cf_id', 'cf.name', 'cf.tr_id', 'cf.work_team_id'], sql);\n}",
"function selectRecipients() {\n window.parent.$(\"mail_task[user_ids]\").value = $F(\"user_ids\");\n}",
"function handleOriginSelect(e) {\n props.setOrigin(e.target.value);\n }",
"function SP_MapERapprovers()\n{\n \t//Setting Extension Request Approvers to be passed\n \tvar ERApproverList = document.getElementById(arguments[0]);\n \tvar users = \"\";\n \tvar userId = \"\"; \n \tvar ListOption = \"\";\n\tif(ERApproverList.length != 0)\n\t{\n\t\tfor(var i=0; i<ERApproverList.length; i++)\n\t\t{\n\t\t ListOption = ERApproverList.options[i];\n\t\t if(SP_Trim(ListOption.value)!=\"\" )\n\t\t {\n\t\t\t userId = SP_GetUserID(ListOption.value);\n\t\t\t users += userId +\"*\"; \n\t\t }\n\t\t}\n\t}\n document.getElementById(arguments[1]).value = users;\n}",
"function takeSelectedApplicant() {\n\tofferToApplicant = getURLParameter(\"AID\");\n\n\tvar username = tmpApplicantUserName; // wird in function\n\t// markOfferSelected(id)\n\t// initialisiert\n\n\t// alert(\"username: \"+username);\n\n\tconnect(\"/hiwi/Provider/js/takeSelectedApplicant\", \"aid=\"\n\t\t\t+ offerToApplicant + \"&usernameTakenApplicant=\" + username,\n\t\t\thandleTakeSelectedApplicantResponse);\n\n}",
"function getOriginatorList(){\n var callback = {\n success: getOriginatorListcallback,\n failure: showError\n };\n var data = composePostDataFromUiDisputeTab();\n YAHOO.util.Connect.asyncRequest(\"POST\", \"getOriginatorListAndReturnJSON.action\", callback, data);\n}",
"function changeRole(){\n\trole = $(\"#role\").val();\n\n\tif (role==\"Host Site Coordinator\"){\n\t\tdocument.getElementById(\"associated-hostsite-area\").style.display = 'block';\n\t}\n\telse{\n\t\t$(\"#associated-site\").val(\"--Select--\")\n\t\tdocument.getElementById(\"associated-hostsite-area\").style.display = 'none';\n\t}\n}",
"function onPageInitFromQuoteForm(){\r\n\tif(isCreate()){\r\n\t\tnlapiSetFieldValue(LEAD_SOURCE,'');\r\n\t}\r\n}",
"function CallerLocationForm() {\r\n this.callerLocation = null; \r\n //Append to variable dictionary\r\n this._variableDict['callerLocation'] = 'caller_location';\r\n}",
"function showDistributorList(distributors) {\n\n var distributorsBox = $(\"#distributor_choice\").get(0);\n\n var referrerCodeEdit = $(\"#referrer_code\").get(0);\n\n // handle empty list in reply\n\n if ((distributors === undefined) || (distributors.length === 0)) {\n\n // hide the distributor box and show the referrer code box,\n\n $(\"#distributor_choice_div\").hide();\n\n $(\"#referrer_code_div\").show();\n\n distributorsBox.value = 0;\n\n referrerCodeEdit.value = '';\n\n } else {\n\n // a single distributor for a country\n\n if (distributors.length == 1) {\n\n // don't show distributor list\n\n $(\"#referrer_code_div\").hide();\n\n $(\"#distributor_choice_div\").hide();\n\n } else {\n\n // for >1 distributor, show distributor list\n\n $(\"#distributor_choice_div\").show();\n\n $(\"#referrer_code_div\").hide();\n\n }\n\n // remove all previous dropdown box options\n\n distributorsBox.options.length = 0;\n\n // fill with options from the distributor list\n\n for ( var distributorIndex = 0; distributorIndex < distributors.length; distributorIndex++ ) {\n\n //alert(distributors.length);\n\n distributorsBox.options[distributorIndex] = new Option(\n\n distributors[distributorIndex][0],\t// label\n\n distributors[distributorIndex][1]);\t// value\n\n }\n\n var oQry = new Querystring();\n\n var referrerCode = oQry.get( 'referrer_code', '');\n\n if (referrerCode !== '') {\n\n // if this form is recalled after an error, referrer_code is set in the query string\n\n // in this case re-select the previously selected distributor\n\n distributorsBox.value = referrerCode;\n\n } else {\n\n // otherwise select \"other\" variant\n\n // need to set via .selectedIndex, not .value, because referrer codes\n\n // are not unique\n\n distributorsBox.selectedIndex = distributors.length - 1;\n\n distributorsBox.options[distributorsBox.selectedIndex].text = OTHER_DISTRIBUTOR;\n\n }\n\n applyDistributor();\n\n }\n\n}",
"function SP_SelectRouteLaunched(routeName, listFieldId) {\n var oListRoute = document.getElementById(listFieldId),\n \tisRouteExist = false,\n \titemFace,\n \ti = 0,\n \tl = oListRoute.length;\n\t\n\toListRoute.disabled = false;\n\n\tfor (/*i = 0, l = oListRoute.length*/; i < l; ++i) {\n\t\titemFace = oListRoute[i].text;\n\n\t\tif (itemFace.toLowerCase() === routeName.toLowerCase()) {\n \t oListRoute.selectedIndex = i;\n\t\t\tisRouteExist = true;\n\t\t break; \n }\n\t}\n\t\n\tif (!isRouteExist) {\n\t\tif (typeof message === \"object\") {\n\t\t\talert(message.task_launch);\n\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\talert(\"The task you are trying to launch is not available.\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}",
"getOrigin() {\n const currentFlightPlan = this._flightPlans[this._currentFlightPlanIndex];\n return currentFlightPlan.originAirfield;\n }",
"function saveCurrentUser(){\n\tcommLogController.commForm.setFieldValue(\"ls_comm.recorded_by\", View.user.name);\n}",
"setOrigin(originValue) {\n this.retrievedOrigin = originValue;\n }",
"function targetOrigin() {\n return messageEvent.origin === 'null'\n ? options.targetOrigin\n : messageEvent.origin;\n }",
"function planFormCaller() {\n plan.planForm();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Catalog contains zero or more multilayer datasets One layer is always "active", corresponding to the currently selected layer in the GUI or the current target in the CLI | function Catalog() {
var datasets = [],
defaultTargets = [];// saved default command targets [{layers:[], dataset}, ...]
this.forEachLayer = function(cb) {
var i = 0;
datasets.forEach(function(dataset) {
dataset.layers.forEach(function(lyr) {
cb(lyr, dataset, i++);
});
});
};
// remove a layer from a dataset
this.deleteLayer = function(lyr, dataset) {
// if deleting first target layer (selected in gui) -- switch to some other layer
if (this.getActiveLayer().layer == lyr) {
defaultTargets = [];
}
// remove layer from its dataset
dataset.layers.splice(dataset.layers.indexOf(lyr), 1);
if (dataset.layers.length === 0) {
this.removeDataset(dataset);
}
// remove layer from defaultTargets
defaultTargets = defaultTargets.filter(function(targ) {
var i = targ.layers.indexOf(lyr);
if (i == -1) return true;
targ.layers.splice(i, 1);
return targ.layers.length > 0;
});
};
// @arg: a layer object or a test function
this.findLayer = function(arg) {
var test = typeof arg == 'function' ? arg : null;
var found = null;
this.forEachLayer(function(lyr, dataset) {
if (test ? test(lyr, dataset) : lyr == arg) {
found = layerObject(lyr, dataset);
}
});
return found;
};
this.findCommandTargets = function(pattern, type) {
if (!pattern) return this.getDefaultTargets() || [];
return findCommandTargets(this.getLayers(), pattern, type);
};
this.findSingleLayer = function(pattern) {
var matches = findMatchingLayers(this.getLayers(), pattern);
if (matches.length > 1) {
stop('Ambiguous pattern (multiple layers were matched):', pattern);
}
return matches[0] || null;
};
this.removeDataset = function(dataset) {
defaultTargets = defaultTargets.filter(function(targ) {
return targ.dataset != dataset;
});
datasets = datasets.filter(function(d) {
return d != dataset;
});
};
this.getDatasets = function() {
return datasets;
};
this.getLayers = function() {
var layers = [];
this.forEachLayer(function(lyr, dataset) {
layers.push(layerObject(lyr, dataset));
});
return layers;
};
this.addDataset = function(dataset) {
this.setDefaultTarget(dataset.layers, dataset);
return this;
};
this.findNextLayer = function(lyr) {
var layers = this.getLayers(),
idx = indexOfLayer(lyr, layers);
return idx > -1 ? layers[(idx + 1) % layers.length] : null;
};
this.findPrevLayer = function(lyr) {
var layers = this.getLayers(),
idx = indexOfLayer(lyr, layers);
return idx > -1 ? layers[(idx - 1 + layers.length) % layers.length] : null;
};
this.isEmpty = function() {
return datasets.length === 0;
};
this.getDefaultTargets = function() {
if (defaultTargets.length === 0 && !this.isEmpty()) {
defaultTargets = [{dataset: datasets[0], layers: datasets[0].layers.slice(0, 1)}];
}
return defaultTargets;
};
this.setDefaultTarget = function(layers, dataset) {
if (datasets.indexOf(dataset) == -1) {
datasets.push(dataset);
}
defaultTargets = [{
// Copy layers array, in case layers is a reference to dataset.layers.
// This prevents layers that are added to the dataset inside a command from
// being added to the next command's target, e.g. debugging layers added
// by '-join unmatched unjoined'.
layers: layers.concat(),
dataset: dataset
}];
};
this.setDefaultTargets = function(arr) {
defaultTargets = arr;
};
// should be in gui-model.js, moved here for testing
this.getActiveLayer = function() {
var targ = (this.getDefaultTargets() || [])[0];
// var lyr = targ.layers[0];
// Reasons to select the last layer of a multi-layer target:
// * This layer was imported last
// * This layer is displayed on top of other layers
// * This layer is at the top of the layers list
// * In TopoJSON input, it makes sense to think of the last object/layer
// as the topmost one -- it corresponds to the painter's algorithm and
// the way that objects are ordered in SVG.
var lyr = targ.layers[targ.layers.length - 1];
return targ ? {layer: lyr, dataset: targ.dataset} : null;
};
function layerObject(lyr, dataset) {
return {
layer: lyr,
dataset: dataset
};
}
function indexOfLayer(lyr, layers) {
var idx = -1;
layers.forEach(function(o, i) {
if (o.layer == lyr) idx = i;
});
return idx;
}
} | [
"setActiveLayer(layer) {\r\n this.activeLayer = layer;\r\n }",
"function getCurrentLayers() {\nvar comp = getCurrentComp();\nif (!comp) return null;\nvar layers = comp.selectedLayers;\nif (!layers.length)\n{\nalert(tr(\"No selected layer.\\nPlease select a layer/property.\"));\nreturn null;\n}\nreturn layers;\n}",
"getActiveLayer(mode) {\n return this.findWhere({\n active: true,\n category: mode\n });\n }",
"showLayers(layers) {\n layers.forEach(layer => layer.show());\n }",
"function getSelectedLayers()\n{\n var layers = getSelectedLayersInfo();\n\n // if we _really_ want to get artLayers we can select them one by one with IDs\n for (var i = 0; i < layers.length; i++)\n {\n selectByID(layers[i].id);\n // alert(app.activeDocument.activeLayer.name);\n }\n \n // and reselecting everything back\n for (var i = 0; i < layers.length; i++)\n {\n selectByID(layers[i].id, true);\n }\n \n}",
"toggleBaseLayer(layer) {\n for (var i = 0; i < this.baseLayers.length; i++) {\n this.baseLayers[i].setVisible(false)\n }\n\n layer.setVisible(true)\n this.selectedBaseLayer = layer.get('title');\n\n }",
"function setActiveLayers() {\n activeLayers = Array();\n for(var i = 0; i < layers.length; i++) {\n if(layers[i].visibility) {\n activeLayers.push(\"\"+i);\n }\n }\n updateAnchor();\n}",
"activator() {\n this.toolManager.selectedTool.activate(this.layerManager.selectedLayer);\n }",
"triggerToggleLayer() {\n const { dataset } = this.state;\n this.props.toggleDatasetActive(dataset.id);\n this.props.layersHidden.includes(dataset.id) && this.hideLayer(dataset.id);\n }",
"selectLayer(layer) {\n this.canvas.setActiveObject(layer);\n }",
"function selectVisibleLayer(name) {\n layers.forEach(layer => layer.setVisible(false));\n layers[layersName.findIndex(layer => layer === 'vector')].setVisible(true);\n layersName.forEach(layer => {\n if (layer !== 'vector') {\n document.getElementById(layer).setAttribute('class', 'col-3 btn btn-secondary btn-lg');\n }\n });\n document.getElementById(name).setAttribute('class', 'col-3 btn btn-primary btn-lg');\n layers[layersName.findIndex(layer => layer === name)].setVisible(true);\n}",
"setActiveLayer(mode, slug) {\n let specs = this.toJSON();\n specs.filter(layer => layer.category === mode)\n .forEach(layer => {\n const isActive = layer.slug === slug;\n layer.active = isActive;\n\n if(isActive && ENVIRONMENT === 'production') {\n /* Google Analytics */\n ga('send', 'event', 'Map', 'Toggle', layer.name);\n }\n });\n this.set(specs);\n this.trigger('change');\n }",
"function GetCurrentLayer() {\n var layer = null;\n switch (currentLayer) {\n case \"event\":\n layer = eventsLayer;\n break;\n case \"todo\":\n layer = todoLayer;\n break;\n case \"food\":\n layer = foodLayer;\n break;\n case \"shelter\":\n layer = shelterLayer;\n break;\n case \"other\":\n layer = otherLayer;\n break;\n default:\n layer = null;\n break;\n }\n layer.name = currentLayer;\n\n return layer;\n }",
"function showLayerServices() {\n var layer = $(this).closest(\".addLayer\").data(\"layer\");\n LayerServiceView.show(layer);\n }",
"onlyDisplayValidLayers() {\n const validSource = 'regional';\n\n // get the layer list from the config file\n const { TMSLayers } = mapConfig;\n const layers = store.getStateItem('mapLayerDisplayStatus');\n\n // filter the layers based on current source\n Object.keys(layers).forEach((layer) => {\n const asource = TMSLayers.filter(TMSlayer => (\n TMSlayer.id === layer && TMSlayer.source === validSource\n ));\n\n // layer is on and not part of the tabs data so it needs to be off\n if (layers[layer] && asource.length === 0) {\n this.mapComponent.toggleVisLayerOff(layer);\n }\n\n // layer is on IS part of the tabs data os it needs to be on\n if (layers[layer] && asource.length > 0) {\n this.mapComponent.toggleVisLayerOn(layer);\n }\n });\n }",
"function onLayerButtonClick(type,num) {\n let layer = viewer.dataSources.getByName(type + '_' + num)[0];\n Cesium.when(layer).then(it=>{\n if (it){\n it.show = !it.show;\n }\n else{\n loadGeoJSON([num],type)\n }\n })\n}",
"function contextSelectAlternateLayers()\n\t\t{\n\t\t\tvar context = Context.create();\n\t\t\tfor(var i = 0; i < context.timeline.layerCount; i+=2)\n\t\t\t{\n\t\t\t\tcontext.setLayer(i).select(true)\n\t\t\t\ttrace(context)\n\t\t\t}\n\t\t}",
"getLayer() {\n // At this point, loading is still true\n const widgetConfig = this.getWidgetConfig();\n\n fetch(`${process.env.WRI_API_URL}/layer/${widgetConfig.layer_id}`, {\n headers: {\n 'Upgrade-Insecure-Requests': 1\n }\n })\n .then((res) => {\n if (res.ok) return res.json();\n throw new Error(res.statusText);\n })\n .then(({ data }) => {\n this.setState({\n layers: [{\n dataset: data.attributes.dataset,\n visible: true,\n layers: [{\n id: data.id,\n active: true,\n ...data.attributes\n }]\n }]\n });\n })\n .catch(err => this.setState({ error: err.message }))\n // We remove the loader because the map will render\n // right away\n .then(() => this.setState({ loading: false }));\n }",
"selectDeselectAllLayers() {\n me.btnSelectDeseletClicked = !me.btnSelectDeseletClicked;\n me.compoData.layers.forEach(layer => layer.checked = me.btnSelectDeseletClicked);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a resolver is defined, it must be a function. | function isValidResolver(resolver) {
return resolver == null || typeof resolver === 'function';
} | [
"function isValidResolver(resolver) {\n return resolver == null || typeof resolver === 'function';\n }",
"function isVariantResolver(variant) {\n return typeof variant === \"function\";\n}",
"function Resolver() {}",
"function ResolvedFunctionType() {\n}",
"function toResolver(resolve) {\n return typeof resolve.resolve === 'function' ? resolve : {\n supports,\n resolve\n };\n} // Catch-all resolvers support everything",
"getRegistryResolver(): Function {\n const Resolver = registryResolvers[this.registry];\n if (Resolver) {\n return Resolver;\n } else {\n throw new MessageError(this.reporter.lang('unknownRegistryResolver', this.registry));\n }\n }",
"resolveFunction(js) {\n return _.isFunction(js) ? this.resolveFunction(js()) : js;\n }",
"bindResolve (fn, fieldDef) {\n if (!fn) return\n\n const resolve = _.isString(fn)\n ? _.get(this.functions, `[\"${fn}\"]`)\n : fn\n\n if (!_.isFunction(resolve)) {\n this.error = new Error('GraphQLFactoryGenerateError: No resolve found')\n return\n }\n\n // return the middleware resolvers\n return (source, args, context, info) => {\n // build a new context\n const ctx = _.assign({}, this._context, { fieldDef }, context)\n\n // create a request object\n const req = {\n source,\n args,\n context: ctx,\n info,\n reroutes: 0\n }\n\n // call the middleware\n return middleware(this, resolve, req)\n }\n }",
"function resolve(value) {\n\t\t\treturn typeof value === 'function' ? value() : value;\n\t\t}",
"function isTypeResolver(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfn) {\n // 1. A type provider must be a function\n if (typeof fn !== 'function')\n return false;\n // 2. A class constructor is not a type provider\n if (/^class/.test(fn.toString()))\n return false;\n // 3. Built-in types like Date & Array are not type providers\n if (isBuiltinType(fn))\n return false;\n // TODO(bajtos): support model classes defined via ES5 constructor function\n return true;\n}",
"function evaluateDesignSystemResolver(arg, designSystem) {\n return typeof arg === 'function' ? arg(designSystem) : arg;\n}",
"function ImplResolver() {\n}",
"function evaluateDesignSystemResolver(arg, designSystem) {\n return typeof arg === \"function\" ? arg(designSystem) : arg;\n}",
"function getResolver({ operation, argsFromLink = {}, payloadName, data, baseUrl, requestOptions }) {\n // Determine the appropriate URL:\n if (typeof baseUrl === 'undefined') {\n baseUrl = Oas3Tools.getBaseUrl(operation);\n }\n // Return custom resolver if it is defined\n const customResolvers = data.options.customResolvers;\n const title = operation.oas.info.title;\n const path = operation.path;\n const method = operation.method;\n if (typeof customResolvers === 'object' &&\n typeof customResolvers[title] === 'object' &&\n typeof customResolvers[title][path] === 'object' &&\n typeof customResolvers[title][path][method] === 'function') {\n translationLog(`Use custom resolver for ${operation.operationString}`);\n return customResolvers[title][path][method];\n }\n // Return resolve function:\n return (root, args, ctx, info = {}) => {\n /**\n * Retch resolveData from possibly existing _openapiToGraphql\n *\n * NOTE: _openapiToGraphql is an object used to pass security info and data\n * from previous resolvers\n */\n let resolveData = {};\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] === 'object' &&\n typeof root['_openapiToGraphql'].data === 'object') {\n const parentIdentifier = getParentIdentifier(info);\n if (!(parentIdentifier.length === 0) &&\n parentIdentifier in root['_openapiToGraphql'].data) {\n /**\n * Resolving link params may change the usedParams, but these changes\n * should not be present in the parent _openapiToGraphql, therefore copy\n * the object\n */\n resolveData = JSON.parse(JSON.stringify(root['_openapiToGraphql'].data[parentIdentifier]));\n }\n }\n if (typeof resolveData.usedParams === 'undefined') {\n resolveData.usedParams = {};\n }\n /**\n * Handle default values of parameters, if they have not yet been defined by\n * the user.\n */\n operation.parameters.forEach(param => {\n const paramName = Oas3Tools.sanitize(param.name, Oas3Tools.CaseStyle.camelCase);\n if (typeof args[paramName] === 'undefined' &&\n param.schema &&\n typeof param.schema === 'object') {\n let schema = param.schema;\n if (schema && schema.$ref && typeof schema.$ref === 'string') {\n schema = Oas3Tools.resolveRef(schema.$ref, operation.oas);\n }\n if (schema &&\n schema.default &&\n typeof schema.default !== 'undefined') {\n args[paramName] = schema.default;\n }\n }\n });\n // Handle arguments provided by links\n for (let paramName in argsFromLink) {\n let value = argsFromLink[paramName];\n let paramNameWithoutLocation = paramName;\n if (paramName.indexOf('.') !== -1) {\n paramNameWithoutLocation = paramName.split('.')[1];\n }\n /**\n * see if the link parameter contains constants that are appended to the link parameter\n *\n * e.g. instead of:\n * $response.body#/employerId\n *\n * it could be:\n * abc_{$response.body#/employerId}\n */\n if (value.search(/{|}/) === -1) {\n args[paramNameWithoutLocation] = isRuntimeExpression(value)\n ? resolveLinkParameter(paramName, value, resolveData, root, args)\n : value;\n }\n else {\n // Replace link parameters with appropriate values\n const linkParams = value.match(/{([^}]*)}/g);\n linkParams.forEach(linkParam => {\n value = value.replace(linkParam, resolveLinkParameter(paramName, linkParam.substring(1, linkParam.length - 1), resolveData, root, args));\n });\n args[paramNameWithoutLocation] = value;\n }\n }\n // Stored used parameters to future requests:\n resolveData.usedParams = Object.assign(resolveData.usedParams, args);\n // Build URL (i.e., fill in path parameters):\n const { path, query, headers } = Oas3Tools.instantiatePathAndGetQuery(operation.path, operation.parameters, args);\n const url = baseUrl + path;\n /**\n * The Content-type and accept property should not be changed because the\n * object type has already been created and unlike these properties, it\n * cannot be easily changed\n *\n * NOTE: This may cause the user to encounter unexpected changes\n */\n headers['content-type'] =\n typeof operation.payloadContentType !== 'undefined'\n ? operation.payloadContentType\n : 'application/json';\n headers['accept'] =\n typeof operation.responseContentType !== 'undefined'\n ? operation.responseContentType\n : 'application/json';\n let options = {\n url,\n method: operation.method\n };\n if (requestOptions) {\n options = Object.assign(Object.assign({}, options), requestOptions);\n if (requestOptions.headers) {\n if (typeof requestOptions.headers === 'object') {\n Object.assign(requestOptions.headers, headers);\n }\n else if (typeof requestOptions.headers === 'function') {\n options.headers = requestOptions.headers({\n context: ctx,\n method,\n path,\n title\n });\n }\n }\n else {\n options['headers'] = headers;\n }\n if (options.qs) {\n Object.assign(options.qs, query);\n }\n else {\n options['qs'] = query;\n }\n }\n else {\n options = {\n method: operation.method,\n url: url,\n headers: headers,\n qs: query\n };\n }\n /**\n * Determine possible payload\n *\n * GraphQL produces sanitized payload names, so we have to sanitize before\n * lookup here\n */\n resolveData.usedPayload = undefined;\n if (payloadName && typeof payloadName === 'string') {\n const sanePayloadName = Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);\n if (sanePayloadName in args) {\n if (typeof args[sanePayloadName] === 'object') {\n // We need to desanitize the payload so the API understands it:\n const rawPayload = JSON.stringify(Oas3Tools.desanitizeObjKeys(args[sanePayloadName], data.saneMap));\n options.body = rawPayload;\n resolveData.usedPayload = rawPayload;\n }\n else {\n // Payload is not an object (stored as an application/json)\n const rawPayload = args[sanePayloadName];\n options.body = rawPayload;\n resolveData.usedPayload = rawPayload;\n }\n }\n }\n /**\n * Pass on OpenAPI-to-GraphQL options\n */\n if (typeof data.options === 'object') {\n // Headers:\n if (typeof data.options.headers === 'object' &&\n (!requestOptions || !requestOptions.headers)) {\n for (let header in data.options.headers) {\n const val = data.options.headers[header];\n options.headers[header] = val;\n }\n }\n // Query string:\n if (typeof data.options.qs === 'object') {\n for (let query in data.options.qs) {\n const val = data.options.qs[query];\n options.qs[query] = val;\n }\n }\n }\n // Get authentication headers and query parameters\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] == 'object') {\n const { authHeaders, authQs, authCookie } = getAuthOptions(operation, root['_openapiToGraphql'], data);\n // ...and pass them to the options\n Object.assign(options.headers, authHeaders);\n Object.assign(options.qs, authQs);\n // Add authentication cookie if created\n if (authCookie !== null) {\n const j = NodeRequest.jar();\n j.setCookie(authCookie, options.url);\n options.jar = j;\n }\n }\n // Extract OAuth token from context (if available)\n if (data.options.sendOAuthTokenInQuery) {\n const oauthQueryObj = createOAuthQS(data, ctx);\n Object.assign(options.qs, oauthQueryObj);\n }\n else {\n const oauthHeader = createOAuthHeader(data, ctx);\n Object.assign(options.headers, oauthHeader);\n }\n resolveData.usedRequestOptions = options;\n resolveData.usedStatusCode = operation.statusCode;\n // Make the call\n httpLog(`Call ${options.method.toUpperCase()} ${options.url}?${querystring.stringify(options.qs)}\\n` +\n `headers:${JSON.stringify(options.headers)}`);\n return new Promise((resolve, reject) => {\n NodeRequest(options, (err, response, body) => {\n if (err) {\n httpLog(err);\n reject(err);\n }\n else if (response.statusCode < 200 || response.statusCode > 299) {\n httpLog(`${response.statusCode} - ${Oas3Tools.trim(body, 100)}`);\n const errorString = `Could not invoke operation ${operation.operationString}`;\n if (data.options.provideErrorExtensions) {\n let responseBody;\n try {\n responseBody = JSON.parse(body);\n }\n catch (e) {\n responseBody = body;\n }\n const extensions = {\n method: operation.method,\n path: operation.path,\n statusCode: response.statusCode,\n responseHeaders: response.headers,\n responseBody\n };\n reject(graphQLErrorWithExtensions(errorString, extensions));\n }\n else {\n reject(new Error(errorString));\n }\n // Successful response 200-299\n }\n else {\n httpLog(`${response.statusCode} - ${Oas3Tools.trim(body, 100)}`);\n if (response.headers['content-type']) {\n /**\n * Throw warning if the non-application/json content does not\n * match the OAS.\n *\n * Use an inclusion test in case of charset\n *\n * i.e. text/plain; charset=utf-8\n */\n if (!(response.headers['content-type'].includes(operation.responseContentType) ||\n operation.responseContentType.includes(response.headers['content-type']))) {\n const errorString = `Operation ` +\n `${operation.operationString} ` +\n `should have a content-type '${operation.responseContentType}' ` +\n `but has '${response.headers['content-type']}' instead`;\n httpLog(errorString);\n reject(errorString);\n }\n else {\n /**\n * If the response body is type JSON, then parse it\n *\n * content-type may not be necessarily 'application/json' it can be\n * 'application/json; charset=utf-8' for example\n */\n if (response.headers['content-type'].includes('application/json')) {\n let responseBody;\n try {\n responseBody = JSON.parse(body);\n }\n catch (e) {\n const errorString = `Cannot JSON parse response body of ` +\n `operation ${operation.operationString} ` +\n `even though it has content-type 'application/json'`;\n httpLog(errorString);\n reject(errorString);\n }\n resolveData.responseHeaders = response.headers;\n // Deal with the fact that the server might send unsanitized data\n let saneData = Oas3Tools.sanitizeObjKeys(responseBody);\n // Pass on _openapiToGraphql to subsequent resolvers\n if (saneData && typeof saneData === 'object') {\n if (Array.isArray(saneData)) {\n saneData.forEach(element => {\n if (typeof element['_openapiToGraphql'] === 'undefined') {\n element['_openapiToGraphql'] = {\n data: {}\n };\n }\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] == 'object') {\n Object.assign(element['_openapiToGraphql'], root['_openapiToGraphql']);\n }\n element['_openapiToGraphql'].data[getIdentifier(info)] = resolveData;\n });\n }\n else {\n if (typeof saneData['_openapiToGraphql'] === 'undefined') {\n saneData['_openapiToGraphql'] = {\n data: {}\n };\n }\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] == 'object') {\n Object.assign(saneData['_openapiToGraphql'], root['_openapiToGraphql']);\n }\n saneData['_openapiToGraphql'].data[getIdentifier(info)] = resolveData;\n }\n }\n // Apply limit argument\n if (data.options.addLimitArgument &&\n /**\n * NOTE: Does not differentiate between autogenerated args and\n * preexisting args\n *\n * Ensure that there is not preexisting 'limit' argument\n */\n !operation.parameters.find(parameter => {\n return parameter.name === 'limit';\n }) &&\n // Only array data\n Array.isArray(saneData) &&\n // Only array of objects/arrays\n saneData.some(data => {\n return typeof data === 'object';\n })) {\n let arraySaneData = saneData;\n if ('limit' in args) {\n const limit = args['limit'];\n if (limit >= 0) {\n arraySaneData = arraySaneData.slice(0, limit);\n }\n else {\n reject(new Error(`Auto-generated 'limit' argument must be greater than or equal to 0`));\n }\n }\n else {\n reject(new Error(`Cannot get value for auto-generated 'limit' argument`));\n }\n saneData = arraySaneData;\n }\n resolve(saneData);\n }\n else {\n // TODO: Handle YAML\n resolve(body);\n }\n }\n }\n else {\n /**\n * Check to see if there is not supposed to be a response body,\n * if that is the case, that would explain why there is not\n * a content-type\n */\n const { responseContentType } = Oas3Tools.getResponseObject(operation, operation.statusCode, operation.oas);\n if (responseContentType === null) {\n resolve(null);\n }\n else {\n const errorString = 'Response does not have a Content-Type property';\n httpLog(errorString);\n reject(errorString);\n }\n }\n }\n });\n });\n };\n}",
"function resolver (value, resolve) {\n\t\t\tresolved[resolved.length] = value;\n\n\t\t\tif (resolved.length === deps.length) {\n\t\t\t\tresolve(resolved)\n\t\t\t}\n\t\t}",
"function register(resolver) {\n if (resolvers.indexOf(resolver) < 0)\n resolvers.push(resolver);\n }",
"_initResolver () {\n Resolver.setTypes(this.types)\n }",
"function resolver (value, resolve) {\n\t\t\tresolved[resolved.length] = value;\n\t\n\t\t\tif (resolved.length === deps.length) {\n\t\t\t\tresolve(resolved);\n\t\t\t}\n\t\t}",
"callback(value) {\n return this.registerResolver(3\n /* callback */\n , value);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
implPath :: Array String > Nullable Function | function implPath(path) {
return _funcPath (false, path, implementations);
} | [
"function implPath(path) {\n return _funcPath(false, path, implementations);\n }",
"isPath(value) {\n return Array.isArray(value) && (value.length === 0 || typeof value[0] === \"number\");\n }",
"function arrayifyPath(path) {\n return path.replace(/\\.(\\d)\\./g, '._arr[$1].');\n}",
"isPath(value) {\n return Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number');\n }",
"extendArrayWithPaths (array, path) {\n if (array.length && path) {\n const extendedArray = []\n array.forEach(function (value) {\n extendedArray.push(`${path}/${value}`)\n })\n return extendedArray\n }\n }",
"getPathElements() {\n return FsFile.getPathElements(this.path)\n }",
"_pathAt(paths, index) {\n return paths[index] || paths[0];\n }",
"function pathToString(arr) {\n return arr.join('');\n }",
"function PathMapper() {\n\t}",
"function PathUtils () {\n}",
"function PebblesPath(path) {\n if (!(this instanceof PebblesPath)) {\n return new PebblesPath(path);\n }\n if (path instanceof PebblesPath) {\n return new PebblesPath(path.toArray());\n }\n path || (path = []);\n if (!Array.isArray(path)) {\n return new PebblesPath(path.split(\".\"));\n }\n // The path is represented as an array internally\n this._path = path || [];\n}",
"function genArrayPath (pathObj, dbCache) {\n var seedn = pathObj.options.seedn || 1;\n if (typeof seedn == 'function') seedn = seedn.call(mchance);\n var innerSeed = mchance.path.bind(mchance, pathObj.caster, dbCache);\n return mchance.n(innerSeed, seedn).filter(function (elem) {\n return elem !== undefined;\n });\n }",
"function getKeyPathCore(keyOrPath) {\n if (keyOrPath === undefined) {\n return [];\n }\n\n if (typeof keyOrPath === 'string' ||\n typeof keyOrPath === 'number') {\n return [keyOrPath];\n }\n\n if (Array.isArray(keyOrPath)) {\n return keyOrPath;\n }\n\n return notKeyOrPath;\n}",
"getPath() {\n let path = null;\n try {\n path = this.stringTuples().filter((tuple) => {\n const proto = protocols_1.protocols(tuple[0]);\n if (proto.path) {\n return true;\n }\n })[0][1];\n }\n catch (e) {\n path = null;\n }\n return path;\n }",
"buildPath(components) {\n if (components == []) {\n return;\n }\n let comparray = [\"\"]\n components.map(element => {\n if (element) {\n comparray.push(element)\n }\n })\n return comparray.join('/').toString();\n }",
"function d3c_path() {\n var paths = [], i = 0;\n \n function path() {\n return path.toString();\n }\n \n path.push = function (_type, coordinates) {\n paths.push(_type);\n i = 1;\n while (i < arguments.length) {\n paths.push(arguments[i]);\n i++;\n }\n return path;\n };\n \n path.toString = function () {\n return paths.join(' ');\n };\n \n return path;\n}",
"static getPathFromPathElements(pathElements) {\n return pathElements.join(PATH_SEPARATOR)\n }",
"function funcPath(path, x) {\n return _funcPath (true, path, x);\n }",
"function PathContestProvider() {\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make this function return the least expensive item. | function leastExpensive(items) {
var current2 = groceries[0].cost;
for(var i = 0; i < groceries.length; i++){
if(groceries[i].cost < current2) {
current2 = groceries[i].cost;
}
}
return current2;
} | [
"function leastExpensive(items) {\n var leastExpensiveItem = items[0];\n for (var i = 0; i < items.length; i++) {\n if (items[i].cost < leastExpensiveItem.cost) {\n leastExpensiveItem = items[i];\n }\n }\n return leastExpensiveItem;\n}",
"function MinimumItem()\r\n{\r\n var minitem, min = 100000000;\r\n e = (new VBArray(Q.Keys())).toArray();\r\n for (key in e)\r\n {\r\n x = e[key];\r\n if (Estimate.Item(x) < min)\r\n {\r\n minitem = x;\r\n min = Estimate.Item(x);\r\n }\r\n }\r\n return minitem;\r\n}",
"function mostExpensive(items) {\n var mostExpensiveItem = items[0];\n for (var i = 1; i < items.length; i++) {\n if (items[i].cost > mostExpensiveItem.cost) {\n mostExpensiveItem = items[i];\n }\n }\n return mostExpensiveItem;\n}",
"function mostSpentOnItem(obj){\n let mostExpensiveItem = false;\n for(let i = 0; i < obj.items.length; i++){\n if(!mostExpensiveItem || (obj.items[i].price * obj.items[i].quantity) > (mostExpensiveItem.price * mostExpensiveItem.quantity)){\n mostExpensiveItem = obj.items[i];\n }\n }\n return mostExpensiveItem;\n}",
"get cheapestBeer() {\n\t\tif (!this.beers.length) {\n\t\t\treturn this.minPriceHappy ? this.minPrice ? Math.min(this.minPrice, this.minPriceHappy) : this.minPriceHappy : this.minPriceHappy;\n\t\t};\n\t\tlet cheapestBeer = Math.min.apply(null, this.beers.map(b => {\n\t\t\treturn Math.min.apply(null, b.pricing.map(beer => {\n\t\t\t\treturn beer.priceHappy ? beer.priceBeer ? Math.min(beer.priceHappy, beer.priceBeer) : beer.priceHappy : beer.priceBeer;\n\t\t\t}));\n\t\t}));\n\t\treturn cheapestBeer;\n\t}",
"function mostExpensiveItem(products) {\n let product = products[0];\n\n for (let i = 1; i < products.length; i++) {\n const newProduct = products[i];\n if (product.priceInCents < newProduct.priceInCents) {\n product = newProduct;\n }\n }\n\n return product;\n}",
"function mostExpensive(items) {\n var current = groceries[0].cost;\n for(var i = 0; i < groceries.length; i++){\n if(groceries[i].cost > current) {\n current = groceries[i].cost;\n }\n }\n return current;\n}",
"function getLowest() {\n var lowest = openList[0];\n for (var i = 0; i < openList.length; i++) {\n if (openList[i].fCost < lowest.fCost) {\n lowest = openList[i];\n }\n }\n return lowest;\n}",
"function lowestPriceBook(leastExpensiveBookHere){\n //takes in the above defined array of objects \"books\"\n //returns the object containing the title, price, and author of the book with the lowest priced book.\n var floating = Math.isinf;// tried this but isn't required\n var leastExpensive = {\n \"price\": Infinity, // float('inf') == Infinity\n }\n for (let i = 0; i < leastExpensiveBookHere.length; i++) {\n if (leastExpensiveBookHere[i].price < leastExpensive.price){\n leastExpensive = leastExpensiveBookHere[i];\n }\n }\n return leastExpensive;// shows us what is most expensive book\n}",
"function getBestBuilding() {\r\n //TODO Remove cost from return\r\n var min = Infinity;\r\n var payback;\r\n var Building;\r\n for (i in Game.Objects)\r\n if ((payback = getPaybackAjustedValue(Game.Objects[i].price, Game.Objects[i].storedCps)) < min) {\r\n min = payback;\r\n Building = Game.Objects[i];\r\n }\r\n if (min == Infinity && Building == undefined) //This happens when game is new and there are no buildings\r\n return [1, Game.Objects[\"Cursor\"]];\r\n return [min, Building];\r\n}",
"function expensivePhone(phones) {\n let expensive=phones[0];\n for(const phone of phones){\n if (phone.price>expensive.price) {\n expensive=phone;\n }\n }\n return expensive;\n}",
"getBestPrice(product) {\n let lowestPrice = null;\n this.market.sellers.forEach(seller => {\n if (seller.inventory.hasOwnProperty(product)) {\n const price = seller.quote(product);\n if (lowestPrice === null || lowestPrice > price) lowestPrice = price;\n }\n });\n\n return lowestPrice || 0;\n }",
"function mostExpensiveItemName(arr=items){\n result = arr.reduce((a,{price})=>price>a?price:a,0)\n item = arr[arr.findIndex(obj=>obj.price===result)]\n return item.itemName\n}",
"function cheapestItem(products) {\r\n const itemWithLowestPrice = [];\r\n const prices = products.map((product) => {\r\n return product.price;\r\n });\r\n const lowestPrice = Math.min(...prices);\r\n for (let i = 0; i < products.length; i++) {\r\n if (products[i].price === lowestPrice) {\r\n itemWithLowestPrice.push(products[i]);\r\n }\r\n }\r\n //convert from JavaScript object to a JSON string\r\n return JSON.stringify(itemWithLowestPrice);\r\n}",
"function getLowestPrice() {\n // $scope.self.formProcessing = true;\n if (!$scope.auction || !$scope.auction.id) {\n return;\n }\n auctionManager.one($scope.auction.id).one('price').one('next').get()\n .then(\n function (data) {\n $scope.self.lowestPrice = data[0];\n $scope.model.price = data[0];\n },\n function (error) {\n $scope.self.lowestPrice = 0;\n $scope.model.price = 0;\n });\n }",
"static getCost (item) { return item }",
"min() {\n let min = 100000;\n for (let a = 0; a < this.size(); a++) {\n if (this.v[a] < min) {\n min = this.v[a];\n }\n }\n return min;\n }",
"function getMinimum(){\n var currentMinimumIndex = -1;\n var currentBestWeight = 2000;\n //Loop through and find the minimum weight\n for(var i = 0; i < frontier.length; i++){\n if(frontier[i].weight < currentBestWeight){\n currentBestWeight = frontier[i].weight;\n currentMinimumIndex = i;\n }\n }\n\n //Error Check\n if(currentMinimumIndex == -1){\n console.log(\"Wuh woah: Error line 92 - Frontier is empty, yet was still called\");\n } else {\n //Return the minimum\n var temp = frontier.splice(currentMinimumIndex,1)[0];\n //console.log(\"Removed \" + temp.x + \" \" + temp.y);\n return temp;\n }\n \n }",
"smallestOf(collection) {\n if (!assert.isDefined(collection, \"spellCore.smallestOf(collection)\")) return undefined\n if (spellCore.itemCountOf(collection) === 0) return undefined\n const values = spellCore.valuesOf(collection)\n return values.reduce((smallest, next) => (next < smallest ? next : smallest), values[0])\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Represents a Wix Activity Type, representing both the schema definition and the Wix Activity name | function ActivityType(name, schema) {
/**
* The name of the Activity Schema
* @member
* @readonly
*/
this.name = name;
/**
* The path to the Activity JSON Schema
* @member
* @readonly
*/
this.schema = schema;
} | [
"function WixActivity() {\n\n /**\n * Updates to the existing contact that performed this activity. The structure of this object should match the schema for Contact, with the relevant fields updated.\n * @member\n * @type {Object}\n */\n this.contactUpdate = schemaFactory(this.TYPES.CONTACT_CREATE.name);\n /**\n * Configures this Activity with a given type\n * @param {ActivityType} type the type of the Activity to create\n * @returns {WixActivity}\n */\n this.withActivityType = function(type) {\n this.activityType = type.name;\n this.activityInfo = schemaFactory(type.name);\n return this;\n };\n\n /**\n * Configures the activityLocationUrl of this Activity\n * @param {string} url The URL of the Activities location\n * @returns {WixActivity}\n */\n this.withLocationUrl = function(url) {\n this.activityLocationUrl = url;\n return this;\n };\n\n /**\n * Configures the details of this Activity\n * @param {string} summary A summary of this Activity\n * @param {string} additionalInfoUrl a link to additional information about this Activity\n * @returns {WixActivity}\n */\n this.withActivityDetails = function(summary, additionalInfoUrl) {\n if(summary !== null && summary !== undefined) {\n this.activityDetails.summary = summary;\n }\n if(additionalInfoUrl !== null && additionalInfoUrl !== undefined) {\n this.activityDetails.additionalInfoUrl = additionalInfoUrl;\n }\n return this;\n };\n\n var readOnlyTypes = [\n this.TYPES.CONTACT_CREATE.name\n ];\n this.isWritable = function() {\n return (readOnlyTypes.indexOf(this.activityType) == -1);\n };\n\n this.isValid = function() {\n //TODO provide slightly better validation\n return this.activityLocationUrl !== null\n && this.activityType !== null\n && this.activityDetails.summary !== null\n && this.createdAt !== null\n && this.activityDetails.additionalInfoUrl !== null;\n };\n\n /**\n * Posts the Activity to Wix. Returns a Promise for an id\n * @param {string} sessionToken The current session token for the active Wix site visitor\n * @param {Wix} wix A Wix API object\n * @returns {Promise.<string, error>} A new id, or an error\n */\n this.post = function(sessionToken, wix) {\n return wix.Activities.postActivity(this, sessionToken);\n };\n\n function removeNulls(obj){\n var isArray = obj instanceof Array;\n for (var k in obj){\n if (obj[k]===null) isArray ? obj.splice(k,1) : delete obj[k];\n else if (typeof obj[k]==\"object\") removeNulls(obj[k]);\n }\n }\n\n this.toJSON = function() {\n var _this = this;\n removeNulls(_this.contactUpdate);\n removeNulls(_this.activityInfo);\n return {\n createdAt : _this.createdAt,\n activityType : _this.activityType,\n contactUpdate : _this.contactUpdate,\n activityLocationUrl : _this.activityLocationUrl,\n activityDetails : _this.activityDetails,\n activityInfo: _this.activityInfo\n };\n };\n}",
"function WixActivityData() {\n /**\n * Information about the Activity\n * @typedef {Object} WixActivityData.ActivityDetails\n * @property {?String} additionalInfoUrl Url linking to more specific contextual information about the activity for use in the Dashboard\n * @property {?string} summary A short description about the activity for use in the Dashboard\n */\n\n /**\n * The id of the Activity\n * @member WixActivityData#id\n * @type {string}\n */\n\n /**\n * A timestamp to indicate when this Activity took place\n * @member\n * @type {Date}\n */\n this.createdAt = new Date().toISOString();\n\n /**\n * The URL where the activity was performed\n * @member\n * @type {String}\n */\n this.activityLocationUrl = null;\n\n /**\n * Information about the Activity\n * @member\n * @type {WixActivityData.ActivityDetails}\n */\n this.activityDetails = {summary : null, additionalInfoUrl : null};\n\n /**\n * The type of Activity\n * @member\n * @type {string}\n */\n this.activityType = null;\n\n /**\n * Schema information about the Activity\n * @member\n * @type {Object}\n */\n this.activityInfo = null;\n /**\n * @private\n */\n this.init = function(obj) {\n this.activityType = { name: obj.activityType };\n this.activityDetails = obj.activityDetails;\n this.activityInfo = obj.activityInfo;\n this.id = obj.id;\n this.activityLocationUrl = obj.activityLocationUrl;\n this.createdAt = obj.createdAt;\n return this;\n };\n}",
"function Activity() {\n this.name = null;\n this.active = false;\n this.data = {};\n this.allowedTypes = {\n image: false,\n video: false,\n both: false\n };\n debug('initialized');\n}",
"function createTypingActivity() {\n return { type: index_1.ActivityTypes.Typing };\n }",
"function Activity(name,length,typeid,description){\n\tvar _name = name;\n\tvar _length = length;\n\tvar _typeid = typeid;\n\tvar _description = description;\n\t\n\t// sets the name of the activity\n\tthis.setName = function(name) {\n\t\t_name = name;\n\t}\n\n\t// get the name of the activity\n\tthis.getName = function(name) {\n\t\treturn _name;\n\t}\n\t\n\t// sets the length of the activity\n\tthis.setLength = function(length) {\n\t\t_length = length;\n\t}\n\n\t// get the name of the activity\n\tthis.getLength = function() {\n\t\treturn _length;\n\t}\n\t\n\t// sets the typeid of the activity\n\tthis.setTypeId = function(typeid) {\n\t\t_typeid = typeid;\n\t}\n\n\t// get the type id of the activity\n\tthis.getTypeId = function() {\n\t\treturn _typeid;\n\t}\n\t\n\t// sets the description of the activity\n\tthis.setDescription = function(description) {\n\t\t_description = description;\n\t}\n\n\t// get the description of the activity\n\tthis.getDescription = function() {\n\t\treturn _description;\n\t}\n\t\n\t// This method returns the string representation of the\n\t// activity type.\n\tthis.getType = function () {\n\t\treturn ActivityType[_typeid];\n\t};\n}",
"function createEventActivity() {\n return { type: index_1.ActivityTypes.Event };\n }",
"static typing() {\n return { type: botbuilder_core_1.ActivityTypes.Typing };\n }",
"static get __resourceType() {\n\t\treturn 'CarePlanActivity';\n\t}",
"createActivityWidget(type) {\n let element = document.createElement(\"li\", {\n is: type.bindingName,\n });\n\n if (element) {\n element.setAttribute(\"actID\", type.id);\n }\n\n return element;\n }",
"function isActivity(source, activityType) {\n /*\n * NOTE: This code was migrated from .NET implementation applying optimizations to make\n * it more verbose. The goal is to have zero allocations because it is called by all\n * of the .asXXXActivity methods to \"pseudo-cast\" the activity based on its type.\n */\n const type = source.type;\n // If there's no type set then we can't tell if it's the type they're looking for\n if (type == undefined || typeof type !== 'string') {\n return false;\n }\n // Check if the full type value starts with the type they're looking for\n let result = type.toUpperCase().startsWith(activityType.toUpperCase());\n // If the full type value starts with the type they're looking for, then we need to check if it's definitely the right type\n if (result) {\n // If the lengths are equal, then it's the exact type they're looking for\n result = type.length === activityType.length;\n }\n if (!result) {\n // Finally, if the type is longer than the type they're looking for then we need to check if there's a / separator right after the type they're looking for\n result = type.length > activityType.length && type[activityType.length] === '/';\n }\n return result;\n }",
"function ActionType() { }",
"static get __resourceType() {\n\t\treturn 'ActivityDefinitionDynamicValue';\n\t}",
"function GetBodySchedule(activity){\n\tvar activityType = \"\";\n\tswitch(activity)\n\t{\n\t\tcase \"freestyle\":\n \t\t\tactivityType = \"Freestyle\";\n \t\t\tbreak;\n\t\tcase \"SkateLessons\":\n\t\t\tactivityType = \"Class\";\n\t\t\tbreak;\n case \"Public\":\n \t\tactivityType = \"Public\";\n\t\t\tbreak;\n\t}\n\n}",
"function createInvokeActivity() {\n return { type: index_1.ActivityTypes.Invoke };\n }",
"function getActivityObject(activityType, orderId, lineItemUid) {\n switch (activityType) {\n case \"ACTIVATE\":\n return {\n activateActivityDetails: {\n orderId,\n lineItemUid\n }\n };\n case \"LOAD\":\n return {\n loadActivityDetails: {\n orderId,\n lineItemUid\n }\n };\n // Add more Gift Card Activities types you wish to support here!\n default:\n console.error(\"Unrecognized type\");\n }\n}",
"constructor(type, actions = [], condition) {\n super(adaptiveEvents_1.AdaptiveEvents.activityReceived, actions, condition);\n this.type = type;\n }",
"function createHandoffActivity() {\n return { type: index_1.ActivityTypes.Handoff };\n }",
"function createContactRelationUpdateActivity() {\n return { type: index_1.ActivityTypes.ContactRelationUpdate };\n }",
"function createMessageActivity() {\n return { type: index_1.ActivityTypes.Message };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test whether an input object is 1D. Assumes we already know the object is an array. Looks only at the first element, if the dimensionality is not consistent we won't figure that out here. | function isArray1D(a) {
return !isArrayOrTypedArray(a[0]);
} | [
"__is_1D_array(arr) {\n if ((typeof (arr[0]) == \"number\") || (typeof (arr[0]) == \"string\") || (typeof (arr[0]) == \"boolean\")) {\n return true\n } else {\n return false\n }\n }",
"function isArray1D(a) {\n return !isArrayOrTypedArray(a[0]);\n }",
"function isArray1D(a) {\n return !isArrayOrTypedArray(a[0]);\n}",
"function isSingleDim(matrix) {\r\n return matrix[0][0] == undefined\r\n}",
"function isSingleDim(matrix) {\r\n\treturn matrix[0][0] == undefined\r\n}",
"is1d() {\n return this.dimension == \"1d\";\n }",
"function validateMatrix1D(X) {\r\n if (!util_1.isArray(X)) {\r\n throw new Errors_1.ValidationError('validateMatrix1D has received a non-array argument');\r\n }\r\n var shape = tensors_1.inferShape(X);\r\n if (shape.length !== 1 || shape[0] === 0) {\r\n throw new Errors_1.Validation1DMatrixError(\"The matrix is not 1D shaped: \" + JSON.stringify(X) + \" of \" + JSON.stringify(shape));\r\n }\r\n return X;\r\n}",
"function is_array(input){\n\t\t\t \n\t\t\t return typeof (input) =='object' && (input instanceof Array);\n\t\t\t \n\t\t\t}",
"function likeArray(obj) {\n return obj && typeof obj === \"object\" && typeof obj.length === \"number\";\n }",
"function isArrayOfShapes(x) {\n return Array.isArray(x) && Array.isArray(x[0]);\n}",
"function isArr(obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n}",
"function is2DArray(s) {\n var pattern = /type\\s=\\s.*\\s[[0-9]*][[0-9]*]/;\n return pattern.test(s);\n}",
"function is_array(input) {\n if (toString.call(input) === \"[object Array]\") {\n return true;\n } else {\n return false;\n }\n }",
"static isSingle(coordinates) {\n if (!coordinates[0]) {\n console.log(coordinates);\n }\n return !Array.isArray(coordinates[0][0][0]);\n }",
"function is_array(input) {\n if (Object.prototype.toString.call(input) === \"[object Array]\") {\n return true;\n }\n return false;\n}",
"function is_array(obj){\n return Array.isArray(obj)\n\n}",
"function check(obj) {\n if (Object.prototype.toString.call(obj) === \"[object Array]\") {\n return true;\n } else {\n return false;\n }\n}",
"static isSingle(coordinates) {\n return !Array.isArray(coordinates[0][0]);\n }",
"function isMatrixLikeArray(arr) {\n\t if (!_.isArray(arr)) return false;\n\t if (arr.length <= 0) return false;\n\n\t if (!_.isArray(arr[0])) return false;\n\t var m = arr.length, n = arr[0].length;\n\t if (n <= 0) return false;\n\n\t var i;\n\t for (i = 1; i < m; ++i)\n\t if (!_.isArray(arr[i]) || arr[i].length !== n) return false;\n\n\t return true;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of titles that were launched in 2015. field: title_year | function titlesFrom2015() {
let movies15 = [];
data.map((movie)=>{
if (movie.title_year === 2015){
movies15++
}
return null;
});
return movies15;
} | [
"function titlesFrom2015() {\n let count = 0;\n data.forEach(obj => {\n if(obj.title_year === 2015) {\n count += 1\n }\n })\n return count;\n}",
"function titlesFrom2015() {\n let movies2015 = 0;\n data.map((movie) => {\n if (movie.title_year === 2015) movies2015 += 1;\n return null;\n });\n return movies2015;\n}",
"function getYearCount(metadata) {\n const timesPlayed = metadata.game_info.times_played;\n timesPlayed.forEach((time) => {\n const date = time.date_year.trim();\n\n // checks if the date is already in the \"playedByYears\" array\n // if it is it bumps the count by one and if not it pushes a new item to the array\n if (includesChild(playedByYear, date)[0]) {\n const statsPos = includesChild(playedByYear, date)[1];\n const statsCount = playedByYear[statsPos].count;\n playedByYear[statsPos].count = statsCount + 1;\n } else {\n playedByYear.push({\n label: date,\n count: 1\n });\n }\n });\n }",
"function count_songs(year) {\n\tvar count = 0\n\tfor (var i= 0; i < songs.length; i++) {\n\t\tif (songs[i].year >= year && songs[i].year < year + 10)\n\t\t\tcount = count +1\n\t}\nreturn count\n}",
"function countByYear(items, year) {\n var count = _.countBy(items, function(i) {\n return i === year;\n });\n return count.true || 0; // lodash count returns true and false counts\n }",
"function showsInGivenYear(year)\n{\n return getNumberOfShowsInYear(new Date(year,0,1));\n \n \n}",
"function countYears(arrayToCount) {\r\n\treturn arrayToCount[arrayToCount.length - 1].year - arrayToCount[0].year + 1\r\n}",
"function numberOfMatchesInEveryYear(matches) {\n const numberOfMatchPlayedPerYear = matches.reduce(\n (matchPerYear, matchObj) => {\n matchPerYear[matchObj.season] = (matchPerYear[matchObj.season] || 0) + 1;\n return matchPerYear;\n },\n {}\n );\n return numberOfMatchPlayedPerYear;\n}",
"function movieAge(title){\n return getMovie(title)\n .then((movie) =>( new Date()).getFullYear()- movie.Year)\n .then((year) => console.log(year))\n }",
"function getYears(data) {\n var countYears=0;\n $.each(data.features[0].properties, function(k, v){\n if(k[0]==\"y\") {\n countYears += 1;\n }\n })\n return countYears;\n}",
"function getTitleDates() {\n var links = document.evaluate(\n \"//a[contains(@href,'/year/')]/text()\",\n document,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null);\n\n year = new Date();\n year.setFullYear(links.snapshotItem(0).data);\n return year;\n}",
"function getYearOccurStatistics(records) {\n return getOccurStatistics(records, function(record) {\n return record.occurred_date.year.toString();\n });\n}",
"function showYearTitles() {\n // Another way to do this would be to create\n // the year texts once and then just hide them.\n let yearsData = d3.keys(yearsTitleX);\n let years = svg.selectAll('.year').data(yearsData);\n\n years\n .enter()\n .append('text')\n .attr('class', 'year')\n .attr('x', function (d) {\n return yearsTitleX[d];\n })\n .attr('y', 40)\n .attr('text-anchor', 'middle')\n .text(function (d) {\n return d;\n });\n }",
"function getMatchesPlayedPerYear(matches) {\n return matches.reduce((matchesPerYear, match) => {\n const season = match.season;\n if (matchesPerYear.hasOwnProperty(season)) {\n matchesPerYear[season] += 1;\n } else {\n matchesPerYear[season] = 1;\n }\n return matchesPerYear;\n }, {});\n}",
"function extractYearsFromEventTitle(title) {\n var regex = new RegExp(\"\\\\(.*\\\\)\", \"g\");\n var years = regex.exec(title)[0];\n return years.replace('(', '').replace(')', '');\n}",
"'getVotingCount'(year) {\n var query = Votings.find({ [year]: { $exists: true } }, { fields: { [year]: 1, \"votedBy\": 1, \"_id\": 0 } }).fetch();\n return query.length;\n }",
"function pageTitle(data) {\n\tvar amount = data.length\n var year = getCurrentYear()\n var amountYr = countCurrentYear(data, year)\n\tvar contents = Sheetsee.ich.title({\n \tnumBooks: amount,\n currentYear: year,\n numBooksYr: amountYr\n\t})\n$('#title').html(contents)\n}",
"function sortYears() {\n benji.json(\"/graphsdata\", data => {\n //console.log(data);\n\n var yearBuilt = data.map(data => data.yearbuilt);\n // console.log(yearBuilt);\n \n // Code help from Andy\n yearBuilt.forEach(row => {\n\n for (let i = 0; i < decadeLength; i++) {\n\n if (row.includes(decade[i])) {\n count[i] = count[i] + 1;\n }\n }\n });\n // console.log(decade);\n //console.log(count);\n});\n}",
"calculateMatchPerYear (matches) {\n const matchesPerYear = {};\n\n for(match of matches) {\n if(match.season in matchesPerYear) {\n matchesPerYear[match.season] += 1;\n } else {\n matchesPerYear[match.season] = 1;\n }\n }\n return matchesPerYear;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the resize direction | function getDirection(e) {
var opts = $(e.data.target).resizable('options');
var tt = $(e.data.target);
var dir = '';
var offset = tt.offset();
var width = tt.outerWidth();
var height = tt.outerHeight();
var edge = opts.edge;
if (e.pageY > offset.top && e.pageY < offset.top + edge) {
dir += 'n';
} else if (e.pageY < offset.top + height && e.pageY > offset.top + height - edge) {
dir += 's';
}
if (e.pageX > offset.left && e.pageX < offset.left + edge) {
dir += 'w';
} else if (e.pageX < offset.left + width && e.pageX > offset.left + width - edge) {
dir += 'e';
}
var handles = opts.handles.split(',');
handles = $.map(handles, function(h){return $.trim(h).toLowerCase();});
if ($.inArray('all', handles) >= 0 || $.inArray(dir, handles) >= 0){
return dir;
}
for(var i=0; i<dir.length; i++){
var index = $.inArray(dir.substr(i,1), handles);
if (index >= 0){
return handles[index];
}
}
return '';
} | [
"function getDirection(e) {\r\n\t\tvar opts = $(e.data.target).resizable('options');\r\n\t\tvar tt = $(e.data.target);\r\n\t\tvar dir = '';\r\n\t\tvar offset = tt.offset();\r\n\t\tvar width = tt.outerWidth();\r\n\t\tvar height = tt.outerHeight();\r\n\t\tvar edge = opts.edge;\r\n\t\tif (e.pageY > offset.top && e.pageY < offset.top + edge) {\r\n\t\t\tdir += 'n';\r\n\t\t} else if (e.pageY < offset.top + height && e.pageY > offset.top + height - edge) {\r\n\t\t\tdir += 's';\r\n\t\t}\r\n\t\tif (e.pageX > offset.left && e.pageX < offset.left + edge) {\r\n\t\t\tdir += 'w';\r\n\t\t} else if (e.pageX < offset.left + width && e.pageX > offset.left + width - edge) {\r\n\t\t\tdir += 'e';\r\n\t\t}\r\n\t\t\r\n\t\tvar handles = opts.handles.split(',');\r\n\t\thandles = $.map(handles, function(h){return $.trim(h).toLowerCase();});\r\n\t\tif ($.inArray('all', handles) >= 0 || $.inArray(dir, handles) >= 0){\r\n\t\t\treturn dir;\r\n\t\t}\r\n\t\tfor(var i=0; i<dir.length; i++){\r\n\t\t\tvar index = $.inArray(dir.substr(i,1), handles);\r\n\t\t\tif (index >= 0){\r\n\t\t\t\treturn handles[index];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn '';\r\n\t}",
"function getResizeMode() {\n return internal.resizeMode;\n }",
"function getResizeType() {return resizeType; }",
"get resizeStep() {\n\t\treturn this.nativeElement ? this.nativeElement.resizeStep : undefined;\n\t}",
"getSizeDirection (caps) {\n if (caps) return this.props.direction === 'column' ? 'Height' : 'Width'\n else return this.props.direction === 'column' ? 'height' : 'width'\n }",
"get resizeBehavior() {\n return this.i.nj;\n }",
"isResizable(direction) {\n return (this._editFlags & direction) === direction;\n }",
"getResizeCalculatePositions() {\n return this.calculatePercent(this.getDomTransform());\n }",
"getWidthMode(){return this.__widthMode}",
"observeScrollDir(){\r\n var dims = this.dimensions;\r\n if( dims.lastViewportTop === dims.viewportTop ) return;\r\n \r\n var furthest = 'down' === this.direction ? Math.min : Math.max;\r\n \r\n // If the browser is scrolling not in the same direction.\r\n if( dims.viewportTop === furthest(dims.viewportTop, dims.lastViewportTop) )\r\n this.direction = 'down' === this.direction ? 'up' : 'down';\r\n }",
"observeScrollDir(){\n var dims = this.dimensions;\n if( dims.lastViewportTop === dims.viewportTop ) return;\n \n var furthest = 'down' === this.direction ? Math.min : Math.max;\n \n // If the browser is scrolling not in the same direction.\n if( dims.viewportTop === furthest(dims.viewportTop, dims.lastViewportTop) )\n this.direction = 'down' === this.direction ? 'up' : 'down';\n }",
"getSide() {\n // Item´s center point.\n const center = {x: this.rect.left+this.rect.width/2, y: this.rect.top+this.rect.height/2};\n return center.x >= winsize.width/2 ? 'right' : 'left';\n }",
"getSide() {\n // Item´s center point.\n const center = {\n x: this.rect.left + this.rect.width / 2,\n y: this.rect.top + this.rect.height / 2\n };\n return center.x >= winsize.width / 2 ? 'right' : 'left';\n }",
"dir() {\n if (TouchInput.isPressed() && Input.isPressed('control')) {\n\n //if ($.editor.wedit = 'point' && !Input.isPressed('ctrl')) return;\n\n // RIGHT\n\n if (Haya.Mouse.x > this.mouse.x) {\n return 'right'\n }\n\n // LEFT\n\n if (Haya.Mouse.x < this.mouse.x) {\n return 'left'\n }\n\n // UP\n\n if (Haya.Mouse.y < this.mouse.y) {\n return 'up'\n }\n\n // DOWN\n if (Haya.Mouse.y > this.mouse.y) {\n return 'down'\n }\n } else {\n this.mouse.x = Haya.Mouse.x + this.threshold_mouse;\n this.mouse.y = Haya.Mouse.y + this.threshold_mouse;\n }\n\n }",
"function repositionSideResizer() {\n posTop.style.left = ((element.offsetWidth / 2) - 5) + 'px';\n\n posleft.style.top = ((element.offsetHeight / 2) - 5) + 'px';\n\n posBottom.style.left = ((element.offsetWidth / 2) - 5) + 'px';\n\n posRight.style.top = ((element.offsetHeight / 2) - 5) + 'px';\n }",
"get PortraitUpsideDown() {}",
"_resizeMoveHandler(event) {\n const that = this;\n\n if (that.disabled || !that.resizable || !that._resizeStarted) {\n return;\n }\n\n const rectObject = that.getBoundingClientRect(),\n min = { width: 50, height: 50 },\n newWidth = that.rightToLeft ? (rectObject.width + rectObject.left - event.clientX) : (event.clientX - rectObject.left),\n newHeight = event.clientY - rectObject.top;\n\n if (newWidth > min.width) {\n that.style.width = newWidth + 'px';\n }\n\n if (newHeight > min.height) {\n that.style.height = newHeight + 'px';\n }\n }",
"getScrollDirection() {\n let xDiff = this.tStart[0] - this.tMove[0]\n let yDiff = this.tStart[1] - this.tMove[1]\n // Converting both the difference in to positive number\n // and calculating which is higher. We can't always drag in a straight line\n // This is necessary to calculate or guess the user slided direction\n\n // Horizontal difference is more than the vertical difference\n // Then the we try to move left or right\n if (Math.abs(xDiff) > Math.abs(yDiff)) {\n // Sliding in the left direction\n if (xDiff > 0) {\n return \"L\";\n }\n // Sliding in the right direction\n else if (xDiff < 0) {\n return \"R\";\n }\n }\n else {\n // Sliding in the Up direction\n if (yDiff > 0) {\n return \"U\";\n }\n // Sliding in the Down direction\n if (yDiff < 0) {\n return \"D\";\n }\n }\n }",
"get resizable() {\n return this._resizable;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cria os elementos html dos eventos (cards) de acordo com seu estado | function createAndAddEvents(deck, eventsObj, headerType) {
let parent = document.createElement('div')
parent.innerHTML =
`<div class="card border-secondary" data-id="${eventsObj.id}" data-toggle="modal" data-target="#formModal">
<div class="card-header p-0 d-flex text-center ${headerType}">
<div class="d-block w-100 separator-left">
<span class="label-sm">Começa:</span>
<h6>${viewDateFormat(eventsObj.start_datetime)}</h6>
</div>
<div class="d-block w-100">
<span class="label-sm">Termina:</span>
<h6>${viewDateFormat(eventsObj.end_datetime)}</h6>
</div>
</div>
<div class="card-body">
<h4>${eventsObj.name}</h4>
</div>
<div class="card-footer">
<small class="text-muted">Última modificação: ${viewDateFormat(eventsObj.last_modification)}</small>
</div>
</div>`;
parent.classList.add('mt-3');
parent.classList.add('col-xl-4');
parent.classList.add('col-md-6');
parent.classList.add('col-sm-12');
parent.classList.add('event-card');
deck.appendChild(parent);
} | [
"function buildDOM(){\n var area = document.getElementsByClassName(\"cardArea\")[0];\n for(var i = 0; i < gameCards.totalCards; i++){\n var div = document.createElement('div');\n div.className = \"card\";\n area.appendChild(div);\n div.setAttribute(\"id\", i);\n var domDispObj = {\n obj: div,\n color: CARD_BACK_COLOR,\n body: null\n }\n domCardDisp.push(domDispObj);\n div.addEventListener(\"click\", flip);\n }\n}",
"function createEventCard(day,eventIndex){\n let card = document.createElement('div');\n let eventTime = document.createElement('h1')\n let eventName = document.createElement('h3')\n let eventLocation = document.createElement('h4')\n card.classList.add(\"card\");\n eventTime.textContent = unixToTime(eventsArray[day][eventIndex].startTime);\n eventName.textContent = eventsArray[day][eventIndex].name;\n eventLocation.textContent = eventsArray[day][eventIndex].location;\n card.appendChild(eventTime);\n card.appendChild(eventName);\n card.appendChild(eventLocation);\n card.addEventListener('click', function(){selectEvent(eventsArray[day][eventIndex].startTime, eventsArray[day][eventIndex].location)})\n return card\n}",
"function newCardElement(name, themes, picture, url, id){\n //PARTE de crear los elementos html\n\n var bodycontainer = document.createElement(\"div\");\n bodycontainer.className = \"card\";\n\n var container = document.createElement(\"div\");\n container.className = \"card-body\";\n\n //imagen\n var img = document.createElement(\"img\");\n img.src = picture;\n img.className = \"card-img-top\";\n\n //name del autor\n var nameH = document.createElement(\"h3\");\n nameH.className=\"card-title\"; \n var nameText = document.createTextNode(name);\n nameH.appendChild(nameText); \n //data\n if(themes != null){\n var dataP = document.createElement(\"p\");\n dataP.className = \"card-text\";\n var dataText = document.createTextNode(themes);\n dataP.appendChild(dataText);\n }\n\n //link a la página del autor/a\n var aBook = document.createElement(\"a\");\n var aText = document.createTextNode(\"Go to this book\");\n aBook.className = \"btn btn-primary\"\n aBook.href = url;\n aBook.appendChild(aText);\n\n\n container.appendChild(nameH);\n if(themes != null){\n container.appendChild(dataP);\n }\n container.appendChild(aBook);\n bodycontainer.appendChild(img);\n bodycontainer.appendChild(container);\n //bodycontainer.getElementById(id).appendChild(nameHBook);\n //supercontainer.appendChild(bodycontainer);\n document.getElementById(id).appendChild(bodycontainer);\n}",
"function createTimeCards(){\n let events = $('.event');\n events.each(function(){\n let eventColor = $(this).find('.info').css('background-color'),\n eventId = $(this).find('.info').data('id'),\n eventTime = $(this).find('.event-time').attr('placeholder'),\n countBoxTime = timeConversation(eventTime);\n createTimeCardsFromOneEvent(eventColor, eventId, countBoxTime);\n });\n}",
"function displayCards()\n {\n //loop through event event (regardless of however many events we are capturing) and incriment by 2\n for (var s=0; s<cardElements.length; s+=2)\n {\n //first variable (s) will be used to grab the first event\n //second variable (t) will be used to grab the second event\n var t = s+1;\n\n //a string variable to hold the html content that is the cards\n //cardRow = \"<div class='row justify-content-md-center'><div class='col-xs-6'><div class='card' value='\"+eventID+\"' style='width: 18rem;'><div class='card-body'><h5 class='card-title1'>\"+cardElements[s].act+\"</h5><h6 class='card-subtitle1 mb-2 text-muted'>Date: \"+cardElements[s].date+\"</h6><p class='card-text1'>Time: \"+cardElements[s].time+\"</p><p class='card-text1'>Venue: \"+cardElements[s].venue+\"</p></div></div></div><div class='col-xs-6'><div class='card' style='width: 18rem;'><div class='card-body'><h5 class='card-title2'>\"+cardElements[t].act+\"</h5><h6 class='card-subtitle2 mb-2 text-muted'>Date: \"+cardElements[t].date+\"</h6><p class='card-text2'>Time: \"+cardElements[t].time+\"</p><p class='card-text2'>Venue: \"+cardElements[t].venue+\"</p></div></div></div></div>\";\n\n cardRow = \"<div class='row justify-content-md-center'><div class='col-xs-6 margin'><div class='card' value='\"+cardElements[s].ID+\"' style='width: 18rem; margin: 20px; background: rgba(76, 72, 88, .5); color: white; font-family: \"+\"'\"+\"Merriweather\"+\"'\"+\", serif;'><div class='card-body'><h5 class='card-title1'>\"+cardElements[s].act+\"</h5><h6 class='card-subtitle1 mb-2'>\"+cardElements[s].venue+\"</h6><p class='card-text1'>\"+cardElements[s].date+\"</p><p class='card-text1'>\"+cardElements[s].time+\"</p></div></div></div><div class='col-xs-6 margin'><div class='card' value='\"+cardElements[t].ID+\"' style='width: 18rem; margin: 20px; background: rgba(76, 72, 88, .5); color: white; font-family: \"+\"'\"+\"Merriweather\"+\"'\"+\", serif;'><div class='card-body'><h5 class='card-title2'>\"+cardElements[t].act+\"</h5><h6 class='card-subtitle2 mb-2'>\"+cardElements[t].venue+\"</h6><p class='card-text2'>\"+cardElements[t].date+\"</p><p class='card-text2'>\"+cardElements[t].time+\"</div></div></div>\";\n\n //jquery to append the cars to the screen\n $(\"#variableContent\").append(cardRow);\n }\n }",
"_initCardElements() {\n this.cardsElement = this.sliderElement.querySelector(\".cards\");\n this.cardElements = [];\n for (let cardData of this.cardsData) {\n const cardElement = CardHelper.createCardElement(cardData);\n this.cardElements.push(cardElement);\n }\n\n for (let cardElement of this.cardElements) {\n this._addCardElement(cardElement);\n }\n }",
"_initCardElements() {\n this.cardsElement = this.sliderElement.querySelector(\".cards\");\n this.cardElements = [];\n for (let cardData of this.cardsData) {\n const cardElement = CardHelper.createCardElement(cardData);\n this.cardElements.push(cardElement);\n }\n\n for (let cardElement of this.cardElements) {\n this._addCardElement(cardElement);\n }\n }",
"function generatePlayerHandHTML(CardNr) {\r\n let cardDiv = document.createElement(\"div\"); // Eventlistener erstellt Karten Div \r\n cardDiv.setAttribute(\"id\", \"playerCard\" + (CardNr + 1));\r\n cardDiv.setAttribute(\"class\", \"card\");\r\n cardDiv.addEventListener('click', function () { playCard(CardNr, SpielerZug); }, false);\r\n document.getElementById(\"playerHand\").appendChild(cardDiv);\r\n let tempkartenwert = SpielerZugArray[CardNr].kartenwert + \"\"; // Inhalt der Karte wird erstellt\r\n switch (SpielerZugArray[CardNr].spezialfunktion) {\r\n case \"Plus 2\":\r\n tempkartenwert = \"+2\";\r\n break;\r\n case \"Plus 4\":\r\n tempkartenwert = \"+4\";\r\n break;\r\n }\r\n let kartenwertP1 = document.createElement(\"p\"); // Erstellen der <p>-Tags mit dem Inhalt in gewollter Farbe \r\n kartenwertP1.innerHTML = tempkartenwert + \"\";\r\n kartenwertP1.setAttribute(\"class\", SpielerZugArray[CardNr].KartenFarbe);\r\n cardDiv.appendChild(kartenwertP1);\r\n let kartenwertP2 = document.createElement(\"p\");\r\n kartenwertP2.innerHTML = tempkartenwert + \"\";\r\n kartenwertP2.setAttribute(\"class\", SpielerZugArray[CardNr].KartenFarbe);\r\n cardDiv.appendChild(kartenwertP2);\r\n}",
"function createCardElements() {\n var wikiLink = d.createElement(\"a\"); // creates link tag\n var card = d.createElement(\"div\"); // creates div tag\n var cardTitle = d.createElement(\"p\"); // creates title \n var cardDescription = d.createElement(\"p\"); // creates description\n setAttributes(card, cardTitle, cardDescription, wikiLink);\n generateCard(card, cardTitle, cardDescription, wikiLink);\n }",
"function addCard(){\n \n newTask.setAttribute(\"value\", \"defaultValue\"); \n const title = newTask.value; \n \n todo = { \n id: Date.now(),\n heading: title,\n }\n\n popupAdd.style.visibility = \"hidden\";\n page.style.filter = \"blur(0)\";\n \n const nodeCard = document.createElement(\"card\"); \n nodeCard.setAttribute(\"class\", `card`);\n nodeCard.setAttribute(\"id\", `${todo.id}`);\n\n nodeCard.innerHTML = ` <div class=\"cardsSection\" id = \"${todo.id}\">\n <p id=\"todoTitle\" > ${todo.heading} </p>\n <hr/>\n \n <ul class = \"listsSection\"> \n \n </ul>\n \n <div class=\"icon functions\">\n <div id=\"iconSubtask\" onclick=\"addSubtask(event) ; parentCard(event)\">\n <i class=\"fas fa-plus-circle\"></i>\n </div>\n <div id = \"iconDelete\" onclick=\"deleteCard(event)\">\n <i class=\"fas fa-trash-alt\"></i>\n </div>\n </div>\n </div>`;\n\n document.getElementsByTagName(\"section\")[0].appendChild(nodeCard); \n todoList.push(todo);\n \n}",
"buildEvent(object) {\n const IconMain = new DOMComponent(\"i\", { className: \"material-icons circle\", textContent: \"date_range\" })\n const Span = new DOMComponent(\"span\", { className: \"event grey-text text-darken-1 dateText\", textContent: `${object.date}` })\n const H5 = new DOMComponent(\"h5\", { className: \"grey-text nameText\", textContent: `${object.name}` })\n const P = new DOMComponent(\"p\", { className: \"grey-text locationText\", textContent: `${object.location}` })\n\n const IconEdit = new DOMComponent(\"i\", { className: \"material-icons edit\", textContent: \"edit\" })\n const IconDelete = new DOMComponent(\"i\", { className: \"material-icons delete\", textContent: \"delete_forever\" })\n const EditLink = new DOMComponent(\"a\", { className: \"btn-floating btn-small waves-effect waves-light\" }, IconEdit)\n const DeleteLink = new DOMComponent(\"a\", { className: \"btn-floating btn-small waves-effect waves-light \" }, IconDelete)\n const Div = new DOMComponent(\"div\", { className: \"secondary-content\" }, EditLink, DeleteLink)\n\n const Event = new DOMComponent(\"li\", { className: \"collection-item avatar\", id: `${object.id}` }, IconMain, Span, H5, P, Div)\n return Event\n }",
"function setDate(button, date){\n debugger;\n button.addEventListener('click', function(){\n var cards = document.getElementsByClassName(date);\n var noEvents = document.getElementById('empty');\n var eventCards = document.getElementsByClassName('events');\n if(cards.length != 0){\n //hide the no events card\n noEvents.style.display = 'none';\n for(i=0;i<eventCards.length;i++){\n eventCards[i].style.display = 'none';\n }\n for(i=0;i<cards.length;i++){\n cards[i].style.display = 'block';\n }\n }\n else{\n for(i=0;i<eventCards.length;i++){\n eventCards[i].style.display = 'none';\n }\n var noEvents = document.getElementById('empty');\n noEvents.style.display = 'block';\n }\n });\n}",
"function createCards () {\n const cardList = document.body.querySelector('.deck');\n const cardStatus = cardList.getElementsByTagName('li');\n for (let i = 0; i < cardStatus.length; i++) {\n const cardName = cardStatus[i].getElementsByTagName('i');\n game.deck[i] = new Card(cardName[0].className, cardStatus[i].className);\n\n //Adds the event listener to each card. The EventListener will\n //start the game.timer, if it hasn't already started, and flip the\n //cards to check for matches.\n cardStatus[i].addEventListener('click', function () {\n if (game.start === false) {\n game.start = true;\n startTimer();\n checkMatch(game.deck[i], cardStatus[i]);\n } else {\n checkMatch(game.deck[i], cardStatus[i]);\n }\n });\n }\n }",
"function renderCards(eventsToDisplay) {\n // start by removing cards if some are alredy there\n document.getElementById('to-display-events').innerHTML = \"\";\n\n for (var i = 0; i < eventsToDisplay.length; i++) {\n var div = document.createElement('div');\n div.className = '';\n div.innerHTML = `\n <div class=\"card m-1\">\n <img src=\"assets/${eventsToDisplay[i].image}\" class=\"card-img-top\" alt=\"...\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">${eventsToDisplay[i].title}</h5>\n <p><strong>Speaker:</strong> ${eventsToDisplay[i].speaker}</p>\n <p><strong>Audience:</strong> ${eventsToDisplay[i].audience}</p>\n <p class=\"card-text\">\n ${eventsToDisplay[i].short_Summary}<br>\n </p> \n </div>\n <div class=\"card-footer\">\n <p>${eventsToDisplay[i].when} </p>\n <small class=\"text-muted\"><strong>${eventsToDisplay[i].city}</strong> ${eventsToDisplay[i].adress}</small> <br>\n <a href=\"map.html\" id=\"${eventsToDisplay[i].city}\" onclick=\"citySet(this.id)\">find on map</a>\n </div>\n </div>\n \n `\n // div.innerHTML = eventInCard[i].presentateur\n document.getElementById('to-display-events').appendChild(div);\n }\n}",
"function cardGen(){\n\t\t card = $(\"<div class='card float-left'>\");\n\t\t cardImage = $(\"<img class='card-img-top'>\");\n\t\t cardBody = $(\"<div class='card-body'>\");\n\t }",
"__CreateCards() {\n //Clear the existing cards in the html\n let existing = document.querySelectorAll('[data-servercard=\"true\"]');\n existing.forEach(m => {\n m.parentElement.removeChild(m);\n })\n\n let element = document.getElementById(__appglobals.views_sideNavHeaderId);\n let cards = { card: new Array() };\n\n configurationcontroller.__config_list.forEach((c) => {\n cards.card.push(c)\n })\n\n let rendedCards = configurationcontroller.GetViewAsHtml(\"sidebar/server-card\", cards);\n element.insertAdjacentHTML('afterend', rendedCards);\n }",
"function movieDomCreator(movie) {\n movie.forEach(elem => {\n var div = document.createElement(\"div\");\n\n div.classList.add(\"box\");\n div.id = `${id}`;\n var img = document.createElement(\"img\");\n var p = document.createElement(\"p\");\n var heart = document.createElement(\"i\");\n heart.classList.add(\"heart\");\n\n var moreInfo = document.createElement(\"btn\");\n moreInfo.classList.add(\"button\");\n moreInfo.classList.add(\"is-primary\");\n moreInfo.textContent = \"More Info\";\n\n heart.classList.add(\"far\");\n heart.classList.add(\"fa-heart\");\n\n p.textContent = elem.title;\n\n if (elem.poster_path != undefined) {\n img.src = `${imageTemplate}${elem.poster_path}`;\n } else {\n img.src = \"not found\";\n }\n div.appendChild(img);\n div.appendChild(p);\n div.appendChild(moreInfo);\n div.appendChild(heart);\n contain.appendChild(div);\n id++;\n\n moreInfo.addEventListener(\"click\", function() {\n movieId = elem.id;\n getMoreDetails();\n console.log(\"card\");\n });\n });\n\n // Corner hearts inside box\n var hearts = document.querySelectorAll(\".heart\");\n\n hearts.forEach(function(heart) {\n heart.addEventListener(\"click\", function(e) {\n if (!heart.classList.contains(\"fontScale\")) {\n heart.classList.add(\"fontScale\");\n clonedTag = heart.parentNode.cloneNode(true);\n\n // appending each liked movie to watchlistBody\n clonedTag.removeChild(clonedTag.childNodes[3]);\n clonedTag.removeChild(clonedTag.childNodes[2]);\n\n var bigDiv = document.createElement(\"div\");\n bigDiv.appendChild(clonedTag);\n console.log(clonedTag);\n\n watchListInner.appendChild(bigDiv);\n allClones.push(clonedTag);\n }\n });\n });\n}",
"static displayEvents() {\n //for-loop der kører igennem alle events\n for (let i=0; i<listOfEvents.length; i++) {\n //node med html-tag P skabes og får tilknyttet string (eventnavn[i])\n let eventName = document.createElement(\"p\");\n eventName.innerHTML = listOfEvents[i].eventName;\n //Klasse tilføjes for at kunne bruge CSS\n eventName.classList.add(\"eventDisplay\");\n //Tilknytter (appendChild) alle eventnavne (noder som <p>) til div'en eventName\n document.getElementById(\"eventName\").appendChild(eventName);\n\n //samme fremgangsmåde\n let eventLocation = document.createElement(\"p\");\n eventLocation.innerHTML = listOfEvents[i].eventLocation;\n eventLocation.classList.add(\"eventDisplay\");\n document.getElementById(\"eventLocation\").appendChild(eventLocation);\n\n //samme fremgangsmåde\n let eventKategori = document.createElement(\"p\");\n eventKategori.innerHTML = listOfEvents[i].Category;\n eventKategori.classList.add(\"eventDisplay\");\n document.getElementById(\"eventKategori\").appendChild(eventKategori);\n\n //Skal laves drastisk om, ved implementering af tidskoder\n //samme fremgangsmåde\n let eventTid = document.createElement(\"p\");\n eventTid.innerHTML = listOfEvents[i].eventTime;\n eventTid.classList.add(\"eventDisplay\");\n document.getElementById(\"eventTid\").appendChild(eventTid);\n\n //samme fremgangsmåde\n let eventHost = document.createElement(\"p\");\n eventHost.innerHTML = listOfEvents[i].eventHost;\n eventHost.classList.add(\"eventDisplay\");\n document.getElementById(\"eventVært\").appendChild(eventHost);\n\n //samme fremgangsmåde\n let eventBeskrivelse = document.createElement(\"p\");\n eventBeskrivelse.innerHTML = listOfEvents[i].eventDescription;\n eventBeskrivelse.classList.add(\"eventDisplay\");\n document.getElementById(\"eventBeskrivelse\").appendChild(eventBeskrivelse);\n\n //samme fremgangsmåde\n let eventKapacitet = document.createElement(\"p\");\n\n //Metode der skal beregne om et event har kapacitet\n //Variabel der tager det valgte index af listOfEvents\n events = listOfEvents[i];\n //Variabel der bestemmer antal pladser tilbage i et event, ved at trække længden af array'et eventParticipants fra eventCapacity som er et nummer\n remainingCapacity = events.eventCapacity - events.eventParticipants.length;\n eventKapacitet.innerHTML = remainingCapacity;\n eventKapacitet.classList.add(\"eventDisplay\");\n document.getElementById(\"eventKapacitet\").appendChild(eventKapacitet);\n\n //Tilmeldningsknap (join-metode)\n let tilmeldEvent = document.createElement(\"p\");\n tilmeldEvent.innerHTML = \"Tilmeld\";\n tilmeldEvent.classList.add(\"eventDisplay\");\n //Jeg kunne ikke få værdien af index i loop ud af loop'et uden at funktionen kørte sammen med loop'et, hvorfor funktionen er skrevet herinde\n //addeventlistener der tjekker om der bliver klikket på noden. Hvis der klikkes køres funktionen nedenfor.\n tilmeldEvent.addEventListener('click', function () {\n //variabel der tager det event der bliver klikket på\n subscribedEvent = listOfEvents[i];\n EventUtility.subscribe();\n });\n document.getElementById(\"tilmeldEvent\").appendChild(tilmeldEvent);\n }\n }",
"createCardElement() {\n let card = document.createElement(\"div\");\n card.className = \"card\";\n card.id = this.id;\n let img = document.createElement(\"img\");\n if (this.visible) {\n img.src = this.image;\n } else {\n img.src = \"Images/Cards/flipped.png\";\n }\n img.id = this.suit + this.value + \"Image\";\n img.onclick = function() {cardClicked(card);};\n card.appendChild(img);\n this.element = card;\n return card;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
whoWon should return 0 if the game is not yet finished, 1 or 2 depending on which player won, else 3 if the game is a draw. | function whoWon () {
if (!quiz.isGameOver) return 0
if (quiz.player1Points > quiz.player2Points) return 1
if (quiz.player1Points < quiz.player2Points) return 2
return 3
} | [
"function whoWon() {\n if (!quiz.isGameOver) {\n return 0\n }\n else if (quiz.isGameOver) {\n if (quiz.player1score > quiz.player2score) {\n return 1\n }\n else if (quiz.player2score > quiz.player1score) {\n return 2\n }\n }\n else {\n return 3\n }\n}",
"function whoWon() {\n if ((quiz.currentQuestion + 1) < quiz.questions.length && isGameOver() === false) {\n console.log(\"game is ongoing\");\n return 0\n } else if (quiz.player1Points> quiz.player2Points && isGameOver() === true) {\n alert(\"Player 1 wins!\");\n return 1\n } else if (quiz.player2Points> quiz.player1Points && isGameOver() === true) {\n alert(\"Player 2 Wins!\")\n return 2\n } else {\n alert(\"It's a draw!\")\n return 3\n }\n}",
"function whoWon() {\n var waysToWin = [\"0,1,2\",\"3,4,5\",\"6,7,8\",\"0,4,8\",\"2,4,6\",\"0,3,6\",\"1,4,7\",\"2,5,8\"]\n if (board.length === 0) {\n return 0\n }\n else if (board.length === 9) {\n return 3\n }\n else if (board.length % 2 !== 0) {\n playerOneMoves.push(board[board.length-1])\n playerOneMovesStr = playerOneMoves.sort().join()\n for (var i=0; i<waysToWin.length; i++) {\n if (playerOneMovesStr.includes(waysToWin[i])) {\n return 1\n }\n }\n return 0\n }\n else if (board.length % 2 === 0) {\n playerTwoMoves.push(board[board.length-1])\n playerTwoMovesStr = playerTwoMoves.sort().join()\n for (var i=0; i<waysToWin.length; i++) {\n if (playerTwoMovesStr.includes(waysToWin[i])) {\n return 2\n }\n }\n return 0\n }\n}",
"hasWon() {\n // if player won (over 100) then return true. Otherwise, return false\n if (this.totalScore() >= 100) {\n return true;\n } else {\n return false;\n }\n }",
"function checkWhoWon() {\n if (gameBall.yBall < 0) {\n gameState.playerWins++;\n newGameRecord.humanWins = gameState.playerWins;\n newGameRecord.aiWins = gameState.enemyWins;\n newPlayerRecord.winLoseAI = \"Win\";\n setProperty(\"winLoseLabel\", \"text-color\", \"green\");\n setText(\"winLoseLabel\", \"You won!\");\n } else {\n gameState.enemyWins++;\n newGameRecord.humanWins = gameState.playerWins;\n newGameRecord.aiWins = gameState.enemyWins;\n newPlayerRecord.winLoseAI = \"Lose\";\n setProperty(\"winLoseLabel\", \"text-color\", \"red\");\n setText(\"winLoseLabel\", \"You lost!\");\n }\n gameState.winRatio = Math.round((gameState.playerWins / (gameState.enemyWins + gameState.playerWins)) * 100);\n newGameRecord.winRatio = gameState.winRatio;\n}",
"function checkIfWon() {\n\n if (scores[\"player1\"] == 3) {\n markAsWinner(1)\n return true\n } else if (scores[\"player2\"] == 3) {\n markAsWinner(2)\n return true\n }\n\n return false\n}",
"function checkGameWon() {\n if (window.board.workspace.winCheck()) {\n\t// They won!!\n\n\tvar solutions = window.board.workspace.getSolutions();\n\n\t// Calculate score for correct words\n var base = 0;\n\tfor (var i = 0; i < solutions.length; i++) {\n\t base += scoreFunc(solutions[i]);\n\t}\n\n\tvar timeBonus = Math.max(0, (TIMER_CUTOFF - (timer.getMin() * 60 + timer.getSec())) * TIMER_PENALTY);\n\n // show score components in transition screen\n $('#score-base').text(base);\n $('#score-bonus').text(timeBonus);\n // score currently contains accumulated penalties\n $('#score-penalty').text(score);\n $('#score-breakdown').show();\n\n score += base;\n\tscore += timeBonus;\n\n\t// Show the transition screen\n\tTransitionScreen(true, score);\n }\n}",
"function getGameWinner() {\n if (!playerOneMoveOneType || !playerOneMoveOneValue || !playerOneMoveTwoType || !playerOneMoveThreeType || !playerOneMoveThreeValue || !playerTwoMoveOneType || !playerTwoMoveOneValue || !playerTwoeMoveTwoType || !playerTwoMoveTwoValue || !playerTwoMoveThreeType || !playerTwoMoveThreeValue) {\n return null;\n }\n playerOneWins = 0;\n playerTwoWins = 0;\n\n const roundOneWinner = getRoundWinner(1);\n const roundTwoWinner = getRoundWinner(2);\n const roundThreeWinner = getRoundWinner(3);\n\n winRound(roundOneWinner);\n winRound(roundTwoWinner);\n winRound(roundThreeWinner);\n\n if (playerOneWins > playerTwoWins) {\n return 'Player One';\n } else if (playerOneWins < playerTwoWins) {\n return 'Player Two';\n } else {\n return 'Tie';\n }\n}",
"function showPlayerWon() {\n\n showHint(`You hit the number within ${triesCount} ${triesCount > 1 ? 'tries' : 'try'}!`, \"h2\");\n showHint('You won!!!', \"h1\");\n\n // finally call endGame() to show the start screen\n endGame();\n}",
"function hasUserWonOrLost() {\n // check if user has won\n if (userTotalScore == bigCrystalNumber) {\n wins++;\n console.log(\"user won\");\n initializeVariables();\n }\n\n // check if user has lost\n if (userTotalScore > bigCrystalNumber) {\n losses++;\n console.log(\"user lost\");\n initializeVariables();\n }\n }",
"function gameWon() {\n if (PLAYER.win && SCORE.sx === 96) { // if player wins and if score indicator is full (game should not end before score is updated)\n GAME_WON_SOUND.play();\n stopTimer();\n fillModal('gamewon');\n show(MODAL);\n cancelAnimation(); // stop drawing on canvas if game is won\n } else {\n startAnimation(); // continue drawing on canvas since game is not won yet\n }\n}",
"function checkIfWon() {\n if (userScore === randomNumber) {\n wins++;\n winAudio.play();\n status='You won!!';\n reset(); \n return true;\n }\n if (userScore > randomNumber) {\n losses++;\n lostAudio.play();\n status='You lost!!';\n reset();\n return true;\n }\n \n return false;\n \n}",
"function playerWon() {\n // Contents of playerWins before adding the win\n // console.log(\"-----Wins before counter updated---\");\n // console.log(playerWins);\n // Add 1 to player's win count\n playerWins = playerWins + 1;\n // console.log(\"-----Wins after counter updated---\");\n // console.log(playerWins);\n // alert(\"You won!\");\n msgArrIndex = Math.floor(Math.random() * arrCongrats.length - 1) + 1;\n // console.log(\"-----Random Arr Index----\");\n // console.log(msgArrIndex);\n // console.log(\"----- Message at Random Index----\");\n // console.log(arrCongrats[msgArrIndex]);\n //Assign the message from arrCongrats at the randomly generated index to playerWonMsg variable\n playerWonMsg=(\"You won! \" + arrCongrats[msgArrIndex]);\n //Alert the message\n alert(playerWonMsg);\n //Call newGame() function\n $(newGame);\n }",
"function youWon() {\n wins += 1\n endGameToast(true)\n setTimeout(restartGame, timer)\n\n}",
"_showGameWon() {\r\n // Show a game over screen\r\n this._showEnd();\r\n\r\n // Custom background color for game won\r\n this.endElement.css('background-color', '#0097e6');\r\n\r\n // Custom message to user\r\n $( '#end-message' ).text( 'You won!' );\r\n\r\n // Muliply score by difficulty multiplier\r\n this.player.score *= DIFFICULTIES[this.difficulty].SCORE_MULTIPLIER;\r\n\r\n // Check for new highscore\r\n if ( ScoreHandler.isHighScore( this.player.score ) ) {\r\n $( '#high-score-message' ).html( \"New high score!\" );\r\n } else {\r\n // Get the highest score from local storage\r\n $( '#high-score-message' ).html( \"Highest score: \" + ScoreHandler.getHighestScore() );\r\n }\r\n\r\n // Save score to local storage\r\n ScoreHandler.saveScore( this.player.score );\r\n // Update UI\r\n $( '#end-score' ).text( this.player.score );\r\n this._refreshScoresView();\r\n\r\n // Play theme\r\n this._stopAllMusic();\r\n APP.MUSIC.GAME_WON.play();\r\n }",
"function winner() {\n wins++\n }",
"function whoWon(){\n//finds out if it is a tie and adds to the counter and prints an output appriately\n if ((userChoiceGlobal==2&&computerChoiceGlobal==2)||(userChoiceGlobal==3&&computerChoiceGlobal==3)||(userChoiceGlobal==1&&computerChoiceGlobal==1)) {\n tiedCount=tiedCount+1;\n document.getElementById(\"printOutcome\").innerHTML = `It's a Tie!`;\n }\n//finds out if it is a win and adds to the counter and prints an output appriately\n if ((userChoiceGlobal==1&&computerChoiceGlobal==3)||(userChoiceGlobal==2&&computerChoiceGlobal==1)||(userChoiceGlobal==3&&computerChoiceGlobal==2)) {\n winsCount=winsCount+1;\n document.getElementById(\"printOutcome\").innerHTML = `You Won!`;\n }\n//finds out if it is a loss and adds to the counter and prints an output appriately\n if ((userChoiceGlobal==3&&computerChoiceGlobal==1)||(userChoiceGlobal==2&&computerChoiceGlobal==3)||(userChoiceGlobal==1&&computerChoiceGlobal==2)) {\n lossCount=lossCount+1;\n document.getElementById(\"printOutcome\").innerHTML = `You Lost!`;\n }\n}",
"function countWins(){\n\n if(self.grid.winner === \"x\"){\n self.grid.xCounter++;\n self.grid.winMessage = \"x wins!\";\n }\n\n else if(self.grid.winner === \"o\"){\n self.grid.oCounter++;\n self.grid.winMessage = \"o wins!\";\n }\n\n else if(self.grid.winner === \"tie\"){\n self.grid.winMessage = \"tie game\";\n }\n }",
"function checkWhoWon(botsWeapon, playersWeapon) {\n if (botsWeapon === playersWeapon) {\n displayCompleteMessage(\"There was a tie\");\n }\n // if bot wins console.log (\"bot wins\") bot score is updates ++1\t\n else if (\n (botsWeapon === \"scissors\" && playersWeapon === \"paper\") ||\n (botsWeapon === \"scissors\" && playersWeapon === \"lizard\") ||\n (botsWeapon === \"paper\" && playersWeapon === \"rock\") ||\n (botsWeapon === \"paper\" && playersWeapon === \"spock\") ||\n (botsWeapon === \"rock\" && playersWeapon === \"scissors\") ||\n (botsWeapon === \"rock\" && playersWeapon === \"lizard\") ||\n (botsWeapon === \"lizard\" && playersWeapon === \"paper\") ||\n (botsWeapon === \"lizard\" && playersWeapon === \"spock\") ||\n (botsWeapon === \"spock\" && playersWeapon === \"scissors\") ||\n (botsWeapon === \"spock\" && playersWeapon === \"rock\")\n ) {\n increaseBotScore();\n }\n // if user wins console.log (\"you win\") user score is updated ++1 \n else if (\n (playersWeapon === \"scissors\" && botsWeapon === \"paper\") ||\n (playersWeapon === \"scissors\" && botsWeapon === \"lizard\") ||\n (playersWeapon === \"paper\" && botsWeapon === \"rock\") ||\n (playersWeapon === \"paper\" && botsWeapon === \"spock\") ||\n (playersWeapon === \"rock\" && botsWeapon === \"scissors\") ||\n (playersWeapon === \"rock\" && botsWeapon === \"lizard\") ||\n (playersWeapon === \"lizard\" && botsWeapon === \"paper\") ||\n (playersWeapon === \"lizard\" && botsWeapon === \"spock\") ||\n (playersWeapon === \"spock\" && botsWeapon === \"scissors\") ||\n (playersWeapon === \"spock\" && botsWeapon === \"rock\")\n ) {\n increasePlayerScore();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get btn val concatenate with queryURL scroll to gif section | function clickMeme(){
var btnValue = $(this).text();
console.log(btnValue);
var apiKEY = "&api_key=dc6zaTOxFJmzC";
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + btnValue + "&limit=10" + apiKEY;
// make call to api
getGifyData(queryURL);
$('html, body').animate({
scrollTop: $("#gif-wrap").offset().top
}, 500);
} | [
"function displayGif(){\n\tquery($(this).attr('data-name'));\n}",
"function btnSearch(){\n\n var btnName = $(this).attr(\"data-name\");\n\n getGiphy(btnName);\n }",
"function populateContinueHref() {\n $(\".btn-continue\").attr(\"href\", getQueryParam(\"url\"));\n }",
"function giphyUrl(query, offset) {\n let baseUrl = \"https://api.giphy.com/v1/gifs/search?\";\n let params = {\n api_key: giphyKey,\n q: query,\n limit: 5,\n offset: offset\n };\n let url = baseUrl + $.param(params);\n return url;\n}",
"function updateButtonUrl(flag)\n {\n var downloadUrl;\n if (flag)\n {\n downloadUrl = $.perc_paths.WEBRESOURCESMGT + '/' + finder.getCurrentPath().slice(3).join(\"/\");\n }\n else\n {\n downloadUrl = \"#\";\n }\n btn.attr('href', downloadUrl);\n }",
"function updateButtonUrl(flag)\n {\n var downloadUrl;\n if (flag) {\n downloadUrl = $.perc_paths.WEBRESOURCESMGT + '/' + finder.getCurrentPath().slice(3).join(\"/\");\n }\n else {\n downloadUrl = \"#\";\n }\n btn.attr('href', downloadUrl);\n }",
"function searchGiphyByButton() {\n var name = $(this).html();\n grabGiphy(name);\n console.log('Name: ', name);\n}",
"function showGif(){\r\n $('img').each(function(){\r\n var old_src = $(this).prop('src');\r\n\r\n if (old_src.includes('?gifUrl='))\r\n $(this).prop('src', old_src.substring(old_src.indexOf('gifUrl') + 7)); // 'gifUrl='.length = 7\r\n });\r\n}",
"function displayAnimalGifs() {\n\n console.log(\"We captured your button click \");\n // get the animal to query\n var animal = $(this).attr(\"data-animal\");\n console.log(\"We captured your button click \" + animal);\n\n // make a call to Giphy API asking for ten datasets for animal\n var queryURL = \"https://api.giphy.com/v1/gifs/search?api_key=xTa0qr0MAiqCvVgseueh2yCaBpml6y6h&q=\" + animal + \"&limit=10&offset=0&rating=G&rating=PG&lang=en\";\n\n // call display gifs false means as a search display not as a favorites display\n displayGifs(queryURL, \"false\");\n}",
"function animalButtonClicked() {\n var userBlank = $('#animal-blank').val();\n searchGif(userBlank);\n}",
"function updateChronografBtnHtml(newLinkUrl) {\n $.each($('.view-in-chronograf'), function() {\n var newQuery = $(this).data('query')\n var newEncodedQuery = encodeURIComponent(newQuery)\n $('.chronograf-btn', this).attr('href', newLinkUrl + \"?query=\" + newEncodedQuery )\n })\n}",
"function getText() {\n\n // console.log(searchText);\n // let giphyUrl= api.giphy.com/v1/gifs/search?&q=' + searchText + '&api_key=iBag6lGxhBwV0gHDqNYT40XlbhPwKaoO&limit=10'\";\n // console.log(giphyUrl)\n}",
"function getGif(query) {\n query = query.replace(' ', '+');\n var params = { 'api_key': apikey, 'q': query};\n params = encodeQueryData(params);\n\n httpGetAsync('http://api.giphy.com/v1/gifs/search?' + params, function(data) {\n \n var gifs = JSON.parse(data);\n var target = $('#image')\n for(var x=0; x<gifs.data.length-16; x++){\n var showgif = gifs.data[x].images.fixed_width.url;\n $(\"#image\"+(x+1)).html(\"<img src='\" + showgif + \"'>\");\n };\n\n\n })\n }",
"function displayBtn(btnName) {\n $.ajax({\n url: baseUrl + btnName,\n method: 'GET',\n }).done(function (response) {\n var gifObjList = response.data;\n for(var gifObjIndex=0; gifObjIndex < gifObjList.length; gifObjIndex++){\n var newGif = $(\"<img>\");\n $(newGif).attr(\"class\",gifClass);\n $(newGif).attr(\"src\",gifObjList[gifObjIndex].images.fixed_height_small.url);\n $(gifsDiv).append(newGif);\n }\n })\n}",
"function buttonClick(index) {\n var name = names[index];\n return function (event) {\n event.preventDefault();\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" +\n name + \"&api_key=EeLVOUPGYR0IFcYTnM4KxPnPy4CEKtkr&limit=10\";\n\n // Performing an AJAX request with the queryURL\n $.ajax({\n url: queryURL,\n method: \"GET\"\n })\n .then(function (response) {\n console.log(queryURL);\n console.log(response);\n // storing the data from the AJAX request in the results variable\n var results = response.data;\n //var animate = results[i].images.fixed_height.url;\n // Looping through each result item\n for (var i = 0; i < results.length; i++) {\n // create and store a div tag to hold the gif\n var gifDiv = $(\"<div>\");\n // Creating a paragraph tag with the result item's rating\n var p = $(\"<p>\").text(\"Rating: \" + results[i].rating);\n // Creating and storing an image tag\n var gifImage = $(\"<img>\");\n // Setting the src attribute of the image to a property pulled off the result item\n gifImage.attr(\"src\", results[i].images.fixed_height.url);\n // Appending the paragraph and image tag to the gifDiv\n gifDiv.append(p);\n gifDiv.append(gifImage);\n // Prependng the animalDiv to the HTML page in the \"#gif-view\" div\n $(\"#gif-view\").prepend(gifDiv);\n }\n });\n }\n }",
"function get_api_url( cmd , param ){\n switch(cmd) {\n case \"gif\":\n return API_PATH + \"?cmd=gif&id=\" + param;\n break;\n case \"rand\":\n default:\n return API_PATH + \"?cmd=rand&gif=\" + param;\n }\n}",
"function mainProcess() {\n\t\tvar selText = $(this).text();\n\t\t// check if same button selected as previous, if so fetch next 20 gifs from API by setting offset\n\t\tif (selText === prevSeletion) {\n\t\t\toffset += 20;\n\t\t} else {\n\t\t\tprevSeletion = selText;\n\t\t\toffset = 0;\n\t\t\tresulObj = [];\n\t\t\t$('.serResuls').empty();\n\t\t}\n\t\tvar queryURL = buildqueryURL(selText, offset);\n\t\tcallGiphyAPI(queryURL);\n\n\t}",
"clickOnGif(){\n return $('(//div[contains(@class,\"ListWrapper\")]//li//div[contains(@class,\"Container-sc\")])[1]');\n }",
"function sendApiRequest(e) {\n // e.preventDefault(); Button has no default behaviour\n let apikey = \"DV4iN2mItn9xsI2WSKzWWKpTaNpw9H9n\";\n let url = `https://api.giphy.com/v1/gifs/search?api_key=${apikey}&limit=10&q=`;\n let str = document.getElementById(\"giphy\").value.trim();\n url = url.concat(str);\n console.log(url);\n\n fetch(url)\n .then((r) => r.json())\n .then((content) => {\n let gifimg = document.getElementById(\"gifPreview\");\n gifimg.setAttribute(\n \"src\",\n content.data[Math.floor(content.data.length * Math.random())]\n .images.downsized.url\n ); // choose a random gif out of the limit of 10\n gifimg.classList.add(\"imgFormat\");\n //let gifContainer = document.getElementById(\"gifContainer\");\n //gifContainer.append(gifimg);\n //gifContainer.insertAdjacentElement(\"afterbegin\", gifimg); // gif image will show up as a preview in the make a post section\n })\n .catch((err) => {\n console.log(err);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a new binding root index so that host template functions can execute. Bindings inside the host template are 0 index. But because we don't know ahead of time how many host bindings we have we can't precompute them. For this reason they are all 0 index and we just shift the root so that they match next available location in the LView. | function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {
var lFrame = instructionState.lFrame;
lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
setCurrentDirectiveIndex(currentDirectiveIndex);
} | [
"function setBindingRootForHostBindings(value) {\n var lframe = instructionState.lFrame;\n lframe.bindingIndex = lframe.bindingRootIndex = value;\n}",
"function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {\n var lFrame = instructionState.lFrame;\n lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;\n setCurrentDirectiveIndex(currentDirectiveIndex);\n }",
"function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {\n var lFrame = instructionState.lFrame;\n lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;\n lFrame.currentDirectiveIndex = currentDirectiveIndex;\n}",
"function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {\n const lFrame = instructionState.lFrame;\n lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;\n setCurrentDirectiveIndex(currentDirectiveIndex);\n}",
"function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {\n var lFrame = instructionState.lFrame;\n lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;\n setCurrentDirectiveIndex(currentDirectiveIndex);\n}",
"function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {\n const lFrame = instructionState.lFrame;\n lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;\n setCurrentDirectiveIndex(currentDirectiveIndex);\n}",
"function setHostBindings(tView, viewData) {\n var selectedIndex = getSelectedIndex();\n try {\n if (tView.expandoInstructions) {\n var bindingRootIndex = viewData[BINDING_INDEX] = tView.expandoStartIndex;\n setBindingRoot(bindingRootIndex);\n var currentDirectiveIndex = -1;\n var currentElementIndex = -1;\n for (var i = 0; i < tView.expandoInstructions.length; i++) {\n var instruction = tView.expandoInstructions[i];\n if (typeof instruction === 'number') {\n if (instruction <= 0) {\n // Negative numbers mean that we are starting new EXPANDO block and need to update\n // the current element and directive index.\n currentElementIndex = -instruction;\n setActiveHostElement(currentElementIndex);\n // Injector block and providers are taken into account.\n var providerCount = tView.expandoInstructions[++i];\n bindingRootIndex += INJECTOR_BLOOM_PARENT_SIZE + providerCount;\n currentDirectiveIndex = bindingRootIndex;\n }\n else {\n // This is either the injector size (so the binding root can skip over directives\n // and get to the first set of host bindings on this node) or the host var count\n // (to get to the next set of host bindings on this node).\n bindingRootIndex += instruction;\n }\n setBindingRoot(bindingRootIndex);\n }\n else {\n // If it's not a number, it's a host binding function that needs to be executed.\n if (instruction !== null) {\n viewData[BINDING_INDEX] = bindingRootIndex;\n var hostCtx = unwrapRNode(viewData[currentDirectiveIndex]);\n instruction(2 /* Update */, hostCtx, currentElementIndex);\n // Each directive gets a uniqueId value that is the same for both\n // create and update calls when the hostBindings function is called. The\n // directive uniqueId is not set anywhere--it is just incremented between\n // each hostBindings call and is useful for helping instruction code\n // uniquely determine which directive is currently active when executed.\n incrementActiveDirectiveId();\n }\n currentDirectiveIndex++;\n }\n }\n }\n }\n finally {\n setActiveHostElement(selectedIndex);\n }\n}",
"function setHostBindings(tView,viewData){if(tView.expandoInstructions){var bindingRootIndex=viewData[BINDING_INDEX]=tView.expandoStartIndex;setBindingRoot(bindingRootIndex);var currentDirectiveIndex=-1;var currentElementIndex=-1;for(var i=0;i<tView.expandoInstructions.length;i++){var instruction=tView.expandoInstructions[i];if(typeof instruction==='number'){if(instruction<=0){// Negative numbers mean that we are starting new EXPANDO block and need to update\n// the current element and directive index.\ncurrentElementIndex=-instruction;// Injector block and providers are taken into account.\nvar providerCount=tView.expandoInstructions[++i];bindingRootIndex+=INJECTOR_BLOOM_PARENT_SIZE+providerCount;currentDirectiveIndex=bindingRootIndex;}else{// This is either the injector size (so the binding root can skip over directives\n// and get to the first set of host bindings on this node) or the host var count\n// (to get to the next set of host bindings on this node).\nbindingRootIndex+=instruction;}setBindingRoot(bindingRootIndex);}else{// If it's not a number, it's a host binding function that needs to be executed.\nif(instruction!==null){viewData[BINDING_INDEX]=bindingRootIndex;instruction(2/* Update */,readElementValue(viewData[currentDirectiveIndex]),currentElementIndex);}currentDirectiveIndex++;}}}}",
"function initBindings() {\n ngDevMode && assertEqual(viewData[BINDING_INDEX], -1, 'Binding index should not yet be set ' + viewData[BINDING_INDEX]);\n if (tView.bindingStartIndex === -1) {\n tView.bindingStartIndex = viewData.length;\n }\n viewData[BINDING_INDEX] = tView.bindingStartIndex;\n}",
"function initBindings() {\n ngDevMode && assertEqual(currentView.bindingStartIndex, -1, 'Binding start index should only be set once, when null');\n ngDevMode && assertEqual(currentView.bindingIndex, -1, 'Binding index should not yet be set ' + currentView.bindingIndex);\n currentView.bindingIndex = currentView.bindingStartIndex = data.length;\n}",
"function setHostBindings(bindings) {\n if (bindings != null) {\n var defs = currentView.tView.directives;\n for (var i = 0; i < bindings.length; i += 2) {\n var dirIndex = bindings[i];\n var def = defs[dirIndex];\n def.hostBindings && def.hostBindings(dirIndex, bindings[i + 1]);\n }\n }\n}",
"function setHostBindings(bindings) {\n if (bindings != null) {\n var defs = tView.directives;\n for (var i = 0; i < bindings.length; i += 2) {\n var dirIndex = bindings[i];\n var def = defs[dirIndex];\n def.hostBindings && def.hostBindings(dirIndex, bindings[i + 1]);\n }\n }\n}",
"function queueHostBindingForCheck(dirIndex) {\n // Must subtract the header offset because hostBindings functions are generated with\n // instructions that expect element indices that are NOT adjusted (e.g. elementProperty).\n ngDevMode &&\n assertEqual(firstTemplatePass, true, 'Should only be called in first template pass.');\n (tView.hostBindings || (tView.hostBindings = [])).push(dirIndex, viewData.length - 1 - HEADER_OFFSET);\n}",
"function restoreBindingIndex(index) {\n viewData[BINDING_INDEX] = index;\n}",
"function processHostBindingOpCodes(tView, lView) {\n const hostBindingOpCodes = tView.hostBindingOpCodes;\n if (hostBindingOpCodes === null) return;\n try {\n for (let i = 0; i < hostBindingOpCodes.length; i++) {\n const opCode = hostBindingOpCodes[i];\n if (opCode < 0) {\n // Negative numbers are element indexes.\n setSelectedIndex(~opCode);\n } else {\n // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex.\n const directiveIdx = opCode;\n const bindingRootIndx = hostBindingOpCodes[++i];\n const hostBindingFn = hostBindingOpCodes[++i];\n setBindingRootForHostBindings(bindingRootIndx, directiveIdx);\n const context = lView[directiveIdx];\n hostBindingFn(2 /* RenderFlags.Update */, context);\n }\n }\n } finally {\n setSelectedIndex(-1);\n }\n}",
"function insertTStylingBinding(tData, tNode, tStylingKey, index, isHostBinding, isClassBinding) {\n ngDevMode && assertFirstUpdatePass(getLView()[TVIEW]);\n var tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;\n var tmplHead = getTStylingRangePrev(tBindings);\n var tmplTail = getTStylingRangeNext(tBindings);\n tData[index] = tStylingKey;\n if (isHostBinding) {\n // We are inserting host bindings\n // If we don't have template bindings then `tail` is 0.\n var hasTemplateBindings = tmplTail !== 0;\n // This is important to know because that means that the `head` can't point to the first\n // template bindings (there are none.) Instead the head points to the tail of the template.\n if (hasTemplateBindings) {\n // template head's \"prev\" will point to last host binding or to 0 if no host bindings yet\n var previousNode = getTStylingRangePrev(tData[tmplHead + 1]);\n tData[index + 1] = toTStylingRange(previousNode, tmplHead);\n // if a host binding has already been registered, we need to update the next of that host\n // binding to point to this one\n if (previousNode !== 0) {\n // We need to update the template-tail value to point to us.\n tData[previousNode + 1] =\n setTStylingRangeNext(tData[previousNode + 1], index);\n }\n // The \"previous\" of the template binding head should point to this host binding\n tData[tmplHead + 1] = setTStylingRangePrev(tData[tmplHead + 1], index);\n }\n else {\n tData[index + 1] = toTStylingRange(tmplHead, 0);\n // if a host binding has already been registered, we need to update the next of that host\n // binding to point to this one\n if (tmplHead !== 0) {\n // We need to update the template-tail value to point to us.\n tData[tmplHead + 1] = setTStylingRangeNext(tData[tmplHead + 1], index);\n }\n // if we don't have template, the head points to template-tail, and needs to be advanced.\n tmplHead = index;\n }\n }\n else {\n // We are inserting in template section.\n // We need to set this binding's \"previous\" to the current template tail\n tData[index + 1] = toTStylingRange(tmplTail, 0);\n ngDevMode && assertEqual(tmplHead !== 0 && tmplTail === 0, false, 'Adding template bindings after hostBindings is not allowed.');\n if (tmplHead === 0) {\n tmplHead = index;\n }\n else {\n // We need to update the previous value \"next\" to point to this binding\n tData[tmplTail + 1] = setTStylingRangeNext(tData[tmplTail + 1], index);\n }\n tmplTail = index;\n }\n // Now we need to update / compute the duplicates.\n // Starting with our location search towards head (least priority)\n markDuplicates(tData, tStylingKey, index, (isClassBinding ? tNode.classes : tNode.styles) || '', true, isClassBinding);\n markDuplicates(tData, tStylingKey, index, '', false, isClassBinding);\n tBindings = toTStylingRange(tmplHead, tmplTail);\n if (isClassBinding) {\n tNode.classBindings = tBindings;\n }\n else {\n tNode.styleBindings = tBindings;\n }\n}",
"BindIndex() {\n for (var i = 0; i < this._tabCount; i++) {\n var tab = this.nodeTab.children[i];\n tab.tabIndex = i;\n tab.on('click', this.OnTabClicked, this);\n }\n\n for (var i = 0; i < this._contentCount; i++) {\n var content = this.nodeContent.children[i]\n content.contentIndex = i;\n }\n }",
"function processHostBindingOpCodes(tView, lView) {\n const hostBindingOpCodes = tView.hostBindingOpCodes;\n if (hostBindingOpCodes === null) return;\n const consumer = getReactiveLViewConsumer(lView, REACTIVE_HOST_BINDING_CONSUMER);\n try {\n for (let i = 0; i < hostBindingOpCodes.length; i++) {\n const opCode = hostBindingOpCodes[i];\n if (opCode < 0) {\n // Negative numbers are element indexes.\n setSelectedIndex(~opCode);\n } else {\n // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex.\n const directiveIdx = opCode;\n const bindingRootIndx = hostBindingOpCodes[++i];\n const hostBindingFn = hostBindingOpCodes[++i];\n setBindingRootForHostBindings(bindingRootIndx, directiveIdx);\n const context = lView[directiveIdx];\n consumer.runInContext(hostBindingFn, 2 /* RenderFlags.Update */, context);\n }\n }\n } finally {\n if (lView[REACTIVE_HOST_BINDING_CONSUMER] === null) {\n commitLViewConsumerIfHasProducers(lView, REACTIVE_HOST_BINDING_CONSUMER);\n }\n setSelectedIndex(-1);\n }\n}",
"function setBindingPointer (el, prefixPointer, index) {\n var binding = util.parseXBind(el),\n attribute = binding.attribute ? binding.attribute + ':' : '',\n newBinding = attribute + replaceIndex(prefixPointer, index, binding.pointer);\n attr(el).set('x-bind', newBinding);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::Kendra::DataSource.SalesforceKnowledgeArticleConfiguration` resource | function cfnDataSourceSalesforceKnowledgeArticleConfigurationPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnDataSource_SalesforceKnowledgeArticleConfigurationPropertyValidator(properties).assertSuccess();
return {
CustomKnowledgeArticleTypeConfigurations: cdk.listMapper(cfnDataSourceSalesforceCustomKnowledgeArticleTypeConfigurationPropertyToCloudFormation)(properties.customKnowledgeArticleTypeConfigurations),
IncludedStates: cdk.listMapper(cdk.stringToCloudFormation)(properties.includedStates),
StandardKnowledgeArticleTypeConfiguration: cfnDataSourceSalesforceStandardKnowledgeArticleTypeConfigurationPropertyToCloudFormation(properties.standardKnowledgeArticleTypeConfiguration),
};
} | [
"function cfnDataSourceSalesforceCustomKnowledgeArticleTypeConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceCustomKnowledgeArticleTypeConfigurationPropertyValidator(properties).assertSuccess();\n return {\n DocumentDataFieldName: cdk.stringToCloudFormation(properties.documentDataFieldName),\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}",
"function cfnDataSourceSalesforceStandardKnowledgeArticleTypeConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceStandardKnowledgeArticleTypeConfigurationPropertyValidator(properties).assertSuccess();\n return {\n DocumentDataFieldName: cdk.stringToCloudFormation(properties.documentDataFieldName),\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n };\n}",
"function cfnDataSourceServiceNowKnowledgeArticleConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_ServiceNowKnowledgeArticleConfigurationPropertyValidator(properties).assertSuccess();\n return {\n CrawlAttachments: cdk.booleanToCloudFormation(properties.crawlAttachments),\n DocumentDataFieldName: cdk.stringToCloudFormation(properties.documentDataFieldName),\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n ExcludeAttachmentFilePatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.excludeAttachmentFilePatterns),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n FilterQuery: cdk.stringToCloudFormation(properties.filterQuery),\n IncludeAttachmentFilePatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.includeAttachmentFilePatterns),\n };\n}",
"function renderProperties(setup) {\n // print available exams\n var html = '';\n if (!('localStorage' in window)) {\n html += warning(getMessage('msg_options_change_disabled', 'Changing options is disabled, because your browser does not support localStorage.'));\n }\n for (var section in setup) {\n if (setup[section].opts.length) {\n html += '<p class=\"opts-header\">' + getMessage(section + '_label', setup[section].label) + '</p>';\n html += '<div class=\"list-group\">';\n for (var p in setup[section].opts) {\n html += prepareProperty(setup[section].opts[p]);\n }\n html += '</div>';\n }\n }\n renderElement('#app-properties', html);\n}",
"function cfnDataSourceSalesforceConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceConfigurationPropertyValidator(properties).assertSuccess();\n return {\n ChatterFeedConfiguration: cfnDataSourceSalesforceChatterFeedConfigurationPropertyToCloudFormation(properties.chatterFeedConfiguration),\n CrawlAttachments: cdk.booleanToCloudFormation(properties.crawlAttachments),\n ExcludeAttachmentFilePatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.excludeAttachmentFilePatterns),\n IncludeAttachmentFilePatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.includeAttachmentFilePatterns),\n KnowledgeArticleConfiguration: cfnDataSourceSalesforceKnowledgeArticleConfigurationPropertyToCloudFormation(properties.knowledgeArticleConfiguration),\n SecretArn: cdk.stringToCloudFormation(properties.secretArn),\n ServerUrl: cdk.stringToCloudFormation(properties.serverUrl),\n StandardObjectAttachmentConfiguration: cfnDataSourceSalesforceStandardObjectAttachmentConfigurationPropertyToCloudFormation(properties.standardObjectAttachmentConfiguration),\n StandardObjectConfigurations: cdk.listMapper(cfnDataSourceSalesforceStandardObjectConfigurationPropertyToCloudFormation)(properties.standardObjectConfigurations),\n };\n}",
"renderProperties(x) { return ui.divText(`Properties for ${x.name}`); }",
"function cfnDataSourceSalesforceChatterFeedConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceChatterFeedConfigurationPropertyValidator(properties).assertSuccess();\n return {\n DocumentDataFieldName: cdk.stringToCloudFormation(properties.documentDataFieldName),\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n IncludeFilterTypes: cdk.listMapper(cdk.stringToCloudFormation)(properties.includeFilterTypes),\n };\n}",
"function cfnDataSourceConfluenceConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_ConfluenceConfigurationPropertyValidator(properties).assertSuccess();\n return {\n AttachmentConfiguration: cfnDataSourceConfluenceAttachmentConfigurationPropertyToCloudFormation(properties.attachmentConfiguration),\n BlogConfiguration: cfnDataSourceConfluenceBlogConfigurationPropertyToCloudFormation(properties.blogConfiguration),\n ExclusionPatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.exclusionPatterns),\n InclusionPatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.inclusionPatterns),\n PageConfiguration: cfnDataSourceConfluencePageConfigurationPropertyToCloudFormation(properties.pageConfiguration),\n SecretArn: cdk.stringToCloudFormation(properties.secretArn),\n ServerUrl: cdk.stringToCloudFormation(properties.serverUrl),\n SpaceConfiguration: cfnDataSourceConfluenceSpaceConfigurationPropertyToCloudFormation(properties.spaceConfiguration),\n Version: cdk.stringToCloudFormation(properties.version),\n VpcConfiguration: cfnDataSourceDataSourceVpcConfigurationPropertyToCloudFormation(properties.vpcConfiguration),\n };\n}",
"properties() {\n return this.display.show(\n this._section(\n Text(`Properties accessible from ${this.getSignature()}`),\n this._renderProperties(2, this.metadata.allProperties())\n )\n );\n }",
"function cfnPlaceIndexDataSourceConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnPlaceIndex_DataSourceConfigurationPropertyValidator(properties).assertSuccess();\n return {\n IntendedUse: cdk.stringToCloudFormation(properties.intendedUse),\n };\n}",
"function CfnDataSource_SalesforceKnowledgeArticleConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('customKnowledgeArticleTypeConfigurations', cdk.listValidator(CfnDataSource_SalesforceCustomKnowledgeArticleTypeConfigurationPropertyValidator))(properties.customKnowledgeArticleTypeConfigurations));\n errors.collect(cdk.propertyValidator('includedStates', cdk.requiredValidator)(properties.includedStates));\n errors.collect(cdk.propertyValidator('includedStates', cdk.listValidator(cdk.validateString))(properties.includedStates));\n errors.collect(cdk.propertyValidator('standardKnowledgeArticleTypeConfiguration', CfnDataSource_SalesforceStandardKnowledgeArticleTypeConfigurationPropertyValidator)(properties.standardKnowledgeArticleTypeConfiguration));\n return errors.wrap('supplied properties not correct for \"SalesforceKnowledgeArticleConfigurationProperty\"');\n}",
"function cfnDataSourceSharePointConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SharePointConfigurationPropertyValidator(properties).assertSuccess();\n return {\n CrawlAttachments: cdk.booleanToCloudFormation(properties.crawlAttachments),\n DisableLocalGroups: cdk.booleanToCloudFormation(properties.disableLocalGroups),\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n ExclusionPatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.exclusionPatterns),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n InclusionPatterns: cdk.listMapper(cdk.stringToCloudFormation)(properties.inclusionPatterns),\n SecretArn: cdk.stringToCloudFormation(properties.secretArn),\n SharePointVersion: cdk.stringToCloudFormation(properties.sharePointVersion),\n SslCertificateS3Path: cfnDataSourceS3PathPropertyToCloudFormation(properties.sslCertificateS3Path),\n Urls: cdk.listMapper(cdk.stringToCloudFormation)(properties.urls),\n UseChangeLog: cdk.booleanToCloudFormation(properties.useChangeLog),\n VpcConfiguration: cfnDataSourceDataSourceVpcConfigurationPropertyToCloudFormation(properties.vpcConfiguration),\n };\n}",
"_generateEntityConfig() {\n let content = renders.renderEntityConfig(this._config);\n this._writer.writeEntityConfig(content);\n }",
"function renderWorkflowConfiguration() {\n const configurationHolder = $('#configurationHolder');\n const configurationValue = configurationHolder.val();\n\n if (configurationValue) {\n configurationHolder.val(JSON.stringify(JSON.parse(configurationValue), null, 2));\n }\n }",
"function cfnDataSourceSalesforceStandardObjectAttachmentConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceStandardObjectAttachmentConfigurationPropertyValidator(properties).assertSuccess();\n return {\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n };\n}",
"function cfnDataSourceSalesforceStandardObjectConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_SalesforceStandardObjectConfigurationPropertyValidator(properties).assertSuccess();\n return {\n DocumentDataFieldName: cdk.stringToCloudFormation(properties.documentDataFieldName),\n DocumentTitleFieldName: cdk.stringToCloudFormation(properties.documentTitleFieldName),\n FieldMappings: cdk.listMapper(cfnDataSourceDataSourceToIndexFieldMappingPropertyToCloudFormation)(properties.fieldMappings),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}",
"function cfnDataSourceInlineCustomDocumentEnrichmentConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_InlineCustomDocumentEnrichmentConfigurationPropertyValidator(properties).assertSuccess();\n return {\n Condition: cfnDataSourceDocumentAttributeConditionPropertyToCloudFormation(properties.condition),\n DocumentContentDeletion: cdk.booleanToCloudFormation(properties.documentContentDeletion),\n Target: cfnDataSourceDocumentAttributeTargetPropertyToCloudFormation(properties.target),\n };\n}",
"function hostedZoneResourceHostedZoneConfigPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n HostedZoneResource_HostedZoneConfigPropertyValidator(properties).assertSuccess();\n return {\n Comment: cdk.stringToCloudFormation(properties.comment),\n };\n }",
"function cfnDataSourceCustomDocumentEnrichmentConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_CustomDocumentEnrichmentConfigurationPropertyValidator(properties).assertSuccess();\n return {\n InlineConfigurations: cdk.listMapper(cfnDataSourceInlineCustomDocumentEnrichmentConfigurationPropertyToCloudFormation)(properties.inlineConfigurations),\n PostExtractionHookConfiguration: cfnDataSourceHookConfigurationPropertyToCloudFormation(properties.postExtractionHookConfiguration),\n PreExtractionHookConfiguration: cfnDataSourceHookConfigurationPropertyToCloudFormation(properties.preExtractionHookConfiguration),\n RoleArn: cdk.stringToCloudFormation(properties.roleArn),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move finger to the center of the element | async moveToCenter(): Promise<void> {
const center = await this._parent.getAbsoluteCenter();
await this.driver.activeWindow.touch.move(center.x, center.y);
} | [
"function moveFinger() {\n finger.x = mouseX;\n finger.y = mouseY;\n}",
"async upAtCenter(): Promise<void> {\n const center = await this._parent.getAbsoluteCenter();\n await this.driver.activeWindow.touch.down(center.x, center.y);\n }",
"center() {\n this.translationX = this.canvas.width * 0.5\n this.translationY = this.canvas.height * 0.5\n }",
"_updatePosFromCenter() {\n let half = this._size.$multiply(0.5);\n this._topLeft = this._center.$subtract(half);\n this._bottomRight = this._center.$add(half);\n }",
"function moveToCenter() {\n $._resetToCenter();\n}",
"function on_touch_move(e) {\r\n\r\n move_delta.set(move_start.x - e.touches[0].pageX, move_start.y - e.touches[0].pageY);\r\n\r\n dom_element.style.left = (dom_start.x - move_delta.x) + \"px\";\r\n dom_element.style.bottom = (dom_start.y + move_delta.y) + \"px\";\r\n\r\n event.preventDefault();\r\n event.stopPropagation();\r\n }",
"async downAtCenter(): Promise<void> {\n const center = await this._parent.getAbsoluteCenter();\n await this.driver.activeWindow.touch.down(center.x, center.y);\n }",
"stepExactCenter_() {\n this.mutateElement(() => {\n this.updatePositions_(0.5);\n });\n }",
"function moveFinger(id, xPosition, yPosition, size = DEFAULT_SIZE) {\n var halfSize = size / 2;\n var elem = document.getElementById('touch' + id);\n elem.style.left = (xPosition - halfSize) + \"px\";\n elem.style.top = (yPosition - halfSize) + \"px\";\n}",
"setMiddleCanva(){\n this.setX(this.canvas.width/2);\n this.setY(this.canvas.height/2);\n this.setDx(0);\n this.setDy(0);\n }",
"function centerElement(element) {\r\n var pixel = viewer.viewport.pixelFromPoint(viewer.viewport.getCenter());\r\n $(element).css({\r\n top: pixel.y,\r\n left: pixel.x\r\n });\r\n }",
"function moveToViewCenter() {\n if (visible) {\n ctx.translate((width / 2) - x(viewCenter.x), -y(viewCenter.y) + (height / 2));\n }\n }",
"function moveDownCenter() {\n var x = 40;\n var y = hero.pos.y - 12;\n hero.moveXY(x, y);\n}",
"centerScreen() {\n self.moveCenter(0,0);\n }",
"function touchShip(ev) {\n // make the element draggable by giving it an absolute position and modifying the x and y coordinates\n ship.classList.add(\"fixed\");\n const {pageX, pageY} = ev.targetTouches[0];\n // Place element where the finger is\n ship.style.left = pageX - 25 + \"px\";\n ship.style.top = pageY - 25 + \"px\";\n ev.preventDefault();\n }",
"centerSelected(event) {\n\t\tlet element = document.querySelector('.slide img#active')\n\t\tlet scrollMax = this.slider.scrollWidth;\n\t\tlet offsetLeft = element.offsetLeft - this.slider.offsetLeft;\n\t\tlet centerView = this.slider.offsetWidth / 2;\n\t\tlet width = element.getBoundingClientRect().width;\n\t\tlet offset = offsetLeft - centerView + width / 2;\n\t\toffset = (offset <= 0) ? 0 : (offset >= scrollMax) ? scrollMax : offset\n\t\tthis.slider.scrollLeft = offset;\n\t\tthis.scrollOffset = offset;\n\t\tconsole.log('setting ', offset)\n\n\t}",
"function scrollToCenter(){\n\t\t\t\t\tvar pw = $zoomContain.width();\n\t\t\t\t\tvar ph = $zoomContain.height();\n\t\t\t\t\tvar w = targetImg.offsetWidth;\n\t\t\t\t\tvar h = targetImg.offsetHeight;\n\t\t\t\t\t$zoomContain[ 0 ].scrollLeft = ( w / 2 ) - ( pw / 2 );\n\t\t\t\t\t$zoomContain[ 0 ].scrollTop = ( h / 2 ) - ( ph / 2 );\n\t\t\t\t}",
"computeCenter() {\n self.centerX = self.screenX + self.screenDisplacementX;\n self.centerY = self.screenY + self.screenDisplacementY;\n }",
"onTouchStart (e) {\n var t = e.touches[0]\n this.swipe.sX = t.screenX\n this.swipe.sY = t.screenY\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets log level for all Firebase SDKs. All of the log types above the current log level are captured (i.e. if you set the log level to `info`, errors are logged, but `debug` and `verbose` logs are not). | function setLogLevel(logLevel) {
(0,_firebase_logger__WEBPACK_IMPORTED_MODULE_1__.setLogLevel)(logLevel);
} | [
"function setLogLevel(logLevel) {\n Object(_firebase_logger__WEBPACK_IMPORTED_MODULE_1__[\"setLogLevel\"])(logLevel);\n}",
"function setLevel(level) {\n switch (level.toUpperCase()) {\n case 'TRACE':\n level = TRACE;\n break;\n case 'DEBUG':\n level = DEBUG;\n break;\n case 'INFO' :\n level = INFO;\n break;\n case 'WARN':\n case 'WARNING':\n level = WARN;\n break;\n case 'ERROR':\n level = ERROR;\n break;\n case 'FATAL':\n level = FATAL;\n break;\n }\n console.log(\"Set log level to \" + level);\n defaultLevel = level;\n}",
"function setLogLevel(newLevel) {\n exports.commonLogger.level = newLevel;\n}",
"setLogLevel(logLevel) {\n if (this.availableLogLevels.indexOf(logLevel) > -1) {\n this.logLevel = logLevel;\n }\n }",
"function setLogLevel(level) {\n Logger.GLOBAL_LEVEL = level;\n}",
"function setLogLevel(level) {\r\n currentLogLevel = Level[level];\r\n}",
"function setLevel(l) {\n level = validateLevel(l);\n if (useBaseLevel) {\n log.level = level;\n }\n }",
"function setDefaultLogFunctions() {\n _(['trace', 'debug', 'info', 'warning', 'error']).forEach((name, index) => {\n addLogLevel.call(this, index, name);\n });\n this.setLevel('debug');\n}",
"setLogLevel(logLevel) {\n CTKAdSettingsManager.setLogLevel(logLevel);\n }",
"async function _setLogOpts() {\n const fbRootRef = await FBHelper.getRootRefUnlimited();\n const base = `/config/${APP_NAME}/logs`;\n\n const fbConsoleLogOptRef = await fbRootRef.child(`${base}/console`);\n fbConsoleLogOptRef.on('value', (snapshot) => {\n const opts = snapshot.val();\n const level = opts?.logLevel || 100;\n log.log(APP_NAME, `Changing 'console' log settings`, {level});\n log.setConsoleLogOpts(level);\n });\n\n const fbFileLogOptRef = await fbRootRef.child(`${base}/file`);\n fbFileLogOptRef.on('value', (snapshot) => {\n const opts = snapshot.val();\n const level = opts?.logLevel || 50;\n const logPath = opts?.logPath || LOG_PATH_FILE;\n log.log(APP_NAME, `Changing 'file' log settings`, {level, logPath});\n log.setFileLogOpts(level, logPath);\n });\n\n const fbFirebaseLogOptRef = await fbRootRef.child(`${base}/firebase`);\n fbFirebaseLogOptRef.on('value', (snapshot) => {\n const opts = snapshot.val();\n const level = opts?.logLevel || 50;\n const logPath = opts?.logPath || LOG_PATH_FB;\n log.log(APP_NAME, `Changing 'firebase' log settings`, {level, logPath});\n log.setFirebaseLogOpts(level, logPath);\n });\n}",
"function setDefaultLogFunctions() {\n var _this2 = this;\n\n (0, _lodash2.default)(['trace', 'debug', 'info', 'warning', 'error']).forEach(function (name, index) {\n addLogLevel.call(_this2, index, name);\n });\n this.setLevel('debug');\n}",
"function setLevels() { // request logger must have same methods as log\n\tfor (var level in log.levels) { // define functions if available in log\n\t\tif (log[level]){\n\t\t\tLogger[level] = (function (level) {\n\t\t\t\treturn function (msg, meta) {\n\t\t\t\t\tvar meta = meta || msg || {};\n\t\t\t\t\tif ('string' === typeof meta) meta = {};\n\t\t\t\t\tif ('string' !== typeof msg) msg = '' + msg;\n\t\t\t\t\tlog[level](msg, x(this.extend(meta),{name:this.name}));\n\t\t\t\t};\n\t\t\t})(level);\n\t\t}\n\t\telse {\n\t\t\tif (Logger[level]) {\n\t\t\t\tdelete Logger[level];\n\t\t\t}\n\t\t}\n\t}\n}",
"setLevel( newLevel ) {\n /* Checks that the new level provided isn't invalid */\n if ( newLevel > LogLevel.MAX || newLevel < LogLevel.MIN ) {\n /* New logging level doesn't exist, throw an exception */\n throw new LoggerException( `${newLevel} is not a valid logging level` );\n }\n\n /* Set the new logging level and log it internally */\n this.level = newLevel;\n this.log.debug( `Log level set to ${LogLevel.getDisplayName( this.level )}` );\n }",
"function enableLevels () {\n for (let namespace in loggers) {\n let logger = loggers[namespace];\n defineFns(logger, namespace);\n }\n}",
"function set_log_level() {\n var e = document.getElementById(\"logger_namespace\");\n var namespace = e.options[e.selectedIndex].value;\n e = document.getElementById(\"logger_level\");\n var level = e.options[e.selectedIndex].value;\n _socket_send({\n action: \"set_log_level\",\n namespace: namespace,\n level: level\n });\n}",
"setStandardMode() {\n this.logger.level = STANDARD_MODE_LOGGER_LEVEL;\n }",
"function setLogLevelHandler(request, reply) {\n request.sth = request.sth || {};\n request.sth.context = getContext(request);\n\n caLogger.debug(\n request.sth.context,\n request.method.toUpperCase() + ' ' + request.url.path +\n ' with headers: ' + JSON.stringify(request.headers)\n );\n\n var level = (request.query.level.toUpperCase() === 'WARNING') ?\n 'WARN' : request.query.level.toUpperCase();\n caLogger.setLevel(level);\n\n caLogger.info(\n request.sth.context,\n 'Log level set to: ' + level\n );\n\n reply();\n}",
"setLogLevel(level) {\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n // tslint:disable-next-line: no-unsafe-any\n return RNSentry.setLogLevel(level);\n }",
"async _enableLogging() {\n try {\n let result = await this.stub.getState(LOGLEVEL_KEY);\n if (result.length === 0) {\n result = process.env.CORE_CHAINCODE_LOGGING_LEVEL;\n if (!result) {\n result = 'INFO';\n }\n }\n this.currentLogLevel = LOG_LEVELS[result] ? LOG_LEVELS[result] : LOG_LEVELS.INFO;\n }\n catch(err) {\n this.currentLogLevel = LOG_LEVELS.INFO;\n this.logWarning('failed to get logging level from world state: ' + err);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displaying profiles from local storage | static displayProfiles() {
const profiles = Store.getProfilesFromLocalStorage();
profiles.forEach(profile => {
const ui = new UI();
ui.addProfileToList(profile)
})
} | [
"function displayProfiles() {\r\n let store = browser.storage.local.get({\r\n profiles: []\r\n });\r\n store.then(function(results) {\r\n var profiles = results.profiles;\r\n\r\n for (var i = 0; i < profiles.length; i++) {\r\n addProfileToAList(profiles[i]);\r\n }\r\n });\r\n}",
"static displayProfiles() {\n const profiles = Store.getProfiles();\n profiles.forEach(profile => {\n const ui = new UI();\n ui.addProfileToLIst(profile);\n });\n }",
"function loadProfiles(){\n\n\t//query the database, if empty, create an empty list, otherwise parse the stored JSON into a list of javascript objects\n\tprofiles = JSON.parse(localStorage.getItem(\"profiles\")) || [];\n\n\t//if other classes exist, show them, otherwise hide the panel to show them\n\tif(profiles.length == 0){\n\t\taddClass(\"existingProfilesHolder\", \"hidden\");\n\t}else{\n\t\tremoveClass(\"existingProfilesHolder\", \"hidden\");\n\t}\n\tupdateViews();\n}",
"async function showProfiles() {\n const userId = localStorage.getItem('currentAccount');\n const profiles = await util.getProfilesByUserAccount(userId);\n\n await profiles.forEach(createProfileElement);\n}",
"function displayProfile() {\n //Format and display the profile bits\n $('#profile-view .nickname').text(userProfile.nickname);\n $('#profile-view .full-profile').text(JSON.stringify(userProfile, null, 2));\n $('#profile-view img').attr('src', userProfile.picture);\n }",
"function displayProfile() {\n\tcurrentGrade = localStorage.getItem(\"Student Grade:\");\n\tcurrentGender = localStorage.getItem(\"Student Gender:\");\n\tcurrentClub = localStorage.getItem(\"Student Club:\");\n\tcurrentStudentNumber = localStorage.getItem(\"Student Number:\");\n\tcurrentProfile = \"<p>Grade: \" + currentGrade + \"<br>Gender: \" + currentGender + \"<br>Club: \" + currentClub + \"<br>Student Number: \" + currentStudentNumber;\n\tdocument.getElementById(\"currentprofile\").innerHTML = currentProfile;\n}",
"static getProfile() {\r\n let profiles;\r\n if (localStorage.getItem('profiles') === null) {\r\n profiles = []\r\n } else {\r\n profiles = JSON.parse(localStorage.getItem('profiles'));\r\n }\r\n return profiles;\r\n }",
"function displayProfile(){\n\t\tGlobalFactory.getUserInfo($stateParams.id).then(function(res){\n\t\t\tvm.profile = res.data;\n\t\t\tconsole.log(vm.profile);\n\t\t});\n\t}",
"function saveProfiles(){\n\tlocalStorage.setItem(\"profiles\", JSON.stringify(profiles));\n}",
"static getProfilesFromLocalStorage() {\n let profiles;\n if (localStorage.getItem('profiles') === null) {\n profiles = [];\n } else {\n profiles = JSON.parse(localStorage.getItem('profiles'));\n }\n return profiles;\n }",
"function viewProfiles(){\n\n\t//set current profile to null (need to login one profile now)\n\tprofile = null;\n\n\tloadProfiles();\n\tswitchView(\"profilesPage\");\n}",
"static getProfiles() {\r\n let profiles;\r\n if (localStorage.getItem('profiles') === null) {\r\n profiles = [];\r\n } else {\r\n profiles = JSON.parse(localStorage.getItem('profiles'));\r\n }\r\n return profiles;\r\n }",
"function _storeProfile() {\n var encoded = {\n 'n': nacl.util.encodeBase64(_profile.n),\n 'id': _profile.id\n };\n localStorage.setItem('profile', JSON.stringify(encoded));\n }",
"function setupProfilePicture() {\n if (loggedIn && localStorage.getItem(\"profile\")) {\n $(\"#profile\").attr(\"src\", localStorage.getItem(\"profile\"));\n }\n}",
"function loadProfile() {\n if(!supportsHTML5Storage()) { return false; }\n // we have to provide to the callback the basic\n // information to set the profile\n getLocalProfile(function(profileImgSrc, profileName, profileReAuthEmail) {\n //changes in the UI\n $(\"#profile-img\").attr(\"src\",profileImgSrc);\n $(\"#profile-name\").html(profileName);\n $(\"#reauth-email\").html(profileReAuthEmail);\n $(\"#inputEmail\").hide();\n $(\"#remember\").hide();\n });\n}",
"function loadProfile() {\n if(!supportsHTML5Storage()) { return false; }\n // we have to provide to the callback the basic\n // information to set the profile\n getLocalProfile(function(profileImgSrc, profileName, profileReAuthEmail) {\n //changes in the UI\n $(\"#profile-img\").attr(\"src\",profileImgSrc);\n $(\"#profile-name\").html(profileName);\n $(\"#reauth-email\").html(profileReAuthEmail);\n $(\"#inputEmail\").hide();\n $(\"#remember\").hide();\n });\n }",
"function loadProfile() {\r\n\r\n if (!supportsHTML5Storage()) {\r\n return false;\r\n }\r\n // we have to provide to the callback the basic\r\n // information to set the profile\r\n getLocalProfile(function (profileImgSrc, profileName, profileReAuthEmail) {\r\n //changes in the UI\r\n $(\"#profile-img\").attr(\"src\", profileImgSrc);\r\n $(\"#profile-name\").html(profileName);\r\n $(\"#reauth-email\").html(profileReAuthEmail);\r\n $(\"#inputEmail\").hide();\r\n $(\"#remember\").hide();\r\n });\r\n}",
"function retrieveProfileInfo() {\n return JSON.parse(sessionStorage.getItem(\"user\"));\n}",
"function updateProfileDataInStorage() {\n\n if (myProfile.username) {\n var myProfileDataString = JSON.stringify(myProfile);\n updateAllProfilesFromMyProfile();\n var allProfilesDataString = JSON.stringify(allProfiles);\n var allPetCardsDataString = JSON.stringify(allPetCards);\n localStorage.setItem('currentUser', myProfileDataString);\n localStorage.setItem('allProfiles', allProfilesDataString);\n localStorage.setItem('allPetCards', allPetCardsDataString);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method creates the `Controllers` folder | createControllerFolder() {
// check if folder `Controllers` already exists
if (!fs.existsSync(`${this.controller}`)) {
// create `Controllers` folder
fs.mkdirSync(`${this.controller}`);
return;
}
console.error(`${this.controller} folder already exists`);
} | [
"function createControllersFolder() {\n createFolder(`${dir}controllers`);\n let template = require('./generators/controllers_gen')();\n fs.writeFile(`${dir}controllers/example_controller.js`, template, (err) => {\n if (err) console.log(`... an error occured while creating controllers ...`);\n else console.log(`... controllers created ...`);\n });\n}",
"function createController(controller) {\n mkpath('app/controllers', function (err) {\n if (err) throw err;\n console.log('Created or confirmed - app/controllers/');\n\n // Pulls controller from seed-controller.js\n var body = generateController(controller);\n\n // Creates controllername(s).js file\n fs.writeFile(\"app/controllers/\" + controller + \"s.js\", body , function(err) {\n if(err) {\n console.log(err);\n } else {\n console.log(\"Created - app/controllers/\" + controller + \"s.js\");\n }\n }); \n });\n}",
"async initControllers() {\n // define o caminho onde os controllers da aplicacao se encontram\n const caminho = path.join(__dirname, \"app\", \"controllers\");\n // lista os controllers da aplicacao\n const controllers = await fs.readdirSync(caminho);\n // caso encontre algum controller\n if (controllers && controllers.length > 0) {\n controllers.forEach(controller => {\n // Inicializa a rota dos controllers, exceto do arquivo Controller.js\n // que eh a classe que os outros controllers estendem\n if (controller.toLowerCase() !== \"controller.js\") {\n this.initRoute(`${caminho}/${controller.replace(\".js\", \"\")}`);\n }\n });\n }\n }",
"loadControllers() {\n if (!this.controllersDir)\n throw new Error(`Please specify a 'controllersDir' when initialising`);\n let controllers = {};\n fs.readdirSync(this.controllersDir).forEach(controllerFile => {\n if (!controllerFile.match(/\\.js$/))\n return;\n const path = `${process.cwd()}/${this.controllersDir}/${controllerFile}`;\n const r = require(path);\n const controllerName = controllerFile.replace('.js', '');\n controllers[controllerName] = r;\n });\n this.controllers = controllers;\n }",
"setupControllers() {\n const globalController = new global_1.GlobalController();\n const authController = new auth_1.AuthController();\n const userController = new user_1.UserController();\n const uploadController = new file_1.FileController();\n const projectController = new project_1.ProjectController();\n const homeController = new home_1.HomeController();\n super.addControllers([globalController, authController, userController, uploadController, projectController, homeController]);\n }",
"createControllerFile() {\n // check if `auth.js` exists already in the controllers folder\n if (!fs.existsSync(`${this.controller}/auth.js`)) {\n const file = path.join(__dirname, '../files/auth.js');\n\n fs.readFile(file, \"utf-8\", (err, data) => {\n if (err) {\n console.log(err);\n return;\n }\n\n // write `auth.js` file\n fs.writeFile(`${this.controller}/auth.js`, data, (err) => {\n if (err) {\n console.log('Error creating auth.js file');\n return;\n }\n\n console.log(\"Successfully created auth.js\");\n });\n });\n\n return;\n }\n\n console.log(`auth.js already exists`);\n }",
"function makeFolder() {\n utils.createDirectory('app');\n utils.createDirectory('app/custom_filters');\n utils.createDirectory('app/modules');\n utils.createDirectory('app/plugins');\n utils.createDirectory('app/widgets');\n utils.createDirectory('app/middleware');\n\n utils.createDirectory('core');\n utils.createDirectory('core/custom_filters');\n utils.createDirectory('core/modules');\n utils.createDirectory('core/plugins');\n utils.createDirectory('core/widgets');\n}",
"_createAppFolders() {\n\n /* Base folder */\n mkdirp('app/fonts');\n mkdirp('app/images');\n mkdirp('app/scripts');\n mkdirp('app/styles');\n\n /* Folder for enginge */\n mkdirp('app/_documentation');\n mkdirp('app/_config');\n mkdirp('app/_patterns');\n mkdirp('app/_data');\n\n }",
"function loadControllers() {\n const dir = process.cwd();\n\n if (!fs.existsSync(`${dir}/app/controllers`)) {\n throw new Error(\n `Cannot locate app/controllers in directory ${dir}. Ensure rails was started in the same filepath as your package.json and that app/controllers exists.`\n );\n }\n\n const controllers = fs.readdirSync(`${dir}/app/controllers`);\n\n for (let i = 0; i < controllers.length; i++) {\n if (\n !fs.lstatSync(`${dir}/app/controllers/${controllers[i]}`).isDirectory()\n ) {\n continue;\n }\n\n routes[controllers[i]] = {\n handlers: [],\n \":id\": {\n handlers: []\n }\n };\n\n const actions = fs.readdirSync(\n `${dir}/app/controllers/${controllers[i]}`\n );\n\n for (let j = 0; j < actions.length; j++) {\n const action = actions[j].split(\".\");\n\n if (\n action.length !== 3 ||\n action[1] !== \"action\" ||\n action[2] !== \"js\" ||\n Config.actionNames.indexOf(action[0]) === -1 ||\n !fs\n .lstatSync(`${dir}/app/controllers/${controllers[i]}/${actions[j]}`)\n .isFile()\n ) {\n throw new Error(\n `Action ${action[0]} for controller ${\n controllers[i]\n } is not of the supported format.`\n );\n }\n\n // todo: maybe extract these to independent functions and a switch?\n if (action[0] === \"create\") {\n routes[controllers[i]].handlers.push({\n verb: \"POST\",\n accepts: \"application/json\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/create.action.js`)\n });\n } else if (action[0] === \"delete\") {\n routes[controllers[i]][\":id\"].handlers.push({\n verb: \"DELETE\",\n accepts: \"application/json\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/delete.action.js`)\n });\n } else if (action[0] === \"edit\") {\n routes[controllers[i]][\":id\"][\"edit\"] = {\n handlers: [\n {\n verb: \"GET\",\n accepts: \"application/html\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/edit.action.js`)\n }\n ]\n };\n } else if (action[0] === \"find\") {\n routes[controllers[i]][\":id\"].handlers.push({\n verb: \"GET\",\n accepts: \"application/json\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/find.action.js`)\n });\n } else if (action[0] === \"index\") {\n routes[controllers[i]].handlers.push({\n verb: \"GET\",\n accepts: \"application/html\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/index.action.js`)\n });\n } else if (action[0] === \"list\") {\n routes[controllers[i]].handlers.push({\n verb: \"GET\",\n accepts: \"application/json\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/list.action.js`)\n });\n } else if (action[0] === \"new\") {\n routes[controllers[i]][\"edit\"] = {\n handlers: [\n {\n verb: \"GET\",\n accepts: \"application/html\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/new.action.js`)\n }\n ]\n };\n } else if (action[0] === \"show\") {\n routes[controllers[i]][\":id\"].handlers.push({\n verb: \"GET\",\n accepts: \"application/html\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/show.action.js`)\n });\n } else if (action[0] === \"update\") {\n routes[controllers[i]][\":id\"].handlers.push({\n verb: \"PUT\",\n accepts: \"application/json\",\n fn: require(`${dir}/app/controllers/${\n controllers[i]\n }/update.action.js`)\n });\n } else {\n throw new Error(`action ${action[0]} not supported in Rails`);\n }\n }\n }\n }",
"function loadControllers() {\n var controllersDir = path.join(__dirname, 'controllers/');\n fs.readdirSync(controllersDir)\n .filter(function (file) {\n return (file.indexOf('.') !== 0) && (file.slice(-3) === '.js');\n })\n .forEach(function (file) {\n var controller = require(path.join(controllersDir, file));\n app.use(controller.createRouter());\n });\n}",
"function createControllers() {\n\t// Create wrapper div\n\tvar controller = document.createElement(\"div\");\n\tcontroller.className = \"controller\";\n\tdocument.querySelector(\"body\").appendChild(controller);\n\n\t// Previous button\n\tvar prevButton = document.createElement(\"button\");\n\tprevButton.id = \"prevButton\";\n\tprevButton.textContent = \"Prev\";\n\tcontroller.appendChild(prevButton);\n\tprevButton.addEventListener(\"click\", gotoPreviousPage);\n\n\t// Next button\n\tvar nextButton = document.createElement(\"button\");\n\tnextButton.id = \"nextButton\";\n\tnextButton.textContent = \"Next\";\n\tcontroller.appendChild(nextButton);\n\tnextButton.addEventListener(\"click\", gotoNextPage);\n\n\t// Page number\n\tvar pageNumber = document.createElement(\"span\");\n\tpageNumber.id = \"pageNumber\";\n\tcontroller.appendChild(pageNumber);\n}",
"function createRoutesFolder() {\n createFolder(`${dir}routes`);\n let template = require('./generators/routes_gen')();\n fs.writeFile(`${dir}routes/example_routes.js`, template, (err) => {\n if (err) console.log(`... an error occured while creating routes ...`);\n else console.log(`... routes created ...`);\n });\n}",
"_constructControllers() {\n this.accountsController = new AccountsController(this.registration);\n this.clientsController = new ClientController();\n this.authorityController = new AuthorityController();\n this.errorsController = new ErrorController();\n this.tokenController = new TokenController();\n }",
"function create( name ){\n const folder = createFolder({\n textCreator,\n name,\n guiAdd: add,\n guiRemove: remove,\n addSlider: addSimpleSlider,\n addDropdown: addSimpleDropdown,\n addCheckbox: addSimpleCheckbox,\n addButton: addSimpleButton\n });\n\n controllers.push( folder );\n if( folder.hitscan ){\n hitscanObjects.push( ...folder.hitscan );\n }\n\n return folder;\n }",
"get controllerPath() {\n return path.resolve(this.rootPath, this.appPath, this.paths.controller || 'controller');\n }",
"function addController( name )\n\t{\n\t\tif ( _controller[name] )\n\t\t\treturn ;\n\n\t\ttry\n\t\t{\n\t\t\tvar obj = require( \"./controllers/\" + name + \".js\" );\n\t\t\t_controller[name] = new obj( _app, _helpers );\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\tconsole.log(\"[ERROR] Failed to instantiate '%s' controller, check routes.json or ./controllers/%s.js\", name, name);\n\t\t}\n\t}",
"function createRoutes(controllerPath,tablas){\n var contenido=`\\n`;\n contenido+=`const auth= require('../auth/auth');\\n`;\n contenido+=`\\n`; \n contenido+=`app.route('/autenticar').post(auth.authentication);\\n`;\n contenido+=`\\n`;\n tablas.forEach(a=>{\n contenido+=`//--${a}---\\n`;\n contenido+=`var ${a.toLowerCase()}Controller = require(\"../controllers/${a.toLowerCase()}Controller\");\\n`;\n contenido+=`app.route('/${a.toLowerCase()}').get(auth.rp(app),${a.toLowerCase()}Controller.list_all_${a})\\n`;\n contenido+=`.post(auth.rp(app),${a.toLowerCase()}Controller.create_a_${a})\\n`\n contenido+=`.put(auth.rp(app),${a.toLowerCase()}Controller.update_a_${a});\\n`;\n contenido+=`app.route('/${a.toLowerCase()}/filter').post(auth.rp(app),${a.toLowerCase()}Controller.list_filter_${a})\\n`;\n contenido+=`\\n`;\n contenido+=`\\n`;\n });\n const content= `'use strict';\n module.exports = function(app) {\n ${contenido} \n }`;\n createFile(controllerPath,'index.js',content);\n}",
"function Controller () {}",
"static loadControllers(http) {\n let config = http.config;\n let controllerPath = require('path').normalize(sand.appPath + config.controllerPath);\n\n if (!fs.existsSync(controllerPath)) {\n http.log.warn(\"WARN: Missing controllers directory. Skipping loading of controllers...\".yellow);\n return;\n }\n\n let controllers = require('require-all')({\n dirname: controllerPath,\n filter: /(\\w+)\\.js/\n });\n\n Router.controllers = flattenObject(controllers);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all trajectories from the grid. | _clearTrajectories() {
this.elem.selectAll('.intention').remove();
for (let i = 0; i < this.gridSize; i++) {
for (let j = 0; j < this.gridSize; j++) {
if (!this._isCornerCell(i, j)) {
this.grid[i][j].hexagon.attr('fill', 'none');
}
}
}
} | [
"function clearGrid() {\n clearPipes();\n clearObstacles();\n}",
"function clearGrid() {\n while (grid.firstChild) {\n grid.removeChild(grid.firstChild);\n }\n }",
"function clearGrids() {\n\t\t var removeGridId;\n\t\t var removeGridElement;\n\t\t var parentElement = document.getElementById(\"canvasFloat\");\n\t\t for (var i = 0; i <= nextGrid; i++) {\n\t\t\t removeGrids = String(\"#canvasGrid\"+i);\n\t\t\t $(removeGrids).remove();\n\t\t }\n\t\t removeGridsFromList();\n\t\t nextGrid = 0;\n\t\t gridArray.splice(0,gridArray.length);\n\t\t gridArrayIndex = 0;\n\t\t console.log(gridArray);\n\t\t console.log(\"successfully removed all grids\");\n\t }",
"function clearGrid() {\n while (container.firstChild) {\n container.removeChild(container.lastChild);\n }\n}",
"clearLines(){\n let lines = Array(this.grid[0].length);\n for(let i=0;i<lines.length;i++){\n lines[i] = true;\n }\n for(let x=0;x<this.grid.length;x++){\n for(let y=0;y<this.grid[x].length;y++){\n if(this.grid[x][y] == null){\n lines[y] = false;\n }\n }\n }\n let empty = 0;\n for(let y=lines.length-1;y>0;y--){\n if(lines[y]){\n for(let x=0;x<this.grid.length;x++){\n this.grid[x].splice(y,1);\n }\n empty++;\n }\n }\n for(let x=0;x<this.grid.length;x++){\n for(let i=0;i<empty;i++){\n this.grid[x].splice(0,0,null);\n }\n }\n }",
"function clearGrid() {\n const gridArray = Array.from(gridContainer.childNodes);\n gridArray.forEach((element) => {\n gridContainer.removeChild(element);\n });\n}",
"function deleteGrid() {\r\n squares.forEach((square) => {\r\n gridArea.removeChild(square);\r\n });\r\n}",
"function clearGrid() {\n const boxes = gridContainer.querySelectorAll('.box');\n boxes.forEach(box => {\n box.remove();\n })\n}",
"ClearAllTiles()\n {\n for(let y = 0; y < this.height ; y++)\n {\n for(let x = 0; x < this.width ; x++)\n {\n this.tiles[y][x].Clear();\n }\n }\n }",
"function remove_all() {\r\n paper.clear();\r\n ml.length = 0;\r\n xy.length = 0;\r\n pa.length = 0;\r\n pathObjects.length = 0;\r\n marquees.length = 0;\r\n currpaths = \"\";\r\n datastring = '';\r\n }",
"function removeGrid() {\n grid.empty();\n}",
"clear() {\n while (this.tBodies.length) {\n this.tBodies[0].remove()\n }\n }",
"cleanBoard() {\n this.pieces = []\n\n this.tiles.forEach(row => {\n row.forEach(tile => {\n tile.clearPieces()\n })\n })\n }",
"function removeGrid() {\n for (var i = 0; i<= gridGroup.children.length-1; i++) {\n gridGroup.children[i].remove();\n }\n gridGroup.remove();\n}",
"function clear() {\n pause();\n\n // Set the grid to a completely new generated grid\n setGrid(generateGrid());\n }",
"disposeRows() {\n // cleanup unused rows\n while (this.rows.length) {\n this.sceneGraph.root.removeChild(this.rows.pop());\n }\n this.rows = this.newRows;\n this.newRows = null;\n }",
"function clearGrid (){\n for (let i = 0; i < 625; i++){\n cells[i].classList = null\n \n }\n }",
"clearBoard(){\n\n this.getCells().forEach(function(item){\n\n item.removeFigure();\n });\n }",
"destroyTiles(quadTrees) {\n let count = 0;\n for (let [url, tile] of this.available.entries()) {\n if (!quadTrees.has(url)) {\n this.removeChild(tile);\n tile.destroy(true);\n this.requested.delete(url);\n this.available.delete(url);\n count += 1;\n }\n }\n if (count && this.debug)\n console.log('destroyObsoleteTiles', this.level, count);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is Valid AMOUNT value | function isValidAMOUNTValue(amount) {
return amount != '' && /^\d*$/.test(amount)
} | [
"function validProductAmount(amount)\n {\n if(!isNaN(amount)) //if is not a number\n {\n var flval=parseFloat(amount); //get float value of the amount\n if(Number.isInteger(flval)) //check if amount is integer number\n { \n if(flval>0)\n return true;\n }\n }\n return false;\n }//end function validProductAmount ",
"function CheckAmount(value) {\r\n\tvar s = true;\r\n\tfor (var a = 0; a < value.length; a++) {\r\n\t\tvar c = value.substring(a, a+1);\r\n\t\tif (c < \"0\" || c > \"9\") {\r\n\t\t\tif (c == \".\") {\r\n\t\t\t\ts = true\r\n\t\t\t} else {\r\n\t\t\t\ts = false\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (s == true) {\r\n\t\treturn true;\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}",
"validate(value){\n if (!isNaN(parseFloat(value)) && isFinite(value)){ //is numeric\n if (value >= 0 && value <= this.props.account.balanceUsd){\n return true;\n }\n }\n return false;\n }",
"function isAmount(value) {\n return new RegExp(regExpAmount, 'gi').test(value);\n}",
"function isAmount(obj) {\n if (obj === null || typeof obj !== \"object\") {\n return false\n }\n if (typeof obj.value !== \"string\" || !isFloat(obj.value)) {\n return false\n }\n if (!isTumCode(obj.currency)) {\n return false\n }\n // AMOUNT could have a field named\n // either as 'issuer'\n // or as 'counterparty'\n // for SWT, this can be undefined\n if (typeof obj.issuer !== \"undefined\" && obj.issuer !== \"\") {\n if (!Wallet.isValidAddress(obj.issuer)) {\n return false\n }\n } else {\n // if currency === 'SWT',自动补全issuer.\n if (obj.currency === \"SWT\") {\n obj.issuer = \"\"\n } else {\n return false\n }\n }\n return true\n }",
"function checkAmountInput(amount) {\r\n let regexpattern = new RegExp(\"^\\\\d+\\.?\\\\d*$\");\r\n return regexpattern.test(amount); // returns true if passed\r\n}",
"function isValidAmount(amount) {\n return amount > 0 && typeof Number(amount) == \"number\";\n}",
"function checkAmount (amount) {\n var valid;\n if (typeof amount === \"number\"){\n valid = true;\n } else {\n valid = false;\n }\n return valid;\n}",
"function validateAmounts() {\n\tif (dollarAmount.value != '') {\n\t\tif (!isDecimal(dollarAmount)) {\n\t\t\tshowErrorMessage(\"Please enter a valid amount(Example 100.00)\");\n\t\t\t\tdollarAmount.select();\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (!validateDollarAmount()){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t}\n\t// validate manual deposit amount\n\tif (manualDepositAmount.value != '') {\n\t\tif (!isDecimal(manualDepositAmount)) {\n\t\t\tshowErrorMessage(\"Please enter a valid amount(Example 100.00)\");\n\t\t\tmanualDepositAmount.select();\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// validate manual deposit amount\n\t\tif (!validateManualDepositAmount()){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}",
"function validateAmount(amount) {\n var re = /^\\s*-?\\d+(\\.\\d{1,2})?\\s*$/;\n return re.test(amount);\n }",
"function checkAmount(e) {\n var invalidChars = /[^0-9]/gi;\n if (invalidChars.test(e.value)){\n e.value = e.value.replace(invalidChars,'');\n }\n}",
"function validateAmount(amount) {\n if (amount <= 0 || amount >= 10000000) {\n return false;\n }\n\n return true;\n}",
"function validateMoney(amount) {\r\n if (isNaN(amount)) {\r\n //console.log(\"Not valid dollar amount. Check your dollar input. It needs to follow he format ##.##\");\r\n return false;\r\n } else {\r\n if (dollarRegex.test(amount)) {\r\n return true;\r\n } else {\r\n //console.log(\"Not valid dollar amount. Check your dollar input\");\r\n return false;\r\n }\r\n }\r\n}",
"function isAmount(in_obj) {\n if (typeof(in_obj) != 'object')\n return false;\n if (typeof in_obj.value !== 'string' || !isFloat(in_obj.value))\n return false;\n if (!isTumCode(in_obj.currency))\n return false;\n //AMOUNT could have a field named\n //either as 'issuer'\n //or as 'counterparty'\n //for SWT, this can be undefined\n if (typeof(in_obj.issuer) != 'undefined' &&\n in_obj.issuer != '') {\n if (!base.isValidAddress(in_obj.issuer))\n return false;\n } else {\n if (in_obj.currency === 'SWT')//if currency === 'SWT',自动补全issuer.\n in_obj.issuer = '';\n else return false;\n }\n\n return true;\n}",
"function validateAmount(amount){\n\t\tamount = parseFloatIgnoreCommas(amount);\n\t\tamount = amount.toFixed(2);\n\t\t\n\t\tif ( amount.length > 13){\n\t\t\tamount = \"9999999999\";\n\t\t}\n\t\t\t\n\treturn amount;\n\n}",
"isPriceValid(price){\n\n if(isNaN(parseFloat(price))){\n return false;\n }\n \n if(price.length > 0){\n return true;\n } else {\n return false;\n }\n }",
"function validAmount() {\n var FLOAT_REGEXP = /^\\-?\\d+((\\.|\\,)\\d+)?$/;\n var directive = {\n restrict: 'A',\n require: 'ngModel',\n link: link\n };\n return directive;\n\n function link(scope, elm, attrs, ctrl) {\n ctrl.$parsers.unshift(function (viewValue) {\n if (FLOAT_REGEXP.test(viewValue)) {\n var floatValue = parseFloat(viewValue);\n if (floatValue > 0) {\n ctrl.$setValidity('validAmount', true);\n return parseFloat(viewValue.replace(',', '.'));\n }\n }\n\n ctrl.$setValidity('validAmount', false);\n return undefined;\n });\n }\n }",
"function checkAmountNumeric(betAmount) {\n if(!($.isNumeric(betAmount) && (parseInt(betAmount) > 0))) {\n messageDisplay(\"Error\", \"Please enter a integer value greater than 0 in the Bet Amount field.\");\n return false; // Return false when Number in Bet Amount is not a number and greater than 0\n }\n return true;\n}",
"function checkPrice(value){\n var userPrice = (typeof parseFloat(value)) === \"number\";\n var givenSign = parseFloat(value) > 0;\n if (userPrice && givenSign){\n return true;\n }\n else {\n return(\"Please enter a positive sale price.\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates exchange rates for all tokens | async updateExchangeRates () {
if (!this.isActive) {
return
}
const contractExchangeRates = {}
const nativeCurrency = this.currency ? this.currency.state.nativeCurrency.toLowerCase() : 'eth'
const pairs = this._tokens.map(token => token.address).join(',')
const query = `contract_addresses=${pairs}&vs_currencies=${nativeCurrency}`
if (this._tokens.length > 0) {
try {
const response = await fetch(`https://api.coingecko.com/api/v3/simple/token_price/ethereum?${query}`)
const prices = await response.json()
this._tokens.forEach(token => {
const price = prices[token.address.toLowerCase()] || prices[ethUtil.toChecksumAddress(token.address)]
contractExchangeRates[normalizeAddress(token.address)] = price ? price[nativeCurrency] : 0
})
} catch (error) {
log.warn(`MetaMask - TokenRatesController exchange rate fetch failed.`, error)
}
}
this.store.putState({ contractExchangeRates })
} | [
"async updateExchangeRates () {\n if (!this.isActive) { return }\n const contractExchangeRates = {}\n for (const i in this._tokens) {\n const address = this._tokens[i].address\n contractExchangeRates[address] = await this.fetchExchangeRate(address)\n }\n this.store.putState({ contractExchangeRates })\n }",
"async updateExchangeRates() {\n const contractExchangeRates = {}\n const nativeCurrency = this.currency ? this.currency.getState().nativeCurrency.toLowerCase() : 'eth'\n const pairs = this._tokens.map((token) => token.tokenAddress).join(',')\n const query = `contract_addresses=${pairs}&vs_currencies=${nativeCurrency}`\n if (this._tokens.length > 0) {\n try {\n const response = await fetch(`https://api.coingecko.com/api/v3/simple/token_price/ethereum?${query}`)\n const prices = await response.json()\n this._tokens.forEach((token) => {\n const price = prices[token.tokenAddress.toLowerCase()]\n contractExchangeRates[normalizeAddress(token.tokenAddress)] = price ? price[nativeCurrency] : 0\n })\n this.store.putState({ contractExchangeRates })\n } catch (error) {\n log.warn('MetaMask - TokenRatesController exchange rate fetch failed.', error)\n }\n }\n }",
"updateExchangeRates() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.tokenList.length === 0) {\n return;\n }\n const newContractExchangeRates = {};\n const { nativeCurrency } = this.config;\n const pairs = this.tokenList.map((token) => token.address).join(',');\n const query = `contract_addresses=${pairs}&vs_currencies=${nativeCurrency.toLowerCase()}`;\n const prices = yield this.fetchExchangeRate(query);\n this.tokenList.forEach((token) => {\n const address = util_1.toChecksumHexAddress(token.address);\n const price = prices[token.address.toLowerCase()];\n newContractExchangeRates[address] = price\n ? price[nativeCurrency.toLowerCase()]\n : 0;\n });\n this.update({ contractExchangeRates: newContractExchangeRates });\n });\n }",
"function updateExchangeRates() {\n var currencies = [];\n var hasNegative = false;\n for (var cur in $scope.balances) {if ($scope.balances.hasOwnProperty(cur)){\n var components = $scope.balances[cur].components;\n for (var issuer in components) {if (components.hasOwnProperty(issuer)){\n // While we're at it, check for negative balances:\n hasNegative || (hasNegative = components[issuer].is_negative());\n currencies.push({\n currency: cur,\n issuer: issuer\n });\n }}\n }}\n $scope.hasNegative = hasNegative;\n var pairs = currencies.map(function(c){\n return {\n base:c,\n counter:{currency:'XRP'}\n };\n });\n if (pairs.length) {\n $scope.exchangeRatesNonempty = false;\n $http.post('https://api.ripplecharts.com/api/exchangeRates', {pairs: pairs, last: true})\n .success(function(response){\n for (var i = 0; i < response.length; i++) {\n var pair = response[i];\n if (pair.last > 0) { // Disregard unmarketable assets\n $scope.exchangeRates[pair.base.currency + ':' + pair.base.issuer] = pair.last;\n }\n }\n\n $scope.exchangeRatesNonempty = true;\n console.log('Exchange Rates: ', $scope.exchangeRates);\n });\n } else {\n $scope.exchangeRatesNonempty = true;\n }\n }",
"function updateExchangeRates() {\n\t var currencies = [];\n\t var hasNegative = false;\n\t for (var cur in $scope.balances) {if ($scope.balances.hasOwnProperty(cur)){\n\t var components = $scope.balances[cur].components;\n\t for (var issuer in components) {if (components.hasOwnProperty(issuer)){\n\t // While we're at it, check for negative balances:\n\t hasNegative || (hasNegative = components[issuer].is_negative());\n\t currencies.push({\n\t currency: cur,\n\t issuer: issuer\n\t });\n\t }}\n\t }}\n\t $scope.hasNegative = hasNegative;\n\t var pairs = currencies.map(function(c){\n\t return {\n\t base:c,\n\t counter:{currency:'XRP'}\n\t };\n\t });\n\t if (pairs.length) {\n\t $scope.exchangeRatesNonempty = false;\n\t $http.post('https://api.ripplecharts.com/api/exchangeRates', {pairs: pairs, last: true})\n\t .success(function(response){\n\t for (var i = 0; i < response.length; i++) {\n\t var pair = response[i];\n\t if (pair.last > 0) { // Disregard unmarketable assets\n\t $scope.exchangeRates[pair.base.currency + ':' + pair.base.issuer] = pair.last;\n\t }\n\t }\n\n\t $scope.exchangeRatesNonempty = true;\n\t console.log('Exchange Rates: ', $scope.exchangeRates);\n\t });\n\t } else {\n\t $scope.exchangeRatesNonempty = true;\n\t }\n\t }",
"function exhange_rate_update()\n{\n\n rate_value = format_currency_value($(\"#exhange_rate\").val());\n $(\"#exhange_rate\").val(rate_value);\n $.each(transactions_array, function()\n {\n this.update_zl(rate_value);\n } \n );\n update_transaction_summary();\n}",
"updateExchangeRate() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.disabled || !this.activeCurrency || !this.activeNativeCurrency) {\n return;\n }\n const releaseLock = yield this.mutex.acquire();\n const { conversionDate, conversionRate } = yield this.fetchExchangeRate(this.activeCurrency, this.activeNativeCurrency);\n this.update({\n conversionDate,\n conversionRate,\n currentCurrency: this.activeCurrency,\n nativeCurrency: this.activeNativeCurrency\n });\n releaseLock();\n return this.state;\n });\n }",
"getNewExchangeRate() {\n fetch('https://api.exchangeratesapi.io/latest?base=' + this.mainCurrency)\n .then(resp => resp.json())\n .then(resp => {\n // change data on ui\n var addedRates = this.addedRate\n addedRates.map(el => {\n el.rate = resp.rates[el.currency]\n })\n })\n \n }",
"async function updateTokenPrices () {\n for (var i = 0; i < tokens.length; i++) {\n const newPrice = await getTokenPrice(tokens[i])\n await recordNewPrice(newPrice)\n }\n}",
"function setExchangeRate(currencyPair, rate) {\n setExchangeRates(Object.assign({}, exchangeRates, {\n [currencyPair]: rate,\n }));\n }",
"setExchangeRate() {\n const method = \"GET\";\n const url = \"https://www.alphavantage.co/query?\" +\n \"function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=\" + apiKey;\n const dataType = \"json\";\n\n // Fetch current exchange rate from API.\n $.ajax({\n method: method,\n url: url,\n dataType: dataType,\n success: this.setExchangeRateFromData.bind(this)\n });\n }",
"_updateRateInfo() {\n if (this._rates) {\n const day = 24 * 60 * 60 * 1000;\n const rateDate = new Date(`${this._rates.date}T00:00:00`);\n const daysToday = new Date().getTime() / day;\n const daysRates = rateDate.getTime() / day;\n const days = Math.floor(daysToday - daysRates);\n\n this._model.rates.date.value = rateDate.toISOString().split('T', 1)[0];\n\n this._model.rates.message.value = 'Rates updated ';\n if (days === 0) {\n this._model.rates.relative.value = 'today';\n } else {\n this._model.rates.relative.value =\n `${days} day${days === 1 ? '' : 's'} ago`;\n }\n }\n }",
"set tokens(tokens) {\n this.tokenList = tokens;\n !this.disabled && util_1.safelyExecute(() => this.updateExchangeRates());\n }",
"async function updateAggregatorRates(\n\texchangeRates,\n\tcircuitBreaker,\n\tkeys,\n\trates,\n\ttimestamp = undefined\n) {\n\ttimestamp = timestamp || (await currentTime());\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst aggregatorAddress = await exchangeRates.aggregators(keys[i]);\n\t\tif (aggregatorAddress === ZERO_ADDRESS) {\n\t\t\tthrow new Error(`Aggregator set to zero address, use \"setupPriceAggregators\" to set it up`);\n\t\t}\n\t\tconst aggregator = await MockAggregator.at(aggregatorAddress);\n\t\t// set the rate\n\t\tawait aggregator.setLatestAnswer(rates[i], timestamp);\n\n\t\tif (circuitBreaker) {\n\t\t\tawait circuitBreaker.resetLastValue([aggregatorAddress], [rates[i]], {\n\t\t\t\tfrom: await circuitBreaker.owner(),\n\t\t\t});\n\t\t}\n\t}\n}",
"getExchangeRates() {\n let apiUrl = \"https://api.fixer.io/latest?base=GBP\";\n // Load the rates into the money.js library\n $.getJSON(apiUrl, function(data) {\n fx.rates = data.rates;\n fx.base = data.base;\n });\n }",
"static set updateRate(value) {}",
"async function cacheRates() {\n\t\tconst axios = require('axios');\n\n\t\tconst response = await axios(\n\t\t\t`https://api.exchangeratesapi.io/latest?base=USD`\n\t\t);\n\n\t\tif (response.status === 200) {\n\t\t\tconfig.set({\n\t\t\t\trates: response.data.rates,\n\t\t\t\tlast_cached: new Date()\n\t\t\t});\n\t\t}\n\n\t\treturn;\n\t}",
"function update_rates(data){\n var ticker = data.product_id;\n var price = data.price;\n //only update and emit events if there is a change of rate\n if (rates[ticker] != price){\n rates[ticker] = price;\n //console.log(rates); //debug\n io.sockets.emit('msg-rate', {\n market : ticker,\n rate : parseFloat(price).toFixed(2),\n timestamp : get_ts_string() \n });\n }\t\n}",
"async refresh() {\n try {\n let data = await cc.price('BTC', 'USD', { exchanges: this.exchange });\n this.updateValue(data.USD);\n } catch(err) {\n console.error(chalk.red(\"Couldn't reach Cryptocompare API\"));\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.