language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ErpInvoice extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpInvoice; if (null == bucket) cim_data.ErpInvoice = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpInvoice[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpInvoice"; base.parse_element (/<cim:ErpInvoice.amount>([\s\S]*?)<\/cim:ErpInvoice.amount>/g, obj, "amount", base.to_string, sub, context); base.parse_attribute (/<cim:ErpInvoice.billMediaKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "billMediaKind", sub, context); base.parse_element (/<cim:ErpInvoice.dueDate>([\s\S]*?)<\/cim:ErpInvoice.dueDate>/g, obj, "dueDate", base.to_string, sub, context); base.parse_attribute (/<cim:ErpInvoice.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context); base.parse_element (/<cim:ErpInvoice.mailedDate>([\s\S]*?)<\/cim:ErpInvoice.mailedDate>/g, obj, "mailedDate", base.to_string, sub, context); base.parse_element (/<cim:ErpInvoice.proForma>([\s\S]*?)<\/cim:ErpInvoice.proForma>/g, obj, "proForma", base.to_boolean, sub, context); base.parse_element (/<cim:ErpInvoice.referenceNumber>([\s\S]*?)<\/cim:ErpInvoice.referenceNumber>/g, obj, "referenceNumber", base.to_string, sub, context); base.parse_element (/<cim:ErpInvoice.transactionDateTime>([\s\S]*?)<\/cim:ErpInvoice.transactionDateTime>/g, obj, "transactionDateTime", base.to_datetime, sub, context); base.parse_element (/<cim:ErpInvoice.transferType>([\s\S]*?)<\/cim:ErpInvoice.transferType>/g, obj, "transferType", base.to_string, sub, context); base.parse_attributes (/<cim:ErpInvoice.ErpInvoiceLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItems", sub, context); base.parse_attribute (/<cim:ErpInvoice.CustomerAccount\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CustomerAccount", sub, context); let bucket = context.parsed.ErpInvoice; if (null == bucket) context.parsed.ErpInvoice = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_element (obj, "ErpInvoice", "amount", "amount", base.from_string, fields); base.export_attribute (obj, "ErpInvoice", "billMediaKind", "billMediaKind", fields); base.export_element (obj, "ErpInvoice", "dueDate", "dueDate", base.from_string, fields); base.export_attribute (obj, "ErpInvoice", "kind", "kind", fields); base.export_element (obj, "ErpInvoice", "mailedDate", "mailedDate", base.from_string, fields); base.export_element (obj, "ErpInvoice", "proForma", "proForma", base.from_boolean, fields); base.export_element (obj, "ErpInvoice", "referenceNumber", "referenceNumber", base.from_string, fields); base.export_element (obj, "ErpInvoice", "transactionDateTime", "transactionDateTime", base.from_datetime, fields); base.export_element (obj, "ErpInvoice", "transferType", "transferType", base.from_string, fields); base.export_attributes (obj, "ErpInvoice", "ErpInvoiceLineItems", "ErpInvoiceLineItems", fields); base.export_attribute (obj, "ErpInvoice", "CustomerAccount", "CustomerAccount", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpInvoice_collapse" aria-expanded="true" aria-controls="ErpInvoice_collapse" style="margin-left: 10px;">ErpInvoice</a></legend> <div id="ErpInvoice_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#amount}}<div><b>amount</b>: {{amount}}</div>{{/amount}} {{#billMediaKind}}<div><b>billMediaKind</b>: {{billMediaKind}}</div>{{/billMediaKind}} {{#dueDate}}<div><b>dueDate</b>: {{dueDate}}</div>{{/dueDate}} {{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}} {{#mailedDate}}<div><b>mailedDate</b>: {{mailedDate}}</div>{{/mailedDate}} {{#proForma}}<div><b>proForma</b>: {{proForma}}</div>{{/proForma}} {{#referenceNumber}}<div><b>referenceNumber</b>: {{referenceNumber}}</div>{{/referenceNumber}} {{#transactionDateTime}}<div><b>transactionDateTime</b>: {{transactionDateTime}}</div>{{/transactionDateTime}} {{#transferType}}<div><b>transferType</b>: {{transferType}}</div>{{/transferType}} {{#ErpInvoiceLineItems}}<div><b>ErpInvoiceLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpInvoiceLineItems}} {{#CustomerAccount}}<div><b>CustomerAccount</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{CustomerAccount}}");}); return false;'>{{CustomerAccount}}</a></div>{{/CustomerAccount}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["billMediaKindBillMediaKind"] = [{ id: '', selected: (!obj["billMediaKind"])}]; for (let property in BillMediaKind) obj["billMediaKindBillMediaKind"].push ({ id: property, selected: obj["billMediaKind"] && obj["billMediaKind"].endsWith ('.' + property)}); obj["kindErpInvoiceKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in ErpInvoiceKind) obj["kindErpInvoiceKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)}); if (obj["ErpInvoiceLineItems"]) obj["ErpInvoiceLineItems_string"] = obj["ErpInvoiceLineItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["billMediaKindBillMediaKind"]; delete obj["kindErpInvoiceKind"]; delete obj["ErpInvoiceLineItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpInvoice_collapse" aria-expanded="true" aria-controls="{{id}}_ErpInvoice_collapse" style="margin-left: 10px;">ErpInvoice</a></legend> <div id="{{id}}_ErpInvoice_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_amount'>amount: </label><div class='col-sm-8'><input id='{{id}}_amount' class='form-control' type='text'{{#amount}} value='{{amount}}'{{/amount}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_billMediaKind'>billMediaKind: </label><div class='col-sm-8'><select id='{{id}}_billMediaKind' class='form-control custom-select'>{{#billMediaKindBillMediaKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/billMediaKindBillMediaKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dueDate'>dueDate: </label><div class='col-sm-8'><input id='{{id}}_dueDate' class='form-control' type='text'{{#dueDate}} value='{{dueDate}}'{{/dueDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindErpInvoiceKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindErpInvoiceKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_mailedDate'>mailedDate: </label><div class='col-sm-8'><input id='{{id}}_mailedDate' class='form-control' type='text'{{#mailedDate}} value='{{mailedDate}}'{{/mailedDate}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_proForma'>proForma: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_proForma' class='form-check-input' type='checkbox'{{#proForma}} checked{{/proForma}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_referenceNumber'>referenceNumber: </label><div class='col-sm-8'><input id='{{id}}_referenceNumber' class='form-control' type='text'{{#referenceNumber}} value='{{referenceNumber}}'{{/referenceNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_transactionDateTime'>transactionDateTime: </label><div class='col-sm-8'><input id='{{id}}_transactionDateTime' class='form-control' type='text'{{#transactionDateTime}} value='{{transactionDateTime}}'{{/transactionDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_transferType'>transferType: </label><div class='col-sm-8'><input id='{{id}}_transferType' class='form-control' type='text'{{#transferType}} value='{{transferType}}'{{/transferType}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_CustomerAccount'>CustomerAccount: </label><div class='col-sm-8'><input id='{{id}}_CustomerAccount' class='form-control' type='text'{{#CustomerAccount}} value='{{CustomerAccount}}'{{/CustomerAccount}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpInvoice" }; super.submit (id, obj); temp = document.getElementById (id + "_amount").value; if ("" !== temp) obj["amount"] = temp; temp = BillMediaKind[document.getElementById (id + "_billMediaKind").value]; if (temp) obj["billMediaKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#BillMediaKind." + temp; else delete obj["billMediaKind"]; temp = document.getElementById (id + "_dueDate").value; if ("" !== temp) obj["dueDate"] = temp; temp = ErpInvoiceKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ErpInvoiceKind." + temp; else delete obj["kind"]; temp = document.getElementById (id + "_mailedDate").value; if ("" !== temp) obj["mailedDate"] = temp; temp = document.getElementById (id + "_proForma").checked; if (temp) obj["proForma"] = true; temp = document.getElementById (id + "_referenceNumber").value; if ("" !== temp) obj["referenceNumber"] = temp; temp = document.getElementById (id + "_transactionDateTime").value; if ("" !== temp) obj["transactionDateTime"] = temp; temp = document.getElementById (id + "_transferType").value; if ("" !== temp) obj["transferType"] = temp; temp = document.getElementById (id + "_CustomerAccount").value; if ("" !== temp) obj["CustomerAccount"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpInvoiceLineItems", "0..*", "1", "ErpInvoiceLineItem", "ErpInvoice"], ["CustomerAccount", "0..1", "0..*", "CustomerAccount", "ErpInvoicees"] ] ) ); } }
JavaScript
class ErpRequisition extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpRequisition; if (null == bucket) cim_data.ErpRequisition = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpRequisition[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpRequisition"; base.parse_attributes (/<cim:ErpRequisition.ErpReqLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpReqLineItems", sub, context); let bucket = context.parsed.ErpRequisition; if (null == bucket) context.parsed.ErpRequisition = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_attributes (obj, "ErpRequisition", "ErpReqLineItems", "ErpReqLineItems", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpRequisition_collapse" aria-expanded="true" aria-controls="ErpRequisition_collapse" style="margin-left: 10px;">ErpRequisition</a></legend> <div id="ErpRequisition_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#ErpReqLineItems}}<div><b>ErpReqLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpReqLineItems}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpReqLineItems"]) obj["ErpReqLineItems_string"] = obj["ErpReqLineItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpReqLineItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpRequisition_collapse" aria-expanded="true" aria-controls="{{id}}_ErpRequisition_collapse" style="margin-left: 10px;">ErpRequisition</a></legend> <div id="{{id}}_ErpRequisition_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "ErpRequisition" }; super.submit (id, obj); return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpReqLineItems", "0..*", "1", "ErpReqLineItem", "ErpRequisition"] ] ) ); } }
JavaScript
class ErpProjectAccounting extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpProjectAccounting; if (null == bucket) cim_data.ErpProjectAccounting = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpProjectAccounting[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpProjectAccounting"; base.parse_attributes (/<cim:ErpProjectAccounting.Works\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Works", sub, context); base.parse_attributes (/<cim:ErpProjectAccounting.WorkCostDetails\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WorkCostDetails", sub, context); base.parse_attributes (/<cim:ErpProjectAccounting.ErpTimeEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpTimeEntries", sub, context); base.parse_attributes (/<cim:ErpProjectAccounting.Projects\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Projects", sub, context); let bucket = context.parsed.ErpProjectAccounting; if (null == bucket) context.parsed.ErpProjectAccounting = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_attributes (obj, "ErpProjectAccounting", "Works", "Works", fields); base.export_attributes (obj, "ErpProjectAccounting", "WorkCostDetails", "WorkCostDetails", fields); base.export_attributes (obj, "ErpProjectAccounting", "ErpTimeEntries", "ErpTimeEntries", fields); base.export_attributes (obj, "ErpProjectAccounting", "Projects", "Projects", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpProjectAccounting_collapse" aria-expanded="true" aria-controls="ErpProjectAccounting_collapse" style="margin-left: 10px;">ErpProjectAccounting</a></legend> <div id="ErpProjectAccounting_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#Works}}<div><b>Works</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Works}} {{#WorkCostDetails}}<div><b>WorkCostDetails</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WorkCostDetails}} {{#ErpTimeEntries}}<div><b>ErpTimeEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpTimeEntries}} {{#Projects}}<div><b>Projects</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Projects}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["Works"]) obj["Works_string"] = obj["Works"].join (); if (obj["WorkCostDetails"]) obj["WorkCostDetails_string"] = obj["WorkCostDetails"].join (); if (obj["ErpTimeEntries"]) obj["ErpTimeEntries_string"] = obj["ErpTimeEntries"].join (); if (obj["Projects"]) obj["Projects_string"] = obj["Projects"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["Works_string"]; delete obj["WorkCostDetails_string"]; delete obj["ErpTimeEntries_string"]; delete obj["Projects_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpProjectAccounting_collapse" aria-expanded="true" aria-controls="{{id}}_ErpProjectAccounting_collapse" style="margin-left: 10px;">ErpProjectAccounting</a></legend> <div id="{{id}}_ErpProjectAccounting_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "ErpProjectAccounting" }; super.submit (id, obj); return (obj); } relations () { return ( super.relations ().concat ( [ ["Works", "0..*", "0..1", "Work", "ErpProjectAccounting"], ["WorkCostDetails", "0..*", "1", "WorkCostDetail", "ErpProjectAccounting"], ["ErpTimeEntries", "0..*", "0..1", "ErpTimeEntry", "ErpProjectAccounting"], ["Projects", "0..*", "1", "Project", "ErpProjectAccounting"] ] ) ); } }
JavaScript
class ErpPayable extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpPayable; if (null == bucket) cim_data.ErpPayable = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpPayable[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpPayable"; base.parse_attributes (/<cim:ErpPayable.ContractorItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ContractorItems", sub, context); base.parse_attributes (/<cim:ErpPayable.ErpPayableLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayableLineItems", sub, context); let bucket = context.parsed.ErpPayable; if (null == bucket) context.parsed.ErpPayable = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_attributes (obj, "ErpPayable", "ContractorItems", "ContractorItems", fields); base.export_attributes (obj, "ErpPayable", "ErpPayableLineItems", "ErpPayableLineItems", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpPayable_collapse" aria-expanded="true" aria-controls="ErpPayable_collapse" style="margin-left: 10px;">ErpPayable</a></legend> <div id="ErpPayable_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#ContractorItems}}<div><b>ContractorItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ContractorItems}} {{#ErpPayableLineItems}}<div><b>ErpPayableLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPayableLineItems}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ContractorItems"]) obj["ContractorItems_string"] = obj["ContractorItems"].join (); if (obj["ErpPayableLineItems"]) obj["ErpPayableLineItems_string"] = obj["ErpPayableLineItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ContractorItems_string"]; delete obj["ErpPayableLineItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpPayable_collapse" aria-expanded="true" aria-controls="{{id}}_ErpPayable_collapse" style="margin-left: 10px;">ErpPayable</a></legend> <div id="{{id}}_ErpPayable_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ContractorItems'>ContractorItems: </label><div class='col-sm-8'><input id='{{id}}_ContractorItems' class='form-control' type='text'{{#ContractorItems}} value='{{ContractorItems_string}}'{{/ContractorItems}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpPayable" }; super.submit (id, obj); temp = document.getElementById (id + "_ContractorItems").value; if ("" !== temp) obj["ContractorItems"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["ContractorItems", "0..*", "0..*", "ContractorItem", "ErpPayables"], ["ErpPayableLineItems", "0..*", "1", "ErpPayableLineItem", "ErpPayable"] ] ) ); } }
JavaScript
class ErpTimeSheet extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpTimeSheet; if (null == bucket) cim_data.ErpTimeSheet = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpTimeSheet[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpTimeSheet"; base.parse_attributes (/<cim:ErpTimeSheet.ErpTimeEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpTimeEntries", sub, context); let bucket = context.parsed.ErpTimeSheet; if (null == bucket) context.parsed.ErpTimeSheet = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_attributes (obj, "ErpTimeSheet", "ErpTimeEntries", "ErpTimeEntries", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpTimeSheet_collapse" aria-expanded="true" aria-controls="ErpTimeSheet_collapse" style="margin-left: 10px;">ErpTimeSheet</a></legend> <div id="ErpTimeSheet_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#ErpTimeEntries}}<div><b>ErpTimeEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpTimeEntries}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpTimeEntries"]) obj["ErpTimeEntries_string"] = obj["ErpTimeEntries"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpTimeEntries_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpTimeSheet_collapse" aria-expanded="true" aria-controls="{{id}}_ErpTimeSheet_collapse" style="margin-left: 10px;">ErpTimeSheet</a></legend> <div id="{{id}}_ErpTimeSheet_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "ErpTimeSheet" }; super.submit (id, obj); return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpTimeEntries", "0..*", "1", "ErpTimeEntry", "ErpTimeSheet"] ] ) ); } }
JavaScript
class ErpReceivable extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpReceivable; if (null == bucket) cim_data.ErpReceivable = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpReceivable[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpReceivable"; base.parse_attributes (/<cim:ErpReceivable.ErpRecLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecLineItems", sub, context); let bucket = context.parsed.ErpReceivable; if (null == bucket) context.parsed.ErpReceivable = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_attributes (obj, "ErpReceivable", "ErpRecLineItems", "ErpRecLineItems", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpReceivable_collapse" aria-expanded="true" aria-controls="ErpReceivable_collapse" style="margin-left: 10px;">ErpReceivable</a></legend> <div id="ErpReceivable_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#ErpRecLineItems}}<div><b>ErpRecLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpRecLineItems}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpRecLineItems"]) obj["ErpRecLineItems_string"] = obj["ErpRecLineItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpRecLineItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpReceivable_collapse" aria-expanded="true" aria-controls="{{id}}_ErpReceivable_collapse" style="margin-left: 10px;">ErpReceivable</a></legend> <div id="{{id}}_ErpReceivable_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "ErpReceivable" }; super.submit (id, obj); return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpRecLineItems", "0..*", "1", "ErpRecLineItem", "ErpReceivable"] ] ) ); } }
JavaScript
class ErpSalesOrder extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpSalesOrder; if (null == bucket) cim_data.ErpSalesOrder = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpSalesOrder[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpSalesOrder"; let bucket = context.parsed.ErpSalesOrder; if (null == bucket) context.parsed.ErpSalesOrder = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpSalesOrder_collapse" aria-expanded="true" aria-controls="ErpSalesOrder_collapse" style="margin-left: 10px;">ErpSalesOrder</a></legend> <div id="ErpSalesOrder_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpSalesOrder_collapse" aria-expanded="true" aria-controls="{{id}}_ErpSalesOrder_collapse" style="margin-left: 10px;">ErpSalesOrder</a></legend> <div id="{{id}}_ErpSalesOrder_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "ErpSalesOrder" }; super.submit (id, obj); return (obj); } }
JavaScript
class ErpPOLineItem extends ErpDocument { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpPOLineItem; if (null == bucket) cim_data.ErpPOLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpPOLineItem[obj.id]; } parse (context, sub) { let obj = ErpDocument.prototype.parse.call (this, context, sub); obj.cls = "ErpPOLineItem"; base.parse_attribute (/<cim:ErpPOLineItem.AssetModelCatalogueItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetModelCatalogueItem", sub, context); base.parse_attribute (/<cim:ErpPOLineItem.ErpReqLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpReqLineItem", sub, context); base.parse_attribute (/<cim:ErpPOLineItem.ErpRecDelLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecDelLineItem", sub, context); base.parse_attribute (/<cim:ErpPOLineItem.ErpPurchaseOrder\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPurchaseOrder", sub, context); let bucket = context.parsed.ErpPOLineItem; if (null == bucket) context.parsed.ErpPOLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpDocument.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpPOLineItem", "AssetModelCatalogueItem", "AssetModelCatalogueItem", fields); base.export_attribute (obj, "ErpPOLineItem", "ErpReqLineItem", "ErpReqLineItem", fields); base.export_attribute (obj, "ErpPOLineItem", "ErpRecDelLineItem", "ErpRecDelLineItem", fields); base.export_attribute (obj, "ErpPOLineItem", "ErpPurchaseOrder", "ErpPurchaseOrder", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpPOLineItem_collapse" aria-expanded="true" aria-controls="ErpPOLineItem_collapse" style="margin-left: 10px;">ErpPOLineItem</a></legend> <div id="ErpPOLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.template.call (this) + ` {{#AssetModelCatalogueItem}}<div><b>AssetModelCatalogueItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetModelCatalogueItem}}");}); return false;'>{{AssetModelCatalogueItem}}</a></div>{{/AssetModelCatalogueItem}} {{#ErpReqLineItem}}<div><b>ErpReqLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpReqLineItem}}");}); return false;'>{{ErpReqLineItem}}</a></div>{{/ErpReqLineItem}} {{#ErpRecDelLineItem}}<div><b>ErpRecDelLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpRecDelLineItem}}");}); return false;'>{{ErpRecDelLineItem}}</a></div>{{/ErpRecDelLineItem}} {{#ErpPurchaseOrder}}<div><b>ErpPurchaseOrder</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpPurchaseOrder}}");}); return false;'>{{ErpPurchaseOrder}}</a></div>{{/ErpPurchaseOrder}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpPOLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpPOLineItem_collapse" style="margin-left: 10px;">ErpPOLineItem</a></legend> <div id="{{id}}_ErpPOLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpDocument.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetModelCatalogueItem'>AssetModelCatalogueItem: </label><div class='col-sm-8'><input id='{{id}}_AssetModelCatalogueItem' class='form-control' type='text'{{#AssetModelCatalogueItem}} value='{{AssetModelCatalogueItem}}'{{/AssetModelCatalogueItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpReqLineItem'>ErpReqLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpReqLineItem' class='form-control' type='text'{{#ErpReqLineItem}} value='{{ErpReqLineItem}}'{{/ErpReqLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRecDelLineItem'>ErpRecDelLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpRecDelLineItem' class='form-control' type='text'{{#ErpRecDelLineItem}} value='{{ErpRecDelLineItem}}'{{/ErpRecDelLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPurchaseOrder'>ErpPurchaseOrder: </label><div class='col-sm-8'><input id='{{id}}_ErpPurchaseOrder' class='form-control' type='text'{{#ErpPurchaseOrder}} value='{{ErpPurchaseOrder}}'{{/ErpPurchaseOrder}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpPOLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_AssetModelCatalogueItem").value; if ("" !== temp) obj["AssetModelCatalogueItem"] = temp; temp = document.getElementById (id + "_ErpReqLineItem").value; if ("" !== temp) obj["ErpReqLineItem"] = temp; temp = document.getElementById (id + "_ErpRecDelLineItem").value; if ("" !== temp) obj["ErpRecDelLineItem"] = temp; temp = document.getElementById (id + "_ErpPurchaseOrder").value; if ("" !== temp) obj["ErpPurchaseOrder"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["AssetModelCatalogueItem", "0..1", "0..*", "AssetModelCatalogueItem", "ErpPOLineItems"], ["ErpReqLineItem", "0..1", "0..1", "ErpReqLineItem", "ErpPOLineItem"], ["ErpRecDelLineItem", "0..1", "0..1", "ErpRecDelvLineItem", "ErpPOLineItem"], ["ErpPurchaseOrder", "1", "0..*", "ErpPurchaseOrder", "ErpPOLineItems"] ] ) ); } }
JavaScript
class ErpBomItemData extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpBomItemData; if (null == bucket) cim_data.ErpBomItemData = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpBomItemData[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpBomItemData"; base.parse_attribute (/<cim:ErpBomItemData.TypeAsset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TypeAsset", sub, context); base.parse_attribute (/<cim:ErpBomItemData.ErpBOM\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpBOM", sub, context); base.parse_attribute (/<cim:ErpBomItemData.DesignLocation\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "DesignLocation", sub, context); let bucket = context.parsed.ErpBomItemData; if (null == bucket) context.parsed.ErpBomItemData = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpBomItemData", "TypeAsset", "TypeAsset", fields); base.export_attribute (obj, "ErpBomItemData", "ErpBOM", "ErpBOM", fields); base.export_attribute (obj, "ErpBomItemData", "DesignLocation", "DesignLocation", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpBomItemData_collapse" aria-expanded="true" aria-controls="ErpBomItemData_collapse" style="margin-left: 10px;">ErpBomItemData</a></legend> <div id="ErpBomItemData_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#TypeAsset}}<div><b>TypeAsset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{TypeAsset}}");}); return false;'>{{TypeAsset}}</a></div>{{/TypeAsset}} {{#ErpBOM}}<div><b>ErpBOM</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpBOM}}");}); return false;'>{{ErpBOM}}</a></div>{{/ErpBOM}} {{#DesignLocation}}<div><b>DesignLocation</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{DesignLocation}}");}); return false;'>{{DesignLocation}}</a></div>{{/DesignLocation}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpBomItemData_collapse" aria-expanded="true" aria-controls="{{id}}_ErpBomItemData_collapse" style="margin-left: 10px;">ErpBomItemData</a></legend> <div id="{{id}}_ErpBomItemData_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TypeAsset'>TypeAsset: </label><div class='col-sm-8'><input id='{{id}}_TypeAsset' class='form-control' type='text'{{#TypeAsset}} value='{{TypeAsset}}'{{/TypeAsset}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpBOM'>ErpBOM: </label><div class='col-sm-8'><input id='{{id}}_ErpBOM' class='form-control' type='text'{{#ErpBOM}} value='{{ErpBOM}}'{{/ErpBOM}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_DesignLocation'>DesignLocation: </label><div class='col-sm-8'><input id='{{id}}_DesignLocation' class='form-control' type='text'{{#DesignLocation}} value='{{DesignLocation}}'{{/DesignLocation}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpBomItemData" }; super.submit (id, obj); temp = document.getElementById (id + "_TypeAsset").value; if ("" !== temp) obj["TypeAsset"] = temp; temp = document.getElementById (id + "_ErpBOM").value; if ("" !== temp) obj["ErpBOM"] = temp; temp = document.getElementById (id + "_DesignLocation").value; if ("" !== temp) obj["DesignLocation"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["TypeAsset", "0..1", "0..*", "CatalogAssetType", "ErpBomItemDatas"], ["ErpBOM", "1", "0..*", "ErpBOM", "ErpBomItemDatas"], ["DesignLocation", "0..1", "0..*", "DesignLocation", "ErpBomItemDatas"] ] ) ); } }
JavaScript
class ErpSiteLevelData extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpSiteLevelData; if (null == bucket) cim_data.ErpSiteLevelData = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpSiteLevelData[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpSiteLevelData"; base.parse_attribute (/<cim:ErpSiteLevelData.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpSiteLevelData.LandProperty\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LandProperty", sub, context); let bucket = context.parsed.ErpSiteLevelData; if (null == bucket) context.parsed.ErpSiteLevelData = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpSiteLevelData", "status", "status", fields); base.export_attribute (obj, "ErpSiteLevelData", "LandProperty", "LandProperty", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpSiteLevelData_collapse" aria-expanded="true" aria-controls="ErpSiteLevelData_collapse" style="margin-left: 10px;">ErpSiteLevelData</a></legend> <div id="ErpSiteLevelData_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#LandProperty}}<div><b>LandProperty</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{LandProperty}}");}); return false;'>{{LandProperty}}</a></div>{{/LandProperty}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpSiteLevelData_collapse" aria-expanded="true" aria-controls="{{id}}_ErpSiteLevelData_collapse" style="margin-left: 10px;">ErpSiteLevelData</a></legend> <div id="{{id}}_ErpSiteLevelData_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_LandProperty'>LandProperty: </label><div class='col-sm-8'><input id='{{id}}_LandProperty' class='form-control' type='text'{{#LandProperty}} value='{{LandProperty}}'{{/LandProperty}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpSiteLevelData" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_LandProperty").value; if ("" !== temp) obj["LandProperty"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["LandProperty", "0..1", "0..*", "LandProperty", "ErpSiteLevelDatas"] ] ) ); } }
JavaScript
class ErpInventory extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpInventory; if (null == bucket) cim_data.ErpInventory = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpInventory[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpInventory"; base.parse_attribute (/<cim:ErpInventory.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpInventory.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); let bucket = context.parsed.ErpInventory; if (null == bucket) context.parsed.ErpInventory = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpInventory", "status", "status", fields); base.export_attribute (obj, "ErpInventory", "Asset", "Asset", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpInventory_collapse" aria-expanded="true" aria-controls="ErpInventory_collapse" style="margin-left: 10px;">ErpInventory</a></legend> <div id="ErpInventory_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpInventory_collapse" aria-expanded="true" aria-controls="{{id}}_ErpInventory_collapse" style="margin-left: 10px;">ErpInventory</a></legend> <div id="{{id}}_ErpInventory_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpInventory" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Asset", "0..1", "0..1", "Asset", "ErpInventory"] ] ) ); } }
JavaScript
class ErpReqLineItem extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpReqLineItem; if (null == bucket) cim_data.ErpReqLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpReqLineItem[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpReqLineItem"; base.parse_element (/<cim:ErpReqLineItem.code>([\s\S]*?)<\/cim:ErpReqLineItem.code>/g, obj, "code", base.to_string, sub, context); base.parse_element (/<cim:ErpReqLineItem.cost>([\s\S]*?)<\/cim:ErpReqLineItem.cost>/g, obj, "cost", base.to_string, sub, context); base.parse_element (/<cim:ErpReqLineItem.deliveryDate>([\s\S]*?)<\/cim:ErpReqLineItem.deliveryDate>/g, obj, "deliveryDate", base.to_string, sub, context); base.parse_element (/<cim:ErpReqLineItem.quantity>([\s\S]*?)<\/cim:ErpReqLineItem.quantity>/g, obj, "quantity", base.to_string, sub, context); base.parse_attribute (/<cim:ErpReqLineItem.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpReqLineItem.TypeMaterial\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TypeMaterial", sub, context); base.parse_attribute (/<cim:ErpReqLineItem.ErpQuoteLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpQuoteLineItem", sub, context); base.parse_attribute (/<cim:ErpReqLineItem.ErpPOLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPOLineItem", sub, context); base.parse_attribute (/<cim:ErpReqLineItem.TypeAsset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TypeAsset", sub, context); base.parse_attribute (/<cim:ErpReqLineItem.ErpRequisition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRequisition", sub, context); let bucket = context.parsed.ErpReqLineItem; if (null == bucket) context.parsed.ErpReqLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "ErpReqLineItem", "code", "code", base.from_string, fields); base.export_element (obj, "ErpReqLineItem", "cost", "cost", base.from_string, fields); base.export_element (obj, "ErpReqLineItem", "deliveryDate", "deliveryDate", base.from_string, fields); base.export_element (obj, "ErpReqLineItem", "quantity", "quantity", base.from_string, fields); base.export_attribute (obj, "ErpReqLineItem", "status", "status", fields); base.export_attribute (obj, "ErpReqLineItem", "TypeMaterial", "TypeMaterial", fields); base.export_attribute (obj, "ErpReqLineItem", "ErpQuoteLineItem", "ErpQuoteLineItem", fields); base.export_attribute (obj, "ErpReqLineItem", "ErpPOLineItem", "ErpPOLineItem", fields); base.export_attribute (obj, "ErpReqLineItem", "TypeAsset", "TypeAsset", fields); base.export_attribute (obj, "ErpReqLineItem", "ErpRequisition", "ErpRequisition", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpReqLineItem_collapse" aria-expanded="true" aria-controls="ErpReqLineItem_collapse" style="margin-left: 10px;">ErpReqLineItem</a></legend> <div id="ErpReqLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#code}}<div><b>code</b>: {{code}}</div>{{/code}} {{#cost}}<div><b>cost</b>: {{cost}}</div>{{/cost}} {{#deliveryDate}}<div><b>deliveryDate</b>: {{deliveryDate}}</div>{{/deliveryDate}} {{#quantity}}<div><b>quantity</b>: {{quantity}}</div>{{/quantity}} {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#TypeMaterial}}<div><b>TypeMaterial</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{TypeMaterial}}");}); return false;'>{{TypeMaterial}}</a></div>{{/TypeMaterial}} {{#ErpQuoteLineItem}}<div><b>ErpQuoteLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpQuoteLineItem}}");}); return false;'>{{ErpQuoteLineItem}}</a></div>{{/ErpQuoteLineItem}} {{#ErpPOLineItem}}<div><b>ErpPOLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpPOLineItem}}");}); return false;'>{{ErpPOLineItem}}</a></div>{{/ErpPOLineItem}} {{#TypeAsset}}<div><b>TypeAsset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{TypeAsset}}");}); return false;'>{{TypeAsset}}</a></div>{{/TypeAsset}} {{#ErpRequisition}}<div><b>ErpRequisition</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpRequisition}}");}); return false;'>{{ErpRequisition}}</a></div>{{/ErpRequisition}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpReqLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpReqLineItem_collapse" style="margin-left: 10px;">ErpReqLineItem</a></legend> <div id="{{id}}_ErpReqLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_code'>code: </label><div class='col-sm-8'><input id='{{id}}_code' class='form-control' type='text'{{#code}} value='{{code}}'{{/code}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_cost'>cost: </label><div class='col-sm-8'><input id='{{id}}_cost' class='form-control' type='text'{{#cost}} value='{{cost}}'{{/cost}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_deliveryDate'>deliveryDate: </label><div class='col-sm-8'><input id='{{id}}_deliveryDate' class='form-control' type='text'{{#deliveryDate}} value='{{deliveryDate}}'{{/deliveryDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_quantity'>quantity: </label><div class='col-sm-8'><input id='{{id}}_quantity' class='form-control' type='text'{{#quantity}} value='{{quantity}}'{{/quantity}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TypeMaterial'>TypeMaterial: </label><div class='col-sm-8'><input id='{{id}}_TypeMaterial' class='form-control' type='text'{{#TypeMaterial}} value='{{TypeMaterial}}'{{/TypeMaterial}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpQuoteLineItem'>ErpQuoteLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpQuoteLineItem' class='form-control' type='text'{{#ErpQuoteLineItem}} value='{{ErpQuoteLineItem}}'{{/ErpQuoteLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPOLineItem'>ErpPOLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpPOLineItem' class='form-control' type='text'{{#ErpPOLineItem}} value='{{ErpPOLineItem}}'{{/ErpPOLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TypeAsset'>TypeAsset: </label><div class='col-sm-8'><input id='{{id}}_TypeAsset' class='form-control' type='text'{{#TypeAsset}} value='{{TypeAsset}}'{{/TypeAsset}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRequisition'>ErpRequisition: </label><div class='col-sm-8'><input id='{{id}}_ErpRequisition' class='form-control' type='text'{{#ErpRequisition}} value='{{ErpRequisition}}'{{/ErpRequisition}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpReqLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_code").value; if ("" !== temp) obj["code"] = temp; temp = document.getElementById (id + "_cost").value; if ("" !== temp) obj["cost"] = temp; temp = document.getElementById (id + "_deliveryDate").value; if ("" !== temp) obj["deliveryDate"] = temp; temp = document.getElementById (id + "_quantity").value; if ("" !== temp) obj["quantity"] = temp; temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_TypeMaterial").value; if ("" !== temp) obj["TypeMaterial"] = temp; temp = document.getElementById (id + "_ErpQuoteLineItem").value; if ("" !== temp) obj["ErpQuoteLineItem"] = temp; temp = document.getElementById (id + "_ErpPOLineItem").value; if ("" !== temp) obj["ErpPOLineItem"] = temp; temp = document.getElementById (id + "_TypeAsset").value; if ("" !== temp) obj["TypeAsset"] = temp; temp = document.getElementById (id + "_ErpRequisition").value; if ("" !== temp) obj["ErpRequisition"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["TypeMaterial", "0..1", "0..*", "TypeMaterial", "ErpReqLineItems"], ["ErpQuoteLineItem", "0..1", "0..1", "ErpQuoteLineItem", "ErpReqLineItem"], ["ErpPOLineItem", "0..1", "0..1", "ErpPOLineItem", "ErpReqLineItem"], ["TypeAsset", "0..1", "0..*", "CatalogAssetType", "ErpReqLineItems"], ["ErpRequisition", "1", "0..*", "ErpRequisition", "ErpReqLineItems"] ] ) ); } }
JavaScript
class ErpPayableLineItem extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpPayableLineItem; if (null == bucket) cim_data.ErpPayableLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpPayableLineItem[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpPayableLineItem"; base.parse_attribute (/<cim:ErpPayableLineItem.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attributes (/<cim:ErpPayableLineItem.ErpPayments\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayments", sub, context); base.parse_attribute (/<cim:ErpPayableLineItem.ErpPayable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayable", sub, context); base.parse_attributes (/<cim:ErpPayableLineItem.ErpJournalEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpJournalEntries", sub, context); base.parse_attribute (/<cim:ErpPayableLineItem.ErpInvoiceLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItem", sub, context); let bucket = context.parsed.ErpPayableLineItem; if (null == bucket) context.parsed.ErpPayableLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpPayableLineItem", "status", "status", fields); base.export_attributes (obj, "ErpPayableLineItem", "ErpPayments", "ErpPayments", fields); base.export_attribute (obj, "ErpPayableLineItem", "ErpPayable", "ErpPayable", fields); base.export_attributes (obj, "ErpPayableLineItem", "ErpJournalEntries", "ErpJournalEntries", fields); base.export_attribute (obj, "ErpPayableLineItem", "ErpInvoiceLineItem", "ErpInvoiceLineItem", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpPayableLineItem_collapse" aria-expanded="true" aria-controls="ErpPayableLineItem_collapse" style="margin-left: 10px;">ErpPayableLineItem</a></legend> <div id="ErpPayableLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#ErpPayments}}<div><b>ErpPayments</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPayments}} {{#ErpPayable}}<div><b>ErpPayable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpPayable}}");}); return false;'>{{ErpPayable}}</a></div>{{/ErpPayable}} {{#ErpJournalEntries}}<div><b>ErpJournalEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpJournalEntries}} {{#ErpInvoiceLineItem}}<div><b>ErpInvoiceLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInvoiceLineItem}}");}); return false;'>{{ErpInvoiceLineItem}}</a></div>{{/ErpInvoiceLineItem}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpPayments"]) obj["ErpPayments_string"] = obj["ErpPayments"].join (); if (obj["ErpJournalEntries"]) obj["ErpJournalEntries_string"] = obj["ErpJournalEntries"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpPayments_string"]; delete obj["ErpJournalEntries_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpPayableLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpPayableLineItem_collapse" style="margin-left: 10px;">ErpPayableLineItem</a></legend> <div id="{{id}}_ErpPayableLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayments'>ErpPayments: </label><div class='col-sm-8'><input id='{{id}}_ErpPayments' class='form-control' type='text'{{#ErpPayments}} value='{{ErpPayments_string}}'{{/ErpPayments}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayable'>ErpPayable: </label><div class='col-sm-8'><input id='{{id}}_ErpPayable' class='form-control' type='text'{{#ErpPayable}} value='{{ErpPayable}}'{{/ErpPayable}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpJournalEntries'>ErpJournalEntries: </label><div class='col-sm-8'><input id='{{id}}_ErpJournalEntries' class='form-control' type='text'{{#ErpJournalEntries}} value='{{ErpJournalEntries_string}}'{{/ErpJournalEntries}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoiceLineItem'>ErpInvoiceLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoiceLineItem' class='form-control' type='text'{{#ErpInvoiceLineItem}} value='{{ErpInvoiceLineItem}}'{{/ErpInvoiceLineItem}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpPayableLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_ErpPayments").value; if ("" !== temp) obj["ErpPayments"] = temp.split (","); temp = document.getElementById (id + "_ErpPayable").value; if ("" !== temp) obj["ErpPayable"] = temp; temp = document.getElementById (id + "_ErpJournalEntries").value; if ("" !== temp) obj["ErpJournalEntries"] = temp.split (","); temp = document.getElementById (id + "_ErpInvoiceLineItem").value; if ("" !== temp) obj["ErpInvoiceLineItem"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpPayments", "0..*", "0..*", "ErpPayment", "ErpPayableLineItems"], ["ErpPayable", "1", "0..*", "ErpPayable", "ErpPayableLineItems"], ["ErpJournalEntries", "0..*", "0..*", "ErpJournalEntry", "ErpPayableLineItems"], ["ErpInvoiceLineItem", "0..1", "0..1", "ErpInvoiceLineItem", "ErpPayableLineItem"] ] ) ); } }
JavaScript
class ErpInventoryCount extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpInventoryCount; if (null == bucket) cim_data.ErpInventoryCount = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpInventoryCount[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpInventoryCount"; base.parse_attribute (/<cim:ErpInventoryCount.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); let bucket = context.parsed.ErpInventoryCount; if (null == bucket) context.parsed.ErpInventoryCount = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpInventoryCount", "status", "status", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpInventoryCount_collapse" aria-expanded="true" aria-controls="ErpInventoryCount_collapse" style="margin-left: 10px;">ErpInventoryCount</a></legend> <div id="ErpInventoryCount_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpInventoryCount_collapse" aria-expanded="true" aria-controls="{{id}}_ErpInventoryCount_collapse" style="margin-left: 10px;">ErpInventoryCount</a></legend> <div id="{{id}}_ErpInventoryCount_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpInventoryCount" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; return (obj); } }
JavaScript
class ErpRecLineItem extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpRecLineItem; if (null == bucket) cim_data.ErpRecLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpRecLineItem[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpRecLineItem"; base.parse_attribute (/<cim:ErpRecLineItem.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpRecLineItem.ErpInvoiceLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItem", sub, context); base.parse_attributes (/<cim:ErpRecLineItem.ErpPayments\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayments", sub, context); base.parse_attribute (/<cim:ErpRecLineItem.ErpReceivable\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpReceivable", sub, context); base.parse_attributes (/<cim:ErpRecLineItem.ErpJournalEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpJournalEntries", sub, context); let bucket = context.parsed.ErpRecLineItem; if (null == bucket) context.parsed.ErpRecLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpRecLineItem", "status", "status", fields); base.export_attribute (obj, "ErpRecLineItem", "ErpInvoiceLineItem", "ErpInvoiceLineItem", fields); base.export_attributes (obj, "ErpRecLineItem", "ErpPayments", "ErpPayments", fields); base.export_attribute (obj, "ErpRecLineItem", "ErpReceivable", "ErpReceivable", fields); base.export_attributes (obj, "ErpRecLineItem", "ErpJournalEntries", "ErpJournalEntries", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpRecLineItem_collapse" aria-expanded="true" aria-controls="ErpRecLineItem_collapse" style="margin-left: 10px;">ErpRecLineItem</a></legend> <div id="ErpRecLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#ErpInvoiceLineItem}}<div><b>ErpInvoiceLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInvoiceLineItem}}");}); return false;'>{{ErpInvoiceLineItem}}</a></div>{{/ErpInvoiceLineItem}} {{#ErpPayments}}<div><b>ErpPayments</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPayments}} {{#ErpReceivable}}<div><b>ErpReceivable</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpReceivable}}");}); return false;'>{{ErpReceivable}}</a></div>{{/ErpReceivable}} {{#ErpJournalEntries}}<div><b>ErpJournalEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpJournalEntries}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpPayments"]) obj["ErpPayments_string"] = obj["ErpPayments"].join (); if (obj["ErpJournalEntries"]) obj["ErpJournalEntries_string"] = obj["ErpJournalEntries"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpPayments_string"]; delete obj["ErpJournalEntries_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpRecLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpRecLineItem_collapse" style="margin-left: 10px;">ErpRecLineItem</a></legend> <div id="{{id}}_ErpRecLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoiceLineItem'>ErpInvoiceLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoiceLineItem' class='form-control' type='text'{{#ErpInvoiceLineItem}} value='{{ErpInvoiceLineItem}}'{{/ErpInvoiceLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayments'>ErpPayments: </label><div class='col-sm-8'><input id='{{id}}_ErpPayments' class='form-control' type='text'{{#ErpPayments}} value='{{ErpPayments_string}}'{{/ErpPayments}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpReceivable'>ErpReceivable: </label><div class='col-sm-8'><input id='{{id}}_ErpReceivable' class='form-control' type='text'{{#ErpReceivable}} value='{{ErpReceivable}}'{{/ErpReceivable}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpJournalEntries'>ErpJournalEntries: </label><div class='col-sm-8'><input id='{{id}}_ErpJournalEntries' class='form-control' type='text'{{#ErpJournalEntries}} value='{{ErpJournalEntries_string}}'{{/ErpJournalEntries}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpRecLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_ErpInvoiceLineItem").value; if ("" !== temp) obj["ErpInvoiceLineItem"] = temp; temp = document.getElementById (id + "_ErpPayments").value; if ("" !== temp) obj["ErpPayments"] = temp.split (","); temp = document.getElementById (id + "_ErpReceivable").value; if ("" !== temp) obj["ErpReceivable"] = temp; temp = document.getElementById (id + "_ErpJournalEntries").value; if ("" !== temp) obj["ErpJournalEntries"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpInvoiceLineItem", "0..1", "0..1", "ErpInvoiceLineItem", "ErpRecLineItem"], ["ErpPayments", "0..*", "0..*", "ErpPayment", "ErpRecLineItems"], ["ErpReceivable", "1", "0..*", "ErpReceivable", "ErpRecLineItems"], ["ErpJournalEntries", "0..*", "0..*", "ErpJournalEntry", "ErpRecLineItems"] ] ) ); } }
JavaScript
class ErpIssueInventory extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpIssueInventory; if (null == bucket) cim_data.ErpIssueInventory = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpIssueInventory[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpIssueInventory"; base.parse_attribute (/<cim:ErpIssueInventory.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpIssueInventory.TypeMaterial\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TypeMaterial", sub, context); base.parse_attribute (/<cim:ErpIssueInventory.TypeAsset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TypeAsset", sub, context); let bucket = context.parsed.ErpIssueInventory; if (null == bucket) context.parsed.ErpIssueInventory = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpIssueInventory", "status", "status", fields); base.export_attribute (obj, "ErpIssueInventory", "TypeMaterial", "TypeMaterial", fields); base.export_attribute (obj, "ErpIssueInventory", "TypeAsset", "TypeAsset", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpIssueInventory_collapse" aria-expanded="true" aria-controls="ErpIssueInventory_collapse" style="margin-left: 10px;">ErpIssueInventory</a></legend> <div id="ErpIssueInventory_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#TypeMaterial}}<div><b>TypeMaterial</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{TypeMaterial}}");}); return false;'>{{TypeMaterial}}</a></div>{{/TypeMaterial}} {{#TypeAsset}}<div><b>TypeAsset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{TypeAsset}}");}); return false;'>{{TypeAsset}}</a></div>{{/TypeAsset}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpIssueInventory_collapse" aria-expanded="true" aria-controls="{{id}}_ErpIssueInventory_collapse" style="margin-left: 10px;">ErpIssueInventory</a></legend> <div id="{{id}}_ErpIssueInventory_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TypeMaterial'>TypeMaterial: </label><div class='col-sm-8'><input id='{{id}}_TypeMaterial' class='form-control' type='text'{{#TypeMaterial}} value='{{TypeMaterial}}'{{/TypeMaterial}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TypeAsset'>TypeAsset: </label><div class='col-sm-8'><input id='{{id}}_TypeAsset' class='form-control' type='text'{{#TypeAsset}} value='{{TypeAsset}}'{{/TypeAsset}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpIssueInventory" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_TypeMaterial").value; if ("" !== temp) obj["TypeMaterial"] = temp; temp = document.getElementById (id + "_TypeAsset").value; if ("" !== temp) obj["TypeAsset"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["TypeMaterial", "0..1", "0..*", "TypeMaterial", "ErpIssueInventories"], ["TypeAsset", "0..1", "0..*", "CatalogAssetType", "ErpInventoryIssues"] ] ) ); } }
JavaScript
class ErpCompetency extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpCompetency; if (null == bucket) cim_data.ErpCompetency = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpCompetency[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpCompetency"; base.parse_attributes (/<cim:ErpCompetency.ErpPersons\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPersons", sub, context); let bucket = context.parsed.ErpCompetency; if (null == bucket) context.parsed.ErpCompetency = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attributes (obj, "ErpCompetency", "ErpPersons", "ErpPersons", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpCompetency_collapse" aria-expanded="true" aria-controls="ErpCompetency_collapse" style="margin-left: 10px;">ErpCompetency</a></legend> <div id="ErpCompetency_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#ErpPersons}}<div><b>ErpPersons</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPersons}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpPersons"]) obj["ErpPersons_string"] = obj["ErpPersons"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpPersons_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpCompetency_collapse" aria-expanded="true" aria-controls="{{id}}_ErpCompetency_collapse" style="margin-left: 10px;">ErpCompetency</a></legend> <div id="{{id}}_ErpCompetency_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "ErpCompetency" }; super.submit (id, obj); return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpPersons", "0..*", "0..1", "OldPerson", "ErpCompetency"] ] ) ); } }
JavaScript
class ErpRecDelvLineItem extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpRecDelvLineItem; if (null == bucket) cim_data.ErpRecDelvLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpRecDelvLineItem[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpRecDelvLineItem"; base.parse_attribute (/<cim:ErpRecDelvLineItem.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpRecDelvLineItem.ErpReceiveDelivery\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpReceiveDelivery", sub, context); base.parse_attributes (/<cim:ErpRecDelvLineItem.Assets\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Assets", sub, context); base.parse_attribute (/<cim:ErpRecDelvLineItem.ErpPOLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPOLineItem", sub, context); base.parse_attribute (/<cim:ErpRecDelvLineItem.ErpInvoiceLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItem", sub, context); let bucket = context.parsed.ErpRecDelvLineItem; if (null == bucket) context.parsed.ErpRecDelvLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpRecDelvLineItem", "status", "status", fields); base.export_attribute (obj, "ErpRecDelvLineItem", "ErpReceiveDelivery", "ErpReceiveDelivery", fields); base.export_attributes (obj, "ErpRecDelvLineItem", "Assets", "Assets", fields); base.export_attribute (obj, "ErpRecDelvLineItem", "ErpPOLineItem", "ErpPOLineItem", fields); base.export_attribute (obj, "ErpRecDelvLineItem", "ErpInvoiceLineItem", "ErpInvoiceLineItem", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpRecDelvLineItem_collapse" aria-expanded="true" aria-controls="ErpRecDelvLineItem_collapse" style="margin-left: 10px;">ErpRecDelvLineItem</a></legend> <div id="ErpRecDelvLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#ErpReceiveDelivery}}<div><b>ErpReceiveDelivery</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpReceiveDelivery}}");}); return false;'>{{ErpReceiveDelivery}}</a></div>{{/ErpReceiveDelivery}} {{#Assets}}<div><b>Assets</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Assets}} {{#ErpPOLineItem}}<div><b>ErpPOLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpPOLineItem}}");}); return false;'>{{ErpPOLineItem}}</a></div>{{/ErpPOLineItem}} {{#ErpInvoiceLineItem}}<div><b>ErpInvoiceLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInvoiceLineItem}}");}); return false;'>{{ErpInvoiceLineItem}}</a></div>{{/ErpInvoiceLineItem}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["Assets"]) obj["Assets_string"] = obj["Assets"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["Assets_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpRecDelvLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpRecDelvLineItem_collapse" style="margin-left: 10px;">ErpRecDelvLineItem</a></legend> <div id="{{id}}_ErpRecDelvLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpReceiveDelivery'>ErpReceiveDelivery: </label><div class='col-sm-8'><input id='{{id}}_ErpReceiveDelivery' class='form-control' type='text'{{#ErpReceiveDelivery}} value='{{ErpReceiveDelivery}}'{{/ErpReceiveDelivery}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Assets'>Assets: </label><div class='col-sm-8'><input id='{{id}}_Assets' class='form-control' type='text'{{#Assets}} value='{{Assets_string}}'{{/Assets}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPOLineItem'>ErpPOLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpPOLineItem' class='form-control' type='text'{{#ErpPOLineItem}} value='{{ErpPOLineItem}}'{{/ErpPOLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoiceLineItem'>ErpInvoiceLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoiceLineItem' class='form-control' type='text'{{#ErpInvoiceLineItem}} value='{{ErpInvoiceLineItem}}'{{/ErpInvoiceLineItem}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpRecDelvLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_ErpReceiveDelivery").value; if ("" !== temp) obj["ErpReceiveDelivery"] = temp; temp = document.getElementById (id + "_Assets").value; if ("" !== temp) obj["Assets"] = temp.split (","); temp = document.getElementById (id + "_ErpPOLineItem").value; if ("" !== temp) obj["ErpPOLineItem"] = temp; temp = document.getElementById (id + "_ErpInvoiceLineItem").value; if ("" !== temp) obj["ErpInvoiceLineItem"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpReceiveDelivery", "1", "0..*", "ErpReceiveDelivery", "ErpRecDelvLineItems"], ["Assets", "0..*", "0..*", "Asset", "ErpRecDeliveryItems"], ["ErpPOLineItem", "0..1", "0..1", "ErpPOLineItem", "ErpRecDelLineItem"], ["ErpInvoiceLineItem", "0..1", "0..1", "ErpInvoiceLineItem", "ErpRecDelvLineItem"] ] ) ); } }
JavaScript
class ErpJournalEntry extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpJournalEntry; if (null == bucket) cim_data.ErpJournalEntry = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpJournalEntry[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpJournalEntry"; base.parse_element (/<cim:ErpJournalEntry.accountID>([\s\S]*?)<\/cim:ErpJournalEntry.accountID>/g, obj, "accountID", base.to_string, sub, context); base.parse_element (/<cim:ErpJournalEntry.amount>([\s\S]*?)<\/cim:ErpJournalEntry.amount>/g, obj, "amount", base.to_string, sub, context); base.parse_element (/<cim:ErpJournalEntry.postingDateTime>([\s\S]*?)<\/cim:ErpJournalEntry.postingDateTime>/g, obj, "postingDateTime", base.to_datetime, sub, context); base.parse_element (/<cim:ErpJournalEntry.sourceID>([\s\S]*?)<\/cim:ErpJournalEntry.sourceID>/g, obj, "sourceID", base.to_string, sub, context); base.parse_attribute (/<cim:ErpJournalEntry.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_element (/<cim:ErpJournalEntry.transactionDateTime>([\s\S]*?)<\/cim:ErpJournalEntry.transactionDateTime>/g, obj, "transactionDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:ErpJournalEntry.ErpJournal\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpJournal", sub, context); base.parse_attribute (/<cim:ErpJournalEntry.ErpInvoiceLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItem", sub, context); base.parse_attribute (/<cim:ErpJournalEntry.ErpLedgerEntry\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedgerEntry", sub, context); base.parse_attributes (/<cim:ErpJournalEntry.CostTypes\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CostTypes", sub, context); base.parse_attributes (/<cim:ErpJournalEntry.ErpPayableLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayableLineItems", sub, context); base.parse_attributes (/<cim:ErpJournalEntry.ErpRecLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecLineItems", sub, context); let bucket = context.parsed.ErpJournalEntry; if (null == bucket) context.parsed.ErpJournalEntry = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "ErpJournalEntry", "accountID", "accountID", base.from_string, fields); base.export_element (obj, "ErpJournalEntry", "amount", "amount", base.from_string, fields); base.export_element (obj, "ErpJournalEntry", "postingDateTime", "postingDateTime", base.from_datetime, fields); base.export_element (obj, "ErpJournalEntry", "sourceID", "sourceID", base.from_string, fields); base.export_attribute (obj, "ErpJournalEntry", "status", "status", fields); base.export_element (obj, "ErpJournalEntry", "transactionDateTime", "transactionDateTime", base.from_datetime, fields); base.export_attribute (obj, "ErpJournalEntry", "ErpJournal", "ErpJournal", fields); base.export_attribute (obj, "ErpJournalEntry", "ErpInvoiceLineItem", "ErpInvoiceLineItem", fields); base.export_attribute (obj, "ErpJournalEntry", "ErpLedgerEntry", "ErpLedgerEntry", fields); base.export_attributes (obj, "ErpJournalEntry", "CostTypes", "CostTypes", fields); base.export_attributes (obj, "ErpJournalEntry", "ErpPayableLineItems", "ErpPayableLineItems", fields); base.export_attributes (obj, "ErpJournalEntry", "ErpRecLineItems", "ErpRecLineItems", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpJournalEntry_collapse" aria-expanded="true" aria-controls="ErpJournalEntry_collapse" style="margin-left: 10px;">ErpJournalEntry</a></legend> <div id="ErpJournalEntry_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#accountID}}<div><b>accountID</b>: {{accountID}}</div>{{/accountID}} {{#amount}}<div><b>amount</b>: {{amount}}</div>{{/amount}} {{#postingDateTime}}<div><b>postingDateTime</b>: {{postingDateTime}}</div>{{/postingDateTime}} {{#sourceID}}<div><b>sourceID</b>: {{sourceID}}</div>{{/sourceID}} {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#transactionDateTime}}<div><b>transactionDateTime</b>: {{transactionDateTime}}</div>{{/transactionDateTime}} {{#ErpJournal}}<div><b>ErpJournal</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpJournal}}");}); return false;'>{{ErpJournal}}</a></div>{{/ErpJournal}} {{#ErpInvoiceLineItem}}<div><b>ErpInvoiceLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInvoiceLineItem}}");}); return false;'>{{ErpInvoiceLineItem}}</a></div>{{/ErpInvoiceLineItem}} {{#ErpLedgerEntry}}<div><b>ErpLedgerEntry</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpLedgerEntry}}");}); return false;'>{{ErpLedgerEntry}}</a></div>{{/ErpLedgerEntry}} {{#CostTypes}}<div><b>CostTypes</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/CostTypes}} {{#ErpPayableLineItems}}<div><b>ErpPayableLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPayableLineItems}} {{#ErpRecLineItems}}<div><b>ErpRecLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpRecLineItems}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["CostTypes"]) obj["CostTypes_string"] = obj["CostTypes"].join (); if (obj["ErpPayableLineItems"]) obj["ErpPayableLineItems_string"] = obj["ErpPayableLineItems"].join (); if (obj["ErpRecLineItems"]) obj["ErpRecLineItems_string"] = obj["ErpRecLineItems"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["CostTypes_string"]; delete obj["ErpPayableLineItems_string"]; delete obj["ErpRecLineItems_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpJournalEntry_collapse" aria-expanded="true" aria-controls="{{id}}_ErpJournalEntry_collapse" style="margin-left: 10px;">ErpJournalEntry</a></legend> <div id="{{id}}_ErpJournalEntry_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_accountID'>accountID: </label><div class='col-sm-8'><input id='{{id}}_accountID' class='form-control' type='text'{{#accountID}} value='{{accountID}}'{{/accountID}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_amount'>amount: </label><div class='col-sm-8'><input id='{{id}}_amount' class='form-control' type='text'{{#amount}} value='{{amount}}'{{/amount}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_postingDateTime'>postingDateTime: </label><div class='col-sm-8'><input id='{{id}}_postingDateTime' class='form-control' type='text'{{#postingDateTime}} value='{{postingDateTime}}'{{/postingDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_sourceID'>sourceID: </label><div class='col-sm-8'><input id='{{id}}_sourceID' class='form-control' type='text'{{#sourceID}} value='{{sourceID}}'{{/sourceID}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_transactionDateTime'>transactionDateTime: </label><div class='col-sm-8'><input id='{{id}}_transactionDateTime' class='form-control' type='text'{{#transactionDateTime}} value='{{transactionDateTime}}'{{/transactionDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpJournal'>ErpJournal: </label><div class='col-sm-8'><input id='{{id}}_ErpJournal' class='form-control' type='text'{{#ErpJournal}} value='{{ErpJournal}}'{{/ErpJournal}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoiceLineItem'>ErpInvoiceLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoiceLineItem' class='form-control' type='text'{{#ErpInvoiceLineItem}} value='{{ErpInvoiceLineItem}}'{{/ErpInvoiceLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpLedgerEntry'>ErpLedgerEntry: </label><div class='col-sm-8'><input id='{{id}}_ErpLedgerEntry' class='form-control' type='text'{{#ErpLedgerEntry}} value='{{ErpLedgerEntry}}'{{/ErpLedgerEntry}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_CostTypes'>CostTypes: </label><div class='col-sm-8'><input id='{{id}}_CostTypes' class='form-control' type='text'{{#CostTypes}} value='{{CostTypes_string}}'{{/CostTypes}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayableLineItems'>ErpPayableLineItems: </label><div class='col-sm-8'><input id='{{id}}_ErpPayableLineItems' class='form-control' type='text'{{#ErpPayableLineItems}} value='{{ErpPayableLineItems_string}}'{{/ErpPayableLineItems}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRecLineItems'>ErpRecLineItems: </label><div class='col-sm-8'><input id='{{id}}_ErpRecLineItems' class='form-control' type='text'{{#ErpRecLineItems}} value='{{ErpRecLineItems_string}}'{{/ErpRecLineItems}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpJournalEntry" }; super.submit (id, obj); temp = document.getElementById (id + "_accountID").value; if ("" !== temp) obj["accountID"] = temp; temp = document.getElementById (id + "_amount").value; if ("" !== temp) obj["amount"] = temp; temp = document.getElementById (id + "_postingDateTime").value; if ("" !== temp) obj["postingDateTime"] = temp; temp = document.getElementById (id + "_sourceID").value; if ("" !== temp) obj["sourceID"] = temp; temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_transactionDateTime").value; if ("" !== temp) obj["transactionDateTime"] = temp; temp = document.getElementById (id + "_ErpJournal").value; if ("" !== temp) obj["ErpJournal"] = temp; temp = document.getElementById (id + "_ErpInvoiceLineItem").value; if ("" !== temp) obj["ErpInvoiceLineItem"] = temp; temp = document.getElementById (id + "_ErpLedgerEntry").value; if ("" !== temp) obj["ErpLedgerEntry"] = temp; temp = document.getElementById (id + "_CostTypes").value; if ("" !== temp) obj["CostTypes"] = temp.split (","); temp = document.getElementById (id + "_ErpPayableLineItems").value; if ("" !== temp) obj["ErpPayableLineItems"] = temp.split (","); temp = document.getElementById (id + "_ErpRecLineItems").value; if ("" !== temp) obj["ErpRecLineItems"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpJournal", "1", "0..*", "ErpJournal", "ErpJournalEntries"], ["ErpInvoiceLineItem", "0..1", "0..*", "ErpInvoiceLineItem", "ErpJournalEntries"], ["ErpLedgerEntry", "0..1", "0..1", "ErpLedgerEntry", "ErpJounalEntry"], ["CostTypes", "0..*", "0..*", "CostType", "ErpJournalEntries"], ["ErpPayableLineItems", "0..*", "0..*", "ErpPayableLineItem", "ErpJournalEntries"], ["ErpRecLineItems", "0..*", "0..*", "ErpRecLineItem", "ErpJournalEntries"] ] ) ); } }
JavaScript
class ErpLedgerEntry extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpLedgerEntry; if (null == bucket) cim_data.ErpLedgerEntry = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpLedgerEntry[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpLedgerEntry"; base.parse_element (/<cim:ErpLedgerEntry.accountID>([\s\S]*?)<\/cim:ErpLedgerEntry.accountID>/g, obj, "accountID", base.to_string, sub, context); base.parse_attribute (/<cim:ErpLedgerEntry.accountKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "accountKind", sub, context); base.parse_element (/<cim:ErpLedgerEntry.amount>([\s\S]*?)<\/cim:ErpLedgerEntry.amount>/g, obj, "amount", base.to_string, sub, context); base.parse_element (/<cim:ErpLedgerEntry.postedDateTime>([\s\S]*?)<\/cim:ErpLedgerEntry.postedDateTime>/g, obj, "postedDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:ErpLedgerEntry.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_element (/<cim:ErpLedgerEntry.transactionDateTime>([\s\S]*?)<\/cim:ErpLedgerEntry.transactionDateTime>/g, obj, "transactionDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:ErpLedgerEntry.ErpLedgerEntry\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedgerEntry", sub, context); base.parse_attributes (/<cim:ErpLedgerEntry.UserAttributes\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "UserAttributes", sub, context); base.parse_attribute (/<cim:ErpLedgerEntry.ErpJounalEntry\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpJounalEntry", sub, context); base.parse_attribute (/<cim:ErpLedgerEntry.ErpLedger\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedger", sub, context); let bucket = context.parsed.ErpLedgerEntry; if (null == bucket) context.parsed.ErpLedgerEntry = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "ErpLedgerEntry", "accountID", "accountID", base.from_string, fields); base.export_attribute (obj, "ErpLedgerEntry", "accountKind", "accountKind", fields); base.export_element (obj, "ErpLedgerEntry", "amount", "amount", base.from_string, fields); base.export_element (obj, "ErpLedgerEntry", "postedDateTime", "postedDateTime", base.from_datetime, fields); base.export_attribute (obj, "ErpLedgerEntry", "status", "status", fields); base.export_element (obj, "ErpLedgerEntry", "transactionDateTime", "transactionDateTime", base.from_datetime, fields); base.export_attribute (obj, "ErpLedgerEntry", "ErpLedgerEntry", "ErpLedgerEntry", fields); base.export_attributes (obj, "ErpLedgerEntry", "UserAttributes", "UserAttributes", fields); base.export_attribute (obj, "ErpLedgerEntry", "ErpJounalEntry", "ErpJounalEntry", fields); base.export_attribute (obj, "ErpLedgerEntry", "ErpLedger", "ErpLedger", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpLedgerEntry_collapse" aria-expanded="true" aria-controls="ErpLedgerEntry_collapse" style="margin-left: 10px;">ErpLedgerEntry</a></legend> <div id="ErpLedgerEntry_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#accountID}}<div><b>accountID</b>: {{accountID}}</div>{{/accountID}} {{#accountKind}}<div><b>accountKind</b>: {{accountKind}}</div>{{/accountKind}} {{#amount}}<div><b>amount</b>: {{amount}}</div>{{/amount}} {{#postedDateTime}}<div><b>postedDateTime</b>: {{postedDateTime}}</div>{{/postedDateTime}} {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#transactionDateTime}}<div><b>transactionDateTime</b>: {{transactionDateTime}}</div>{{/transactionDateTime}} {{#ErpLedgerEntry}}<div><b>ErpLedgerEntry</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpLedgerEntry}}");}); return false;'>{{ErpLedgerEntry}}</a></div>{{/ErpLedgerEntry}} {{#UserAttributes}}<div><b>UserAttributes</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/UserAttributes}} {{#ErpJounalEntry}}<div><b>ErpJounalEntry</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpJounalEntry}}");}); return false;'>{{ErpJounalEntry}}</a></div>{{/ErpJounalEntry}} {{#ErpLedger}}<div><b>ErpLedger</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpLedger}}");}); return false;'>{{ErpLedger}}</a></div>{{/ErpLedger}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["accountKindErpAccountKind"] = [{ id: '', selected: (!obj["accountKind"])}]; for (let property in ErpAccountKind) obj["accountKindErpAccountKind"].push ({ id: property, selected: obj["accountKind"] && obj["accountKind"].endsWith ('.' + property)}); if (obj["UserAttributes"]) obj["UserAttributes_string"] = obj["UserAttributes"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["accountKindErpAccountKind"]; delete obj["UserAttributes_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpLedgerEntry_collapse" aria-expanded="true" aria-controls="{{id}}_ErpLedgerEntry_collapse" style="margin-left: 10px;">ErpLedgerEntry</a></legend> <div id="{{id}}_ErpLedgerEntry_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_accountID'>accountID: </label><div class='col-sm-8'><input id='{{id}}_accountID' class='form-control' type='text'{{#accountID}} value='{{accountID}}'{{/accountID}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_accountKind'>accountKind: </label><div class='col-sm-8'><select id='{{id}}_accountKind' class='form-control custom-select'>{{#accountKindErpAccountKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/accountKindErpAccountKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_amount'>amount: </label><div class='col-sm-8'><input id='{{id}}_amount' class='form-control' type='text'{{#amount}} value='{{amount}}'{{/amount}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_postedDateTime'>postedDateTime: </label><div class='col-sm-8'><input id='{{id}}_postedDateTime' class='form-control' type='text'{{#postedDateTime}} value='{{postedDateTime}}'{{/postedDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_transactionDateTime'>transactionDateTime: </label><div class='col-sm-8'><input id='{{id}}_transactionDateTime' class='form-control' type='text'{{#transactionDateTime}} value='{{transactionDateTime}}'{{/transactionDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpLedgerEntry'>ErpLedgerEntry: </label><div class='col-sm-8'><input id='{{id}}_ErpLedgerEntry' class='form-control' type='text'{{#ErpLedgerEntry}} value='{{ErpLedgerEntry}}'{{/ErpLedgerEntry}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_UserAttributes'>UserAttributes: </label><div class='col-sm-8'><input id='{{id}}_UserAttributes' class='form-control' type='text'{{#UserAttributes}} value='{{UserAttributes_string}}'{{/UserAttributes}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpJounalEntry'>ErpJounalEntry: </label><div class='col-sm-8'><input id='{{id}}_ErpJounalEntry' class='form-control' type='text'{{#ErpJounalEntry}} value='{{ErpJounalEntry}}'{{/ErpJounalEntry}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpLedger'>ErpLedger: </label><div class='col-sm-8'><input id='{{id}}_ErpLedger' class='form-control' type='text'{{#ErpLedger}} value='{{ErpLedger}}'{{/ErpLedger}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpLedgerEntry" }; super.submit (id, obj); temp = document.getElementById (id + "_accountID").value; if ("" !== temp) obj["accountID"] = temp; temp = ErpAccountKind[document.getElementById (id + "_accountKind").value]; if (temp) obj["accountKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ErpAccountKind." + temp; else delete obj["accountKind"]; temp = document.getElementById (id + "_amount").value; if ("" !== temp) obj["amount"] = temp; temp = document.getElementById (id + "_postedDateTime").value; if ("" !== temp) obj["postedDateTime"] = temp; temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_transactionDateTime").value; if ("" !== temp) obj["transactionDateTime"] = temp; temp = document.getElementById (id + "_ErpLedgerEntry").value; if ("" !== temp) obj["ErpLedgerEntry"] = temp; temp = document.getElementById (id + "_UserAttributes").value; if ("" !== temp) obj["UserAttributes"] = temp.split (","); temp = document.getElementById (id + "_ErpJounalEntry").value; if ("" !== temp) obj["ErpJounalEntry"] = temp; temp = document.getElementById (id + "_ErpLedger").value; if ("" !== temp) obj["ErpLedger"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpLedgerEntry", "0..1", "0..1", "ErpLedBudLineItem", "ErpLedBudLineItem"], ["UserAttributes", "0..*", "0..*", "UserAttribute", "ErpLedgerEntries"], ["ErpJounalEntry", "0..1", "0..1", "ErpJournalEntry", "ErpLedgerEntry"], ["ErpLedger", "1", "0..*", "ErpLedger", "ErpLedgerEntries"] ] ) ); } }
JavaScript
class ErpLedBudLineItem extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpLedBudLineItem; if (null == bucket) cim_data.ErpLedBudLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpLedBudLineItem[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpLedBudLineItem"; base.parse_attribute (/<cim:ErpLedBudLineItem.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpLedBudLineItem.ErpLedgerBudget\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedgerBudget", sub, context); base.parse_attribute (/<cim:ErpLedBudLineItem.ErpLedBudLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedBudLineItem", sub, context); let bucket = context.parsed.ErpLedBudLineItem; if (null == bucket) context.parsed.ErpLedBudLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpLedBudLineItem", "status", "status", fields); base.export_attribute (obj, "ErpLedBudLineItem", "ErpLedgerBudget", "ErpLedgerBudget", fields); base.export_attribute (obj, "ErpLedBudLineItem", "ErpLedBudLineItem", "ErpLedBudLineItem", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpLedBudLineItem_collapse" aria-expanded="true" aria-controls="ErpLedBudLineItem_collapse" style="margin-left: 10px;">ErpLedBudLineItem</a></legend> <div id="ErpLedBudLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#ErpLedgerBudget}}<div><b>ErpLedgerBudget</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpLedgerBudget}}");}); return false;'>{{ErpLedgerBudget}}</a></div>{{/ErpLedgerBudget}} {{#ErpLedBudLineItem}}<div><b>ErpLedBudLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpLedBudLineItem}}");}); return false;'>{{ErpLedBudLineItem}}</a></div>{{/ErpLedBudLineItem}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpLedBudLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpLedBudLineItem_collapse" style="margin-left: 10px;">ErpLedBudLineItem</a></legend> <div id="{{id}}_ErpLedBudLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpLedgerBudget'>ErpLedgerBudget: </label><div class='col-sm-8'><input id='{{id}}_ErpLedgerBudget' class='form-control' type='text'{{#ErpLedgerBudget}} value='{{ErpLedgerBudget}}'{{/ErpLedgerBudget}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpLedBudLineItem'>ErpLedBudLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpLedBudLineItem' class='form-control' type='text'{{#ErpLedBudLineItem}} value='{{ErpLedBudLineItem}}'{{/ErpLedBudLineItem}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpLedBudLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_ErpLedgerBudget").value; if ("" !== temp) obj["ErpLedgerBudget"] = temp; temp = document.getElementById (id + "_ErpLedBudLineItem").value; if ("" !== temp) obj["ErpLedBudLineItem"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpLedgerBudget", "1", "0..*", "ErpLedgerBudget", "ErpLedBudLineItems"], ["ErpLedBudLineItem", "0..1", "0..1", "ErpLedgerEntry", "ErpLedgerEntry"] ] ) ); } }
JavaScript
class ErpQuoteLineItem extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpQuoteLineItem; if (null == bucket) cim_data.ErpQuoteLineItem = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpQuoteLineItem[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpQuoteLineItem"; base.parse_attribute (/<cim:ErpQuoteLineItem.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpQuoteLineItem.Design\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Design", sub, context); base.parse_attribute (/<cim:ErpQuoteLineItem.ErpReqLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpReqLineItem", sub, context); base.parse_attribute (/<cim:ErpQuoteLineItem.AssetModelCatalogueItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetModelCatalogueItem", sub, context); base.parse_attribute (/<cim:ErpQuoteLineItem.ErpInvoiceLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItem", sub, context); base.parse_attribute (/<cim:ErpQuoteLineItem.ErpQuote\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpQuote", sub, context); let bucket = context.parsed.ErpQuoteLineItem; if (null == bucket) context.parsed.ErpQuoteLineItem = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpQuoteLineItem", "status", "status", fields); base.export_attribute (obj, "ErpQuoteLineItem", "Design", "Design", fields); base.export_attribute (obj, "ErpQuoteLineItem", "ErpReqLineItem", "ErpReqLineItem", fields); base.export_attribute (obj, "ErpQuoteLineItem", "AssetModelCatalogueItem", "AssetModelCatalogueItem", fields); base.export_attribute (obj, "ErpQuoteLineItem", "ErpInvoiceLineItem", "ErpInvoiceLineItem", fields); base.export_attribute (obj, "ErpQuoteLineItem", "ErpQuote", "ErpQuote", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpQuoteLineItem_collapse" aria-expanded="true" aria-controls="ErpQuoteLineItem_collapse" style="margin-left: 10px;">ErpQuoteLineItem</a></legend> <div id="ErpQuoteLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#Design}}<div><b>Design</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Design}}");}); return false;'>{{Design}}</a></div>{{/Design}} {{#ErpReqLineItem}}<div><b>ErpReqLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpReqLineItem}}");}); return false;'>{{ErpReqLineItem}}</a></div>{{/ErpReqLineItem}} {{#AssetModelCatalogueItem}}<div><b>AssetModelCatalogueItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetModelCatalogueItem}}");}); return false;'>{{AssetModelCatalogueItem}}</a></div>{{/AssetModelCatalogueItem}} {{#ErpInvoiceLineItem}}<div><b>ErpInvoiceLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInvoiceLineItem}}");}); return false;'>{{ErpInvoiceLineItem}}</a></div>{{/ErpInvoiceLineItem}} {{#ErpQuote}}<div><b>ErpQuote</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpQuote}}");}); return false;'>{{ErpQuote}}</a></div>{{/ErpQuote}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpQuoteLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpQuoteLineItem_collapse" style="margin-left: 10px;">ErpQuoteLineItem</a></legend> <div id="{{id}}_ErpQuoteLineItem_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Design'>Design: </label><div class='col-sm-8'><input id='{{id}}_Design' class='form-control' type='text'{{#Design}} value='{{Design}}'{{/Design}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpReqLineItem'>ErpReqLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpReqLineItem' class='form-control' type='text'{{#ErpReqLineItem}} value='{{ErpReqLineItem}}'{{/ErpReqLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetModelCatalogueItem'>AssetModelCatalogueItem: </label><div class='col-sm-8'><input id='{{id}}_AssetModelCatalogueItem' class='form-control' type='text'{{#AssetModelCatalogueItem}} value='{{AssetModelCatalogueItem}}'{{/AssetModelCatalogueItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoiceLineItem'>ErpInvoiceLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoiceLineItem' class='form-control' type='text'{{#ErpInvoiceLineItem}} value='{{ErpInvoiceLineItem}}'{{/ErpInvoiceLineItem}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpQuote'>ErpQuote: </label><div class='col-sm-8'><input id='{{id}}_ErpQuote' class='form-control' type='text'{{#ErpQuote}} value='{{ErpQuote}}'{{/ErpQuote}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpQuoteLineItem" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_Design").value; if ("" !== temp) obj["Design"] = temp; temp = document.getElementById (id + "_ErpReqLineItem").value; if ("" !== temp) obj["ErpReqLineItem"] = temp; temp = document.getElementById (id + "_AssetModelCatalogueItem").value; if ("" !== temp) obj["AssetModelCatalogueItem"] = temp; temp = document.getElementById (id + "_ErpInvoiceLineItem").value; if ("" !== temp) obj["ErpInvoiceLineItem"] = temp; temp = document.getElementById (id + "_ErpQuote").value; if ("" !== temp) obj["ErpQuote"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Design", "0..1", "0..1", "Design", "ErpQuoteLineItem"], ["ErpReqLineItem", "0..1", "0..1", "ErpReqLineItem", "ErpQuoteLineItem"], ["AssetModelCatalogueItem", "0..1", "0..*", "AssetModelCatalogueItem", "ErpQuoteLineItems"], ["ErpInvoiceLineItem", "0..1", "0..1", "ErpInvoiceLineItem", "ErpQuoteLineItem"], ["ErpQuote", "1", "0..*", "ErpQuote", "ErpQuoteLineItems"] ] ) ); } }
JavaScript
class ErpPersonnel extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpPersonnel; if (null == bucket) cim_data.ErpPersonnel = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpPersonnel[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpPersonnel"; base.parse_attribute (/<cim:ErpPersonnel.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attributes (/<cim:ErpPersonnel.ErpPersons\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPersons", sub, context); let bucket = context.parsed.ErpPersonnel; if (null == bucket) context.parsed.ErpPersonnel = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpPersonnel", "status", "status", fields); base.export_attributes (obj, "ErpPersonnel", "ErpPersons", "ErpPersons", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpPersonnel_collapse" aria-expanded="true" aria-controls="ErpPersonnel_collapse" style="margin-left: 10px;">ErpPersonnel</a></legend> <div id="ErpPersonnel_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#ErpPersons}}<div><b>ErpPersons</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPersons}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ErpPersons"]) obj["ErpPersons_string"] = obj["ErpPersons"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ErpPersons_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpPersonnel_collapse" aria-expanded="true" aria-controls="{{id}}_ErpPersonnel_collapse" style="margin-left: 10px;">ErpPersonnel</a></legend> <div id="{{id}}_ErpPersonnel_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpPersonnel" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpPersons", "0..*", "0..1", "OldPerson", "ErpPersonnel"] ] ) ); } }
JavaScript
class ErpItemMaster extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpItemMaster; if (null == bucket) cim_data.ErpItemMaster = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpItemMaster[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpItemMaster"; base.parse_attribute (/<cim:ErpItemMaster.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpItemMaster.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); let bucket = context.parsed.ErpItemMaster; if (null == bucket) context.parsed.ErpItemMaster = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpItemMaster", "status", "status", fields); base.export_attribute (obj, "ErpItemMaster", "Asset", "Asset", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpItemMaster_collapse" aria-expanded="true" aria-controls="ErpItemMaster_collapse" style="margin-left: 10px;">ErpItemMaster</a></legend> <div id="ErpItemMaster_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpItemMaster_collapse" aria-expanded="true" aria-controls="{{id}}_ErpItemMaster_collapse" style="margin-left: 10px;">ErpItemMaster</a></legend> <div id="{{id}}_ErpItemMaster_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpItemMaster" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Asset", "0..1", "0..1", "Asset", "ErpItemMaster"] ] ) ); } }
JavaScript
class ErpTimeEntry extends ErpIdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ErpTimeEntry; if (null == bucket) cim_data.ErpTimeEntry = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ErpTimeEntry[obj.id]; } parse (context, sub) { let obj = ErpIdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ErpTimeEntry"; base.parse_attribute (/<cim:ErpTimeEntry.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_attribute (/<cim:ErpTimeEntry.ErpTimeSheet\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpTimeSheet", sub, context); base.parse_attribute (/<cim:ErpTimeEntry.ErpProjectAccounting\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpProjectAccounting", sub, context); let bucket = context.parsed.ErpTimeEntry; if (null == bucket) context.parsed.ErpTimeEntry = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = ErpIdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "ErpTimeEntry", "status", "status", fields); base.export_attribute (obj, "ErpTimeEntry", "ErpTimeSheet", "ErpTimeSheet", fields); base.export_attribute (obj, "ErpTimeEntry", "ErpProjectAccounting", "ErpProjectAccounting", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpTimeEntry_collapse" aria-expanded="true" aria-controls="ErpTimeEntry_collapse" style="margin-left: 10px;">ErpTimeEntry</a></legend> <div id="ErpTimeEntry_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.template.call (this) + ` {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#ErpTimeSheet}}<div><b>ErpTimeSheet</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpTimeSheet}}");}); return false;'>{{ErpTimeSheet}}</a></div>{{/ErpTimeSheet}} {{#ErpProjectAccounting}}<div><b>ErpProjectAccounting</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpProjectAccounting}}");}); return false;'>{{ErpProjectAccounting}}</a></div>{{/ErpProjectAccounting}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpTimeEntry_collapse" aria-expanded="true" aria-controls="{{id}}_ErpTimeEntry_collapse" style="margin-left: 10px;">ErpTimeEntry</a></legend> <div id="{{id}}_ErpTimeEntry_collapse" class="collapse in show" style="margin-left: 10px;"> ` + ErpIdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpTimeSheet'>ErpTimeSheet: </label><div class='col-sm-8'><input id='{{id}}_ErpTimeSheet' class='form-control' type='text'{{#ErpTimeSheet}} value='{{ErpTimeSheet}}'{{/ErpTimeSheet}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpProjectAccounting'>ErpProjectAccounting: </label><div class='col-sm-8'><input id='{{id}}_ErpProjectAccounting' class='form-control' type='text'{{#ErpProjectAccounting}} value='{{ErpProjectAccounting}}'{{/ErpProjectAccounting}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ErpTimeEntry" }; super.submit (id, obj); temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_ErpTimeSheet").value; if ("" !== temp) obj["ErpTimeSheet"] = temp; temp = document.getElementById (id + "_ErpProjectAccounting").value; if ("" !== temp) obj["ErpProjectAccounting"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpTimeSheet", "1", "0..*", "ErpTimeSheet", "ErpTimeEntries"], ["ErpProjectAccounting", "0..1", "0..*", "ErpProjectAccounting", "ErpTimeEntries"] ] ) ); } }
JavaScript
class Matches { // # // # // ### ## ### // # # # ## # // ## ## # // # ## ## // ### /** * Processes the request. * @param {Express.Request} req The request. * @param {Express.Response} res The response. * @returns {Promise} A promise that resolves when the request is complete. */ static async get(req, res) { const querySeason = req.query.season && req.query.season.toString() || void 0, season = Number.parseInt(querySeason, 10) || void 0, seasonList = await Season.getSeasonNumbers(), {matches: pending, completed: totalCompleted} = await Match.getUpcomingAndCompletedCount(isNaN(season) ? void 0 : season), completed = await Match.getBySeason(isNaN(season) ? void 0 : season); res.status(200).send(await Common.page( "", {css: ["/css/matches.css"], js: ["/views/matches/match.js", "/js/countdown.js", "/js/matches.js"]}, MatchesView.get({ season, seasonList, pending, totalCompleted, completed, matchesPerPage: Match.matchesPerPage }), req )); } }
JavaScript
class BaseView extends Component { /** * Display the children Component */ displayChildren = () => { return <div>{this.props.children}</div>; }; render() { return ( <div> <nav className="navbar navbar-dark bg-dark p-4"> <h1 className="navbar-brand fs-1" style={{ color: "#F2B5B5" }}> Data Driven Gallery </h1> <img src="/d3-gallery/d3.png" className="" width="60" height="60" alt="" /> </nav> {this.displayChildren()} <footer className="position-relative bottom-0 bg-dark p-1 min-vw-100"> <p className="font-weight-normal text-white">© 2022 MIT</p> </footer> </div> ); } }
JavaScript
class AddEndpointWebhook { /** * Constructor to add new webhook endpoint. * * @param {object} params * @param {number} params.client_id: client id * @param {string} params.url: external url where webhook sent * @param {string} [params.status]: status * * @constructor */ constructor(params) { const oThis = this; oThis.clientId = params.client_id; oThis.endpointUrl = params.url; oThis.status = params.status || webhookEndpointConstants.activeStatus; oThis.endpoint = null; oThis.secretSalt = null; oThis.secret = null; oThis.uuid = null; } /** * Main performer for class. * * @return {Promise<void>} */ async perform() { const oThis = this; await oThis._validateAndSanitizeParams(); await oThis.getEndpoint(); await oThis.createEndpoint(); await oThis._clearCache(); return responseHelper.successWithData({ id: oThis.uuid, url: oThis.endpointUrl, status: webhookEndpointConstants.invertedStatuses[oThis.status], updatedTimestamp: Math.floor(Date.now() / 1000) }); } /** * Validate params. * * @sets oThis.status * * @returns {Promise<*>} */ async _validateAndSanitizeParams() { const oThis = this; oThis.status = oThis.status.toUpperCase(); const validStatuses = basicHelper.deepDup(webhookEndpointConstants.invertedStatuses); delete validStatuses[webhookEndpointConstants.deletedStatus]; if (!validStatuses[oThis.status]) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'l_we_ae_1', api_error_identifier: 'invalid_api_params', params_error_identifiers: ['invalid_status'], debug_options: { status: oThis.status } }) ); } await oThis.validateClient(); } /** * Validate client. * * @returns {Promise<never>} */ async validateClient() { const oThis = this; const clientData = await new ClientModel().fetchById(oThis.clientId); if (!CommonValidators.validateNonEmptyObject(clientData) || clientData.status !== clientConstants.activeStatus) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'l_we_ae_2', api_error_identifier: 'invalid_api_params', params_error_identifiers: ['invalid_clientId'], debug_options: { clientId: oThis.clientId, clientData: clientData } }) ); } } /** * Get endpoint. * * @sets oThis.endpoint * * @returns {Promise<void>} */ async getEndpoint() { // Query and check if endpoint is already present. const oThis = this; const endpoints = await new WebhookEndpointModel() .select('*') .where({ client_id: oThis.clientId, endpoint: oThis.endpointUrl }) .fire(); oThis.endpoint = endpoints[0]; if ( oThis.endpoint && webhookEndpointConstants.statuses[oThis.endpoint.status] !== webhookEndpointConstants.deletedStatus ) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_we_ae_3', api_error_identifier: 'endpoint_already_present' }) ); } } /** * Create endpoint in webhook endpoints table. * * @sets oThis.uuid, oThis.secret * * @returns {Promise<never>} */ async createEndpoint() { const oThis = this; if (oThis.endpoint) { oThis.endpointUrl = oThis.endpoint.endpoint; await new WebhookEndpointModel() .update({ status: webhookEndpointConstants.invertedStatuses[oThis.status] }) .where({ id: oThis.endpoint.id }) .fire(); oThis.uuid = oThis.endpoint.uuid; } else { await oThis._generateSalt(); const secret_salt = oThis.secretSalt.CiphertextBlob; oThis.secret = oThis._getEncryptedApiSecret(); oThis.uuid = uuidV4(); await new WebhookEndpointModel() .insert({ uuid: oThis.uuid, client_id: oThis.clientId, endpoint: oThis.endpointUrl, secret: oThis.secret, secret_salt: secret_salt, status: webhookEndpointConstants.invertedStatuses[oThis.status] }) .fire(); } } /** * Generate secret salt. * * @sets oThis.secretSalt * * @returns {Promise} * @private */ async _generateSalt() { const oThis = this; const kmsObj = new KmsWrapper(webhookEndpointConstants.encryptionSecretPurpose); oThis.secretSalt = await kmsObj.generateDataKey(); } /** * Get encrypted secret. * * @returns {*} * @private */ _getEncryptedApiSecret() { const oThis = this; const apiSecret = util.generateWebhookSecret(); logger.info(`WEBHOOK SECRET: ${apiSecret}`); return localCipher.encrypt(oThis.secretSalt.Plaintext, apiSecret); } /** * Clear cache. * * @returns {Promise<void>} * @private */ async _clearCache() { const oThis = this; await WebhookEndpointModel.flushCache({ uuid: oThis.uuid }); } }
JavaScript
class UnionType extends abstract_1.Type { /** * Create a new TupleType instance. * * @param types The types this union consists of. */ constructor(types) { super(); /** * The type name identifier. */ this.type = "union"; this.types = types; this.normalize(); } /** * Clone this type. * * @return A clone of this type. */ clone() { return new UnionType(this.types); } /** * Test whether this type equals the given type. * * @param type The type that should be checked for equality. * @returns TRUE if the given type equals this type, FALSE otherwise. */ equals(type) { if (!(type instanceof UnionType)) { return false; } return abstract_1.Type.isTypeListSimilar(type.types, this.types); } /** * Return a string representation of this type. */ toString() { const names = []; this.types.forEach((element) => { names.push(element.toString()); }); return names.join(" | "); } normalize() { const trueIndex = this.types.findIndex((t) => t.equals(new literal_1.LiteralType(true))); const falseIndex = this.types.findIndex((t) => t.equals(new literal_1.LiteralType(false))); if (trueIndex !== -1 && falseIndex !== -1) { this.types.splice(Math.max(trueIndex, falseIndex), 1); this.types.splice(Math.min(trueIndex, falseIndex), 1, new intrinsic_1.IntrinsicType("boolean")); } } }
JavaScript
class CommentTextParser { /** * Create a comment text parser. * * @param {CommentForm} commentForm * @param {string} action */ constructor(commentForm, action) { this.commentForm = commentForm; this.target = commentForm.target; this.action = action; this.filePatternEnd = `\\[\\[${cd.g.FILE_PREFIX_PATTERN}.+\\]\\]$`; this.galleryRegexp = /^\x01\d+_gallery\x02$/m; this.setIndentationData(); } /** * Set the properties related to indentation. * * @private */ setIndentationData() { switch (this.commentForm.mode) { case 'reply': this.indentationChars = this.target.inCode.replyIndentationChars; break; case 'edit': // Using originalIndentationChars, not indentationChars, makes a difference with comments // like at // https://commons.wikimedia.org/wiki/User_talk:Jack_who_built_the_house/CD_test_cases#List_inside_a_comment. this.indentationChars = this.target.inCode.originalIndentationChars; break; case 'replyInSection': this.indentationChars = ( this.target.inCode.lastCommentIndentationChars && ( this.target.inCode.lastCommentIndentationChars[0] === '#' || cd.config.indentationCharMode === 'mimic' ) ) ? this.target.inCode.lastCommentIndentationChars[0] : cd.config.defaultIndentationChar; break; default: this.indentationChars = ''; } /** * Is the comment indented. * * @type {boolean} */ this.isIndented = Boolean( ['reply', 'replyInSection'].includes(this.commentForm.mode) || (this.commentForm.mode === 'edit' && this.indentationChars) ); if (this.isIndented) { // In the preview mode, imitate a list so that the user will see where it would break on a // real page. This pseudolist's margin is made invisible by CSS. this.restLinesIndentationChars = this.action === 'preview' ? ':' : this.indentationChars.replace(/\*/g, ':'); } } /** * The main method that actually processes the code. * * @param {string} code * @returns {string} */ parse(code) { this.initialCode = this.code = code.trim(); this.processAndHideSensitiveCode(); this.findWrappers(); this.setSignature(); this.processAllCode(); this.addHeadline(); this.addSignature(); this.addTrailingNewline(); this.addIntentationChars(); this.unhideSensitiveCode(); return this.code; } /** * Process (with {@link CommentTextParser#processCode}) and hide sensitive code, setting the * `hidden` property and updating `code`. * * @private */ processAndHideSensitiveCode() { const templateHandler = (code) => this.processCode(code, true); Object.assign(this, hideSensitiveCode(this.code, templateHandler)); } /** * Find tags in the code and do something about them. * * @private */ findWrappers() { // Find tags around potential markup. if (this.isIndented) { const tagMatches = this.code.match(generateTagsRegexp(['[a-z]+'])) || []; const quoteMatches = this.code.match(cd.g.QUOTE_REGEXP) || []; const matches = tagMatches.concat(quoteMatches); this.areThereTagsAroundListMarkup = matches.some((match) => /\n[:*#;]/.test(match)); } // If the user wrapped the comment in <small></small>, remove the tags to later wrap the // comment together with the signature into the tags and possibly ensure the correct line // spacing. this.wrapInSmall = false; if (!this.commentForm.headlineInput) { this.code = this.code.replace(/^<small>([^]*)<\/small>$/i, (s, content) => { this.wrapInSmall = true; return content; }); } } /** * Set the `signature` property. Also fix the code according to it. * * @private */ setSignature() { if (this.commentForm.omitSignatureCheckbox?.isSelected()) { this.signature = ''; } else { this.signature = this.commentForm.mode === 'edit' ? this.target.inCode.signatureCode : cd.g.USER_SIGNATURE; } // Make so that the signature doesn't turn out to be at the end of the last item of the list if // the comment contains one. if ( this.signature && // The existing signature doesn't start with a newline. (this.commentForm.mode !== 'edit' || !/^[ \t]*\n/.test(this.signature)) && /(^|\n)[:*#;].*$/.test(this.code) ) { this.code += '\n'; } } /** * Replace list markup (`:*#;`) with respective tags. * * @param {string} code * @returns {string} * @private */ listMarkupToTags(code) { const replaceLineWithList = (lines, i, list, isNested = false) => { if (isNested) { const previousItemIndex = i - list.items.length - 1; if (previousItemIndex >= 0) { const item = { type: lines[previousItemIndex].type, items: [lines[previousItemIndex], list], }; lines.splice(previousItemIndex, list.items.length + 1, item); } else { const item = { type: lines[0].type, items: [list], }; lines.splice(i - list.items.length, list.items.length, item); } } else { lines.splice(i - list.items.length, list.items.length, list); } parseLines(list.items, true); }; const parseLines = (lines, isNested = false) => { let list = { items: [] }; for (let i = 0; i <= lines.length; i++) { if (i === lines.length) { if (list.type) { replaceLineWithList(lines, i, list, isNested); } } else { const text = lines[i].text; const firstChar = text[0] || ''; const listType = listTags[firstChar]; if (list.type && listType !== list.type) { const itemsCount = list.items.length; replaceLineWithList(lines, i, list, isNested); i -= itemsCount - 1; list = { items: [] }; } if (listType) { list.type = listType; list.items.push({ type: itemTags[firstChar], text: text.slice(1), }); } } } return lines; }; const listToTags = (lines, isNested = false) => { let text = ''; lines.forEach((line, i) => { if (line.text === undefined) { const itemsText = line.items .map((item) => { const itemText = item.text === undefined ? listToTags(item.items, true) : item.text.trim(); return item.type ? `<${item.type}>${itemText}</${item.type}>` : itemText; }) .join(''); text += `<${line.type}>${itemsText}</${line.type}>`; } else { text += isNested ? line.text.trim() : line.text; } if (i !== lines.length - 1) { text += '\n'; } }); return text; }; const listTags = { ':': 'dl', ';': 'dl', '*': 'ul', '#': 'ol', }; const itemTags = { ':': 'dd', ';': 'dt', '*': 'li', '#': 'li', }; let lines = code .split('\n') .map((line) => ({ type: '', text: line, })); parseLines(lines); return listToTags(lines); } /** * Add indentation chars to the start of the line. * * @param {string} indentationChars * @param {string} line * @param {boolean} [addLine=true] Add the line itself. * @returns {string} * @private */ prepareLineStart(indentationChars, line, addLine = true) { const addSpace = ( indentationChars && cd.config.spaceAfterIndentationChars && !/^[:*#;]/.test(line) ); return indentationChars + (addSpace ? ' ' : '') + (addLine ? line : ''); } /** * Perform operations with code in an indented comment. * * @param {string} code * @param {boolean} isWrapped Is the code wrapped. * @returns {string} * @private */ handleIndentedComment(code, isWrapped) { if (!this.isIndented) { return code; } // Remove spaces at the beginning of lines. code = code.replace(/^ +/gm, ''); // Remove paragraphs if the wiki has no paragraph template. if (!cd.config.paragraphTemplates.length) { code = code.replace(/\n\n+/g, '\n'); } // Replace list markup (`:*#;`) with respective tags if otherwise layout will be broken. if (/^[:*#;]/m.test(code) && (isWrapped || this.restLinesIndentationChars === '#')) { code = this.listMarkupToTags(code); } // Add indentation characters to lines with the list and table markup as well as lines wholly // occupied by the file markup. File markup is tricky because, depending on the alignment and // line breaks, the result can be very different. The safest way to fight that is to use // indentation. const lineStartMarkupRegexp = new RegExp(`(\\n+)([:*#;\\x03]|${this.filePatternEnd})`, 'gmi'); code = code.replace(lineStartMarkupRegexp, (s, newlines, nextLine) => { // Many newlines will be replaced with a paragraph template below. It could help visual // formatting. If there is no paragraph template, there won't be multiple newlines, as they // will have been removed above. const newlinesToAdd = newlines.length > 1 ? '\n\n\n' : '\n'; const line = this.prepareLineStart(this.restLinesIndentationChars, nextLine); return newlinesToAdd + line; }); // Add newlines before and after gallery (yes, even if the comment starts with it). code = code .replace(/(^|[^\n])(\x01\d+_gallery\x02)/g, (s, before, m) => before + '\n' + m) .replace(/\x01\d+_gallery\x02(?=(?:$|[^\n]))/g, (s) => s + '\n'); // Table markup is OK only with colons as indentation characters. if (this.restLinesIndentationChars.includes('#') && code.includes('\x03')) { throw new CdError({ type: 'parse', code: 'numberedList-table', }); } if (this.restLinesIndentationChars === '#') { if (this.galleryRegexp.test(code)) { throw new CdError({ type: 'parse', code: 'numberedList', }); } } // Add indentation characters to lines following the lines with the list, table, and gallery // markup. const followingLinesRegexp = /^((?:[:*#;\x03].+|\x01\d+_gallery\x02))(\n+)(?![:#])/mg; code = code.replace(followingLinesRegexp, (s, previousLine, newlines) => { // Many newlines will be replaced with a paragraph template below. If there is no // paragraph template, there wouldn't be multiple newlines, as they would've been removed // above. const newlinesToAdd = newlines.length > 1 ? '\n\n' : ''; return ( previousLine + '\n' + this.prepareLineStart(this.restLinesIndentationChars, newlinesToAdd) ); }); const paragraphCode = cd.config.paragraphTemplates.length ? `$1{{${cd.config.paragraphTemplates[0]}}}` : `$1<br>`; code = code.replace(/^(.*)\n\n+(?!:)/gm, paragraphCode); return code; } /** * Process newlines by adding or not adding `<br>` and keeping or not keeping the newline. `\x01` * and `\x02` mean the beginning and ending of sensitive code except for tables. `\x03` and `\x04` * mean the beginning and ending of a table. Note: This should be kept coordinated with the * reverse transformation code in {@link Comment#codeToText}. * * @param {string} code * @param {boolean} isInTemplate * @returns {string} code */ processNewlines(code, isInTemplate = false) { const entireLineRegexp = new RegExp(/^(?:\x01\d+_(block|template)\x02) *$/); const entireLineFromStartRegexp = /^(=+).*\1[ \t]*$|^----/; const fileRegexp = new RegExp('^' + this.filePatternEnd, 'i'); let currentLineInTemplates = ''; let nextLineInTemplates = ''; if (isInTemplate) { currentLineInTemplates = '|='; nextLineInTemplates = '|\\||}}'; } const currentLineEndingRegexp = new RegExp( `(?:<${cd.g.PNIE_PATTERN}(?: [\\w ]+?=[^<>]+?| ?\\/?)>|<\\/${cd.g.PNIE_PATTERN}>|\\x04|<br[ \\n]*\\/?>${currentLineInTemplates}) *$`, 'i' ); const nextLineBeginningRegexp = new RegExp( `^(?:<\\/${cd.g.PNIE_PATTERN}>|<${cd.g.PNIE_PATTERN}${nextLineInTemplates})`, 'i' ); const newlinesRegexp = this.isIndented ? /^(.+)\n(?![:#])(?=(.*))/gm : /^((?![:*#; ]).+)\n(?![\n:*#; \x03])(?=(.*))/gm; code = code.replace(newlinesRegexp, (s, currentLine, nextLine) => { const lineBreakOrNot = ( entireLineRegexp.test(currentLine) || entireLineRegexp.test(nextLine) || ( !this.isIndented && (entireLineFromStartRegexp.test(currentLine) || entireLineFromStartRegexp.test(nextLine)) ) || fileRegexp.test(currentLine) || fileRegexp.test(nextLine) || this.galleryRegexp.test(currentLine) || this.galleryRegexp.test(nextLine) || // Removing <br>s after block elements is not a perfect solution as there would be no // newlines when editing such a comment, but this way we would avoid empty lines in cases // like "</div><br>". currentLineEndingRegexp.test(currentLine) || nextLineBeginningRegexp.test(nextLine) ) ? '' : '<br>'; // Current line can match galleryRegexp only if the comment will not be indented. const newlineOrNot = this.isIndented && !this.galleryRegexp.test(nextLine) ? '' : '\n'; return currentLine + lineBreakOrNot + newlineOrNot; }); return code; } /** * Make the core code transformations. * * @param {string} code * @param {boolean} isInTemplate Is the code in a template. * @returns {string} * @private */ processCode(code, isInTemplate) { code = this.handleIndentedComment(code, isInTemplate || this.areThereTagsAroundListMarkup); code = this.processNewlines(code, isInTemplate); return code; } /** * Make the core code transformations with all code. * * @private */ processAllCode() { this.code = this.processCode(this.code); } /** * Add the headline to the code. * * @private */ addHeadline() { const headline = this.commentForm.headlineInput?.getValue().trim(); if ( !headline || ( this.commentForm.mode === 'addSection' && this.commentForm.submitSection && this.action === 'submit' ) ) { return; } let level; if (this.commentForm.mode === 'addSection') { level = 2; } else if (this.commentForm.mode === 'addSubsection') { level = this.target.level + 1; } else { // 'edit' level = this.target.inCode.headingLevel; } const equalSigns = '='.repeat(level); if ( this.commentForm.mode === 'addSection' || // To have pretty diffs. (this.commentForm.isSectionOpeningCommentEdited && /^\n/.test(this.target.inCode.code)) ) { this.code = '\n' + this.code; } this.code = `${equalSigns} ${headline} ${equalSigns}\n${this.code}`; } /** * Add the signature to the code. * * @private */ addSignature() { if (!this.commentForm.omitSignatureCheckbox?.isSelected()) { // Remove signature tildes from the end of the comment. this.code = this.code.replace(/\s*~{3,}$/, ''); } if (this.action === 'preview' && this.signature) { this.signature = `<span class="cd-commentForm-signature">${this.signature}</span>`; } // A space in the beggining of the last line, creating <pre>, or a heading. if (!this.isIndented && /(^|\n)[ =].*$/.test(this.code)) { this.code += '\n'; } // Remove starting spaces if the line starts with the signature. if (!this.code || this.code.endsWith('\n') || this.code.endsWith(' ')) { this.signature = this.signature.trimLeft(); } // Process the small font wrappers, add the signature. if (this.wrapInSmall) { let before; if (/^[:*#; ]/.test(this.code)) { before = '\n' + (this.isIndented ? this.restLinesIndentationChars : ''); } else { before = ''; } if (cd.config.smallDivTemplates.length && !/^[:*#;]/m.test(this.code)) { // Hide links that have "|", then replace "|" with "{{!}}", then wrap in a small div // template. const hiddenLinks = []; this.code = hideText(this.code.trim(), /\[\[[^\]|]+\|/g, hiddenLinks, 'link'); this.code = this.code.replace(/\|/g, '{{!}}') + this.signature; this.code = unhideText(this.code, hiddenLinks, 'link'); this.code = `{{${cd.config.smallDivTemplates[0]}|1=${this.code}}}`; } else { this.code = `<small>${before}${this.code}${this.signature}</small>`; } } else { this.code += this.signature; } } /** * Add a newline to the code. * * @private */ addTrailingNewline() { if (this.commentForm.mode !== 'edit') { this.code += '\n'; } } /** * Add the indentation characters to the code. * * @private */ addIntentationChars() { // If the comment starts with a list or table, replace all asterisks in the indentation // characters with colons to have the comment HTML generated correctly. if (this.isIndented && this.action !== 'preview' && /^[*#;\x03]/.test(this.code)) { this.indentationChars = this.restLinesIndentationChars; } if (this.action !== 'preview') { this.code = this.prepareLineStart(this.indentationChars, this.code); if (this.mode === 'addSubsection') { this.code += '\n'; } } else if (this.action === 'preview' && this.isIndented && this.initialCode) { this.code = this.prepareLineStart(':', this.code); } } /** * Restore the hidden sensitive code. * * @private */ unhideSensitiveCode() { this.code = unhideText(this.code, this.hidden); } }
JavaScript
class Doorman extends Fabric { /** * Construct a Doorman. * @param {Object} [config] Configuration. * @param {Object} [config.path] Local path for {@link Store}. * @param {Array} [config.services] List of services to enable. * @param {String} [config.trigger] Prefix to use as a trigger. */ constructor (config) { super(config); this.config = merge({ path: './stores/doorman', services: [ 'local', 'fabric' ], trigger: '!' }, config); this.triggers = {}; this.router = new Router({ trigger: this.config.trigger }); this.router.trust(this); return this; } static Service (name) { let disk = new Disk(); let path = `services/${name}`; let fallback = `node_modules/@fabric/doorman/${path}.js`; let plugin = null; // load from local `services` path, else fall back to Doorman if (disk.exists(path + '.js') || disk.exists(path)) { plugin = disk.get(path); } else if (disk.exists(fallback)) { plugin = disk.get(fallback); } else if (Fabric.registry[name]) { plugin = Fabric.registry[name]; } else { plugin = Fabric.Service; } return plugin; } /** * Look for triggers in a message. * @param {Message} msg Message to evaluate. */ async parse (msg) { let answers = await this.router.route(msg); let message = null; if (answers && answers.length) { switch (answers.length) { case 1: message = answers[0]; break; default: message = answers.join('\n\n'); break; } } else { console.warn('[DOORMAN:CORE]', '[PARSER]', `Input message ${msg} did not get routed to any services:`, msg); } return message || null; } async _loadServices () { const self = this; for (let i in self.config.services) { try { let name = self.config.services[i].toLowerCase(); let service = self.constructor.Service(name); // Register and enable if we have service if (service) { await self.register(service); await self.enable(name); } } catch (exception) { console.error('[DOORMAN:CORE]', exception); } } return this; } /** * Activates a Doorman instance. * @return {Doorman} Chainable method. */ async start () { let self = this; await this._loadServices(); // identify ourselves to the network await this.identify(); if (self.config.plugins && Array.isArray(self.config.plugins)) { for (let name in self.config.plugins) { self.use(self.config.plugins[name]); } } if (self.config.triggers) { Object.keys(self.config.triggers).forEach(name => { let route = { name: self.config.trigger + name, value: self.config.triggers[name] }; self.router.use(route); }); } self._defineTrigger({ name: 'help', value: `Available triggers: ${Object.keys(self.triggers).map(x => '`' + self.config.trigger + x + '`').join(', ')}` }); if (self.config.debug) { this.log('[DEBUG]', 'triggers:', Object.keys(self.triggers)); } this.log('started!'); return this; } /** * Halt a Doorman instance. * @return {Doorman} Chainable method. */ async stop () { let self = this; self.log('Stopping...'); if (self.plugins) { for (let name in self.plugins) { await self.plugins[name].stop(); } } await super.stop(); self.log('Stopped!'); return self; } /** * Configure Doorman to use a Plugin. * @param {Mixed} plugin Can be of type Map (trigger name => behavior) or Plugin (constructor function). * @return {Doorman} Chainable method. */ use (plugin) { let self = this; let name = null; let Handler = null; if (typeof plugin === 'string') { Handler = Plugin.fromName(plugin); name = plugin; } else if (plugin instanceof Function) { Handler = plugin; name = Handler.name.toLowerCase(); } else { Handler = plugin; } self.log(`enabling plugin "${name}"...`, Handler); if (!Handler) return false; if (Handler instanceof Function) { util.inherits(Handler, Plugin); let handler = new Handler(self.config[name]); handler.on('whisper', function (whisper) { let parts = whisper.target.split('/'); self.services[parts[0]].whisper(parts[2], whisper.message); }); handler.on('message', function (message) { self.log(`[PLUGIN:${name.toUpperCase()}]`, 'sent (unhandled) message:', message); let parts = message.target.split('/'); self.services[parts[0]].send(parts[2], message.object); }); self.plugins[name] = handler; self.plugins[name].trust(self).start(); if (self.plugins[name].triggers) { console.log(`plugin "${name}" has triggers:`, self.plugins[name].triggers); Object.keys(self.plugins[name].triggers).forEach(trigger => { self._defineTrigger(Object.assign({ plugin: name }, self.plugins[name].triggers[trigger])); }); } } else { Object.keys(Handler).forEach(name => { let value = Handler[name]; self._defineTrigger({ name, value }); }); } return this; } /** * Register a Trigger. * @param {Trigger} handler Trigger to handle. * @return {Doorman} Instance of Doorman configured to handle Trigger. */ _defineTrigger (handler) { if (!handler.name) return false; if (!handler.value) return false; this.triggers[handler.name] = handler.value; this.router.use(handler); this.emit('trigger', handler); return this; } _joinRoom (channel) { for (let id in this.services) { let result = this.services[id].join(channel); this.log(`service ${id} join: ${result}`); } } }
JavaScript
class App extends React.Component{ constructor(){ super() this.state = { country : null, category:null, query:null, data: [] } this.callBack = this.callBack.bind(this) this.fetchData = this.fetchData.bind(this); } async fetchData(){ var cou = this.state.country; var cat = this.state.category; var q = this.state.query; // console.log(this.state); var data = await Axios.post('http://192.168.1.81:8080/', {country : cou,category: cat,query:q}) var res = await data.data this.setState({data:res},()=>{ console.log(this.state.data) }) } callBack = (category , query) => { // console.log("category: "+category +" query: " + query); this.setState({category:category , query:query}, ()=>{ this.fetchData() }) } componentDidMount(){ this.fetchData(); } render(){ return( <div className='wrapper'> <NavbarComponent parentCallback={this.callBack} fromParent={this.state}></NavbarComponent> <div className='wrapperCardList'> <CardComponent renderList={this.state.data}></CardComponent> </div> <Footer></Footer> </div> ) } }
JavaScript
class Item { getPricePerItem(...args) { return this.price; } getPrice(...args) { return this.getPricePerItem(...args); } }
JavaScript
class ItemLine { getPricePerItem(...args) { return this.price; } getQuantity() { return 1; } getTotal(...args) { return mul(this.getPricePerItem(...args), this.getQuantity()); } }
JavaScript
class ItemRange extends Array { getPricePerItem(item, ...args) { return item.getPrice(...args); } getPriceRange(...args) { let prices = this.map(item => this.getPricePerItem(item)); if (!prices) throw "Cannot call getPriceRange() on an empty ItemRange"; return [min(...prices), max(...prices)]; } }
JavaScript
class ItemSet extends Array { getTotal(...args) { let subTotals = this.map(item => { return item.getTotal(...args); }); if (!subTotals) throw "Cannot call getTotal() on an empty ItemSet"; return sum(...subTotals); } }
JavaScript
class ExcludeMiniCssModulePlugin { apply(compiler) { let CssDependency; pluginCompat.tap( compiler, 'make', 'SupportMiniCssExtractPlugin', ({ dependencyFactories }) => { const Dependencies = dependencyFactories.keys(); for (const Dep of Dependencies) { if (Dep.name === 'CssDependency') { CssDependency = Dep; break; } } }, ); pluginCompat.tap( compiler, '_hardSourceAfterFreezeModule', 'HardMiniCssExtractPlugin', (frozen, module, extra) => { if ( CssDependency && module.dependencies.some(dep => dep instanceof CssDependency) ) { return null; } return frozen; }, ); } }
JavaScript
class FramelixFormField { /** * Eventname when a fields value has changed * This can happen multiple times during input * Doesn't matter if done by a user or a script * @type {string} */ static EVENT_CHANGE = 'framelix-form-field-change' /** * Eventname when a fields value has changed by a user action * @type {string} */ static EVENT_CHANGE_USER = 'framelix-form-field-change-user' /** * Hide the field completely * Does layout jumps but hidden fields take no space * @type {string} */ static VISIBILITY_HIDDEN = 'hidden' /** * Hide the field almost transparent * Prevent a lot of layout jumps but hidden fields will take the space * @type {string} */ static VISIBILITY_TRANSPARENT = 'transparent' /** * Class references for class name to reference * @type {{}} */ static classReferences = {} /** * All field instances * @type {FramelixFormField[]} */ static instances = [] /** * The whole field container * @type {Cash} */ container /** * The container where the actual field is in * @type {Cash} */ field /** * The form the field is attached to * @type {FramelixForm|null} */ form = null /** * Name of the field * @type {string} */ name /** * Label * @type {string|null} */ label = null /** * Label description * @type {string|null} */ labelDescription = null /** * Minimal width in pixel or other unit * Number is considered pixel, string is passed as is * @type {number|string|null} */ minWidth = null /** * Maximal width in pixel or other unit * Number is considered pixel, string is passed as is * @type {number|string|null} */ maxWidth = null /** * The default value for this field * @type {*} */ defaultValue = null /** * Is the field disabled * @type {boolean} */ disabled = false /** * Is the field required * @type {boolean} */ required = false /** * The current shown validation message * @type {string|null} */ validationMessage = null /** * The instance of the current validation popup message * @type {FramelixPopup|null} */ validationPopup = null /** * A condition to define when this field is visible * Hidden fields will not be validated * At the moment this cannot only be defined in the backend * @type {Object|null} */ visibilityCondition = null /** * Define how hidden fields should be hidden * @type {string} */ visibilityConditionHideMethod = FramelixFormField.VISIBILITY_TRANSPARENT /** * A promise that is resolved when the field is completely rendered * @type {Promise} */ rendered /** * The resolve function to resolve the rendered promise * @type {function} * @private */ _renderedResolve /** * Create a field from php data * @param {Object} phpData * @return {FramelixFormField} */ static createFromPhpData (phpData) { let fieldClass = phpData.class fieldClass = fieldClass.substr(9).replace(/\\/g, '') const instance = new this.classReferences[fieldClass]() for (let key in phpData.properties) { instance[key] = phpData.properties[key] } return instance } /** * Get field by name in given container * @param {Cash|FramelixForm|HTMLElement|string} container * @param {string|null} name Null if you want to find the first field in the container * @return {FramelixFormField|null} */ static getFieldByName (container, name) { const fields = $(container instanceof FramelixForm ? container.container : container).find('.framelix-form-field') if (!fields.length) return null let field if (!name) { field = fields.first() } else { field = fields.filter('[data-name=\'' + name + '\']') } if (!field.length) return null return FramelixFormField.instances[field.attr('data-instance-id')] || null } /** * Callback doc * @callback FramelixFormField~onValueChange * @param {FramelixFormField} field */ /** * Quick bind an action on form change * @param {FramelixForm|string|Cash} container * @param {FramelixFormField|FramelixFormField[]|string|string[]} fields * @param {boolean} onUserChangeOnly If true, fires only when an user changed a value, not by a script change * @param {FramelixFormField~onValueChange} callback */ static onValueChange (container, fields, onUserChangeOnly, callback) { if (!fields) return if (!Array.isArray(fields)) fields = [fields] $(document).on(this.EVENT_CHANGE_USER, function (ev) { let el = container if (!el) el = $('body') if (typeof el === 'string') el = FramelixForm.getById(el).container for (let i in fields) { let field = fields[i] if (typeof field === 'string') { field = FramelixFormField.getFieldByName(el, field) } const fieldName = $(ev.target).closest('.framelix-form-field').attr('data-name') if (fieldName === field.name) callback(field) } }) } /** * Constructor */ constructor () { const self = this this.rendered = new Promise(function (resolve) { self._renderedResolve = resolve }) FramelixFormField.instances.push(this) this.container = $(`<div class="framelix-form-field"> <div class="framelix-form-field-label"></div> <div class="framelix-form-field-label-description"></div> <div class="framelix-form-field-container"></div> </div>`) this.container.attr('data-instance-id', FramelixFormField.instances.length - 1) let classes = [] let parent = Object.getPrototypeOf(this) while (parent && parent.constructor.name !== 'FramelixFormField') { classes.push('framelix-form-field-' + parent.constructor.name.substr(17).toLowerCase()) parent = Object.getPrototypeOf(parent) if (classes.length > 10) break } this.container.addClass(classes.join(' ')) this.field = this.container.find('.framelix-form-field-container') } /** * Convert any value into a string * @param {*} value * @return {string} */ stringifyValue (value) { if (value === null || value === undefined) { return '' } if (typeof value === 'boolean') { return value ? '1' : '0' } if (typeof value !== 'string') { return value.toString() } return value } /** * Set value for this field * @param {*} value * @param {boolean} isUserChange Indicates if this change was done because of an user input */ setValue (value, isUserChange = false) { console.error('setValue need to be implemented in ' + this.constructor.name) } /** * Get value for this field * @return {*} */ getValue () { console.error('getValue need to be implemented in ' + this.constructor.name) } /** * Trigger change on given element * @param {Cash} el * @param {boolean} isUserChange Indicates if this change was done because of an user input */ triggerChange (el, isUserChange = false) { el.trigger(FramelixFormField.EVENT_CHANGE) if (isUserChange) { el.trigger(FramelixFormField.EVENT_CHANGE_USER) } } /** * Validate * Return error message on error or true on success * @return {Promise<string|true>} */ async validate () { if (!this.isVisible()) return true if (this.required && !(this instanceof FramelixFormFieldHtml) && !(this instanceof FramelixFormFieldHidden)) { const value = this.getValue() if (value === null || value === undefined || (typeof value === 'string' && !value.length) || (typeof value === 'object' && !FramelixObjectUtils.hasKeys(value))) { return FramelixLang.get('__framelix_form_validation_required__') } } return true } /** * Show validation message * Does append message if already visible * @param {string} message */ showValidationMessage (message) { this.container.toggleClass('framelix-form-field-group-hidden', false) if (!this.isVisible()) { this.form.showValidationMessage(message) return } message = FramelixLang.get(message) this.validationMessage = message let container = null this.container.find('[tabindex],input,select,textarea').each(function () { if (FramelixDom.isVisible(this)) { container = this return false } }) if (!container) container = this.field container = $(container) if (this.validationPopup && FramelixDom.isInDom(this.validationPopup.content)) { this.validationPopup.content.append($(`<div>`).append(message)) } else { this.validationPopup = FramelixPopup.show(container, message, { closeMethods: 'click', color: 'error', placement: 'bottom-start', group: 'field-validation', stickInViewport: true }) } } /** * Hide validation message */ hideValidationMessage () { this.validationMessage = null this.validationPopup?.destroy() } /** * Set visibility condition hidden status * @param {boolean} flag True is visible */ setVisibilityConditionHiddenStatus (flag) { this.container.toggleClass('framelix-form-field-hidden', !flag) if (!flag) { this.container.attr('data-visibility-hidden-method', this.visibilityConditionHideMethod) } if (this.visibilityConditionHideMethod === FramelixFormField.VISIBILITY_TRANSPARENT) { this.container.find('[tabindex],input,select,textarea').each(function () { if (!flag && this.getAttribute('tabindex') !== null && this.getAttribute('data-tabindex-original') === null) { this.setAttribute('data-tabindex-original', this.getAttribute('tabindex')) } if (!flag) { this.setAttribute('tabindex', '-1') } else { this.setAttribute('tabindex', this.getAttribute('data-tabindex-original')) } }) } } /** * Is this field visible in dom * @return {boolean} */ isVisible () { return !this.container.hasClass('framelix-form-field-hidden') } /** * Render the field into the container * @return {Promise<void>} Resolved when field is fully functional * @protected */ async renderInternal () { const self = this this.container.attr('data-name', this.name) this.field.css('minWidth', this.minWidth !== null ? typeof this.minWidth === 'number' ? this.minWidth + 'px' : this.minWidth : '') this.field.css('maxWidth', this.maxWidth !== null ? typeof this.maxWidth === 'number' ? this.maxWidth + 'px' : this.maxWidth : '') this.container.attr('data-disabled', this.disabled ? 1 : 0) let requiredInfoDisplayed = false const labelEl = this.container.find('.framelix-form-field-label') if (this.label !== null) { requiredInfoDisplayed = true labelEl.html(FramelixLang.get(this.label)) if (this.required) { labelEl.append(`<span class="framelix-form-field-label-required" title="__framelix_form_validation_required__"></span>`) } } else { labelEl.remove() } const labelDescEl = this.container.find('.framelix-form-field-label-description') if (this.labelDescription !== null) { labelDescEl.html(FramelixLang.get(this.labelDescription)) if (!requiredInfoDisplayed && this.required) { labelDescEl.append(`<span class="framelix-form-field-label-required" title="__framelix_form_validation_required__"></span>`) } } else { labelDescEl.remove() } this.field.on('focusin change', function () { self.hideValidationMessage() }) } /** * Render the field into the container * @return {Promise<void>} Resolved when field is fully functional */ async render () { await this.renderInternal() if (this.validationMessage !== null) this.showValidationMessage(this.validationMessage) if (this._renderedResolve) { this._renderedResolve() this._renderedResolve = null } } }
JavaScript
class Property { /** * Constructs a new <code>Property</code>. * PropertyPayload describes a property of a thing. No field is mandatory * @alias module:model/Property * @param name {String} The friendly name of the property * @param permission {module:model/Property.PermissionEnum} The permission of the property * @param type {module:model/Property.TypeEnum} The type of the property * @param updateStrategy {module:model/Property.UpdateStrategyEnum} The update strategy for the property value */ constructor(name, permission, type, updateStrategy) { Property.initialize(this, name, permission, type, updateStrategy); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, name, permission, type, updateStrategy) { obj['name'] = name; obj['permission'] = permission; obj['type'] = type; obj['update_strategy'] = updateStrategy; } /** * Constructs a <code>Property</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/Property} obj Optional instance to populate. * @return {module:model/Property} The populated <code>Property</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Property(); if (data.hasOwnProperty('max_value')) { obj['max_value'] = ApiClient.convertToType(data['max_value'], 'Number'); } if (data.hasOwnProperty('min_value')) { obj['min_value'] = ApiClient.convertToType(data['min_value'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('permission')) { obj['permission'] = ApiClient.convertToType(data['permission'], 'String'); } if (data.hasOwnProperty('persist')) { obj['persist'] = ApiClient.convertToType(data['persist'], 'Boolean'); } if (data.hasOwnProperty('tag')) { obj['tag'] = ApiClient.convertToType(data['tag'], 'Number'); } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('update_parameter')) { obj['update_parameter'] = ApiClient.convertToType(data['update_parameter'], 'Number'); } if (data.hasOwnProperty('update_strategy')) { obj['update_strategy'] = ApiClient.convertToType(data['update_strategy'], 'String'); } if (data.hasOwnProperty('variable_name')) { obj['variable_name'] = ApiClient.convertToType(data['variable_name'], 'String'); } } return obj; } }
JavaScript
class Datasets { constructor(baseUrl) { this.baseUrl = baseUrl; } /** * @description GET dataset by given id. * @param id * @return {Promise} */ getSingle(id) { return new Promise((resolve, reject) => { // 1. Prepare the response data to match the following datamodels /** * @property dataset * @type JSON * @description A dataset object. * @example dataset = { * categories: [{ id: 'energy', title: 'energy' }, ..], * description: 'This is dataset1', * distributions: [{}], * distributionFormats: ['csv', 'pdf'], * id: 'abc123qwe345', * idName: 'dataset-1', * language: 'EN', * licence: 'ABC Licence', * modificationDate: '2002-02-02T00:00', * publisher: 'Publisher1', * releaseDate: '2001-01-01T00:00', * tags: ['tag1', 'tag2'], * title: 'dataset1', * } */ /** * @property distributions * @type Array * @description Distributions of a dataset * @example distributions: [{ * accessUrl: 'http://demo-url-to-this-resource.org/someID-123-xyz/blabla', * downloadUrl: 'http://demo-url-to-this-resource.org/someID-123-xyz/filename.csv', * description: 'A description of this distribution', * format: 'csv', * id: 'someID-123-xyz', * licence: 'ABC Licence', * modificationDate: 2017-05-31T18:33:48.018695, * releaseDate: 2017-05-31T18:33:48.018695, * title: 'someTitle', * urlType: 'download', * },{..}] */ // 2. resolve the promise with the prepared data matching the datamodels }); } /** * @description GET all datasets matching the given criteria. * @param query {String} - The given query string * @param facets {Array} - The active facets * @param limit {Number} - The maximum amount of datasets to fetch * @param offset {Number} - The number of datasets to skip * @returns {Promise} */ get(query, facets, limit, offset) { return new Promise((resolve, reject) => { // 1. Prepare the response data to match the following datamodels /** * @property datasets * @type Array<JSON> * @description An array of datasets. * @example datasets = [{ * categories: [{ id: 'energy', title: 'energy' }, ..], * description: 'This is dataset1', * distributions: [{}], * distributionFormats: ['csv', 'pdf'], * id: 'abc123qwe345', * idName: 'dataset-1', * language: 'EN', * licence: 'ABC Licence', * modificationDate: '2002-02-02T00:00', * publisher: 'Publisher1', * releaseDate: '2001-01-01T00:00', * tags: ['tag1', 'tag2'], * title: 'dataset1', * }, {..}] */ /** * @property distributions * @type Array * @description Distributions of a dataset * @example distributions: [{ * accessUrl: 'http://demo-url-to-this-resource.org/someID-123-xyz/blabla', * downloadUrl: 'http://demo-url-to-this-resource.org/someID-123-xyz/filename.csv', * description: 'A description of this distribution', * format: 'csv', * id: 'someID-123-xyz', * licence: 'ABC Licence', * modificationDate: 2017-05-31T18:33:48.018695, * releaseDate: 2017-05-31T18:33:48.018695, * title: 'someTitle', * urlType: 'download', * },{..}] */ // 2. resolve the promise with the prepared data matching the datamodels }); } }
JavaScript
class Meetup extends Model { /** * constructor * @param {string} table - name of database table */ constructor( table = 'meetups' ) { super(table); } /** * Get the meetups scheduled by a specified user * @param {Number} userId - the id of the user who made scheduled * @returns {Array} - array of meetups scheduled by the user */ async listScheduledMeetups(userId) { const queryText = `SELECT * FROM rsvps WHERE rsvps.user = ${userId}`; const { rows } = await connection.query(queryText); const promisedMeetups = rows.map(response => this.getOne(response.meetupId)); const meetups = await Promise.all(promisedMeetups); return meetups; } /** * Get all upcoming meetups * @returns {Array} - array of all upcoming meetups */ async listUpcoming() { const allResources = await this.getAll(); const currentTimestamp = Date.now(); const upcoming = []; allResources.forEach((resource) => { const timestamp = new Date(resource.happeningOn); if (currentTimestamp < timestamp.getTime()) { upcoming.push(resource); } }); return upcoming; } /** * Attach tags associated with a meetup * @param {Array} meetups - and array of meetups * @returns {Array} - and array of meetups with the tags attached */ async attachTags(meetups) { const tagsQuery = await connection.query('SELECT * FROM tags'); const actualTags = tagsQuery.rows; meetups.forEach((meetup) => { const { tags } = meetup; const tagResult = []; if (tags !== null) { tags.forEach((tagId) => { const singleTag = actualTags.find(tag => tag.id === Number(tagId)); if (singleTag !== undefined) { tagResult.push(singleTag); } }); } meetup.tags = tagResult; }); return meetups; } /** * Attach author object to meetup * @param {Array} meetups - Array of meetups * @returns {Array} - Array of meetups incuding their author object */ async attachAuthor(meetups) { const records = meetups.map(async (meetup) => { const { rows } = await connection.query(`SELECT * FROM users WHERE users.id = ${meetup.createdBy}`); // eslint-disable-next-line prefer-destructuring meetup.author = rows[0]; return meetup; }); const meetupsList = await Promise.all(records); return meetupsList; } /** * Respond to a meetup invitation * @param {Array} data - an array of the properties * @returns {Object} - created resource */ async replyInvite(data) { const text = `INSERT INTO rsvps("meetupId", "user", "response") VALUES ($1, $2, $3) returning *`; const values = [ Number(data.meetupId), Number(data.user), data.response, ]; try { const { rows } = await connection.query(text, values); return rows[0]; } catch (err) { throw err; } } /** * Add tags to a meetup * @param {Number} id - the id of the specified meetup * @param {Array} tags - an array of tags * @returns {Object} - updated resource */ async addTags(id, tags) { const meetup = await this.getOne(id); if (!meetup) throw new Error('Required meetup does not exist'); const queryText = `UPDATE meetups SET tags = '{ ${tags} }' WHERE id = ${meetup.id} returning *`; try { const { rows } = await connection.query(queryText); return rows[0]; } catch (err) { throw err; } } }
JavaScript
class ApplicationChooserDialog extends DialogWindow { /** * @param {Object} args An object with arguments * @param {String} args.title Dialog title * @param {String} args.message Dialog message * @param {FileMetadata} args.file The file to open * @param {CallbackDialog} callback Callback when done */ constructor(args, callback) { args = Object.assign({}, {}, args); super('ApplicationChooserDialog', { title: args.title || _('DIALOG_APPCHOOSER_TITLE'), width: 400, height: 400 }, args, callback); } init() { const root = super.init(...arguments); const cols = [{label: _('LBL_NAME')}]; const rows = []; const metadata = PackageManager.getPackages(); (this.args.list || []).forEach((name) => { const iter = metadata[name]; if ( iter && iter.type === 'application' ) { const label = [iter.name]; if ( iter.description ) { label.push(iter.description); } rows.push({ value: iter, columns: [ {label: label.join(' - '), icon: Theme.getIcon(iter.icon, null, name), value: JSON.stringify(iter)} ] }); } }); this._find('ApplicationList').set('columns', cols).add(rows).on('activate', (ev) => { this.onClose(ev, 'ok'); }); let file = '<unknown file>'; let label = '<unknown mime>'; if ( this.args.file ) { file = Utils.format('{0} ({1})', this.args.file.filename, this.args.file.mime); label = _('DIALOG_APPCHOOSER_SET_DEFAULT', this.args.file.mime); } this._find('FileName').set('value', file); this._find('SetDefault').set('label', label); return root; } onClose(ev, button) { let result = null; if ( button === 'ok' ) { const useDefault = this._find('SetDefault').get('value'); const selected = this._find('ApplicationList').get('value'); if ( selected && selected.length ) { result = selected[0].data.className; } if ( !result ) { DialogWindow.create('Alert', { message: _('DIALOG_APPCHOOSER_NO_SELECTION') }, null, this); return; } result = { name: result, useDefault: useDefault }; } this.closeCallback(ev, button, result); } }
JavaScript
class Model { /** * Constructs model with the model name and defined object definition. * @param {string} modelName Model and collection name * @param {import('mongoose').SchemaDefinition} definition Schema definition */ constructor(modelName, definition) { // Initialize model with the name and defined schema this.db = model(modelName, new Schema(definition, { timestamps: true })); } /** * Method for inserting data to the database based on collection name. * @param {object} data The data based on defined schema. */ create(data) { // Calls a promise that returns created data return this.db.create(data); } /** * Method for fetching data either with or without search queries within the defined collection. * @param {object} query Contains query filters * @param {string} query.keyword Keyword that is used for data lookup */ read({ keyword }) { // Search parameter object for doing query, can be multiple but implements only keyword for now const searchParams = {}; // Adds full text search query if there is keyword implemented if (keyword) searchParams.$text = { $search: keyword }; // Returns all data if there is no keyword return this.db.find(searchParams); } /** * Method for fetching data based on ObjectId within the defined collection. * @param {string} id the document id for data lookup. */ readById(id) { // Returns one data based on the ObjectId of the data return this.db.findById(id); } /** * Method for updating data to the database based on collection name. * @param {string} id the document id for data lookup. * @param {object} data the data based on defined schema. */ update(id, data) { // Finds the data based on its ObjectId and updates the data return this.db.findByIdAndUpdate(id, data, { new: true }); } /** * Method for deleting data based on ObjectId within the defined collection. * @param {string} id the document id for data lookup. */ delete(id) { // Finds the data based on its ObjectId and deletes the data return this.db.findByIdAndDelete(id); } }
JavaScript
class Story { /** * Constructs Story object for acting as a data model * @param {object} story Request object containing data */ constructor(story) { if (story === null || story === undefined) { /** @private @const {object array} */ this.allStories = []; } else { /** @private @const {number} */ this.story_id = story.story_id || null; /** @private @const {number} */ this.story_title = story.story_title || null; /** @private @const {number} */ this.user_id = story.user_id || null; /** @private @const {string} */ this.summary = story.summary || null; } } /** * Queries database for all stories and adds them to the model */ async getAllStories() { await pool.query(` SELECT story.story_id, story.story_title, user_account.username FROM story INNER JOIN user_account ON user_account.user_id = story.user_id;`) .then( results => { console.log('Story Rows: ', results.rows); this.allStories = results.rows; }) .catch(error => console.error('Error: Query Execution\n', error.stack)); } /** * Queries the database to get all stories by username and adds them to the model * @param {string} username arg1 Username of the story author */ async getAllStoriesByUserId(userId) { await pool.query(` SELECT story.story_id, story.story_title, story.summary, user_account.username FROM story RIGHT JOIN user_account ON user_account.user_id = story.user_id WHERE user_account.user_id = $1;`, [userId]) .then( results => { console.log('Story Rows: ', results.rows); this.allStories = results.rows; } ) .catch(error => console.error(`Error: getAllStoriesByUsername for user ${userId}\n`, error.message, error.stack)); } /** * Queries the database with a story's id and adds story data to the model */ async getStoryById() { await pool.query(` SELECT story.story_id, story.story_title, story.summary, user_account.username FROM story RIGHT JOIN user_account ON user_account.user_id = story.user_id WHERE story.story_id = $1`, [this.story_id]) .then( result => { if (result.rowCount > 0) { console.log('Story Row: ', result.rows); this.story_id = result.rows[0].story_id; this.story_title = result.rows[0].story_title; this.summary = result.rows[0].summary; this.username = result.rows[0].username; } } ) .catch(error => console.error(`Error: getStoryByTitle for title ${this.story_title}\n`, error.message, error.stack)); } /** * Inserts new story into the database */ async createNewStory() { await pool.query(` INSERT INTO story(story_title, user_id, summary) VALUES ($1, $2, $3) RETURNING *`, [this.story_title, this.user_id, this.summary]) .then( result => { console.log('New story: ', result.rows); this.story_id = result.rows[0].story_id; this.story_title = result.rows[0].story_title; this.summary = result.rows[0].summary; this.user_id = result.rows[0].user_id; this.creation_date = result.rows[0].creation_date; } ) .catch(error => console.error(`Error: createNewStory for title ${this.story_title}, id: ${this.story_id}\n`, error.message, error.stack)); } /** * Updates a story from the database */ async updateStory() { await pool.query(` UPDATE story SET story_title = $1, summary = $2 WHERE story_id = $3 RETURNING *;`, [this.story_title, this.summary, this.story_id]) .then( result => { console.log("Updated story: ", result.rows); this.story_id = result.rows[0].story_id; this.story_title = result.rows[0].story_title; this.user_id = result.rows[0].user_id; this.summary = result.rows[0].summary; // if (updatedStory.rowCount === 0) { // console.error(`Error: story_id ${req.params.story_id} cannot be found. User ${req.params.user_id} may not be the story's author.`); // next(); // } else { // console.log('Successful update'); // res.json(updatedStory); // } } ) .catch(error => console.error(`Error: updateStory for title ${this.story_title} \n`, error.message, error.stack)); } /** * Delete a story from the database */ async deleteStory() { await pool.query(` DELETE FROM story where story_id = $1 RETURNING *;`, [req.params.story_id]) .then( result => { console.log(`Success: Deleted story ${req.params.story_id} by user`); } ) .catch(error => console.error(`Error: deleteStory failed, cannot delete story id: ${this.story_id}\n`, error.message, error.stack)); } }
JavaScript
class Train extends Component { constructor(props) { super(props); this.state = { isLanguageSubmitting: false, isLanguageStatusLoading: false, isAcousticSubmitting: false, isAcousticStatusLoading: false, languageModelData: null, acousticModelData: null, languageModelError: '', acousticModelError: '' }; } async componentDidMount() { this.getStatusLanguageModel(); this.getStatusAcousticModel(); } componentWillUnmount() { clearInterval(this.interval); } handleDismiss = errorType => { this.setState({ [errorType]: '' }); } trainLanguageModel = async event => { event.preventDefault(); this.setState({ isLanguageSubmitting: true }); this.setState({ languageModelError: '' }); fetch(`${config.API_ENDPOINT}/train`, { method: 'POST', credentials: 'include', }) .then(handleFetchNonOK) .then((response) => { response.json().then((data) => { this.getStatusLanguageModel(); this.setState({ isLanguageSubmitting: false }); }); }) .catch((err) => { this.setState({ languageModelError: `Error initializing the training: ${err.message}`}); this.setState({ isLanguageSubmitting: false }); }); } trainAcousticModel = async event => { event.preventDefault(); this.setState({ isAcousticSubmitting: true }); fetch(`${config.API_ENDPOINT}/train-acoustic`, { method: 'POST', credentials: 'include', }) .then(handleFetchNonOK) .then((response) => { response.json().then((data) => { this.getStatusAcousticModel(); this.setState({ isAcousticSubmitting: false }); }); }) .catch((err) => { this.setState({ acousticModelError: `Error initializing the training: ${err.message}`}); this.setState({ isAcousticSubmitting: false }); }); } /** * Check if model is in a state that needs continuous polling to check for * updates. */ checkModelStatusDone = status => { let nonPollStatuses = ['ready', 'available', 'failed']; return nonPollStatuses.includes(status); } /** * This function will check if the model is in a state from which you can kick * off a training session from (i.e. not updating, pending, or training). */ checkModelTrainable = data => { if (!data) { return false; } else if (['ready', 'failed'].includes(data.status)) { return true; } return false; } /** * This function will give the appropriate CSS class to color the given * status. */ getStatusColor = status => { if (status === 'ready') { return 'text-info'; } else if (status === 'available') { return 'text-success'; } else if (status === 'training') { return 'text-warning'; } else if (status === 'failed') { return 'text-danger'; } else { return 'text-secondary'; } } pollLanguageModelStatus = async () => { this.getStatusLanguageModel(true); } pollAcousticModelStatus = async () => { this.getStatusAcousticModel(true); } getStatusLanguageModel = async (poll = false) => { if (!poll) this.setState({ isLanguageStatusLoading: true }); fetch(`${config.API_ENDPOINT}/model`, { method: 'GET', credentials: 'include' }) .then(handleFetchNonOK) .then((response) => { response.json().then((data) => { this.setState({ languageModelData: data.data }); let isNotActive = this.checkModelStatusDone(data.data.status); // If polling and if the model is no longer in an active state, stop // polling. if (isNotActive && poll) { clearInterval(this.interval); } // If it is in an active state, initiate the polling. else if (!isNotActive && !poll) { this.interval = setInterval(this.pollLanguageModelStatus, 5000); } if (!poll) this.setState({ isLanguageStatusLoading: false }); }); }) .catch((err) => { this.setState({ languageModelError: `Error getting language model data: ${err.message}`}); if (!poll) this.setState({ isLanguageStatusLoading: false }); }); } getStatusAcousticModel = async (poll = false) => { if (!poll) this.setState({ isAcousticStatusLoading: true }); fetch(`${config.API_ENDPOINT}/acoustic-model`, { method: 'GET', credentials: 'include' }) .then((response) => { response.json().then((data) => { this.setState({ acousticModelData: data.data }); let isNotActive = this.checkModelStatusDone(data.data.status); // If polling and if the model is no longer in an active state, stop // polling. if (isNotActive && poll) { clearInterval(this.interval); } // If it is in an active state, initiate the polling. else if (!isNotActive && !poll) { this.interval = setInterval(this.pollAcousticModelStatus, 5000); } if (!poll) this.setState({ isAcousticStatusLoading: false }); }); }) .catch((err) => { this.setState({ acousticModelError: `Error getting acoustic model data: ${err.message}` }); if (!poll) this.setState({ isAcousticStatusLoading: false }); }); } render() { return ( <div className="Train"> <h1>Train Custom Models</h1> <p>If you have recently added language or audio resources, the model needs to be trained to account for the new data. Kick off a training session here. If a model's status is <code>ready</code>, then this indicates that the model contains data and is ready to be trained. A status of <code>available</code> indicates that the model is trained and ready to use. </p> <Grid> <Row className="show-grid"> <Col md={6}> <h3>Language Model Status</h3> <Well> {this.state.isLanguageStatusLoading && <Glyphicon glyph="refresh" className="loadingstatus" /> } {this.state.languageModelData && !this.state.isLanguageStatusLoading && <div className="modelstatus"> <strong>Name:</strong> {this.state.languageModelData.name}<br /> <strong>Status:</strong>{' '} <span className={this.getStatusColor(this.state.languageModelData.status)}> {this.state.languageModelData.status}{' '} {this.state.languageModelData.status ==='training' && <Glyphicon glyph="refresh" className="training" /> } </span> </div> } </Well> <LoadButton block bsStyle="primary" type="button" disabled={ this.state.isLanguageStatusLoading || !this.checkModelTrainable(this.state.languageModelData) } isLoading={this.state.isLanguageSubmitting} onClick={this.trainLanguageModel} text="Train Language Model" loadingText="Initializing…" /> <AlertDismissable title="Language Model Error" message={this.state.languageModelError} show={this.state.languageModelError} onDismiss={() => this.handleDismiss('languageModelError')} /> </Col> <Col md={6}> <h3>Acoustic Model Status</h3> <Well> {this.state.isAcousticStatusLoading && <Glyphicon glyph="refresh" className="loadingstatus" /> } {this.state.acousticModelData && !this.state.isAcousticStatusLoading && <div className="modelstatus"> <strong>Name:</strong> {this.state.acousticModelData.name}<br /> <strong>Status:</strong>{' '} <span className={this.getStatusColor(this.state.acousticModelData.status)}> {this.state.acousticModelData.status}{' '} {this.state.acousticModelData.status ==='training' && <Glyphicon glyph="refresh" className="training" /> } </span> </div> } </Well> <LoadButton block bsStyle="primary" type="button" disabled={ this.state.isAcousticStatusLoading || !this.checkModelTrainable(this.state.acousticModelData) } isLoading={this.state.isAcousticSubmitting} onClick={this.trainAcousticModel} text="Train Acoustic Model" loadingText="Initializing…" /> <AlertDismissable title="Acoustic Model Error" message={this.state.acousticModelError} show={this.state.acousticModelError} onDismiss={() => this.handleDismiss('acousticModelError')} /> </Col> </Row> </Grid> </div> ); } }
JavaScript
class CreateIssuanceRequestOp { constructor (record) { this.reference = record.reference } }
JavaScript
class AuthenticationPrompt extends _react.default.Component { constructor(props) { super(props); this._onKeyUp = e => { if (e.key === 'Enter') { this.props.onConfirm(); } if (e.key === 'Escape') { this.props.onCancel(); } }; this._disposables = new _atom.CompositeDisposable(); } componentDidMount() { // Hitting enter when this panel has focus should confirm the dialog. this._disposables.add(atom.commands.add(this.refs.root, 'core:confirm', event => this.props.onConfirm())); // Hitting escape should cancel the dialog. this._disposables.add(atom.commands.add('atom-workspace', 'core:cancel', event => this.props.onCancel())); this.refs.password.focus(); const raiseNativeNotification = (0, (_AtomNotifications || _load_AtomNotifications()).getNotificationService)(); if (raiseNativeNotification != null) { const pendingNotification = raiseNativeNotification('Nuclide Remote Connection', 'Nuclide requires additional action to authenticate your remote connection', 2000, false); if (pendingNotification != null) { this._disposables.add(pendingNotification); } } } componentWillUnmount() { this._disposables.dispose(); } focus() { this.refs.password.focus(); } getPassword() { return this.refs.password.value; } render() { // * Need native-key-bindings so that delete works and we need `_onKeyUp` so that escape and // enter work // * `instructions` are pre-formatted, so apply `whiteSpace: pre` to maintain formatting coming // from the server. return _react.default.createElement( 'div', { ref: 'root' }, _react.default.createElement( 'div', { className: 'block', style: { whiteSpace: 'pre' } }, this.props.instructions ), _react.default.createElement('input', { tabIndex: '0', type: 'password', className: 'nuclide-password native-key-bindings', ref: 'password', onKeyPress: this._onKeyUp }) ); } }
JavaScript
class ReposOwnerRepoContentsPathAuthor { /** * Constructs a new <code>ReposOwnerRepoContentsPathAuthor</code>. * The author of the file. Default: The &#x60;committer&#x60; or the authenticated user if you omit &#x60;committer&#x60;. * @alias module:model/ReposOwnerRepoContentsPathAuthor * @param email {String} The email of the author or committer of the commit. You'll receive a `422` status code if `email` is omitted. * @param name {String} The name of the author or committer of the commit. You'll receive a `422` status code if `name` is omitted. */ constructor(email, name) { ReposOwnerRepoContentsPathAuthor.initialize(this, email, name); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, email, name) { obj['email'] = email; obj['name'] = name; } /** * Constructs a <code>ReposOwnerRepoContentsPathAuthor</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ReposOwnerRepoContentsPathAuthor} obj Optional instance to populate. * @return {module:model/ReposOwnerRepoContentsPathAuthor} The populated <code>ReposOwnerRepoContentsPathAuthor</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ReposOwnerRepoContentsPathAuthor(); if (data.hasOwnProperty('date')) { obj['date'] = ApiClient.convertToType(data['date'], 'String'); } if (data.hasOwnProperty('email')) { obj['email'] = ApiClient.convertToType(data['email'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } } return obj; } }
JavaScript
class VisualizerController { constructor(svg) { this.svg = svg; this.runtimeId = 0; } load(model) { this.evalSetting = model.evalSetting; this.data = model.data; } draw() { document.getElementById('loading').remove(); const svg = this.svg; const data = this.data; // Remove anything existing. // while (svg.firstChild) { // svg.removeChild(svg.firstChild); // } svg.innerHTML = `\ <defs> <marker id="head" orient="auto" markerHeight="4" refX="3.5" refY="2" markerWidth="4"> <path fill="black" d="M0,0 V4 L4,2 Z"></path> </marker> </defs>`; // One-letter abbreviations. const tableAbrv = {}; (() => { const abrvs = new Set(); outer: for (const table of Object.keys(data)) { for (let i = 0; i < table.length; i++) { const letter = table[i].toUpperCase(); if (!abrvs.has(letter)) { abrvs.add(letter) tableAbrv[table] = letter; continue outer; } } // Default: use full table name. tableLetters[table] = table; } })(); // Build tables. const allTableVis = this.allTableVis = {}; for (const [ table, { header, rows } ] of Object.entries(data)) { const idIndex = header.indexOf('id'); const color = getColorFromTable(table); const allRecordVis = []; for (const row of rows) { const recordVis = new VisRecord(tableAbrv[table] + row[idIndex], color, { table, row }); allRecordVis.push(recordVis); } const tableVis = new VisStack(allRecordVis); allTableVis[table] = tableVis; } // Table of Contents. const toc = getColorTable(); const tocItems = Object.entries(toc) .map(([ tableName, color ]) => new VisRecord(`${tableName} (${tableAbrv[tableName]})`, color)); const tocDiskRows = Object.values(allTableVis).map((disk, i) => new VisStack([ tocItems[i], disk ], false, 20, 150)); const tocDiskVis = new VisStack([ new VisElem(createTextEl('Tables (On Disk)')), ...tocDiskRows ], true, 20); const tocDiskBox = new VisBox(tocDiskVis, 'rgba(0, 0, 0, 0.05)', 20); const chestnutVis = new VisStack([ new VisElem(createTextEl('Chestnut (In-Memory)')) ], true, 20); const chestnutBox = new VisBox(chestnutVis, 'rgba(0, 0, 0, 0.05)', 20); // TODO find out color order. this.chestnutVis = chestnutVis; // QUERY VIS START this.qpVis = new VisStack([], false, 20); // QUERY VIS END this.root = new VisSvg( new VisStack([ tocDiskBox, chestnutBox, this.qpVis ], true, 20), (width, height) => document.getElementById('spacer').style.height = `calc(${100 * height / width / 2}vw - 250px)`); this.root.attach(svg); } clearPlans() { this.qpVis.clear(); } _makeAQpVis() { const aQpVis = new VisStack([ new VisElem(createTextEl('Query Execution')) ], true, 20); const qpBox = new VisBox(aQpVis, 'rgba(0, 0, 0, 0.05)', 20); qpBox.attach(this.svg, -200, 1000); this.qpVis.push(qpBox); return aQpVis; } async play(model) { this.chestnutModel = new ChestnutModel(model, this.data); this.chestnutModel.bind(this.svg, this.allTableVis); await this.chestnutModel.form(this.svg, this.chestnutVis, () => delay(50)); } async playQp(qpInfo, qpContext, delayer = null) { const runtimeId = ++this.runtimeId; const runtime = document.getElementById('runtime'); runtime.innerHTML = ''; getRuntime(qpInfo.hrName, this.evalSetting) .then(d => { if (!d || this.runtimeId !== runtimeId) return; const fmt = ms => { if (ms > 5000) return ((ms / 1000) | 0).toString().slice(0, 3) + 's' ms = (ms | 0); return ms.toString() + 'ms'; }; const sql = d.sql_query_time + d.rails_deserialize; const cn = d.chestnut_query_time + d.chestnut_deserialize; runtime.innerHTML = `MySQL+AR: ${fmt(sql)}<br>Chestnut: ${fmt(cn)}`; }); if (!delayer) delayer = (s = 1) => delay(s * 400); this.qpModel = new QueryPlanModel(qpInfo, this.data); // this.qpModel.bind(this.svg, this.chestnutModel); // await this.qpModel.form(this.svg, this.qpVis, () => delay(100)) // TODO // Delay needs to match or be greater than css transition speed. this.qpModel.form(qpInfo, qpContext, this.svg, this._makeAQpVis(), this.chestnutModel, delayer); } }
JavaScript
class PictureModel { init() { this.subscribe(this.id, "addImage", "addImage"); this.subscribe(this.id, "removeImage", "removeImage"); this.subscribe(this.id, "goToImage", "goToImage"); this.subscribe(this.sessionId, "loadImage", "loadImage"); if (!this._get("images")) { this._set("images", [{key: 0, width: 1024, height: 768}]); this._set("index", 0); // there is already an entry this._set("key", 1); // 0 is used as default let image = this.createElement("img"); image.domId = "image"; this.appendChild(image); let buttons = ["addButton", "delButton", "prevButton", "nextButton"]; buttons.forEach(name => { let button = this.createElement(); button.classList.add("picture-button"); button.domId = name; this.appendChild(button); }); } console.log("PictureModel.init"); } find(key) { let images = this._get("images"); return images.find(i => i.key === key); } findIndex(key) { let images = this._get("images"); return images.findIndex(i => i.key === key); } addImage(data) { // let {handle, type, width, height, name} = data; let key = this._get("key"); data.key = key; this._set("key", key + 1); let images = [...this._get("images")]; let index = this._get("index"); let current = images[index]; images.splice(index + 1, 0, data); this._set("images", images); this._set("index", index + 1); this.goToImage({from: current && current.key, to: data.key}); } goToImage(obj) { let images = this._get("images"); let index = this.findIndex(obj.to); if (images && images.length > index) { this._set("index", index); let entry = images[index]; this.publish(this.sessionId, "loadImage", entry); } } removeImage(key) { if (key === 0) {return;} // there should be always at least one let images = [...this._get("images")]; let index = this.findIndex(key); if (index > 0) { images.splice(index, 1); this._set("images", images); let prev = images[index - 1]; this.goToImage({to: prev.key}); } } loadImage(entry) { let img = this.querySelector("#image"); if (!entry) {return;} let {handle, type, width, height, name: _name} = entry; img.style.setProperty("width", `${width}px`); img.style.setProperty("height", `${height}px`); if (entry.key !== 0) { img._set("src", {handle, type}); } else { img._delete("src"); } this.publish(this.id, "loadImage", entry); } loadPersistentData(data) { this._set("images", data); this._set("index", data && data.length > 0 ? 0 : -1); } savePersistentData() { let top = this.wellKnownModel("modelRoot"); let func = () => this._get("images"); top.persistSession(func); } }
JavaScript
class DFPDurationError extends Error { constructor(interval) { super(`Invalid interval: '${interval}'ls`); } }
JavaScript
class OrgsScreen extends React.Component { state = { loading: true, data: null, } load = async() => { const querySnapshot = await db.collection('orgs').get() const data = [] querySnapshot.forEach((doc) => data.push({ ...doc.data(), key: doc.id })) this.setState({ data, loading: false }) } handleReloadOrgs = () => { this.setState({ loading: true }) this.load() } componentDidMount = () => { const { navigation } = this.props navigation.setParams({ reloadOrgs: this.handleReloadOrgs }) this.load() } render() { const { navigation } = this.props const { data, loading } = this.state return ( <Container> <Content> { loading ? ( <S.View.Center> <S.Spinner color='blue' /> <S.Text>loading orgs...</S.Text> </S.View.Center> ) : ( <List data={data} navigation={navigation} reloadOrgs={this.handleReloadOrgs} /> )} </Content> </Container> ) } }
JavaScript
class Node { constructor(value, next = null) { this.value = value this.next = next } }
JavaScript
class App extends React.Component { render() { const { classes } = this.props; return ( <div className={classes.root}> <NavBar /> <Switch> <Route exact path="/" component={UsersPage} /> <Route path="/posts" component={PostsPage} /> <Route component={NotFoundPage} /> </Switch> </div> ); } }
JavaScript
class DLORulesProbe { /** @return {Object} data collected when the target embed script *is not* loaded @return {Object.success} always true */ async gatherBaselineData(){ console.log('DLO rules baseline') if (Array.isArray(window._testRuleResults) === false) { console.error('No window._testRuleResults in the page'); return { success: false }; } return { success: window._testRuleResults.length === 0 }; } /** @return {object} the results of the probe */ async probe(basis, baseline){ console.log('Probing DLO rules ' + (basis ? 'with' : 'without') + ' basis'); if(!basis) return { passed: true } const results = { passed: true, results: window._testRuleResults, // List of rule results failures: [] } if (typeof basis.count === 'number') { console.log('Testing DLO rule result count: ' + basis.count + ': ' + window._testRuleResults.length); if (basis.count !== window._testRuleResults.length) { results.passed = false; results.failures.push('Count does not match results length'); } } if (Array.isArray(basis.parameters)) { for (let i=0; i < basis.parameters.length; i += 1) { const paramInfo = basis.parameters[i]; if (Array.isArray(paramInfo) && typeof paramInfo[0] === 'number' && typeof paramInfo[1] === 'number') { if (results.results[paramInfo[0]][paramInfo[1]] != paramInfo[2]) { results.passed = false; results.failures.push('Parameter mismatch:', paramInfo); } } else { console.error('The parameters array must contain arrays like [result index, parameter index, value]'); results.passed = false; results.failures.push('The parameters array must contain arrays like [index, value]') } } } return results } }
JavaScript
class StakeholderList extends Component { static propTypes = { handleSearchStakeholders: PropTypes.func.isRequired, stakeholders: PropTypes.arrayOf(PropTypes.object).isRequired, loading: PropTypes.bool.isRequired, }; onSearch = searchText => { const { handleSearchStakeholders } = this.props; handleSearchStakeholders(searchText); }; render() { const { stakeholders, loading } = this.props; const headerStyle = { flexDirection: 'row', alignItems: 'center', width: '100%', background: '#fff', padding: '7px 5px 7px 20px', borderBottom: '1px solid #E0E0E0', }; return ( <Fragment> <Layout style={headerStyle}> <Checkbox /> <div style={{ flex: '1', margin: '0 10px' }}> <Search placeholder="Search stakeholder..." onSearch={value => this.onSearch(value)} style={{ width: '100%' }} enterButton={<Button icon="search" />} /> </div> <Popover placement="bottom" trigger="click" content={actions}> <Button icon="ellipsis" className="f-20 b-0" /> </Popover> </Layout> <div style={{ background: '#fff', height: '100%', overflowY: 'auto', paddingBottom: '50px', }} > <List loading={loading} itemLayout="horizontal" dataSource={stakeholders} renderItem={item => <StakeholderItem stakeholder={item} />} /> {stakeholders.length ? <StakeholderListFooter /> : ''} </div> </Fragment> ); } }
JavaScript
class InstanceEvent { /** * Constructs a new <code>InstanceEvent</code>. * @alias module:model/InstanceEvent * @param type {module:model/InstanceEvent.TypeEnum} * @param target {String} * @param data {Array.<module:model/Instance>} */ constructor(type, target, data) { InstanceEvent.initialize(this, type, target, data); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, type, target, data) { obj['type'] = type; obj['target'] = target; obj['data'] = data; } /** * Constructs a <code>InstanceEvent</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InstanceEvent} obj Optional instance to populate. * @return {module:model/InstanceEvent} The populated <code>InstanceEvent</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InstanceEvent(); if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('target')) { obj['target'] = ApiClient.convertToType(data['target'], 'String'); } if (data.hasOwnProperty('data')) { obj['data'] = ApiClient.convertToType(data['data'], [Instance]); } } return obj; } }
JavaScript
class Judge { constructor() {} static model = use.load(); /** * Generates similarity scores and match counts for an array of sentences. * Returns Object: * { * text: [String], * matches: [Int], * similarity: [Float], * mean: Float * } * similarity is the mean of the similarity of each sentence with all others, * mean is the mean of these mean similarity values (i.e. the global mean). * * @param {[String]} sentences * @param {Boolean=false} detail */ static async score(sentences, detail = false) { // Wait for model if it's not ready yet const model = await Judge.model; // Generate embedding const emb = await model.embed(sentences); const embeddings = await emb.array(); const results = { totals: { text: sentences, matches: [], similarity: [], }, }; // Calculate similarity of each response pair. for (let i = 0; i < embeddings.length; i++) { let scores = []; for (let j = 0; j < embeddings.length; j++) { scores.push(Judge._dotProduct(embeddings[i], embeddings[j])); } results[i] = { text: sentences[i], mean: Judge.mean(scores), similarity: scores, }; results.totals.similarity.push(results[i].mean); } results.totals.mean = Judge.mean(results.totals.similarity); // Calculate number of matches for each response for (let i = 0; i < embeddings.length; i++) { let matches = results[i].similarity.map((s) => s >= results.totals.mean); results[i].matches = matches; results.totals.matches.push(matches.filter(Boolean).length); } if (!detail) return results.totals; return results; } /** * Calculate the mean of an array of numbers. */ static mean = (array) => array.reduce((a, b) => a + b) / array.length; /** * Calculate the dot product of two vector arrays. */ static _dotProduct = (xs, ys) => { const sum = (xs) => (xs ? xs.reduce((a, b) => a + b, 0) : undefined); return xs.length === ys.length ? sum(Judge._zipWith((a, b) => a * b, xs, ys)) : undefined; }; /** * zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] */ static _zipWith = (f, xs, ys) => { const ny = ys.length; return (xs.length <= ny ? xs : xs.slice(0, ny)).map((x, i) => f(x, ys[i])); }; }
JavaScript
class DisplayList extends AbstractSubject { /** * @param {string=} opt_name name of this DisplayList. */ constructor(opt_name) { super(opt_name || 'DISPLAY_LIST_'+(DisplayList.NAME_ID++)); /** * @type {!Array<!DisplayObject>} * @private */ this.drawables_ = []; }; /** @override */ toString() { return Util.ADVANCED ? '' : this.toStringShort().slice(0, -1) +', drawables_: [' + goog.array.map(this.drawables_, function(d, idx) { return idx+': '+d.toStringShort(); }) + ']' + super.toString(); }; /** @override */ toStringShort() { return Util.ADVANCED ? '' : super.toStringShort().slice(0, -1) +', drawables_.length: '+this.drawables_.length +'}'; }; /** @override */ getClassName() { return 'DisplayList'; }; /** Adds the DisplayObject, inserting it at the end of the group of DisplayObjects with the same zIndex; the item will appear visually over objects that have the same (or lower) `zIndex`. @param {!DisplayObject} dispObj the DisplayObject to add */ add(dispObj) { if (!goog.isObject(dispObj)) { throw new Error('non-object passed to DisplayList.add'); } var zIndex = dispObj.getZIndex(); if (Util.DEBUG) { this.preExist(dispObj); } this.sort(); // Objects in drawables_ array should be sorted by zIndex. // Starting at front of drawables_ array, find the object with bigger // zIndex, insert dispObj just before that object. for (var i=0, n= this.drawables_.length; i<n; i++) { var z = this.drawables_[i].getZIndex(); if (zIndex < z) { break; } } goog.array.insertAt(this.drawables_, dispObj, i); this.broadcast(new GenericEvent(this, DisplayList.OBJECT_ADDED, dispObj)); }; /** Returns true if this DisplayList contains the given DisplayObject. @param {!DisplayObject} dispObj the item to search for @return {boolean} true if the DisplayObject was found */ contains(dispObj) { if (!goog.isObject(dispObj)) { throw new Error('non-object passed to DisplayList.contains'); } return goog.array.contains(this.drawables_, dispObj); }; /** Draws the DisplayObjects in order, which means that DisplayObjects drawn later (at the end of the list) will appear to be on top of those drawn earlier (at start of the list). @param {!CanvasRenderingContext2D} context the canvas's context to draw this object into @param {!CoordMap} map the mapping to use for translating between simulation and screen coordinates */ draw(context, map) { this.sort(); goog.array.forEach(this.drawables_, function(dispObj) { dispObj.draw(context, map); }); }; /** Returns the DisplayObject that shows the given SimObject. @param {!SimObject|string|number} search the SimObject to search for, or name of SimObject, or index number of DisplayObject. Name should be English or language-independent version of name. @return {?DisplayObject} the DisplayObject on this list that shows the given SimObject, or null if not found */ find(search) { if (goog.isNumber(search)) { var index = /** @type {number}*/(search); var n = this.drawables_.length; if (index < 0 || index >= n) { return null; } else { this.sort(); return this.drawables_[index]; } } else if (goog.isString(search)) { var objName = Util.toName(search); return goog.array.find(this.drawables_, function(element, index, array) { var simObjs = element.getSimObjects(); for (var i=0, n=simObjs.length; i<n; i++) { if (simObjs[i].getName() == objName) { return true; } } return false; }); } else if (goog.isObject(search)) { return goog.array.find(this.drawables_, function(element, index, array) { var simObjs = element.getSimObjects(); return goog.array.contains(simObjs, search); }); } else { return null; } }; /** Returns the DisplayShape that shows the given SimObject. @param {!SimObject|string|number} search the SimObject to search for, or name of SimObject, or index number of DisplayObject. Name should be English or language-independent version of name. @return {!DisplayShape} the DisplayShape on this list that shows the given SimObject @throws {!Error} if DisplayShape is not found */ findShape(search) { var ds = this.find(search); if (ds instanceof DisplayShape) { return /**!DisplayShape*/(ds); } throw new Error('DisplayShape not found: '+search); }; /** Returns the DisplaySpring that shows the given SimObject. @param {!SimObject|string|number} search the SimObject to search for, or name of SimObject, or index number of DisplayObject. Name should be English or language-independent version of name. @return {!DisplaySpring} the DisplaySpring on this list that shows the given SimObject @throws {!Error} if DisplaySpring is not found */ findSpring(search) { var ds = this.find(search); if (ds instanceof DisplaySpring) { return /**!DisplaySpring*/(ds); } throw new Error('DisplaySpring not found: '+search); }; /** Returns the DisplayObject at the specified position in this DisplayList @param {number} index index number of DisplayObject @return {!DisplayObject} the DisplayObject at the specified position in this DisplayList @throws {!Error} if index out of range */ get(index) { var n = this.drawables_.length; if (index < 0 || index >= n) { throw new Error(index+' is not in range 0 to '+(n-1)); } this.sort(); return this.drawables_[index]; }; /** Returns number of DisplayObjects in this DisplayList, minus 1. @return number of DisplayObjects minus 1 */ length() { return this.drawables_.length; }; /** @param {!DisplayObject} dispObj @private */ preExist(dispObj) { if (Util.DEBUG) { var simObjs = dispObj.getSimObjects(); for (var i=0, len=simObjs.length; i<len; i++) { var obj = simObjs[i]; var preExist = this.find(obj); if (preExist != null) { console.log('*** WARNING PRE-EXISTING DISPLAYOBJECT '+preExist); console.log('*** FOR SIMOBJECT=' + obj); console.log('*** WHILE ADDING '+dispObj); throw new Error('pre-existing object '+preExist+' for '+obj+' adding '+dispObj); } } } }; /** Adds the DisplayObject, inserting it at the front of the group of DisplayObjects with the same zIndex; the item will appear visually under objects that have the same (or higher) `zIndex`. @param {!DisplayObject} dispObj the DisplayObject to prepend */ prepend(dispObj) { if (!goog.isObject(dispObj)) { throw new Error('non-object passed to DisplayList.add'); } var zIndex = dispObj.getZIndex(); if (Util.DEBUG) { this.preExist(dispObj); } this.sort(); // Objects in drawables_ array should be sorted by zIndex. // Starting at back of drawables_ array, find the object with smaller // zIndex, insert dispObj just after that object. for (var n= this.drawables_.length, i=n; i>0; i--) { var z = this.drawables_[i-1].getZIndex(); if (zIndex > z) { break; } } goog.array.insertAt(this.drawables_, dispObj, i); this.broadcast(new GenericEvent(this, DisplayList.OBJECT_ADDED, dispObj)); }; /** Removes the item from the list of DisplayObjects. @param {!DisplayObject} dispObj the item to remove */ remove(dispObj) { if (!goog.isObject(dispObj)) { throw new Error('non-object passed to DisplayList.remove'); } var idx = goog.array.indexOf(this.drawables_, dispObj); if (idx > -1) { goog.array.removeAt(this.drawables_, idx); this.broadcast(new GenericEvent(this, DisplayList.OBJECT_REMOVED, dispObj)); }; }; /** Clears the list of DisplayObjects. * @return {undefined} */ removeAll() { goog.array.forEachRight(this.drawables_, function(dispObj) { this.remove(dispObj); }, this); }; /** Sorts the DisplayList by zIndex. Avoids sorting if the list is already sorted. * @return {undefined} */ sort() { // avoid sorting if the list is already sorted var isSorted = true; var lastZ = Util.NEGATIVE_INFINITY; for (var i=0, n= this.drawables_.length; i<n; i++) { var z = this.drawables_[i].getZIndex(); if (z < lastZ) { isSorted = false; break; } lastZ = z; } if (!isSorted) { goog.array.stableSort(this.drawables_, function(arg1, arg2) { var e1 = /** @type {!DisplayObject}*/(arg1); var e2 = /** @type {!DisplayObject}*/(arg2); var z1 = e1.getZIndex(); var z2 = e2.getZIndex(); if (z1 < z2) { return -1; } else if (z1 > z2) { return 1; } else { return 0; } }); } }; /** Returns set of the DisplayObjects in proper visual sequence, starting with the bottom-most object. @return {!Array<!DisplayObject>} list of DisplayObjects in visual sequence order */ toArray() { this.sort(); return goog.array.clone(this.drawables_); }; } // end class
JavaScript
class Order extends Component { constructor(props) { super(props) this.state = { quantity: 2, price: 400, transportFee: 100, total: 500, notification: '' } this.handleChange = this.handleChange.bind(this); } handleChange(e) { e.preventDefault(); let Qty; const { quantity } = this.state; switch (e.target.id) { case 'minus': if (quantity > 2) { Qty = quantity - 1; setOrderQty(Qty); this.setState({ quantity: Qty, price: Qty * 200, transportFee: Qty * 50, total: (Qty * 50) + (Qty * 200) }); } else { this.setState({ notification: 'Minimum order recieved' }); } break; case 'plus': if (quantity < 30) { Qty = quantity + 1; setOrderQty(Qty); this.setState({ quantity: Qty, price: Qty * 200, transportFee: Qty * 50, total: (Qty * 50) + (Qty * 200) }); } else { this.setState({ notification: 'Maximum order recieved' }); } break; default: setOrderQty(2); this.setState({ quantity: 2, price: 400, transportFee: 100, total: 500, notification: '' }); break; } } componentDidMount() { if (getOrderQty()) { this.setState({ quantity: getOrderQty()*1, price: getOrderQty() * 200, transportFee: getOrderQty() * 50, total: (getOrderQty() * 50) + (getOrderQty() * 200) }); } else { setOrderQty(2); } }; render() { const { quantity, price, transportFee, total } = this.state; return ( <React.Fragment> <Row> <div className="order_content"> <div className="bag"> <p className="bag-head"><span className="uppercase">Your Bag</span> - {quantity} item</p> </div> <div className="bag-product"> <div className="image"> <img src={bag} className="product-image" alt="waste bag" /> </div> <div className="description"> {/* <p className="muted">Order code: SS022592000</p> */} <br /> <span className="invinsible_hr"></span> <span className="h1">Waste Bag Pickup</span> <p className="blur">Type: Standard plastic bag</p> <p className="description-text">Select quantity according to plastic bag in description.</p> <p className="blur">Bag size: 0.5m x 0.5m</p> <span className="h1">₦{price}.00</span> <div className="quantity-wrapper"> <div className="increase_wrapper"> <span className="incremento"> <button type="button" name="button" id="minus" onClick={this.handleChange} className="but"><span id="minus" role="img" aria-label="minus"> &#10134;</span></button> <label htmlFor="quantity"></label> <span className="quantity">{quantity}</span> {/* <Input type="text" id="quantity" maxLength="3" value={'100'} name="location" className="quantity" /> */} <button type="button" name="button" id="plus" onClick={this.handleChange} className="but"><span id="plus" role="img" aria-label="plus"> &#10133;</span></button> </span> </div> <button id="del" className="btn-remove uppercase" onClick={this.handleChange}><span id="del" role="img" aria-label="del">&#128465; del</span></button> </div> </div> </div> <div className="bag-total"> <div className="subtotal"> <p className="">Subtotal:</p> <p className="">₦{price}.00</p> </div> <div className="delivery"> <p className="">Pickup in (8 working days):</p> <p className="">₦{transportFee}.00</p> </div> <hr /> <div className="total"> <h3>Total:</h3> <h3>₦{total}.00</h3> </div> <Link to="/order/summary"><button className="btn-go-checkout uppercase"> Checkout</button></Link> </div> </div> </Row> </React.Fragment> ) } }
JavaScript
class DcClient extends AbstractClient { constructor(credential, region, profile) { super("dc.tencentcloudapi.com", "2018-04-10", credential, region, profile); } /** * This API is used to disable a public IP address of internet tunnels. * @param {DisableInternetAddressRequest} req * @param {function(string, DisableInternetAddressResponse):void} cb * @public */ DisableInternetAddress(req, cb) { let resp = new DisableInternetAddressResponse(); this.request("DisableInternetAddress", req, resp, cb); } /** * This API is used to query connection access points. * @param {DescribeAccessPointsRequest} req * @param {function(string, DescribeAccessPointsResponse):void} cb * @public */ DescribeAccessPoints(req, cb) { let resp = new DescribeAccessPointsResponse(); this.request("DescribeAccessPoints", req, resp, cb); } /** * This API is used to modify connection attributes. * @param {ModifyDirectConnectAttributeRequest} req * @param {function(string, ModifyDirectConnectAttributeResponse):void} cb * @public */ ModifyDirectConnectAttribute(req, cb) { let resp = new ModifyDirectConnectAttributeResponse(); this.request("ModifyDirectConnectAttribute", req, resp, cb); } /** * This API is used to create a dedicated tunnel. * @param {CreateDirectConnectTunnelRequest} req * @param {function(string, CreateDirectConnectTunnelResponse):void} cb * @public */ CreateDirectConnectTunnel(req, cb) { let resp = new CreateDirectConnectTunnelResponse(); this.request("CreateDirectConnectTunnel", req, resp, cb); } /** * This API is used to delete a connection. Only connected connections can be deleted. * @param {DeleteDirectConnectRequest} req * @param {function(string, DeleteDirectConnectResponse):void} cb * @public */ DeleteDirectConnect(req, cb) { let resp = new DeleteDirectConnectResponse(); this.request("DeleteDirectConnect", req, resp, cb); } /** * This API is used to accept an application for a dedicated tunnel. * @param {AcceptDirectConnectTunnelRequest} req * @param {function(string, AcceptDirectConnectTunnelResponse):void} cb * @public */ AcceptDirectConnectTunnel(req, cb) { let resp = new AcceptDirectConnectTunnelResponse(); this.request("AcceptDirectConnectTunnel", req, resp, cb); } /** * This API is used to obtain the public IP address assignment statistics of internet tunnels. * @param {DescribeInternetAddressStatisticsRequest} req * @param {function(string, DescribeInternetAddressStatisticsResponse):void} cb * @public */ DescribeInternetAddressStatistics(req, cb) { let resp = new DescribeInternetAddressStatisticsResponse(); this.request("DescribeInternetAddressStatistics", req, resp, cb); } /** * This API is used to delete a dedicated tunnel. * @param {DeleteDirectConnectTunnelRequest} req * @param {function(string, DeleteDirectConnectTunnelResponse):void} cb * @public */ DeleteDirectConnectTunnel(req, cb) { let resp = new DeleteDirectConnectTunnelResponse(); this.request("DeleteDirectConnectTunnel", req, resp, cb); } /** * This API is used to apply for an internet tunnel’s CIDR block. * @param {ApplyInternetAddressRequest} req * @param {function(string, ApplyInternetAddressResponse):void} cb * @public */ ApplyInternetAddress(req, cb) { let resp = new ApplyInternetAddressResponse(); this.request("ApplyInternetAddress", req, resp, cb); } /** * This API is used to enable a public IP address for internet tunnels. * @param {EnableInternetAddressRequest} req * @param {function(string, EnableInternetAddressResponse):void} cb * @public */ EnableInternetAddress(req, cb) { let resp = new EnableInternetAddressResponse(); this.request("EnableInternetAddress", req, resp, cb); } /** * This API is used to obtain the public IP quota of internet tunnels. * @param {DescribeInternetAddressQuotaRequest} req * @param {function(string, DescribeInternetAddressQuotaResponse):void} cb * @public */ DescribeInternetAddressQuota(req, cb) { let resp = new DescribeInternetAddressQuotaResponse(); this.request("DescribeInternetAddressQuota", req, resp, cb); } /** * This API is used to obtain the public IP address of an internet tunnel. * @param {DescribeInternetAddressRequest} req * @param {function(string, DescribeInternetAddressResponse):void} cb * @public */ DescribeInternetAddress(req, cb) { let resp = new DescribeInternetAddressResponse(); this.request("DescribeInternetAddress", req, resp, cb); } /** * This API is used to query the list of dedicated tunnels. * @param {DescribeDirectConnectTunnelsRequest} req * @param {function(string, DescribeDirectConnectTunnelsResponse):void} cb * @public */ DescribeDirectConnectTunnels(req, cb) { let resp = new DescribeDirectConnectTunnelsResponse(); this.request("DescribeDirectConnectTunnels", req, resp, cb); } /** * This API is used to apply for a connection. When calling this API, please note that: You need to complete identity verification for your account; otherwise, you cannot apply for a connection; If there is any connection in arrears under your account, you cannot apply for more connections. * @param {CreateDirectConnectRequest} req * @param {function(string, CreateDirectConnectResponse):void} cb * @public */ CreateDirectConnect(req, cb) { let resp = new CreateDirectConnectResponse(); this.request("CreateDirectConnect", req, resp, cb); } /** * This API is used to reject an application for a dedicated tunnel. * @param {RejectDirectConnectTunnelRequest} req * @param {function(string, RejectDirectConnectTunnelResponse):void} cb * @public */ RejectDirectConnectTunnel(req, cb) { let resp = new RejectDirectConnectTunnelResponse(); this.request("RejectDirectConnectTunnel", req, resp, cb); } /** * This API is used to query the list of connections. * @param {DescribeDirectConnectsRequest} req * @param {function(string, DescribeDirectConnectsResponse):void} cb * @public */ DescribeDirectConnects(req, cb) { let resp = new DescribeDirectConnectsResponse(); this.request("DescribeDirectConnects", req, resp, cb); } /** * This API is used to release an IP address of internet tunnels. * @param {ReleaseInternetAddressRequest} req * @param {function(string, ReleaseInternetAddressResponse):void} cb * @public */ ReleaseInternetAddress(req, cb) { let resp = new ReleaseInternetAddressResponse(); this.request("ReleaseInternetAddress", req, resp, cb); } /** * This API is used to modify the dedicated tunnel attributes. * @param {ModifyDirectConnectTunnelAttributeRequest} req * @param {function(string, ModifyDirectConnectTunnelAttributeResponse):void} cb * @public */ ModifyDirectConnectTunnelAttribute(req, cb) { let resp = new ModifyDirectConnectTunnelAttributeResponse(); this.request("ModifyDirectConnectTunnelAttribute", req, resp, cb); } }
JavaScript
class Server { //Es un metodo que se ejecuta por la instancia del servidor constructor() { //Almacenamos "express" en el atributo "app" this.app = express_1.default(); //Ejecutamos el metodo "configuracion" this.configuracion(); //Ejecutamos el metodo middleware this.middleware(); //Ejecutamos el metodo "routes" this.routes(); } //Mmetodo que permite realizar ajustes configuracion() { //Busca algun puerto disponible para utilizar y en el caso que no lo encuentre, utilizamos el puerto 3000 por defecto y se almacena en el atributo "app" this.app.set('port', process.env.port || 3000); } //Metodo que permite darles uso a las rutas routes() { //Le damos uso al enrutadorIndex this.app.use(index_route_1.default); this.app.use(catgasto_route_1.default); this.app.use(gasto_route_1.default); this.app.use(categoria_route_1.default); this.app.use(producto_route_1.default); this.app.use(venta_impaga_paga_routes_1.default); this.app.use(venta_route_1.default); this.app.use(localidad_route_1.default); this.app.use(provincia_route_1.default); this.app.use(vendedor_route_1.default); this.app.use(autenticacion_route_1.default); this.app.use(venta_detalle_routes_1.default); } //Metodo donde se realizan las configuraciones extras middleware() { //Especificamos que "app" use formato "json" this.app.use(express_1.default.json()); this.app.use(cors_1.default()); this.app.use(morgan_1.default('dev')); } //Metodo encargado de correr el servidor bajo un puerto determinado listen() { //Introducimos la funcion "listen" en el atributo y declaramos que corra en el puerto 3000 this.app.listen(3000); //Es un mensaje que aparecera si se ejecuta el puerto de forma correcta console.log('Servidor corriendo en el puerto 3000'); } }
JavaScript
class Connector { constructor() { if(new.target.name === "Connector") // On the edge ^_^ throw "Connector shouldnt be instanciated (abstract)"; } get infos () { return { name: 'undefined', serviceId: 'undefined', oauthOptions: {} }; }; get redirectUrl () { var redirect_uri = Config.host + '/api/auth/callback?serviceId=' + this.infos.serviceId; return redirect_uri; }; askLogin(req, res, state) { var url = this.infos.oauthOptions.authorizeUrl; var getParams = this.getLoginPageParams_s(state); res.redirect(url + '?' + querystring.stringify(getParams)); }; authCallback(req, res) { if(req.query.error) { Errors.sendError(res, "AUTH_ERROR", req.query.error_description); return; } var self = this; var code = req.query.code || null; var requestObject = this.getTokenRequest_s(code); request(requestObject, function(error, response, body) { if (!error && response.statusCode === 200) { var connectionData = self.getConnectionData_s(body); req.user.setConnection(self, connectionData); self.getUserInfo_s(req.user, function(userInfo) { req.user.setUserInfo(self, body); }); res.redirect('/'); } else { } }); }; logout(user, cb) { user.unsetConnection(this); cb(null); }; getPlaylistList (user, cb) { this.getPlaylistList_s(user, function(err, playlists_s) { cb(err, playlists_s); }) }; ///////////////////////////////////////////////// // Abstract methods to override getLoginPageParams_s() {} getTokenRequest_s() {} getConnectionData_s() {} getUserInfo_s() {} playlistListConverter_s() {} getPlaylistList_s() {} }
JavaScript
class EtablissementMutualisateurController { /** * Show a list of all etablissementmutualisateurs. * GET etablissementmutualisateurs * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index({ request, response, view }) { try { const query = request.get() let sqlConditions = '' let motCles = [] for (let i = 0; i < Object.keys(query).length; i++) { let field = Object.keys(query)[i] let criterion = Object.values(query)[i] if (criterion === "") { motCles.push(field) } else { switch (field) { case "type_marche": sqlConditions = sqlConditions + `ocga_mutualisateurs.${criterion} = 1 AND ` break case "region": sqlConditions = sqlConditions + `etablissements.region = '${criterion}' AND ` break case "academie": sqlConditions = sqlConditions + `etablissements.academie = '${criterion}' AND ` break case "departement": sqlConditions = sqlConditions + `ocga_mutualisateurs_departements.departement = '${criterion}' AND ` break case "nom": sqlConditions = sqlConditions + `etablissements.nom LIKE '%${criterion}%' AND ` break case "code_uai": sqlConditions = sqlConditions + `ocga_mutualisateurs.code_uai = '${criterion}' AND ` break } } } if (sqlConditions !== '' && motCles.length === 0) { sqlConditions = sqlConditions.slice(0, -4) } if (motCles.length > 0) { let sqlMotsClesConditions = "" for (let j = 0; j < motCles.length; j++) { sqlMotsClesConditions = sqlMotsClesConditions + `ocga_mots_cles.mot_cle = '${motCles[j]}' OR ` } sqlMotsClesConditions = sqlMotsClesConditions.slice(0, -3) sqlConditions = sqlConditions + " (" + sqlMotsClesConditions + ")" } let sqlQuery = ` select COUNT(ocga_mutualisateurs.code_uai), ocga_mutualisateurs.code_uai, email, nombre_adherents, eple, autres_admins_publiques, ville_couverte, services, fournitures, ocga_mutualisateurs.infos_complementaires, ocga_mutualisateurs.up_to_date, ocga_mutualisateurs.status, nom, adresse, code_postal, commune, etablissements.departement, region, academie, ocga_mutualisateurs.telephone from ocga_mutualisateurs inner join etablissements ON etablissements.code_uai = ocga_mutualisateurs.code_uai left join ocga_mutualisateurs_departements ON ocga_mutualisateurs.code_uai = ocga_mutualisateurs_departements.code_uai left join ocga_mutualisateurs_mots_cles on ocga_mutualisateurs_mots_cles.code_uai = ocga_mutualisateurs.code_uai left join ocga_mots_cles on ocga_mots_cles.id = ocga_mutualisateurs_mots_cles.id_mot_cle WHERE (ocga_mutualisateurs.status = 'added' OR ocga_mutualisateurs.status = 'deletePending') AND ${sqlConditions} group by code_uai ` console.log("SQL QUERY : ", sqlQuery) let data = Database .raw(sqlQuery) return await data } catch (error) { return "Error: " + error } } /** * Render a form to be used for creating a new etablissementmutualisateur. * GET etablissementmutualisateurs/create * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async create({ request, response, view }) { } async storeOrUpdate({ request, response, storeOrUpdate }) { const { isAdminLogged, code_uai, email, nombre_adherents, type_adherents, zone_de_couverture, zone_de_couverture_code_postal, zone_de_couverture_departement, zone_de_couverture_departements, type_marche, mots_cles_fournitures, mots_cles_services, propositions_mots_cles_fournitures, propositions_mots_cles_services, infos_complementaires, nom, adresse, code_postal, commune, telephone, region, academie, departement } = request.all() try { let etablissement = await Database .table('etablissements') .where('code_uai', code_uai) .first() if (etablissement) { await Database .table('etablissements') .where('code_uai', code_uai) .update({ nom, adresse, code_postal, commune, region, academie, departement }) } else { response.noContent('L’établissement n’existe pas dans la base') return "response: " + response } } catch (error) { return "Error: " + error } try { let Etablissement = (storeOrUpdate === "store") ? new EtablissementMutualisateur() : await EtablissementMutualisateur.findBy("code_uai", code_uai) Etablissement.code_uai = code_uai Etablissement.email = email Etablissement.telephone = telephone Etablissement.nombre_adherents = nombre_adherents Etablissement.eple = ((type_adherents === "1" || type_adherents === "3") ? 1 : 0) Etablissement.autres_admins_publiques = ((type_adherents === "2" || type_adherents === "3") ? 1 : 0) if (zone_de_couverture_code_postal) { Etablissement.ville_couverte = zone_de_couverture_code_postal } Etablissement.services = ((type_marche === "2" || type_marche === "3") ? 1 : 0) Etablissement.fournitures = ((type_marche === "1" || type_marche === "3") ? 1 : 0) Etablissement.infos_complementaires = infos_complementaires let status if (storeOrUpdate === "update" || isAdminLogged) { status = STATUSES[0] } else { status = STATUSES[1] } Etablissement.status = status await Etablissement.save() } catch (error) { return "Error: " + error } try { await Database.raw('DELETE FROM ocga_mutualisateurs_mots_cles where code_uai = ?', [code_uai]) } catch (error) { return "Error: " + error } if ((type_marche === "1" || type_marche === "3") && mots_cles_fournitures.length > 0) { try { for (let i = 0; i < mots_cles_fournitures.length; i++) { await Database .raw(`INSERT INTO ocga_mutualisateurs_mots_cles VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, mots_cles_fournitures[i], code_uai]) } } catch (error) { return "Error: " + error } } if ((type_marche === "2" || type_marche === "3") && mots_cles_services.length > 0) { try { for (let i = 0; i < mots_cles_services.length; i++) { await Database .raw(`INSERT INTO ocga_mutualisateurs_mots_cles VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, mots_cles_services[i], code_uai]) } } catch (error) { return "Error: " + error } } if (propositions_mots_cles_fournitures.length > 0) { try { for (let i = 0; i < propositions_mots_cles_fournitures.length; i++) { let MotCle = await MotsCle.findBy("mot_cle", propositions_mots_cles_fournitures[i]) if (!MotCle) { let MotCle = new MotsCle() MotCle.mot_cle = propositions_mots_cles_fournitures[i] MotCle.categorie = 1 MotCle.status = "addPending" await MotCle.save() await Database.raw(`INSERT INTO ocga_mutualisateurs_mots_cles VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, MotCle.id, code_uai]) } else { await Database.raw(`INSERT INTO ocga_mutualisateurs_mots_cles VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, MotCle.id, code_uai]) } } } catch (error) { return "Error: " + error } } if (propositions_mots_cles_services.length > 0) { try { for (let i = 0; i < propositions_mots_cles_services.length; i++) { let MotCle = await MotsCle.findBy("mot_cle", propositions_mots_cles_services[i]) if (!MotCle) { let MotCle = new MotsCle() MotCle.mot_cle = propositions_mots_cles_services[i] MotCle.categorie = 2 MotCle.status = "addPending" await MotCle.save() await Database.raw(`INSERT INTO ocga_mutualisateurs_mots_cles VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, MotCle.id, code_uai]) } else { await Database.raw(`INSERT INTO ocga_mutualisateurs_mots_cles VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, MotCle.id, code_uai]) } } } catch (error) { return "Error: " + error } } if (zone_de_couverture) { if (zone_de_couverture_departement) { try { await Database.raw(`UPDATE ocga_mutualisateurs SET ville_couverte = NULL WHERE code_uai = ?`, [code_uai]) } catch (error) { return "Error: " + error } try { await Database.raw(`DELETE FROM ocga_mutualisateurs_departements WHERE code_uai = ?`, [code_uai]) } catch (error) { return "Error: " + error } try { await Database.raw(`INSERT INTO ocga_mutualisateurs_departements VALUES (?, ?) `, [code_uai, zone_de_couverture_departement]) } catch (error) { return "Error: " + error } } else if (zone_de_couverture_code_postal) { try { await Database.raw(`INSERT INTO ocga_mutualisateurs_departements VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, departement, code_uai]) } catch (error) { return "Error: " + error } } else if (zone_de_couverture_departements && zone_de_couverture_departements.length > 0) { try { await Database.raw(`UPDATE ocga_mutualisateurs SET ville_couverte = NULL WHERE code_uai = ?`, [code_uai]) } catch (error) { return "Error: " + error } try { await Database.raw(`DELETE FROM ocga_mutualisateurs_departements WHERE code_uai = ?`, [code_uai]) } catch (error) { return "Error: " + error } try { for (let i = 0; i < zone_de_couverture_departements.length; i++) { await Database.raw(`INSERT INTO ocga_mutualisateurs_departements VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, zone_de_couverture_departements[i], code_uai]) } } catch (error) { return "Error: " + error } } } else { try { await Database.raw(`INSERT INTO ocga_mutualisateurs_departements VALUES (?, ?) ON DUPLICATE KEY UPDATE code_uai = ? `, [code_uai, departement, code_uai]) } catch (error) { return "Error: " + error } } return "response: " + response } /** * Create/save a new etablissementmutualisateur. * POST etablissementmutualisateurs * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store({ request, response }) { return this.storeOrUpdate({ request, response, storeOrUpdate: "store" }) } /** * Display a single etablissementmutualisateur. * GET etablissementmutualisateurs/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show({ params, request, response, view }) { try { let etablissement = await Database.raw(` select *, ocga_mutualisateurs.telephone as thisPhone from ocga_mutualisateurs inner join etablissements ON etablissements.code_uai = ocga_mutualisateurs.code_uai where ocga_mutualisateurs.code_uai = ? `, [params.code_uai]) let departements = await this.getDepartements({ params: { code_uai: params.code_uai } }) let motsCles = await this.getMotsCles({ params: { code_uai: params.code_uai } }) return { etablissement, departements, motsCles } // return etablissement } catch (error) { return "Error: " + error } } /** * Render a form to update an existing etablissementmutualisateur. * GET etablissementmutualisateurs/:id/edit * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async edit({ params, request, response, view }) { } /** * Update etablissementmutualisateur details. * PUT or PATCH etablissementmutualisateurs/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update({ params, request, response }) { const query = request.all() if (!("upToDateOnly" in query)) { let update = await this.storeOrUpdate({ request, response, storeOrUpdate: "update" }) } let date = new Date(); let month = (date.getUTCMonth() + 1) < 10 ? "0" + (date.getUTCMonth() + 1) : (date.getUTCMonth() + 1) let timestamp = date.getUTCFullYear() + "-" + month + "-" + date.getUTCDate() try { await Database .table('ocga_mutualisateurs') .where('code_uai', params.code_uai) .update('up_to_date', timestamp) } catch (error) { return "Error: " + error } return "all good" } /** * Delete a etablissementmutualisateur with id. * DELETE etablissementmutualisateurs/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy({ params, request, response }) { } async getDepartements({ params }) { try { return await Database .raw(`select departement from ocga_mutualisateurs_departements where code_uai = ?`, [params.code_uai]) } catch (error) { return "Error: " + error } } async getMotsCles({ params }) { try { return await Database .raw(`select * from ocga_mutualisateurs_mots_cles inner join ocga_mots_cles on ocga_mots_cles.id = ocga_mutualisateurs_mots_cles.id_mot_cle where ocga_mutualisateurs_mots_cles.code_uai = ?`, [params.code_uai]) } catch (error) { return "Error: " + error } } }
JavaScript
class JiraIssue { /** * Constructor runs all necessary processing for issue card. * * @param {HTMLElement} issue Issue card in DOM */ constructor(issue) { this.issue = $(issue); // Remove useless parts of card this.removeNoneRows(); this.hideDays(); this.removeProgress(); this.removeNormalPriority(); // CSS tweaks (font-size, padding...) this.cssIssue(); this.cssLabels(); this.cssFixVersion(); this.cssAvatar(); // New features this.aging(); this.colorLabels(); this.highlightMyTask(); } /** * Remove "None" rows of card. */ removeNoneRows() { // Browse every extra field row and remove "None" ones this.issue.find('.ghx-extra-field').each((x, elementRow) => { let row = $(elementRow); if (row.text() === 'None') { row.remove(); } }); } /** * Do basic CSS card tweaks. */ cssIssue() { this.issue.find('.ghx-issue-content').css(CONFIG.cssIssueContent); // General issue style this.issue.find('.ghx-summary').css(CONFIG.cssIssueSummary); // Issue text this.issue.find('.aui-label[data-epickey]').css(CONFIG.cssEpic); // Epic label style this.issue.find('.ghx-highlighted-fields, .ghx-extra-fields').css(CONFIG.cssExtraFields); this.issue.find('.ghx-type, .ghx-flags').css({ // Move flags 'left': '5px', }); } cssLabels() { // Labels: style this.issue.find('[data-tooltip^="Labels"]').css(CONFIG.cssLabels); // Labels: normalize letter case this.issue.find('[data-tooltip^="Labels"]').each((x, elementRow) => { let label = $(elementRow); label.text(label.text().toUpperCase()); }); } /** * Edit styles of "Fixed Version" card tag. */ cssFixVersion() { this.issue.find('[data-tooltip^="Fix"]').each((x, elementRow) => { $(elementRow).css(CONFIG.cssFixVersion); }); } /** * Color issue labels. */ colorLabels() { // Each labels field... this.issue.find('[data-tooltip^=Labels]').each((i, element) => { let labelsElement = $(element); let labels = labelsElement.text(); labels = labels.replace(',', ''); // Remove comma separator for labels // Loop through each label and set span color for it for (let [key, value] of Object.entries(CONFIG.labelsColors)) { labels = labels.replace(key, '<span style="padding: 4px; background: ' + value + '">' + key + '</span>'); } labelsElement.html(labels); }); } /** * Change avatar style */ cssAvatar() { // Avatar: default avatar size this.issue.find('.ghx-avatar img').css(CONFIG.cssAvatar); // Avatar: wider card content if no avatar is assigned if (this.issue.find('.ghx-avatar img').length === 0) { this.issue.find('.ghx-issue-fields').css({ 'padding': '0px', }); } else { this.issue.find('.ghx-issue-fields').css({ 'padding-right': '30px', }); } } /** * Hide days indicator. */ hideDays() { this.issue.find('.ghx-days').hide(); } /** * Removed planned and logged time progress. */ removeProgress() { this.issue.find('[data-tooltip*="Progress"]').remove(); // Time: remove logged time from card } /** * Remove normal priority indicator. */ removeNormalPriority() { this.issue.find('.ghx-priority[title=Normal').remove(); } /** * Change opacity for old issues. */ aging() { const agingMinimalOpacity = CONFIG.agingMinimalOpacity; if (agingMinimalOpacity < 1.0) { let age = parseInt(this.issue.find('.ghx-days').attr('title')); let opacity = 1 - (age / 100 * 2); this.issue.css({ 'opacity': opacity <= agingMinimalOpacity ? agingMinimalOpacity : opacity, }); } } /** * Highlight current user's issues. */ highlightMyTask() { let logged = $('#header-details-user-fullname').attr('data-displayname'); let assignee = this.issue.find('.ghx-avatar-img').attr('data-tooltip'); if (typeof assignee !== 'undefined' && assignee.indexOf(logged) !== -1) { this.issue.css(CONFIG.myIssueHighlight); } } }
JavaScript
class LambdaContext { /** * @param {Object} [contextInfo = { * functionName: "__lambda_function_name__", * alias: null * } ] Additional context info that will be used to generate the * lambda context. If omitted, a default object will be generated. * If the functionName property begins with "arn:", it will be * used as specified. Otherwise, the name will be appended to an * autogenerated arn prefix. */ constructor(contextInfo) { if(!contextInfo || typeof contextInfo !== 'object') { contextInfo = {}; } contextInfo.functionName = contextInfo.functionName || DEFAULT_FUNCTION_NAME; contextInfo.invokedFunctionArn = contextInfo.invokedFunctionArn || `${DEFAULT_ARN_PREFIX}:${contextInfo.functionName}`; contextInfo.functionVersion = contextInfo.functionVersion || DEFAULT_FUNCTION_VERSION; this._env = 'na'; if(typeof contextInfo.alias === 'string' && contextInfo.alias.length > 0) { contextInfo.invokedFunctionArn = `${contextInfo.invokedFunctionArn}:${contextInfo.alias}`; if(contextInfo.alias !== '$LATEST') { this._env = contextInfo.alias; } delete contextInfo.alias; } this._context = {}; for(let prop in contextInfo) { this._context[prop] = contextInfo[prop]; } } /** * Gets a reference to the mock aws context object for AWS Lambda functions. * * @return {Object} Reference to the context object. */ get context() { return this._context; } /** * Gets a reference to the current lambda env, derived from the invocation arn. * * @return {String} The current lambda environment */ get env() { return this._env; } }
JavaScript
class ReceivedDocumentItemsListItem { /** * Constructs a new <code>ReceivedDocumentItemsListItem</code>. * @alias module:model/ReceivedDocumentItemsListItem */ constructor () { ReceivedDocumentItemsListItem.initialize(this) } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize (obj) { } /** * Constructs a <code>ReceivedDocumentItemsListItem</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ReceivedDocumentItemsListItem} obj Optional instance to populate. * @return {module:model/ReceivedDocumentItemsListItem} The populated <code>ReceivedDocumentItemsListItem</code> instance. */ static constructFromObject (data, obj) { if (data) { obj = obj || new ReceivedDocumentItemsListItem() if (data.hasOwnProperty('id')) { obj.id = ApiClient.convertToType(data.id, 'Number') } if (data.hasOwnProperty('product_id')) { obj.product_id = ApiClient.convertToType(data.product_id, 'Number') } if (data.hasOwnProperty('code')) { obj.code = ApiClient.convertToType(data.code, 'String') } if (data.hasOwnProperty('name')) { obj.name = ApiClient.convertToType(data.name, 'String') } if (data.hasOwnProperty('measure')) { obj.measure = ApiClient.convertToType(data.measure, 'String') } if (data.hasOwnProperty('net_price')) { obj.net_price = ApiClient.convertToType(data.net_price, 'Number') } if (data.hasOwnProperty('category')) { obj.category = ApiClient.convertToType(data.category, 'String') } if (data.hasOwnProperty('qty')) { obj.qty = ApiClient.convertToType(data.qty, 'Number') } if (data.hasOwnProperty('vat')) { obj.vat = VatType.constructFromObject(data.vat) } if (data.hasOwnProperty('stock')) { obj.stock = ApiClient.convertToType(data.stock, 'Number') } } return obj } }
JavaScript
class PreviewButton extends Button { /** * Constructor */ constructor( toolbar ) { super( toolbar, OPTIONS ); this.on( "click", () => { this.toolbar.editor.preview(); }); // Register status update listeners this.toolbar.editor.on( "preview", () => { this.activate( true ); }); this.toolbar.editor.on( "previewExit", () => { this.activate( false ); }); } }
JavaScript
class LogGroup { /** * @param {object} input */ constructor() { this._logs = []; this._childGroups = []; this._isFallbackMode = false; const ffRegex = /Firefox\/(\d*)\.\d*/.exec(navigator.userAgent); if (ffRegex) { try { const ffVersion = parseInt(ffRegex[1], 10); if (ffVersion < 55) { this._isFallbackMode = true; } } catch (err) { this._isFallbackMode = true; } } if (/Edge\/\d*\.\d*/.exec(navigator.userAgent)) { this._isFallbackMode = true; } } /** *@param {object} logDetails */ addPrimaryLog(logDetails) { this._primaryLog = logDetails; } /** *@param {object} logDetails */ addLog(logDetails) { this._logs.push(logDetails); } /** * @param {object} group */ addChildGroup(group) { if (group._logs.length === 0) { return; } this._childGroups.push(group); } /** * prints out this log group to the console. */ print() { if (this._logs.length === 0 && this._childGroups.length === 0) { this._printLogDetails(this._primaryLog); return; } if (this._primaryLog) { if (!this._isFallbackMode) { console.groupCollapsed(...this._getLogContent(this._primaryLog)); } else { this._printLogDetails(this._primaryLog); } } this._logs.forEach((logDetails) => { this._printLogDetails(logDetails); }); this._childGroups.forEach((group) => { group.print(); }); if (this._primaryLog && !this._isFallbackMode) { console.groupEnd(); } } /** * Prints the specific logDetails object. * @param {object} logDetails */ _printLogDetails(logDetails) { const logFunc = logDetails.logFunc ? logDetails.logFunc : console.log; logFunc(...this._getLogContent(logDetails)); } /** * Returns a flattened array of message with colors and args. * @param {object} logDetails * @return {Array} Returns an array of arguments to pass to a console * function. */ _getLogContent(logDetails) { let message = logDetails.message; if (this._isFallbackMode && typeof message === 'string') { // Replace the %c value with an empty string. message = message.replace(/%c/g, ''); } let allArguments = [message]; if (!this._isFallbackMode && logDetails.colors) { allArguments = allArguments.concat(logDetails.colors); } if (logDetails.args) { allArguments = allArguments.concat(logDetails.args); } return allArguments; } }
JavaScript
class LogHelper { /** * LogHelper constructor. */ constructor() { this._defaultLogLevel = isDevBuild() ? self.workbox.LOG_LEVEL.debug : self.workbox.LOG_LEVEL.warn; } /** * The most verbose log level. * * @param {Object} options The options of the log. */ log(options) { this._printMessage(self.workbox.LOG_LEVEL.verbose, options); } /** * Useful for logs that are more exceptional that log() * but not severe. * * @param {Object} options The options of the log. */ debug(options) { this._printMessage(self.workbox.LOG_LEVEL.debug, options); } /** * Warning messages. * * @param {Object} options The options of the log. */ warn(options) { this._printMessage(self.workbox.LOG_LEVEL.warn, options); } /** * Error logs. * * @param {Object} options The options of the log. */ error(options) { this._printMessage(self.workbox.LOG_LEVEL.error, options); } /** * Method to print to the console. * @param {number} logLevel * @param {Object} logOptions */ _printMessage(logLevel, logOptions) { if (!this._shouldLogMessage(logLevel, logOptions)) { return; } const logGroups = this._getAllLogGroups(logLevel, logOptions); logGroups.print(); } /** * Print a user friendly log to the console. * @param {numer} logLevel A number from self.workbox.LOG_LEVEL * @param {Object} logOptions Arguments to print to the console * @return {LogGroup} Returns a log group to print to the console. */ _getAllLogGroups(logLevel, logOptions) { const topLogGroup = new LogGroup(); const primaryMessage = this._getPrimaryMessageDetails(logLevel, logOptions); topLogGroup.addPrimaryLog(primaryMessage); if (logOptions.error) { const errorMessage = { message: logOptions.error, logFunc: console.error, }; topLogGroup.addLog(errorMessage); } const extraInfoGroup = new LogGroup(); if (logOptions.that && logOptions.that.constructor && logOptions.that.constructor.name) { const className = logOptions.that.constructor.name; extraInfoGroup.addLog( this._getKeyValueDetails('class', className) ); } if (logOptions.data) { if (typeof logOptions.data === 'object' && !(logOptions.data instanceof Array)) { Object.keys(logOptions.data).forEach((keyName) => { extraInfoGroup.addLog( this._getKeyValueDetails(keyName, logOptions.data[keyName]) ); }); } else { extraInfoGroup.addLog( this._getKeyValueDetails('additionalData', logOptions.data) ); } } topLogGroup.addChildGroup(extraInfoGroup); return topLogGroup; } /** * This is a helper function to wrap key value pairss to a colored key * value string. * @param {string} key * @param {string} value * @return {Object} The object containing a message, color and Arguments * for the console. */ _getKeyValueDetails(key, value) { return { message: `%c${key}: `, colors: [`color: ${LIGHT_BLUE}`], args: value, }; } /** * Helper method to color the primary message for the log * @param {number} logLevel One of self.workbox.LOG_LEVEL * @param {Object} logOptions Arguments to print to the console * @return {Object} Object containing the message and color info to print. */ _getPrimaryMessageDetails(logLevel, logOptions) { let logLevelName; let logLevelColor; switch (logLevel) { case self.workbox.LOG_LEVEL.verbose: logLevelName = 'Info'; logLevelColor = LIGHT_GREY; break; case self.workbox.LOG_LEVEL.debug: logLevelName = 'Debug'; logLevelColor = LIGHT_GREEN; break; case self.workbox.LOG_LEVEL.warn: logLevelName = 'Warn'; logLevelColor = LIGHT_YELLOW; break; case self.workbox.LOG_LEVEL.error: logLevelName = 'Error'; logLevelColor = LIGHT_RED; break; } let primaryLogMessage = `%c🔧 %c[${logLevelName}]`; const primaryLogColors = [ `color: ${LIGHT_GREY}`, `color: ${logLevelColor}`, ]; let message; if (typeof logOptions === 'string') { message = logOptions; } else if (logOptions.message) { message = logOptions.message; } if (message) { message = message.replace(/\s+/g, ' '); primaryLogMessage += `%c ${message}`; primaryLogColors.push(`color: ${DARK_GREY}; font-weight: normal`); } return { message: primaryLogMessage, colors: primaryLogColors, }; } /** * Test if the message should actually be logged. * @param {number} logLevel The level of the current log to be printed. * @param {Object|String} logOptions The options to log. * @return {boolean} Returns true of the message should be printed. */ _shouldLogMessage(logLevel, logOptions) { if (!logOptions) { return false; } let minValidLogLevel = this._defaultLogLevel; if (self && self.workbox && typeof self.workbox.logLevel === 'number') { minValidLogLevel = self.workbox.logLevel; } if (minValidLogLevel === self.workbox.LOG_LEVEL.none || logLevel < minValidLogLevel) { return false; } return true; } }
JavaScript
class CacheableResponse { /** * Creates a new `Plugin` instance, which stores configuration and logic * to determine whether a `Response` object is cacheable or not. * * If multiple criteria are present (e.g. both `statuses` and `headers`), then * the `Response` needs to meet all of the criteria to be cacheable. * * @param {Object} input * @param {Array<Number>} [input.statuses] The status codes that are * checked when determining whether a `Response` is cacheable. * @param {Object<String,String>} [input.headers] The header values that are * checked when determining whether a `Response` is cacheable. */ constructor({statuses, headers} = {}) { atLeastOne({statuses, headers}); if (statuses !== undefined) { isArrayOfType({statuses}, 'number'); } if (headers !== undefined) { isType({headers}, 'object'); } this.statuses = statuses; this.headers = headers; } /** * Checks a response to see whether it's cacheable or not, based on the * configuration of this object. * * @param {Object} input * @param {Response} input.response The response that might be cached. * @param {Request} [input.request] Optionally, the request that led to the * response. * @return {boolean} `true` if the `Response` is cacheable, based on the * configuration of this object, and `false` otherwise. */ isResponseCacheable({request, response} = {}) { isInstance({response}, Response); let cacheable = true; if (this.statuses) { cacheable = this.statuses.includes(response.status); } if (this.headers && cacheable) { cacheable = Object.keys(this.headers).some((headerName) => { return response.headers.get(headerName) === this.headers[headerName]; }); } if (!cacheable) { const data = {response}; if (this.statuses) { data['valid-status-codes'] = JSON.stringify(this.statuses); } if (this.headers) { data['valid-headers'] = JSON.stringify(this.headers); } if (request) { data['request'] = request; } logHelper.debug({ message: `The response does not meet the criteria for being added to the cache.`, data, }); } return cacheable; } }
JavaScript
class CacheableResponsePlugin extends CacheableResponse { /** * A "lifecycle" callback that will be triggered automatically by the * `workbox.runtimeCaching` handlers prior to an entry being added to a cache. * * @private * @param {Object} input * @param {Request} input.request The request that led to the response. * @param {Response} input.response The response that might be cached. * @return {boolean} `true` if the `Response` is cacheable, based on the * configuration of this object, and `false` otherwise. */ cacheWillUpdate({request, response} = {}) { return this.isResponseCacheable({request, response}); } }
JavaScript
class InputEditTemplateComponent extends EditCommunicationComponent { /** * @protected * @param {?} formBuilder */ constructor(formBuilder) { super(); this.formBuilder = formBuilder; this.filterFieldName = 'phrase'; this.filterForm = this.formBuilder.group({ [this.filterFieldName]: [''] }); } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { if (changes.value !== undefined) { this.filterForm.get(this.filterFieldName).setValue(this.value); } } /** * @return {?} */ ngOnInit() { this.observeChanges(); } /** * @return {?} */ ngAfterViewInit() { /** @type {?} */ const inputElement = this.inputRef.nativeElement; this.focusField(inputElement); this.emitValueChange(inputElement.value); fromEvent(inputElement, 'blur') .pipe(this.takeUntil()) .subscribe((/** * @return {?} */ () => { this.unsubscribe(); this.submit(); })); /** @type {?} */ const keyup$ = fromEvent(inputElement, 'keyup'); keyup$ .pipe(filter((/** * @param {?} e * @return {?} */ (e) => e.keyCode === this.ENTER_KEY_CODE)), this.takeUntil()) .subscribe((/** * @return {?} */ () => { this.unsubscribe(); this.submit(); })); keyup$ .pipe(filter((/** * @param {?} e * @return {?} */ (e) => e.keyCode === this.ESC_KEY_CODE)), this.takeUntil()) .subscribe((/** * @return {?} */ () => { this.unsubscribe(); this.cancel(); })); } /** * @param {?} inputElement * @return {?} */ focusField(inputElement) { if (this.focus) { inputElement.focus(); } } /** * @private * @return {?} */ observeChanges() { this.filterForm .controls[this.filterFieldName] .valueChanges .pipe(this.takeUntil()) .subscribe((/** * @param {?} value * @return {?} */ (value) => { this.emitValueChange(value); })); } /** * @private * @param {?} value * @return {?} */ emitValueChange(value) { if (this.valueChanges) { this.valueChanges.emit(value); } } }
JavaScript
class Queue { constructor() { this._queue = null; this._pointer = this._queue; } getUnderlyingList() { return this._queue; } enqueue(value) { const node = new ListNode(value); this._queue = this._queue || node; if (this._pointer) { this._pointer.next = node; } this._pointer = node; } dequeue() { if (!this._queue) { throw Error('the Queue is empty'); } const value = this._queue.value; this._queue = this._queue.next; return value; } }
JavaScript
class NumericStepper extends React.Component { shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { let { label, min, max, step, style, value } = this.props value = clamp(value, min, max) let validate = v => step !== undefined ? Math.round(v * (1 / step)) / (1 / step) : v value = validate(value) let onChange = e => { e.preventDefault() let value = parseFloat(e.currentTarget.value) if (!isNaN(value)) this.props.onChange(validate(value)) } return <div style={{ ...base, display: 'flex', alignItems: 'baseline', ...style }}> <label>{label}</label> <style> {` input[type=number] { -moz-appearance:textfield; } input::-webkit-inner-spin-button, input::-webkit-outer-spin-button{ margin: 0; -webkit-appearance: none; } `} </style> <input type='number' {...this.props} style={defaultStyle} value={value} onInput={onChange} onChange={onChange} ref={ref => (this.domRef = ref)} /> </div> } }
JavaScript
class ChatDAO { /** * Creates a new instance and initializes the in-memory datastore. */ constructor() { this.datastore = require('../data/Datastore'); if (this.datastore.users.length === 0) { this.createDefaultUsers(); } } /** * Searches for a user with the specified username. * * @param {string} username The username of the searched user. * @return {array} An array containing all users with the * specified username. Each element in the returned * array is a userDTO. The array is empty if no matching * users were found. */ findUserByUsername(username) { const foundUsers = []; this.datastore.users.forEach((user) => { if (user.username === username) { foundUsers.push(Object.assign({}, user)); } }); return foundUsers; } /** * Searches for a user with the specified id. * * @param {number} id The id of the searched user. * @return {UserDTO} A UserDTO representing the user with the specified id, * or null if no matching user was found. */ findUserById(id) { const foundUser = this.getUserInDbById(id); if (foundUser === null) { return null; } return Object.assign({}, foundUser); } /** * Updates the user with the id of the specified User object. All fields * present in the specified User object are updated. * * @param {UserDTO} user The new state of the user instance. * @throws Throws an exception if failed to update the user. */ updateUser(user) { const foundUser = this.getUserInDbById(user.id); if (foundUser === null) { throw new WError( { info: { ChatDAO: 'Failed to update user.', username: user.username, }, }, `No user with id ${user.id}.` ); } if (user.username !== null) { foundUser.username = user.username; } if (user.loggedInUntil !== null) { foundUser.loggedInUntil = user.loggedInUntil; } } /** * Creates the specified message. * * @param {string} msg The message to add. * @param {UserDTO} author The message author. * @return {MsgDTO} The newly created message. */ createMsg(msg, author) { const newMsg = new MsgDTO( this.datastore.getNextMsgId(), author.id, msg, null ); this.datastore.msgs.push(newMsg); return Object.assign({}, newMsg); } /** * Searches for a message with the specified id. * * @param {number} id The id of the searched message. * @return {MsgDTO} The message with the specified id, or null if there was * no such message. */ findMsgById(id) { const foundMsg = this.getMsgInDbById(id); if (foundMsg === null) { return null; } return Object.assign({}, foundMsg); } /** * Reads all messages. * * @return {MsgDTO[]} An array containing all messages that are not deleted. * The array will be empty if there are no such messages. */ findAllNotDeletedMsgs() { const notDeletedMsgs = []; this.datastore.msgs.forEach((msg) => { if (msg.deletedAt === null) { notDeletedMsgs.push(Object.assign({}, msg)); } }); return notDeletedMsgs; } /** * Deletes the message with the specified id. * * @param {number} id The id of the message that shall be deleted. * @throws Throws an exception if failed to delete the specified message. */ deleteMsg(id) { const foundMsg = this.getMsgInDbById(id); if (foundMsg === null) { throw new WError( { info: { ChatDAO: 'Failed to delete message.', msg: id, }, }, `No message with id ${id}.` ); } foundMsg.deletedAt = new Date().toDateString(); } /* * Only 'private' helper methods below. */ // eslint-disable-next-line require-jsdoc createDefaultUsers() { this.datastore.users.push(new UserDTO(1, 'stina', null)); this.datastore.users.push(new UserDTO(2, 'nisse', null)); } // eslint-disable-next-line require-jsdoc getUserInDbById(id) { let foundUser = null; this.datastore.users.forEach((user) => { if (user.id === id) { foundUser = user; return; } }); return foundUser; } // eslint-disable-next-line require-jsdoc getMsgInDbById(id) { let foundMsg = null; this.datastore.msgs.forEach((msg) => { if (msg.id === id) { foundMsg = msg; return; } }); return foundMsg; } }
JavaScript
class App extends Component { // keep track of previous in-site location componentWillReceiveProps(nextProps) { if (nextProps.location !== this.props.location) { this.props.setRootState('prevPath', this.props.location) } } // Generate GA pageview when route changes componentDidMount = () => ReactGA.pageview(window.location.pathname) // + window.location.search) componentDidUpdate = () => ReactGA.pageview(window.location.pathname) // + window.location.search) render() { // Use curly brackets to retrieve specific items from an object // const { opened } = this.state // children are passed in index.js, which are the actual subpages const { children } = this.props return ( // className is used to give the div an id <div className="App"> <CssBaseline /> {children} </div> ) } }
JavaScript
class AuthenticateUtils { /** * Private constructor to avoid object instantiation from outside * the class. * * @hideconstructor */ // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } /** * Checks if the logged in user has login scope. * * @return {boolean} True or false. */ static hasLoginPermission(allowedScopes) { const scopes = allowedScopes === null || allowedScopes === void 0 ? void 0 : allowedScopes.split(" "); return scopes === null || scopes === void 0 ? void 0 : scopes.includes(TokenConstants.LOGIN_SCOPE); } /** * Checks if the logged in user has a specific scope. * * @return {boolean} True or false. */ static hasScope(scope, allowedScopes) { const scopes = allowedScopes === null || allowedScopes === void 0 ? void 0 : allowedScopes.split(" "); return scopes === null || scopes === void 0 ? void 0 : scopes.includes(scope); } /** * Get the authentication callback URL from the session storage. * * @param {string} app - The name of the app. * @return {string} Authentication Callback from session. */ static getAuthenticationCallbackUrl(app) { return window.sessionStorage.getItem(`auth_callback_url_${app}`); } /** * Update the authentication callback URL in the session storage. * This is used to improve UX in automatic sign-out scenarios due to session timeouts etc. * * @param {string} app - The name of the app. * @param {string} location - history path. */ static updateAuthenticationCallbackUrl(app, location) { window.sessionStorage.setItem(`auth_callback_url_${app}`, location); } /** * @param {string} app - The name of the app. * Removes the authentication callback URL from the session storage. */ static removeAuthenticationCallbackUrl(app) { window.sessionStorage.removeItem(`auth_callback_url_${app}`); } }
JavaScript
class Container { /** * @param {Map<string, *>|Object} items * * @memberOf Container */ constructor(items) { if (!(items instanceof Map)) { if ('object' !== typeof items) { this.items = new Map(); } else { this.items = this.buildMap(items); } } else { this.items = items; } } /** * * @param {Object} obj * @returns {Map<string, Map<>>} * * @memberOf Container */ buildMap(obj) { let map = new Map(); Object.keys(obj).forEach(key => { map.set(key, obj[key]); }); return map; } /** * * @param {string} key * @param {*} value * * @memberOf Container */ set(key, value) { this.items.set(key, value); } /** * * @param {string} key * @returns * * @memberOf Container */ get(key) { if (!this.items.has(key)) { return null; } return this.items.get(key); } }
JavaScript
class DeeplAutoTranslate extends AutoTranslate { /** * setup api reference to deepl translate to be used as message translation provider. * @constructor */ constructor() { super(); this.name = 'deepl-translate'; this.apiEndPointUrl = 'https://api.deepl.com/v1/translate'; // self register & de-register callback - afterSaveMessage based on the activeProvider RocketChat.settings.get('AutoTranslate_ServiceProvider', (key, value) => { if (this.name === value) { this._registerAfterSaveMsgCallBack(this.name); } else { this._unRegisterAfterSaveMsgCallBack(this.name); } }); } /** * Returns metadata information about the service provide * @private implements super abstract method. * @return {object} */ _getProviderMetadata() { return { name: this.name, displayName: TAPi18n.__('AutoTranslate_DeepL'), settings: this._getSettings() }; } /** * Returns necessary settings information about the translation service provider. * @private implements super abstract method. * @return {object} */ _getSettings() { return { apiKey: this.apiKey, apiEndPointUrl: this.apiEndPointUrl }; } /** * Returns supported languages for translation by the active service provider. * @private implements super abstract method. * @param {string} target * @returns {object} code : value pair */ _getSupportedLanguages(target) { if (this.autoTranslateEnabled && this.apiKey) { if (this.supportedLanguages[target]) { return this.supportedLanguages[target]; } return this.supportedLanguages[target] = [ { 'language': 'EN', 'name': TAPi18n.__('English', {lng: target}) }, { 'language': 'DE', 'name': TAPi18n.__('German', {lng: target}) }, { 'language': 'FR', 'name': TAPi18n.__('French', {lng: target}) }, { 'language': 'ES', 'name': TAPi18n.__('Spanish', {lng: target}) }, { 'language': 'IT', 'name': TAPi18n.__('Italian', {lng: target}) }, { 'language': 'NL', 'name': TAPi18n.__('Dutch', {lng: target}) }, { 'language': 'PL', 'name': TAPi18n.__('Polish', {lng: target}) } ]; } } /** * Send Request REST API call to the service provider. * Returns translated message for each target language in target languages. * @private * @param {object} targetMessage * @param {object} targetLanguages * @returns {object} translations: Translated messages for each language */ _sendRequestTranslateMessage(targetMessage, targetLanguages) { const translations = {}; let msgs = targetMessage.msg.split('\n'); msgs = msgs.map(msg => encodeURIComponent(msg)); const query = `text=${ msgs.join('&text=') }`; const supportedLanguages = this._getSupportedLanguages('en'); targetLanguages.forEach(language => { if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, {language})) { language = language.substr(0, 2); } try { const result = HTTP.get(this.apiEndPointUrl, { params: { auth_key: this.apiKey, target_lang: language }, query }); if (result.statusCode === 200 && result.data && result.data.translations && Array.isArray(result.data.translations) && result.data.translations.length > 0) { // store translation only when the source and target language are different. if (result.data.translations.map(translation => translation.detected_source_language).join() !== language) { const txt = result.data.translations.map(translation => translation.text).join('\n'); translations[language] = this.deTokenize(Object.assign({}, targetMessage, {msg: txt})); } } } catch (e) { SystemLogger.error('Error translating message', e); } }); return translations; } /** * Returns translated message attachment description in target languages. * @private * @param {object} attachment * @param {object} targetLanguages * @returns {object} translated messages for each target language */ _sendRequestTranslateMessageAttachments(attachment, targetLanguages) { const translations = {}; const query = `text=${ encodeURIComponent(attachment.description || attachment.text) }`; const supportedLanguages = this._getSupportedLanguages('en'); targetLanguages.forEach(language => { if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, {language})) { language = language.substr(0, 2); } try { const result = HTTP.get(this.apiEndPointUrl, { params: { auth_key: this.apiKey, target_lang: language }, query }); if (result.statusCode === 200 && result.data && result.data.translations && Array.isArray(result.data.translations) && result.data.translations.length > 0) { if (result.data.translations.map(translation => translation.detected_source_language).join() !== language) { translations[language] = result.data.translations.map(translation => translation.text).join('\n'); } } } catch (e) { SystemLogger.error('Error translating message attachment', e); } }); return translations; } }
JavaScript
class Array { constructor(...args) { /* ... */ } static [Symbol.create]() { // Install special [[DefineOwnProperty]] // to magically update 'length' } }
JavaScript
class DBHelper { static initIDB() { var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB; var open = indexedDB.open('restaurant-db', 1); open.onupgradeneeded = function() { var db = open.result; var store = db.createObjectStore("restaurants", {keyPath: "id"}); var reviews = db.createObjectStore("reviews", {keyPath: "id", autoIncrement: true}); }; return open; } static readIDB(callback) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("restaurants", "readonly"); var store = tx.objectStore("restaurants"); var getRestaurants = store.getAll(); getRestaurants.onsuccess = function() { callback(getRestaurants.result); }; // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; } } static writeIDB(data) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("restaurants", "readwrite"); var store = tx.objectStore("restaurants"); store.put(data); // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; } } static clearIDB() { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var transaction = db.transaction("restaurants", "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { console.log('clearIDB -- Transaction completed.'); }; transaction.onerror = function(event) { console.log('clearIDB -- Transaction not opened due to error: ' + transaction.error); }; // create an object store on the transaction var objectStore = transaction.objectStore("restaurants"); // Make a request to clear all the data out of the object store var objectStoreRequest = objectStore.clear(); objectStoreRequest.onsuccess = function(event) { // report the success of our request console.log('clearIDB -- success'); }; // Close the db when the transaction is done transaction.oncomplete = function() { db.close(); }; } } static readRestaurentReviewsIDB(id, callback) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("reviews", "readonly"); var store = tx.objectStore("reviews"); var getReviews = store.getAll(); console.log('readRestaurentReviewsIDB for restaurant ', id); getReviews.onsuccess = function() { let results = getReviews.result.filter(r => r.restaurant_id == id); console.log('unfiltered reviews: ', getReviews.result); console.log('filtered reviews: ', results); if (results.length == 0) { results = {}; } callback(results); }; // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; } } static readAllReviewsIDB(callback) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("reviews", "readonly"); var store = tx.objectStore("reviews"); var getReviews = store.getAll(); getReviews.onsuccess = function() { callback(getReviews.result); }; // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; } } static writeReviewsIDB(data) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("reviews", "readwrite"); var store = tx.objectStore("reviews"); var showMsg = true; if (data.id != undefined) { showMsg = false; } if (data.updatedAt == undefined) { data['updatedAt'] = new Date(); } console.log('IDB store autoIncrement: ', store.autoIncrement); console.log('review data for IDB: ', data); var updateReviewRequest = store.put(data); updateReviewRequest.onsuccess = function() { if (showMsg == true) { var msg = document.getElementById("msg_success"); msg.style.opacity = "1"; msg.style.display = "block"; } console.log('success storing review!'); }; // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; }; open.onerror = function() { console.log("There has been an error within writeReviewsIDB: " + open.error); var msg = document.getElementById("msg_error"); msg.style.opacity = "1"; msg.style.display = "block"; }; } static deleteReviewByIdIDB(reviewID) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("reviews", "readwrite"); var store = tx.objectStore("reviews"); var deleteRequest = store.delete(reviewID); deleteRequest.onsuccess = function() { console.log('review ', reviewID, ' from IDB deleted'); }; // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; } } static deleteReviewByRestaurantIdIDB(restaurantID) { var open = DBHelper.initIDB(); open.onsuccess = function() { // Start a new transaction var db = open.result; var tx = db.transaction("reviews", "readwrite"); var store = tx.objectStore("reviews"); var getReviews = store.getAll(); console.log('deleteReviewByRestaurantIdIDB for restaurant ', restaurantID); getReviews.onsuccess = function() { getReviews.result.map(function(reviews) { if (reviews['restaurant_id'] == restaurantID) { let reviewID = reviews['id']; var deleteRequest = store.delete(reviewID); deleteRequest.onsuccess = function() { console.log('review ', reviewID, ' from IDB deleted'); }; } }); }; // Close the db when the transaction is done tx.oncomplete = function() { db.close(); }; } } /** * Database URL. * Change this to restaurants.json file location on your server. */ static get DATA_URL() { const port = 1337; // Change this to your server port return `http://localhost:${port}/restaurants`; } static get REVIEWS_GET_URL() { const port = 1337; // Change this to your server port return `http://localhost:${port}/reviews/?restaurant_id=`; } static get REVIEW_POST_URL() { const port = 1337; // Change this to your server port return `http://localhost:${port}/reviews/`; } static get FAVORITE_PUT_URL() { const port = 1337; // Change this to your server port return `http://localhost:${port}/restaurants/<restaurant_id>/?is_favorite=`; } static toggleFavoriteRestaurant(restaurant_id, is_favorite) { let url = DBHelper.FAVORITE_PUT_URL.replace('<restaurant_id>', restaurant_id) + is_favorite; fetch(url, {method: "PUT"}) .then(function() { console.log('success PUT favorite: ', url); }) .catch(function(error) { console.log('error PUT favorite: ', error); }); } /** * Fetch reviews by restaurant_id. */ static fetchReviewsByRestaurantId(id, callback) { DBHelper.readRestaurentReviewsIDB(id, (reviews) => { if (typeof reviews !== 'undefined' && reviews.length > 0) { console.log('reviews for restaurant-', id,' from IDB: ', reviews); callback(null, reviews); } else { console.log('reviews for restaurant-', id,' from API'); fetch(DBHelper.REVIEWS_GET_URL + id, {method: "GET"}) .then((resp) => resp.json()) .then(function(data) { data.map(function(reviews) { reviews['fromAPI'] = true; DBHelper.writeReviewsIDB(reviews); }); console.log('fetched reviews for restaurant-', id, ': ', data); callback(null, data); }) .catch(function(error) { callback(error, null); }); } }); } /** * Fetch all restaurants. */ static fetchRestaurants(callback) { DBHelper.readIDB((restaurants) => { if (typeof restaurants !== 'undefined' && restaurants.length > 0) { console.log('restaurants from IDB'); callback(null, restaurants); } else { console.log('restaurants from API'); fetch(DBHelper.DATA_URL, {method: "GET"}) .then((resp) => resp.json()) .then(function(data) { data.map(restaurant => DBHelper.writeIDB(restaurant)); callback(null, data); }) .catch(function(error) { callback(error, null); }); } }); } /** * Fetch a restaurant by its ID. */ static fetchRestaurantById(id, callback) { // fetch all restaurants with proper error handling. DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { const restaurant = restaurants.find(r => r.id == id); if (restaurant) { // Got the restaurant callback(null, restaurant); } else { // Restaurant does not exist in the database callback('Restaurant does not exist', null); } } }); } /** * Fetch restaurants by a cuisine type with proper error handling. */ static fetchRestaurantByCuisine(cuisine, callback) { // Fetch all restaurants with proper error handling DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Filter restaurants to have only given cuisine type const results = restaurants.filter(r => r.cuisine_type == cuisine); callback(null, results); } }); } /** * Fetch restaurants by a neighborhood with proper error handling. */ static fetchRestaurantByNeighborhood(neighborhood, callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Filter restaurants to have only given neighborhood const results = restaurants.filter(r => r.neighborhood == neighborhood); callback(null, results); } }); } /** * Fetch restaurants by a cuisine and a neighborhood with proper error handling. */ static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { let results = restaurants if (cuisine != 'all') { // filter by cuisine results = results.filter(r => r.cuisine_type == cuisine); } if (neighborhood != 'all') { // filter by neighborhood results = results.filter(r => r.neighborhood == neighborhood); } callback(null, results); } }); } /** * Fetch all neighborhoods with proper error handling. */ static fetchNeighborhoods(callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Get all neighborhoods from all restaurants const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood) // Remove duplicates from neighborhoods const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i) callback(null, uniqueNeighborhoods); } }); } /** * Fetch all cuisines with proper error handling. */ static fetchCuisines(callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Get all cuisines from all restaurants const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type) // Remove duplicates from cuisines const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i) callback(null, uniqueCuisines); } }); } /** * Restaurant page URL. */ static urlForRestaurant(restaurant) { return (`./restaurant.html?id=${restaurant.id}`); } /** * Restaurant image URL. */ static imageUrlForRestaurant(restaurant) { return (`/img/${restaurant.photograph}`); } /** * Map marker for a restaurant. */ static mapMarkerForRestaurant(restaurant, map) { const marker = new google.maps.Marker({ position: restaurant.latlng, title: restaurant.name, url: DBHelper.urlForRestaurant(restaurant), map: map, animation: google.maps.Animation.DROP} ); return marker; } static postReview(reviewData) { console.log('post review to API'); fetch(DBHelper.REVIEW_POST_URL, { method: 'POST', body: JSON.stringify(reviewData), headers: new Headers({ 'Content-Type': 'application/json' }), cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached // credentials: 'same-origin', // include, same-origin, *omit mode: 'no-cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }) .then(function() { console.log('post-review restaurantID:', reviewData.restaurant_id); DBHelper.deleteReviewByRestaurantIdIDB(reviewData.restaurant_id); var msg = document.getElementById("msg_success"); msg.style.opacity = "1"; msg.style.display = "block"; console.log('success posting review!'); }) .catch(function(error) { var msg = document.getElementById("msg_error"); msg.style.opacity = "1"; msg.style.display = "block"; console.log('error posting review: ', error); }); } static storeReview(reviewData) { console.log('store review in indexedDB'); var response = DBHelper.writeReviewsIDB(reviewData); } static submitStoredReviews() { DBHelper.readAllReviewsIDB((reviews) => { if (typeof reviews !== 'undefined' && reviews.length > 0) { console.log('reviews from IDB:', reviews); reviews.map((review) => { if (review['fromAPI'] == true) { return; } var reviewID = review['id']; delete review['id']; delete review['updatedAt']; console.log('review: ', review); console.log('post stored review to API'); fetch(DBHelper.REVIEW_POST_URL, { method: 'POST', body: JSON.stringify(review), headers: new Headers({ 'Content-Type': 'application/json' }), cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached // credentials: 'same-origin', // include, same-origin, *omit mode: 'no-cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer }) .then(function() { // DBHelper.deleteReviewByIdIDB(reviewID); DBHelper.deleteReviewByRestaurantIdIDB(review.restaurant_id); console.log('success posting stored review!'); }) .catch(function(error) { console.log('error posting stored review: ', error); }); }); } else { console.log('no stored reviews in IDB'); } }); } }
JavaScript
class x0x { constructor() { this.patterns = {} this.steps = 0; } trig(name, pat, func) { if(this.patterns[name] === undefined) { this.patterns[name] = {}; } if(typeof func === 'function') { this.patterns[name].func = func; } this.patterns[name].trig = pat.replace(/[|\s]/g,""); } mod(what, name, pat) { if(this.patterns[name].mod === undefined) { this.patterns[name].mod = {}; } this.patterns[name].mod[what] = pat.replace(/[|\s]/g,""); } step() { Object.keys(this.patterns).map((p) => { let { trig, func, mod } = this.patterns[p]; let i = this.steps % trig.length; if("-" !== trig[i]) { let opt = { trig: trig[i] }; if (mod !== undefined) { Object.keys(mod).map((m) => { opt[m] = mod[m][this.steps % mod[m].length]; }); } func(opt); } }); this.steps += 1; } reset() { this.steps = 0; } }
JavaScript
class MessageStatus extends ServerPacket_1.ServerPacket { constructor(jsonPacket) { super(jsonPacket); this._type = this.body.$type; this._peer = new Peer_1.Peer(this.body.peer.$type, this.body.peer.id, this.body.peer.accessHash); this._startDate = this.body.startDate; } get type() { return this._type; } get peer() { return this._peer; } get startDate() { return this._startDate; } }
JavaScript
class Field { constructor(domStr, stateKey, type, elementsToTrigger, eventsListeningFor) { this.type = type; this.domStr = domStr; this.stateKey = stateKey; this.element = document.getElementById(domStr); this.elementsToTrigger = []; if (this.type === 'input') { this.elementsToTrigger = elementsToTrigger; this.eventsListeningFor = eventsListeningFor; } else if (this.type === 'text') { this.elementsToTrigger = []; this.eventsListeningFor = ['valueChange']; } } eventHandler() { if (this.type === 'input') { state[this.stateKey] = this.element.value !== '' ? parseFloat(this.element.value) : 0; this.elementsToTrigger.forEach(el => { setTimeout(() => { document.getElementById(el).dispatchEvent(valueChangeEvent) }); }); } else if (this.type === 'text') { this.element.innerText = state[this.stateKey].toFixed(2); } } setupEventListeners() { this.eventsListeningFor.forEach(event => { this.element.addEventListener(event, this.eventHandler.bind(this)); }); } }
JavaScript
class Vec{ constructor(x, y) { this.x = x; this.y = y; } plus(vector) { return new Vec(this.x + vector.x, this.y + vector.y); } minus(vector) { return new Vec(this.x - vector.x, this.y - vector.y); } get length() { return Math.sqrt(this.x ** 2 + this.y ** 2); } }
JavaScript
class CodeFormatter { /** * Formats command code. * @param {string} code - Command code to format. * @returns {string} The formatted command code. */ format(code) { try { let nodes = parser.parse(code); return this._process(nodes).join(''); } catch (e) { return code; } } _process(nodes) { const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1); return nodes.map(node => this[`format${capitalize(node.type)}`](node.text)); } /** * Formats parenthesis. * @param {string} text - Opening or closing parenthesis. * @returns {string} Formatted parenthesis. */ formatParens(text) { return text; } /** * Formats a command name. * @param {string} text - Command name. * @returns {string} Formatted command name. */ formatCommand(text) { return text; } /** * Formats a variable. * @param {string} text - Variable. * @returns {string} Formatted variable. */ formatVariable(text) { return text; } /** * Formats an identifier. * @param {string} text - Identifier. * @returns {string} Formatted identifier. */ formatIdentifier(text) { return text; } /** * Formats a number. * @param {number} num - Number. * @returns {string} Formatted number. */ formatNumber(num) { return num.toString(); } /** * Formats a string. * @param {string} text - String. * @returns {string} Formatted string. */ formatString(text) { return text; } /** * Formats a space (blanks or newlines). * @param {string} text - Space. * @returns {string} Formatted space. */ formatSpace(text) { return text; } /** * Formats a comment. * @param {string} text - Comment text. * @returns {string} Formatted comment. */ formatComment(text) { return text; } }
JavaScript
class OeComponentFieldEditor extends OECommonMixin(PolymerElement) { static get is() { return 'oe-component-field-editor'; } static get template() { return html` <style include="iron-flex iron-flex-alignment"> .section-heading{ padding: 0px 16px; font-size:16px; height:36px; box-shadow: 0px 2px 1px 1px rgba(0, 0, 0, 0.2); background: var(--light-primary-color); } iron-icon{ --iron-icon-width:20px; --iron-icon-height:20px; cursor:pointer; } .section-detail{ padding: 8px 16px; height: 200px; overflow: auto; } .horz-center{ @apply --layout-horizontal; @apply --layout-center; @apply --layout-justified; } oe-data-table{ --oe-data-table-header:{ background: var(--light-primary-color); height:36px; color:#FFF; padding: 0px 16px; font-size:16px; box-shadow: 0px 2px 1px 1px rgba(0, 0, 0, 0.2); } --oe-data-table-header-title:{ color:#FFF; } } .model-fields-list{ box-shadow:-1px 0px 0px 0px rgba(0,0,0,0.2); } .options iron-icon{ margin-left:8px; } .field-item{ padding-bottom: 8px; } </style> <div class="layout vertical"> <oe-data-table id="fieldTable" label="Fields" page-size="4" class="flex" items="{{_fields}}" columns="[[_fieldColumn]]" row-actions="[[_fieldRowActions]]" toolbar-actions="[[_fieldToolbarActions]]" empty-state-message="No Fields found" disable-selection disable-add disable-delete disable-config-editor> </oe-data-table> <div class="layout horizontal start justified flex"> <div class="component-section flex"> <div class="section-heading horz-center"> <label>Excluded fields </label> <div> <iron-icon icon="help-outline"></iron-icon> <paper-tooltip position="left"> <label class="tooltip-helper-text">Fields in excluded list will not be added into the component </label> </paper-tooltip> </div> </div> <div class="section-detail excluded-field-list"> <dom-repeat items=[[_excludedFields]]> <template> <div class="field-item layout horizontal justified center"> <label>[[item]]</label> <div class="options"> <iron-icon icon="clear" on-tap="_removeFromExclude"></iron-icon> <paper-tooltip position="left"> <label class="tooltip-helper-text"> Remove field from Excluded list. </label> </paper-tooltip> </div> </div> </template> </dom-repeat> </div> </div> <div class="component-section flex"> <div class="section-heading horz-center"> <label>Model fields </label> <div> <iron-icon icon="help-outline"></iron-icon> <paper-tooltip position="left"> <label class="tooltip-helper-text"> Fields in this list will be added if "autoInjectFields" flag is true. </label> </paper-tooltip> </div> </div> <div class="section-detail model-fields-list"> <dom-repeat items=[[_modelFields]]> <template> <div class="field-item layout horizontal justified center"> <label>[[item]]</label> <div class="options layout horizontal center"> <div> <iron-icon icon="delete" on-tap="_addToExclude"></iron-icon> <paper-tooltip position="left"> <label class="tooltip-helper-text">Move field to Excluded list.</label> </paper-tooltip> </div> <div> <iron-icon icon="add" on-tap="_addToField"></iron-icon> <paper-tooltip position="left"> <label class="tooltip-helper-text"> Add field to Fields list. </label> </paper-tooltip> </div> </div> </div> </template> </dom-repeat> </div> </div> </div> </div> `; } static get properties() { return { metaData: { type: Object, observer: '_metaDataChanged' }, component: { type: Object, notify:false, value: function () { return {}; } }, containers: { type: Array, value: function () { return []; }, observer: "_containersChanged" } }; } constructor() { super(); this._fieldToolbarActions = [{ "icon": "add", "title": "Add new field", "action": "add-field" }]; this._fieldRowActions = [{ "icon": "create", "title": "Edit field", "action": "edit-field", "formUrl": "/node_modules/oe-component-manager/src/oe-component-field-form.js" }, { "icon": "clear", "title": "Remove field entry", "action": "delete-field" }, { "icon": "arrow-upward", "title": "Move Up", "action": "move-up" }, { "icon": "arrow-downward", "title": "Move down", "action": "move-down" }]; this.addEventListener("oe-data-table-action-add-field", this._addNewField.bind(this)); this.addEventListener("oe-data-table-row-action", this._handleRowEvent.bind(this)); } _metaDataChanged(newVal, oldVal) { if (newVal && newVal !== oldVal) { this._setComponentFields(); } } _setComponentFields(){ var metaData = this.metaData || {}; var fields = []; if (Array.isArray(metaData.fields)) { metaData.fields.forEach(function (field) { if (typeof field === "string") { fields.push({ "fieldId": field }); } else { fields.push(JSON.parse(JSON.stringify(field))); } }); } this.set('_fields', fields); this._excludedFields = metaData.excludeFields || []; this.__computeModelFields(); } __computeModelFields(){ var metaData = this.metaData || {}; var modelFields = []; this._modelName = metaData.modelName; if (!this._modelName) { modelFields = []; } else { var modelObj = metaData.metadata.models[this._modelName]; modelFields = Object.keys(modelObj.properties).filter(function (prop) { var fieldArrIndex = this._fields.findIndex(function(f){ return f.fieldId === prop; }); var excludeArrIndex = this._excludedFields.indexOf(prop); return (fieldArrIndex === -1)&&(excludeArrIndex === -1); }.bind(this)); } this.set('_modelFields', modelFields); } _containersChanged(newVal, oldVal) { if (newVal && newVal !== oldVal) { this._fieldColumn = [{ key: "fieldId", label: "Field Id", type: "string", disableSort: true, disableFilter: true }, { key: "container", label: "Target Selector", type: "string", uiType: "oe-combo", editorAttributes: { "listdata": this.containers }, disableSort: true, disableFilter: true }, { key: "label", label: "Label", type: "string", disableSort: true, disableFilter: true }, { key: "uitype", label: "UI Type", type: "string", disableSort: true, disableFilter: true }]; } } _addNewField() { this.push("_fields",{ "fieldId": "field"+this._fields.length }); } _handleRowEvent(event) { var action = event.detail.action.action; var rowIdx = event.detail.rowIndex; var array = this._fields; var row; switch (action) { case "delete-field": array.splice(rowIdx, 1); this.__computeModelFields(); break; case "move-up": if (rowIdx !== 0) { row = array.splice(rowIdx, 1)[0]; array.splice(rowIdx - 1, 0, row); } break; case "move-down": if (rowIdx !== array.length - 1) { row = array.splice(rowIdx, 1)[0]; array.splice(rowIdx + 1, 0, row); } break; default: return; } this.set("_fields", array.slice()); } _addToExclude(event){ var field = event.model.item; var index = event.model.index; this.splice("_modelFields",index,1); this.push("_excludedFields",field); } _addToField(event){ var field = event.model.item; var index = event.model.index; this.splice("_modelFields",index,1); this.push("_fields",{ "fieldId":field }); } _removeFromExclude(event){ var index = event.model.index; this.splice("_excludedFields",index,1); this.__computeModelFields(); } _getField(){ var component={ fields:this._fields, excludeFields : this._excludedFields }; return { valid:true, result:component }; } _configField(fieldName) { var fieldObj = this.$.fieldTable.items.find(function (item) { return item.fieldId === fieldName; }); this.$.fieldTable.fire("oe-data-table-row-form-load", { "url": "/node_modules/oe-component-manager/src/oe-component-field-form.js", "model": fieldObj }); } }
JavaScript
class Massas { constructor(nome,preco,quantidade){ // 2 - Declarando o método constructor this.name = nome; // 2.1 - definindo os atributos e passando os parâmetros this.price = preco; this.quantity = quantidade; } // 3 - Definindo um método para exibição dos itens que comporão a tabela tabelaPrecos(){ return `Produto: ${this.name} ...... Preço: R$ ${this.price.toFixed(2)} (${this.quantity})` } }
JavaScript
class VaultAPIRequest { // TODO: Parameterize this constructor(publicAPIKey, secretAPIKey) { _defineProperty(this, "publicAPIKey", void 0); _defineProperty(this, "secretAPIKey", void 0); this.publicAPIKey = publicAPIKey; this.secretAPIKey = secretAPIKey; } getAuthorizationHeader(key) { const base64AuthToken = Buffer.from(key).toString("base64"); return `Basic ${base64AuthToken}`; } getAPIKey(keyType) { return keyType === "SECRET" ? this.secretAPIKey : this.publicAPIKey; } getHTTPRequest(key) { return new _.HTTPRequest({ authorization: this.getAuthorizationHeader(key), baseUrl: VaultAPIRequest.BASE_URL }); } get(keyType, uri, payload) { const key = this.getAPIKey(keyType); const httpRequest = this.getHTTPRequest(key); return httpRequest.get(uri, payload); } post(keyType, uri, payload) { const key = this.getAPIKey(keyType); const httpRequest = this.getHTTPRequest(key); return httpRequest.post(uri, payload); } put(keyType, uri, payload) { const key = this.getAPIKey(keyType); const httpRequest = this.getHTTPRequest(key); return httpRequest.put(uri, payload); } delete(keyType, uri, payload) { const key = this.getAPIKey(keyType); const httpRequest = this.getHTTPRequest(key); return httpRequest.delete(uri, payload); } }
JavaScript
class LazyRepeatProvider { /** * @param {Element} wrapperElement * @param {LazyRepeatDelegate} delegate */ constructor(wrapperElement, delegate) { this._wrapperElement = util.validated('wrapperElement', wrapperElement, Element); this._delegate = util.validated('delegate', delegate, LazyRepeatDelegate); if (wrapperElement.tagName.toLowerCase() === 'ons-list') { wrapperElement.classList.add('lazy-list'); } // to be removed soon this._pageContent = util.findParent(wrapperElement, '.ons-scroller__content'); if (!this._pageContent) { this._pageContent = util.findParent(wrapperElement, '.page__content'); } if (!this._pageContent) { throw new Error('ons-lazy-repeat must be a descendant of an <ons-page> or an <ons-scroller> element.'); } this._topPositions = []; this._renderedItems = {}; try { this._delegate.itemHeight || this._delegate.calculateItemHeight(0); } catch (e) { if (!/must be (a|an instance of) function/.test('' + e)) { throw e; } this._unknownItemHeight = true; } this._addEventListeners(); this._onChange(); } _checkItemHeight(callback) { this._delegate.prepareItem(0, ({element}) => { if (this._unknownItemHeight) { this._wrapperElement.appendChild(element); this._itemHeight = element.offsetHeight; this._wrapperElement.removeChild(element); delete this._unknownItemHeight; callback(); } }); } get staticItemHeight() { return this._delegate.itemHeight || this._itemHeight; } _countItems() { return this._delegate.countItems(); } _getItemHeight(i) { return this.staticItemHeight || this._delegate.calculateItemHeight(i); } _onChange() { this._render(); } refresh() { this._removeAllElements(); this._onChange(); } _render() { if (this._unknownItemHeight) { return this._checkItemHeight(this._render.bind(this)); } const items = this._getItemsInView(); if (this._delegate.hasRenderFunction && this._delegate.hasRenderFunction()) { this._delegate._render(items, this._listHeight); return null; } const keep = {}; items.forEach(item => { this._renderElement(item); keep[item.index] = true; }); Object.keys(this._renderedItems).forEach(key => keep[key] || this._removeElement(key)); this._wrapperElement.style.height = this._listHeight + 'px'; } /** * @param {Object} item * @param {Number} item.index * @param {Number} item.top */ _renderElement({index, top}) { let item = this._renderedItems[index]; if (item) { this._delegate.updateItem(index, item); // update if it exists item.element.style.top = top + 'px'; return; } this._delegate.prepareItem(index, (item) => { util.extend(item.element.style, { position: 'absolute', top: top + 'px', left: 0, right: 0 }); this._wrapperElement.appendChild(item.element); this._renderedItems[index] = item; }); } /** * @param {Number} index */ _removeElement(index) { let item = this._renderedItems[index]; this._delegate.destroyItem(index, item); if (item.element.parentElement) { item.element.parentElement.removeChild(item.element); } delete this._renderedItems[index]; } _removeAllElements() { Object.keys(this._renderedItems).forEach(key => this._removeElement(key)); } _calculateStartIndex(current) { let start = 0; let end = this._itemCount - 1; if (this.staticItemHeight) { return parseInt(-current / this.staticItemHeight); } // Binary search for index at top of screen so we can speed up rendering. for (;;) { const middle = Math.floor((start + end) / 2); const value = current + this._topPositions[middle]; if (end < start) { return 0; } else if (value <= 0 && value + this._getItemHeight(middle) > 0) { return middle; } else if (isNaN(value) || value >= 0) { end = middle - 1; } else { start = middle + 1; } } } _recalculateTopPositions() { let l = Math.min(this._topPositions.length, this._itemCount); this._topPositions[0] = 0; for (let i = 1, l; i < l; i++) { this._topPositions[i] = this._topPositions[i - 1] + this._getItemHeight(i); } } _getItemsInView() { const offset = this._wrapperElement.getBoundingClientRect().top; const limit = 4 * window.innerHeight - offset; const count = this._countItems(); if (count !== this._itemCount){ this._itemCount = count; this._recalculateTopPositions(); } let i = Math.max(0, this._calculateStartIndex(offset) - 30); const items = []; for (var top = this._topPositions[i]; i < count && top < limit; i++) { if (i >= this._topPositions.length) { // perf optimization this._topPositions.length += 100; } this._topPositions[i] = top; items.push({top, index: i}); top += this._getItemHeight(i); } this._listHeight = top; return items; } _debounce(func, wait, immediate) { let timeout; return function() { let callNow = immediate && !timeout; clearTimeout(timeout); if (callNow) { func.apply(this, arguments); } else { timeout = setTimeout(() => { timeout = null; func.apply(this, arguments); }, wait); } }; } _doubleFireOnTouchend() { this._render(); this._debounce(this._render.bind(this), 100); } _addEventListeners() { util.bindListeners(this, ['_onChange', '_doubleFireOnTouchend']); if (platform.isIOS()) { this._boundOnChange = this._debounce(this._boundOnChange, 30); } this._pageContent.addEventListener('scroll', this._boundOnChange, true); if (platform.isIOS()) { this._pageContent.addEventListener('touchmove', this._boundOnChange, true); this._pageContent.addEventListener('touchend', this._boundDoubleFireOnTouchend, true); } window.document.addEventListener('resize', this._boundOnChange, true); } _removeEventListeners() { this._pageContent.removeEventListener('scroll', this._boundOnChange, true); if (platform.isIOS()) { this._pageContent.removeEventListener('touchmove', this._boundOnChange, true); this._pageContent.removeEventListener('touchend', this._boundDoubleFireOnTouchend, true); } window.document.removeEventListener('resize', this._boundOnChange, true); } destroy() { this._removeAllElements(); this._delegate.destroy(); this._parentElement = this._delegate = this._renderedItems = null; this._removeEventListeners(); } }
JavaScript
class SmartRoutingPriority { /** * Constructs a new <code>SmartRoutingPriority</code>. * @alias module:model/SmartRoutingPriority * @class */ constructor() { } /** * Constructs a <code>SmartRoutingPriority</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/SmartRoutingPriority} obj Optional instance to populate. * @return {module:model/SmartRoutingPriority} The populated <code>SmartRoutingPriority</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new SmartRoutingPriority(); if (data.hasOwnProperty('priority')) { obj['priority'] = ApiClient.convertToType(data['priority'], 'Number'); } } return obj; } /** * Priority * @member {Number} priority */ priority = undefined; }
JavaScript
class Pointer extends Class { constructor() { super(); this.id = Pointer._MAX_ID++; this._isDown = false; this._wasDown = false; this._actorsUnderPointer = { length: 0 }; this._actors = []; this._actorsLastFrame = []; this._actorsNoLongerUnderPointer = []; /** * The last position on the document this pointer was at. Can be `null` if pointer was never active. */ this.lastPagePos = null; /** * The last position on the screen this pointer was at. Can be `null` if pointer was never active. */ this.lastScreenPos = null; /** * The last position in the game world coordinates this pointer was at. Can be `null` if pointer was never active. */ this.lastWorldPos = null; /** * Returns the currently dragging target or null if it isn't exist */ this.dragTarget = null; this.on('move', this._onPointerMove); this.on('down', this._onPointerDown); this.on('up', this._onPointerUp); } /** * Whether the Pointer is currently dragging. */ get isDragging() { return this._isDown; } /** * Whether the Pointer just started dragging. */ get isDragStart() { return !this._wasDown && this._isDown; } /** * Whether the Pointer just ended dragging. */ get isDragEnd() { return this._wasDown && !this._isDown; } /** * Returns true if pointer has any actors under */ get hasActorsUnderPointer() { return !!this._actorsUnderPointer.length; } on(event, handler) { super.on(event, handler); } once(event, handler) { super.once(event, handler); } off(event, handler) { super.off(event, handler); } /** * Update the state of current pointer, meant to be called a the end of frame */ update() { if (this._wasDown && !this._isDown) { this._wasDown = false; } else if (!this._wasDown && this._isDown) { this._wasDown = true; } this._actorsLastFrame = [...this._actors]; this._actorsNoLongerUnderPointer = []; } /** * Adds an Actor to actorsUnderPointer object. * @param actor An Actor to be added; */ addActorUnderPointer(actor) { if (!this.isActorAliveUnderPointer(actor)) { this._actorsUnderPointer[actor.id] = actor; this._actorsUnderPointer.length += 1; this._actors.push(actor); } // Actors under the pointer are sorted by z, ties are broken by id this._actors.sort((a, b) => { if (a.z === b.z) { return a.id - b.id; } return a.z - b.z; }); } /** * Removes an Actor from actorsUnderPointer object. * @param actor An Actor to be removed; */ removeActorUnderPointer(actor) { if (this.isActorAliveUnderPointer(actor)) { delete this._actorsUnderPointer[actor.id]; this._actorsUnderPointer.length -= 1; removeItemFromArray(actor, this._actors); this._actorsNoLongerUnderPointer.push(actor); } } /** * Returns all actors under this pointer this frame */ getActorsUnderPointer() { return this._actors; } /** * Returns all actors that are no longer under the pointer this frame */ getActorsUnderPointerLastFrame() { return this._actorsLastFrame; } /** * Returns all actors relevant for events to pointer this frame */ getActorsForEvents() { return this._actors.concat(this._actorsLastFrame).filter((actor, i, self) => { return self.indexOf(actor) === i; }); } /** * Checks if Pointer location has a specific Actor bounds contained underneath. * @param actor An Actor for check; */ checkActorUnderPointer(actor) { if (this.lastWorldPos) { return actor.contains(this.lastWorldPos.x, this.lastWorldPos.y, !Actors.isScreenElement(actor)); } return false; } /** * Checks if an actor was under the pointer last frame * @param actor */ wasActorUnderPointer(actor) { return this._actorsLastFrame.indexOf(actor) > -1; // || !!this._actorsUnderPointerLastFrame.hasOwnProperty(actor.id.toString()); } /** * Checks if Pointer has a specific Actor in ActorsUnderPointer list. * @param actor An Actor for check; */ isActorAliveUnderPointer(actor) { return !!(!actor.isKilled() && actor.scene && this._actorsUnderPointer.hasOwnProperty(actor.id.toString())); } _onPointerMove(ev) { this.lastPagePos = new Vector(ev.pagePos.x, ev.pagePos.y); this.lastScreenPos = new Vector(ev.screenPos.x, ev.screenPos.y); this.lastWorldPos = new Vector(ev.worldPos.x, ev.worldPos.y); } _onPointerDown(ev) { this.lastPagePos = new Vector(ev.pagePos.x, ev.pagePos.y); this.lastScreenPos = new Vector(ev.screenPos.x, ev.screenPos.y); this.lastWorldPos = new Vector(ev.worldPos.x, ev.worldPos.y); this._isDown = true; } _onPointerUp(_ev) { this._isDown = false; this.dragTarget = null; } }
JavaScript
class SplitPanel extends SPanel { constructor() { super(...arguments); /** * Emits when the split handle has moved. */ this.handleMoved = new Signal(this); } handleEvent(event) { super.handleEvent(event); if (event.type === 'mouseup') { this.handleMoved.emit(undefined); } } }
JavaScript
class HyperLog extends EventEmitter { constructor({ location, leveldown, encoding }) { super() assert.equal(typeof leveldown, 'function', 'need to specify leveldown function') assert.equal(typeof location, 'string', 'need to specify location string') this._location = location this._leveldown = leveldown const db = levelup(location, { db: leveldown, createIfMissing: true }) this._log = hyperlog(db, { valueEncoding: encoding }) this._log.on('add', n => this.emit('add', n)) } append(value, opts, cb) { this._log.append(value, opts, cb) } createReadStream({ live, since, encoding } = {}) { return this._log.createReadStream({ live, since, valueEncoding: encoding }) } get(key, { encoding } = {}, cb) { return this._log.get(key, { valueEncoding: encoding }, cb) } getHand(data) { return data.value } destroy(cb) { this._leveldown.destroy(this._location, cb) } }
JavaScript
class PagesConfigurator{ /** * Builds a new PagesConfigurator */ constructor(){ /** * The Vuejs router reference * @private * @type {object} */ this._router = null; /** * The list of pages, as { name, route, model } objects * @private * @type {Array} */ this._resources = []; } /** * Adds a new page * @param {string} name The page name * @param {string} route The page route pattern * @param {object} [model={}] The Vuejs model for this page * @return {PagesConfigurator} This configurator, for method chaining */ add(name, route, model = {}){ // *Adding the page: this._resources.push({ name, route, model }); // *Returning this configurator: return this; } /** * Signals that the UI can be initialized * @return Promise A promise that resolves when the UI gets initialized, or rejects if some error has been thrown */ done(){ // *Returning the initialization promise chain: return new Promise((resolve, reject) => { // *When the DOM gets loaded: addEventListener('DOMContentLoaded', () => { // *Trying to start the UI: try{ // *Generating the routes list: const routes = this._resources.map(({ name, route, model }) => { return { name, path:route, component:model }; }); // *Starting the router: const router = new VueRouter({ mode: 'history', routes }); // *Initializing the UI: const app = new Vue({ router }) .$mount('#app'); // *Resolving with the router reference: resolve(router); } catch(err){ // *If some error has been thrown: // *Rejecting with the error: reject(err); } }); }) // *Setting the router reference: .then(router => this._router = router); } /** * Retrieves a copy of the pages list * @readonly * @type {Array} */ get list(){ return this._resources.concat([]); } /** * Retrieves the Vuejs router reference * @readonly * @type {object} */ get router(){ return this._router; } }
JavaScript
class rejectProject extends Component{ constructor(props){ super(props); this.open = this.open.bind(this); } open(){ this.props.getProjectData(this.props.notification.project_id); this.props.close(); } render(){ return( <div className="NotificationPanel"> <div className="InterestPosition"> Project was rejected by supervisor <NavLink className="LinkText" to={url2 + "user/"+this.props.notification.sender.id} onClick={this.open}>{this.props.notification.sender.firstname} {this.props.notification.sender.lastname}</NavLink> </div> </div> ) } }
JavaScript
class UMLContextButtonsInputMode extends InputModeBase { constructor() { super() this.buttonNodes = new DefaultSelectionModel() } /** * Installs the necessary listeners of this input mode. * @param {IInputModeContext} context the context to install this mode into * @param {ConcurrencyController} controller The {@link InputModeBase#controller} for * this mode. */ install(context, controller) { super.install(context, controller) // use a selection indicator manager which only "selects" the current item // so the buttons are only displayed for one node const graphComponent = context.canvasComponent this.manager = new MySelectionIndicatorManager(graphComponent, this.buttonNodes) // keep buttons updated and their add interaction graphComponent.addCurrentItemChangedListener(delegate(this.onCurrentItemChanged, this)) graphComponent.addMouseDragListener(delegate(this.startEdgeCreation, this)) graphComponent.addMouseClickListener(delegate(this.startEdgeCreation, this)) graphComponent.addTouchMoveListener(delegate(this.startEdgeCreation, this)) graphComponent.addTouchDownListener(delegate(this.startEdgeCreation, this)) graphComponent.inputMode.addCanvasClickedListener(delegate(this.onCanvasClicked, this)) graphComponent.graph.addNodeRemovedListener(delegate(this.onNodeRemoved, this)) } /** * Called when the graph component's current item changed to move the buttons to the current item. */ onCurrentItemChanged() { const graphComponent = this.inputModeContext.canvasComponent if (INode.isInstance(graphComponent.currentItem)) { this.buttonNodes.clear() this.buttonNodes.setSelected(graphComponent.currentItem, true) } else { this.buttonNodes.clear() } } /** * Remove the button visuals when the node is deleted. */ onNodeRemoved(src, args) { this.buttonNodes.setSelected(args.item, false) } /** * Called when the mouse button is pressed to initiate edge creation in case a button is hit. */ startEdgeCreation(src, args) { if (this.active && this.canRequestMutex()) { const p = args.location const graphComponent = this.inputModeContext.canvasComponent // check which node currently has the buttons and invoke create edge input mode to create a new edge for (let enumerator = this.buttonNodes.getEnumerator(); enumerator.moveNext(); ) { const buttonNode = enumerator.current const styleButton = ButtonVisualCreator.getStyleButtonAt(graphComponent, buttonNode, p) if (styleButton) { const parentInputMode = this.inputModeContext.parentInputMode if (parentInputMode instanceof GraphEditorInputMode) { const createEdgeInputMode = parentInputMode.createEdgeInputMode // initialize dummy edge const umlEdgeType = styleButton const dummyEdgeGraph = createEdgeInputMode.dummyEdgeGraph const dummyEdge = createEdgeInputMode.dummyEdge dummyEdgeGraph.setStyle(dummyEdge, umlEdgeType) dummyEdgeGraph.edgeDefaults.style = umlEdgeType // start edge creation and hide buttons until the edge is finished this.buttonNodes.clear() createEdgeInputMode.doStartEdgeCreation( new DefaultPortCandidate(buttonNode, FreeNodePortLocationModel.NODE_CENTER_ANCHORED) ) const listener = () => { graphComponent.selection.clear() graphComponent.currentItem = null createEdgeInputMode.removeGestureCanceledListener(listener) createEdgeInputMode.removeGestureFinishedListener(listener) } createEdgeInputMode.addGestureFinishedListener(listener) createEdgeInputMode.addGestureCanceledListener(listener) return } } } } } /** * Check whether a context button has been clicked. */ onCanvasClicked(src, args) { if (this.active && this.canRequestMutex()) { const p = args.location const graphComponent = this.inputModeContext.canvasComponent for (let enumerator = this.buttonNodes.getEnumerator(); enumerator.moveNext(); ) { const buttonNode = enumerator.current const contextButton = ButtonVisualCreator.getContextButtonAt(buttonNode, p) if (contextButton) { if (contextButton === 'interface') { const isInterface = buttonNode.style.model.stereotype === 'interface' buttonNode.style.model.stereotype = isInterface ? '' : 'interface' buttonNode.style.model.constraint = '' buttonNode.style.fill = isInterface ? new SolidColorFill(0x60, 0x7d, 0x8b) : Fill.SEA_GREEN } else if (contextButton === 'abstract') { const isAbstract = buttonNode.style.model.constraint === 'abstract' buttonNode.style.model.constraint = isAbstract ? '' : 'abstract' buttonNode.style.model.stereotype = '' buttonNode.style.fill = isAbstract ? new SolidColorFill(0x60, 0x7d, 0x8b) : Fill.CRIMSON } buttonNode.style.model.modify() args.handled = true graphComponent.invalidate() graphComponent.inputMode.clickInputMode.preventNextDoubleClick() } } } } /** * Removed the installed listeners when they are not needed anymore. * @param {IInputModeContext} context - The context to remove this mode from. This is the same * instance that has been passed to {@link InputModeBase#install}. */ uninstall(context) { const graphComponent = context.canvasComponent graphComponent.removeCurrentItemChangedListener(delegate(this.onCurrentItemChanged, this)) graphComponent.removeMouseDragListener(delegate(this.startEdgeCreation, this)) graphComponent.removeMouseClickListener(delegate(this.startEdgeCreation, this)) graphComponent.removeTouchMoveListener(delegate(this.startEdgeCreation, this)) graphComponent.removeTouchDownListener(delegate(this.startEdgeCreation, this)) graphComponent.inputMode.removeCanvasClickedListener(delegate(this.onCanvasClicked, this)) graphComponent.graph.removeNodeRemovedListener(delegate(this.onNodeRemoved, this)) this.buttonNodes.clear() this.manager.dispose() this.manager = null super.uninstall(context) } }
JavaScript
class MySelectionIndicatorManager extends ModelManager { constructor(canvas, model) { super(canvas) this.model = model this.buttonGroup = canvas.inputModeGroup.addGroup() this.model.addItemSelectionChangedListener(delegate(this.selectionChanged, this)) } /** * @param {T} item The item to find an installer for. * @returns {ICanvasObjectInstaller} */ getInstaller(item) { return new ISelectionIndicatorInstaller((iCanvasContext, iCanvasObjectGroup, node) => iCanvasObjectGroup.addChild( new ButtonVisualCreator(node, this.canvasComponent), ICanvasObjectDescriptor.ALWAYS_DIRTY_INSTANCE ) ) } /** * @param {T} item The item to find a canvas object group for. * @returns {ICanvasObjectGroup} */ getCanvasObjectGroup(item) { return this.buttonGroup } /** * Called when the selection of the internal model changes. * @param {Object} src * @param {ItemSelectionChangedEventArgs} args */ selectionChanged(src, args) { if (args.itemSelected) { this.add(args.item) } else { this.remove(args.item) } } /** * Cleanup the selection manager. */ dispose() { this.model.removeItemSelectionChangedListener(delegate(this.selectionChanged, this)) this.buttonGroup.remove() } onDisabled() {} onEnabled() {} }
JavaScript
class Main extends Component { render() { return ( <View style={styles.container}> <Login navigation={this.props.navigation} /> </View> ); } }