Best Python code snippet using autotest_python
frmProperties.py
Source:frmProperties.py
1from lib.Commands.Properties import CApplyPropertyPatchCommand2from lib.Domains import CDomainObject, CDomainObjectComparator3from lib.Exceptions import DomainTypeError4from lib.Drawing import CElement, CConnection, CDiagram5from frmPropertiesWidgets import *6class CfrmProperties(object):7 8 def __init__(self):9 self.parent=None10 self.element=None11 self.element_changed=False12 self.element_change_ignored=False13 self.attributes={}14 self.tables={}15 self.table_values={}16 self.dialog_sizes={}17 self.domain_object=None18 self.old_domain_object=None19 self.apply_button=None20 21 def SetParent(self,parent):22 self.parent=parent.form23 24 def __ClearFormular(self,type):25 for id in type.IterAttributeIDs():26 if type.GetAttribute(id)['hidden']:27 continue28 if type.GetAttribute(id)['type']=='str' or type.GetAttribute(id)['type']=='int' or type.GetAttribute(id)['type']=='float':29 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):30 self.attributes[type.GetName()][id].SetActiveItemText(str(type.GetDefaultValue(id)))31 elif isinstance(self.attributes[type.GetName()][id],CEditBox):32 self.attributes[type.GetName()][id].SetText(str(type.GetDefaultValue(id)))33 self.attributes[type.GetName()][id].SetBackgroundColor('#FFFFFF')34 if type.GetAttribute(id)['type']=='bool' or type.GetAttribute(id)['type']=='enum':35 self.attributes[type.GetName()][id].SetActiveItemText(str(type.GetDefaultValue(id)))36 if type.GetAttribute(id)['type']=='text':37 self.attributes[type.GetName()][id].SetText(str(type.GetDefaultValue(id)))38 self.attributes[type.GetName()][id].SetBackgroundColor('#FFFFFF')39 if type.GetAttribute(id)['type']=='list':40 if self.attributes[type.GetName()].has_key(id):41 self.attributes[type.GetName()][id].SetText('')42 self.tables[type.GetName()]['ref'].UnselectAll()43 self.tables[type.GetName()]['ref'].SetLastSelect(None)44 45 def __ToString(self,object):46 for joiner in object.GetType().IterJoiners():47 return joiner.CreateString(object)48 return 'not specified yet'49 50 def __ObjectsToString(self,objects):51 val=[]52 for obj in objects:53 val.append(self.__ToString(obj))54 return ';'.join(val)55 56 def __CreateTable(self,type,dialog):57 btnNew=CButton('_New', 'gtk-new')58 btnNew.SetHandler('clicked',self.__onTableNewButtonClick,(type,dialog))59 60 btnSave=CButton('_Save', 'gtk-save')61 btnSave.SetSensitive(False)62 btnSave.SetHandler('clicked',self.__onTableSaveButtonClick,(type,dialog))63 64 btnDelete=CButton('_Delete', 'gtk-delete')65 btnDelete.SetSensitive(False)66 btnDelete.SetHandler('clicked',self.__onTableDeleteButtonClick,(type,dialog))67 btnUp = CButton('Up', 'gtk-go-up', 'Move selected item up.')68 btnUp.SetSensitive(False)69 btnUp.SetHandler('clicked', self.__onTableUpButtonClick, (type, dialog))70 btnDown = CButton('Down', 'gtk-go-down', 'Move selected item down.')71 btnDown.SetSensitive(False)72 btnDown.SetHandler('clicked', self.__onTableDownButtonClick, (type, dialog))73 74 model=[]75 for key in type.IterAttributeIDs():76 if type.GetAttribute(key)['hidden']:77 continue78 model.append(type.GetAttribute(key)['name'])79 table=CTable(model,btnDelete,btnSave,btnNew, btnUp, btnDown)80 81 self.tables[type.GetName()]={}82 self.tables[type.GetName()]['ref']=table83 self.tables[type.GetName()]['new']=btnNew84 self.tables[type.GetName()]['save']=btnSave85 self.tables[type.GetName()]['delete']=btnDelete86 self.tables[type.GetName()]['up'] = btnUp87 self.tables[type.GetName()]['down'] = btnDown88 89 table.SetHandler('row-selected',self.__onTableRowSelect,(type,dialog))90 if len(type.GetName().split('.'))==2 or len(type.GetName().split('.'))%2==1:91 self.__FillTable(type)92 else:93 for key in self.table_values.keys():94 if key.find(type.GetName())!=-1:95 self.table_values.pop(key)96 return table97 98 def __FillTable(self,type):99 table=self.tables[type.GetName()]['ref']100 table.Clear()101 atts=None102 if len(type.GetName().split('.'))<3:103 atts=self.domain_object.GetValue(type.GetName()[type.GetName().rfind('.')+1:])104 elif self.table_values.has_key(type.GetName()):105 atts = self.table_values[type.GetName()]106 if atts is not None and len(atts)>0:107 for att in atts:108 tmp=[]109 for key in type.IterAttributeIDs():110 if type.GetAttribute(key)['hidden']:111 continue112 if type.GetAttribute(key)['type']=='list':113 tmp.append(self.__ObjectsToString(att.GetValue(key)))114 else:115 tmp.append(str(att.GetValue(key)))116 table.AppendRow(tmp,att)117 118 def __onTableNewButtonClick(self,type,dialog):119 dialog.GrabFirst()120 if self.tables[type.GetName()]['save'].GetSensitive():121 question=CResponseDialog('Question',dialog)122 question.AppendResponse('continue','C_ontinue')123 question.AppendResponse('cancel','_Cancel',True)124 question.SetQuestion('There are unsaved changes and if you continue they will be\n lost. '\125 'What do you wish to do?')126 question.Show()127 response=question.Close()128 if response=='cancel':129 return130 self.__ClearFormular(type)131 self.tables[type.GetName()]['save'].SetSensitive(False)132 self.tables[type.GetName()]['delete'].SetSensitive(False)133 self.tables[type.GetName()]['up'].SetSensitive(False)134 self.tables[type.GetName()]['down'].SetSensitive(False)135 for key in self.table_values.keys():136 if key.find(type.GetName())!=-1 and len(key)!=len(type.GetName()):137 self.table_values.pop(key)138 if len(type.GetName().split('.'))>2 and len(type.GetName().split('.'))%2==1:139 for id in type.IterAttributeIDs():140 if type.GetAttribute(id)['hidden']:141 continue142 if type.GetAttribute(id)['type']=='list':143 self.tables[type.GetName()+'.'+id]['ref'].Clear()144 145 def __onTableSaveButtonClick(self,type,dialog):146 if self.__CheckValues(type):147 table=self.tables[type.GetName()]['ref']148 dialog.GrabFirst()149 if table.GetSelectedRowIndex()!=-1:150 domainobject=table.GetRowObject(table.GetSelectedRowIndex())151 idx=0152 for id in type.IterAttributeIDs():153 if type.GetAttribute(id)['hidden']:154 continue155 if type.GetAttribute(id)['type'] in ('str', 'int', 'float'):156 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):157 val=self.attributes[type.GetName()][id].GetActiveItemText()158 elif isinstance(self.attributes[type.GetName()][id],CEditBox):159 val=self.attributes[type.GetName()][id].GetText()160 elif type.GetAttribute(id)['type'] in ('bool', 'enum'):161 val=self.attributes[type.GetName()][id].GetActiveItemText()162 elif type.GetAttribute(id)['type']=='text':163 val=self.attributes[type.GetName()][id].GetText()164 elif type.GetAttribute(id)['type']=='list':165 if self.table_values.has_key(type.GetName()+'.'+id):166 domainobject.SetValue(id,[])167 for object in self.table_values[type.GetName()+'.'+id]:168 domainobject.AppendItem(id,object)169 self.table_values[type.GetName()+'.'+id]=[]170 val=self.__ObjectsToString(domainobject.GetValue(id))171 table.SetCellValue(table.GetSelectedRowIndex(),idx,val)172 idx+=1173 continue174 domainobject.SetValue(id,val)175 table.SetCellValue(table.GetSelectedRowIndex(),idx,val)176 idx+=1177 val=self.__ObjectsToString(table.GetAllRowObjects())178 id=type.GetName()[type.GetName().rfind('.')+1:]179 if self.attributes.has_key(type.GetName()[:type.GetName().rfind('.')]) and self.attributes[type.GetName()[:type.GetName().rfind('.')]].has_key(id):180 self.attributes[type.GetName()[:type.GetName().rfind('.')]][id].SetText(val)181 if len(type.GetName().split('.'))<3:182 self.element_changed=True183 self.apply_button.SetSensitive(True)184 else:185 if len(type.GetName().split('.'))<3:186 item=self.domain_object.AppendItem(type.GetName()[type.GetName().find('.')+1:])187 self.element_changed=True188 self.apply_button.SetSensitive(True)189 else:190 item=CDomainObject(type)191 self.table_values.setdefault(type.GetName(),[]).append(item)192 tmp=[]193 for id in type.IterAttributeIDs():194 if type.GetAttribute(id)['hidden']:195 continue196 if type.GetAttribute(id)['type'] in ('str', 'int', 'float'):197 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):198 val=self.attributes[type.GetName()][id].GetActiveItemText()199 elif isinstance(self.attributes[type.GetName()][id],CEditBox):200 val=self.attributes[type.GetName()][id].GetText()201 tmp.append(val)202 item.SetValue(id,val)203 elif type.GetAttribute(id)['type'] in ('bool', 'enum'):204 val=self.attributes[type.GetName()][id].GetActiveItemText()205 tmp.append(val)206 item.SetValue(id,val)207 elif type.GetAttribute(id)['type']=='text':208 val=self.attributes[type.GetName()][id].GetText()209 tmp.append(val)210 item.SetValue(id,val)211 elif type.GetAttribute(id)['type']=='list':212 if self.table_values.has_key(type.GetName()+'.'+id):213 for object in self.table_values[type.GetName()+'.'+id]:214 item.AppendItem(id,object)215 self.table_values[type.GetName()+'.'+id]=[]216 tmp.append(self.__ObjectsToString(item.GetValue(id)))217 table.AppendRow(tmp,item)218 val=self.__ObjectsToString(table.GetAllRowObjects())219 id=type.GetName()[type.GetName().rfind('.')+1:]220 if self.attributes.has_key(type.GetName()[:type.GetName().rfind('.')]) and self.attributes[type.GetName()[:type.GetName().rfind('.')]].has_key(id):221 self.attributes[type.GetName()[:type.GetName().rfind('.')]][id].SetText(val)222 self.__ClearFormular(type)223 self.tables[type.GetName()]['save'].SetSensitive(False)224 self.tables[type.GetName()]['delete'].SetSensitive(False)225 self.tables[type.GetName()]['up'].SetSensitive(False)226 self.tables[type.GetName()]['down'].SetSensitive(False)227 else:228 warning=CResponseDialog('Warning',dialog)229 warning.AppendResponse('ok','Ok')230 warning.SetWarning('Entered values are wrong and can not be saved.')231 warning.Show()232 warning.Close()233 234 def __onTableDeleteButtonClick(self,type,dialog):235 table=self.tables[type.GetName()]['ref']236 dialog.GrabFirst()237 if table.GetSelectedRowIndex()!=-1:238 idx=table.GetSelectedRowIndex()239 table.RemoveRow(idx)240 path=type.GetName()[type.GetName().rfind('.')+1:]+'['+str(idx)+']'241 if len(type.GetName().split('.'))<3:242 self.domain_object.RemoveItem(path)243 self.element_changed=True244 self.apply_button.SetSensitive(True)245 elif self.table_values.has_key(type.GetName()):246 self.table_values[type.GetName()].pop(idx)247 for key in self.table_values.keys():248 if key.find(type.GetName())!=-1 and len(key)!=len(type.GetName()):249 self.table_values.pop(key)250 val=self.__ObjectsToString(table.GetAllRowObjects())251 id=type.GetName()[type.GetName().rfind('.')+1:]252 if self.attributes.has_key(type.GetName()[:type.GetName().rfind('.')]) and self.attributes[type.GetName()[:type.GetName().rfind('.')]].has_key(id):253 self.attributes[type.GetName()[:type.GetName().rfind('.')]][id].SetText(val)254 self.__ClearFormular(type)255 self.tables[type.GetName()]['save'].SetSensitive(False)256 self.tables[type.GetName()]['delete'].SetSensitive(False)257 self.tables[type.GetName()]['up'].SetSensitive(False)258 self.tables[type.GetName()]['down'].SetSensitive(False)259 def __onTableUpButtonClick(self, type, dialog):260 table = self.tables[type.GetName()]['ref']261 idxs = table.MoveItemUp()262 if idxs:263 item=self.domain_object.SwapItems(type.GetName()[type.GetName().find('.')+1:], idxs)264 self.element_changed=True265 self.apply_button.SetSensitive(True)266 self.apply_button.SetSensitive(True)267 def __onTableDownButtonClick(self, type, dialog):268 table = self.tables[type.GetName()]['ref']269 idxs = table.MoveItemDown()270 if idxs:271 item=self.domain_object.SwapItems(type.GetName()[type.GetName().find('.')+1:], idxs)272 self.element_changed=True273 self.apply_button.SetSensitive(True)274 self.apply_button.SetSensitive(True)275 def __onTableRowSelect(self,type,dialog):276 change=True277 table=self.tables[type.GetName()]['ref']278 if self.tables[type.GetName()]['save'].GetSensitive():279 if table.GetLastSelect()!=str(table.GetSelectedRowIndex()):280 question=CResponseDialog('Question',dialog)281 question.AppendResponse('continue','C_ontinue')282 question.AppendResponse('cancel','_Cancel',True)283 question.SetQuestion('There are unsaved changes and if you continue they will be\n lost. '\284 'What do you wish to do?')285 question.Show()286 response=question.Close()287 if response=='cancel':288 dialog.GrabFirst()289 table.SelectLast()290 change=False291 else:292 table.SelectLast()293 change=False294 if change:295 table.SetLastSelect(str(table.GetSelectedRowIndex()))296 dialog.GrabTable()297 item=table.GetRowObject(table.GetSelectedRowIndex())298 for id in type.IterAttributeIDs():299 if type.GetAttribute(id)['hidden']:300 continue301 val=str(item.GetValue(id))302 if type.GetAttribute(id)['type']=='str' or type.GetAttribute(id)['type']=='int' or type.GetAttribute(id)['type']=='float':303 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):304 self.attributes[type.GetName()][id].SetActiveItemText(val)305 elif isinstance(self.attributes[type.GetName()][id],CEditBox):306 val=self.attributes[type.GetName()][id].SetText(val)307 if type.GetAttribute(id)['type']=='bool' or type.GetAttribute(id)['type']=='enum':308 self.attributes[type.GetName()][id].SetActiveItemText(val)309 if type.GetAttribute(id)['type']=='text':310 self.attributes[type.GetName()][id].SetText(val)311 if type.GetAttribute(id)['type']=='list':312 self.table_values.setdefault(type.GetName()+'.'+id,[])313 self.table_values[type.GetName()+'.'+id]=[]314 for obj in item.GetValue(id):315 self.table_values[type.GetName()+'.'+id].append(obj.GetCopy())316 if len(type.GetName().split('.'))%2==1:317 self.__FillTable(type.GetFactory().GetDomain(type.GetAttribute(id)['list']['type']))318 elif len(type.GetName().split('.'))%2==0 or len(type.GetName().split('.'))==2:319 objects=item.GetValue(id)320 self.attributes[type.GetName()][id].SetText(self.__ObjectsToString(objects))321 self.tables[type.GetName()]['delete'].SetSensitive(True)322 self.tables[type.GetName()]['save'].SetSensitive(False)323 self.tables[type.GetName()]['up'].SetSensitive(True)324 self.tables[type.GetName()]['down'].SetSensitive(True)325 326 def ShowPropertiesWindow(self,element,app):327 if isinstance(element,(CElement,CConnection,CDiagram)):328 self.element=element.GetObject()329 else:330 self.element=element331 self.application=app332 self.old_domain_object=None333 self.domain_object=self.element.GetDomainObject().GetCopy()334 type=self.element.GetDomainObject().GetType()335 self.attributes={}336 self.tables={}337 dlg=self.__CreateBoneWindow(type,'Properties',self.parent,True)338 dlg.Show()339 self.element_changed=False340 341 def ShowPropertiesWindowForDomainObject(self,domainobject,title):342 self.old_domain_object=domainobject343 self.domain_object=domainobject.GetCopy()344 type=domainobject.GetType()345 self.attributes={}346 self.tables={}347 dlg=self.__CreateBoneWindow(type,title,self.parent,True)348 dlg.Show()349 self.element_changed=False350 351 def __CreateBoneWindow(self,type,name,parent,main_dialog=False):352 dialog=CDialog(parent,name)353 if self.dialog_sizes.has_key(type.GetName()):354 x,y=self.dialog_sizes[type.GetName()]355 dialog.SetSize(x,y)356 dialog.SetHandler('close',self.__onMainDialogCloseButtonClick,(dialog,type,main_dialog))357 358 btnClose=CButton('_Close')359 dialog.AppendButton(btnClose)360 btnClose.SetHandler('clicked',self.__onMainDialogCloseButtonClick,(dialog,type,main_dialog))361 362 if main_dialog:363 btnOk=CButton('_Ok')364 dialog.AppendButton(btnOk)365 btnOk.SetHandler('clicked',self.__onMainDialogOkButtonClick,(dialog,type))366 367 btnApply=CButton('_Apply')368 dialog.AppendButton(btnApply)369 btnApply.SetHandler('clicked',self.__onMainDialogApplyButtonClick,(btnApply,dialog,type))370 self.apply_button=btnApply371 372 attributes_order={}373 for id in type.IterAttributeIDs():374 att=type.GetAttribute(id)375 if att['hidden']:376 continue377 if att['type']!='list':378 attributes_order.setdefault('General',[]).append(id)379 else:380 attributes_order.setdefault(att['name'],[]).append(id)381 for key in attributes_order:382 self.__ProcessDomainType(type,key,attributes_order[key],dialog,main_dialog)383 dialog.SetCurrentTab(0)384 385 return dialog386 387 def __onCloseDialogCheckButtonToggle(self,button):388 self.element_change_ignored=button.IsChecked()389 390 def __CreateStr(self,type,att,key):391 if att.has_key('enum'):392 entry=CEditableComboBox()393 for val in att['enum']:394 entry.AppendItem(val)395 entry.SetActiveItemText(type.GetDefaultValue(key))396 else:397 entry=CEditBox()398 entry.SetText(type.GetDefaultValue(key))399 self.attributes.setdefault(type.GetName(),{})400 self.attributes[type.GetName()][key]=entry401 if len(type.GetName().split('.'))==1:402 entry.SetHandler('changed',self.__onMainFormularEntryChange,(type,key))403 else:404 entry.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))405 return entry406 407 def __CreateInt(self,type,att,key):408 if att.has_key('enum'):409 entry=CEditableComboBox('int')410 for val in att['enum']:411 entry.AppendItem(str(val))412 entry.SetActiveItemText(str(type.GetDefaultValue(key)))413 else:414 entry=CEditBox(style='int')415 entry.SetText(str(type.GetDefaultValue(key)))416 self.attributes.setdefault(type.GetName(),{})417 self.attributes[type.GetName()][key]=entry418 if len(type.GetName().split('.'))==1:419 entry.SetHandler('changed',self.__onMainFormularEntryChange,(type,key))420 else:421 entry.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))422 return entry423 424 def __CreateFloat(self,type,att,key):425 if att.has_key('enum'):426 entry=CEditableComboBox('float')427 for val in att['enum']:428 entry.AppendItem(str(val))429 entry.SetActiveItemText(str(type.GetDefaultValue(key)))430 else:431 entry=CEditBox(style='float')432 entry.SetText(str(type.GetDefaultValue(key)))433 self.attributes.setdefault(type.GetName(),{})434 self.attributes[type.GetName()][key]=entry435 if len(type.GetName().split('.'))==1:436 entry.SetHandler('changed',self.__onMainFormularEntryChange,(type,key))437 else:438 entry.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))439 return entry440 441 def __CreateEnum(self,type,att,key):442 combobox=CComboBox()443 for val in att['enum']:444 combobox.AppendItem(val)445 combobox.SetActiveItemText(str(type.GetDefaultValue(key)))446 self.attributes.setdefault(type.GetName(),{})447 self.attributes[type.GetName()][key]=combobox448 if len(type.GetName().split('.'))==1:449 combobox.SetHandler('changed',self.__onMainFormularEntryChange,(type,key))450 else:451 combobox.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))452 return combobox453 454 def __CreateBool(self,type,att,key):455 combobox=CComboBox()456 combobox.AppendItem('False')457 combobox.AppendItem('True')458 combobox.SetActiveItemText(str(type.GetDefaultValue(key)))459 self.attributes.setdefault(type.GetName(),{})460 self.attributes[type.GetName()][key]=combobox461 if len(type.GetName().split('.'))==1:462 combobox.SetHandler('changed',self.__onMainFormularEntryChange,(type,key))463 else:464 combobox.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))465 return combobox466 467 def __CreateText(self,type,att,key):468 text=CTextArea()469 text.SetText(str(type.GetDefaultValue(key)))470 self.attributes.setdefault(type.GetName(),{})471 self.attributes[type.GetName()][key]=text472 if len(type.GetName().split('.'))==1:473 text.SetHandler('changed',self.__onMainFormularEntryChange,(type,key))474 else:475 text.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))476 return text477 478 def __CreateEditBoxWithButton(self,type,att,key,dialog):479 list=CEditBoxWithButton('Edit...')480 self.attributes.setdefault(type.GetName(),{})481 self.attributes[type.GetName()][key]=list482 list.SetHandler('clicked',self.__onShowChildDialogButtonClick,(type.GetFactory().GetDomain(att['list']['type']),dialog))483 list.SetHandler('changed',self.__onTableFormularEntryChange,(type,key))484 return list485 486 def __onMainFormularEntryChange(self,type,key):487 att=type.GetAttribute(key)488 if att['type']=='int' or att['type']=='float' or\489 att['type']=='text' or att['type']=='str':490 min=att['min'] if att.has_key('min') else None491 max=att['max'] if att.has_key('max') else None492 try:493 entry=self.attributes[type.GetName()][key]494 if isinstance(entry,(CEditBox,CTextArea)):495 val=type.TransformValue(entry.GetText(),key)496 elif isinstance(entry,CEditableComboBox):497 val=type.TransformValue(entry.GetActiveItemText(),key)498 type.CheckValue(val,key)499 entry.SetBackgroundColor('#FFFFFF')500 self.element_changed=True501 self.apply_button.SetSensitive(True)502 except ValueError:503 entry.SetBackgroundColor('#FFFF66')504 except DomainTypeError:505 entry.SetBackgroundColor('#FFFF66')506 else:507 self.element_changed=True508 self.apply_button.SetSensitive(True)509 510 def __onTableFormularEntryChange(self,type,key):511 att=type.GetAttribute(key)512 if att['type']=='int' or att['type']=='float' or\513 att['type']=='text' or att['type']=='str':514 min=att['min'] if att.has_key('min') else None515 max=att['max'] if att.has_key('max') else None516 try:517 entry=self.attributes[type.GetName()][key]518 if isinstance(entry,(CEditBox,CTextArea)):519 val=type.TransformValue(entry.GetText(),key)520 elif isinstance(entry,CEditableComboBox):521 val=type.TransformValue(entry.GetActiveItemText(),key)522 type.CheckValue(val,key)523 entry.SetBackgroundColor('#FFFFFF')524 self.tables[type.GetName()]['save'].SetSensitive(True)525 except ValueError:526 entry.SetBackgroundColor('#FFFF66')527 except DomainTypeError:528 entry.SetBackgroundColor('#FFFF66')529 else:530 self.tables[type.GetName()]['save'].SetSensitive(True)531 532 #tato metoda pridava na dialog jednotlive vlastnosti podla ich typu533 def __ProcessDomainType(self,type,tabname,atts_order,dialog,main_dialog=False):534 dialog.AppendTab(tabname)535 is_list=False536 for key in atts_order:537 att=type.GetAttribute(key)538 if att['hidden']:539 continue540 if att['type']=='str':541 dialog.AppendItemToTab(tabname,self.__CreateStr(type,att,key),att['name'])542 elif att['type']=='enum':543 dialog.AppendItemToTab(tabname,self.__CreateEnum(type,att,key),att['name'])544 elif att['type']=='bool':545 dialog.AppendItemToTab(tabname,self.__CreateBool(type,att,key),att['name'])546 elif att['type']=='text':547 dialog.AppendItemToTab(tabname,self.__CreateText(type,att,key),att['name'])548 elif att['type']=='list':549 is_list=True550 type=type.GetFactory().GetDomain(att['list']['type'])551 for key in type.IterAttributeIDs():552 att=type.GetAttribute(key)553 if att['hidden']:554 continue555 if att['type']=='str':556 dialog.AppendItemToTab(tabname,self.__CreateStr(type,att,key),att['name'])557 elif att['type']=='enum':558 dialog.AppendItemToTab(tabname,self.__CreateEnum(type,att,key),att['name'])559 elif att['type']=='bool':560 dialog.AppendItemToTab(tabname,self.__CreateBool(type,att,key),att['name'])561 elif att['type']=='text':562 dialog.AppendItemToTab(tabname,self.__CreateText(type,att,key),att['name'])563 elif att['type']=='list':564 dialog.AppendItemToTab(tabname,self.__CreateEditBoxWithButton(type,att,key,dialog),att['name'])565 elif att['type']=='int':566 dialog.AppendItemToTab(tabname,self.__CreateInt(type,att,key),att['name'])567 elif att['type']=='float':568 dialog.AppendItemToTab(tabname,self.__CreateFloat(type,att,key),att['name'])569 elif att['type']=='int':570 dialog.AppendItemToTab(tabname,self.__CreateInt(type,att,key),att['name'])571 elif att['type']=='float':572 dialog.AppendItemToTab(tabname,self.__CreateFloat(type,att,key),att['name'])573 if not main_dialog or is_list:574 dialog.AppendItemToTab(tabname,self.__CreateTable(type,dialog),att['name'])575 else:576 for id in type.IterAttributeIDs():577 if type.GetAttribute(id)['hidden']:578 continue579 val=str(self.domain_object.GetValue(id))580 if type.GetAttribute(id)['type']=='str':581 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):582 self.attributes[type.GetName()][id].SetActiveItemText(val)583 else:584 self.attributes[type.GetName()][id].SetText(val)585 if type.GetAttribute(id)['type']=='int':586 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):587 self.attributes[type.GetName()][id].SetActiveItemText(val)588 else:589 self.attributes[type.GetName()][id].SetText(val)590 if type.GetAttribute(id)['type']=='float':591 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):592 self.attributes[type.GetName()][id].SetActiveItemText(val)593 else:594 self.attributes[type.GetName()][id].SetText(val)595 if type.GetAttribute(id)['type']=='bool' or type.GetAttribute(id)['type']=='enum':596 self.attributes[type.GetName()][id].SetActiveItemText(val)597 if type.GetAttribute(id)['type']=='text':598 self.attributes[type.GetName()][id].SetText(val)599 self.apply_button.SetSensitive(False)600 601 #metoda vytvori novy poddialog dialogu602 def __onShowChildDialogButtonClick(self,type,parent):603 dname=type.GetName().split('.')604 dname=dname[len(dname)-1]605 dlg=self.__CreateBoneWindow(type,parent.GetTitle()+' - '+dname,parent.GetWidget())606 dlg.Show()607 608 #zatvorenie dialogu cez Close button609 def __onMainDialogCloseButtonClick(self,dialog,type,main_dialog):610 self.dialog_sizes[type.GetName()]=dialog.GetSize()611 if self.element_changed and not self.element_change_ignored and main_dialog and self.__CheckValues(type):612 val=self.__CloseFunction(dialog)613 if val=='close':614 self.element_changed = False615 dialog.Close()616 elif val=='save':617 self.element_changed = False618 self.__SaveFunction(type)619 dialog.Close()620 else:621 dialog.Close()622 623 #stlacenie apply button dialogu624 def __onMainDialogApplyButtonClick(self,button,dialog,type):625 if self.__CheckValues(type):626 self.__SaveFunction(type)627 self.element_changed=False628 button.SetSensitive(False)629 else:630 warning=CResponseDialog('Warning',dialog)631 warning.AppendResponse('ok','Ok')632 warning.SetWarning('Entered values are wrong and can not be saved.')633 warning.Show()634 warning.Close()635 636 #stlacenie save button dialogu637 def __onMainDialogOkButtonClick(self,dialog,type):638 if self.__CheckValues(type):639 self.dialog_sizes[type.GetName()]=dialog.GetSize()640 self.__SaveFunction(type)641 self.element_changed=False642 dialog.Close()643 else:644 warning=CResponseDialog('Warning',dialog)645 warning.AppendResponse('ok','Ok')646 warning.SetWarning('Entered values are wrong and can not be saved.')647 warning.Show()648 warning.Close()649 650 def __CheckValues(self,type):651 try:652 for id in type.IterAttributeIDs():653 if type.GetAttribute(id)['hidden']:654 continue655 if type.GetAttribute(id)['type'] in ('str', 'int', 'float'):656 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):657 val=self.attributes[type.GetName()][id].GetActiveItemText()658 elif isinstance(self.attributes[type.GetName()][id],CEditBox):659 val=self.attributes[type.GetName()][id].GetText()660 type.CheckValue(val,id)661 elif type.GetAttribute(id)['type']=='text':662 val=self.attributes[type.GetName()][id].GetText()663 type.CheckValue(val,id)664 return True665 except DomainTypeError:666 return False667 668 def __CloseFunction(self,parent):669 close_dialog=CResponseDialog('Question',parent)670 close_dialog.AppendResponse('close','_Close')671 close_dialog.AppendResponse('cancel','C_ancel')672 close_dialog.AppendResponse('save','_Save & close',True)673 close_dialog.SetQuestion('There are unsaved changes.What do you want to do?')674 button=CCheckButton('Do not show this dialog again.')675 button.SetHandler('toggled',self.__onCloseDialogCheckButtonToggle,tuple([button]))676 close_dialog.SetToggleButton(button)677 close_dialog.Show()678 ret_val=close_dialog.Close()679 if ret_val is None or ret_val=='cancel':680 return 'cancel'681 elif ret_val=='close':682 return 'close'683 if ret_val=='save':684 return 'save'685 686 def __SaveFunction(self,type):687 for id in type.IterAttributeIDs():688 if type.GetAttribute(id)['hidden']:689 continue690 if type.GetAttribute(id)['type'] in ('str', 'int', 'float'):691 if isinstance(self.attributes[type.GetName()][id],CEditableComboBox):692 val=self.attributes[type.GetName()][id].GetActiveItemText()693 elif isinstance(self.attributes[type.GetName()][id],CEditBox):694 val=self.attributes[type.GetName()][id].GetText()695 elif type.GetAttribute(id)['type'] in ('bool', 'enum'):696 val=self.attributes[type.GetName()][id].GetActiveItemText()697 elif type.GetAttribute(id)['type']=='text':698 val=self.attributes[type.GetName()][id].GetText()699 elif type.GetAttribute(id)['type']=='list':700 continue701 self.domain_object.SetValue(id,val)702 if self.old_domain_object is not None:703 self.old_domain_object.SetValues(self.domain_object)704 #self.domain_object=self.old_domain_object.GetCopy()705 if self.element is not None:706 diff = CDomainObjectComparator(self.element.GetDomainObject(), self.domain_object)707 l = list(diff)708 cmd = CApplyPropertyPatchCommand(self.element, list(diff))...
monsterQuest.py
Source:monsterQuest.py
...6from hero import *7import random8import sys9def battle(h, m):10 print('You have encountered ' + m.getName())11 #print hero's and monster's name and health12 print(h.getName() + ': ' + str(h.getHealth()) + '/' + str(h.maxHealth()) + ' health')13 print(m.getName() + ':', str(m.getHealth()) + '/' + str(m.maxHealth()) + ' health')14 #fight while both sides still have health, end when one's health hits 015 while(h.getHealth() > 0 and m.getHealth() > 0):16 print('Remaining:', h.getFireballs(), 'Fireballs', h.getPotions(), 'Potions')17 command = input('Enter command: Sword / Shield / Fireball / Potion / Exit \n')18 #uses sword attack19 if(command.lower() == 'sword'):20 print('Sword Attack!')21 hero.attack(m)22 #checks if monster is still alive after the hero attacks. If the monster is dead, break the loop and move to the next monster. Else, keep going23 if(m.getHealth() <= 0):24 m.setHealth(0)25 print(h.getName(), 'defeated', m.getName())26 break27 print(m.getName() + ' attacks you! ')28 m.attack(hero)29 if(command.lower() == 'shield'):30 print('Shield!')31 hero.shield()32 print(m.getName() + ' attacks you! ')33 m.attack(hero)34 #make sure user has fireballs before attacking. If there are no fireballs, user loses the turn and is notified. Else, attacks35 if(command.lower() == 'fireball'):36 print('Fireball Attack!')37 if(h.getFireballs() == 0):38 print('No fireballs left!')39 else:40 hero.fireballAttack(m)41 #checks if monster is still alive after the hero attacks. If the monster is dead, break the loop and move to the next monster. Else, keep going42 if(m.getHealth() <= 0):43 m.setHealth(0)44 print(h.getName(), 'defeated ', m.getName())45 break46 print(m.getName() + ' attacks you! ')47 m.attack(hero)48 #make sure user is in a condition to use potion, if they are, use it. if not, turn is lost and user is notified49 if(command.lower() == 'potion'):50 print('Potion!')51 if(h.getPotions() == 0):52 print('No Potions Left!')53 elif(h.getHealth() == h.maxHealth()):54 print('Already at Full Health!')55 else:56 hero.potionHeal()57 print(m.getName() + ' attacks you! ')58 m.attack(hero)59 #if user enters exit, exit60 if(command.lower() == 'exit'):61 print('Thanks for playing!')62 sys.exit()63 #if hero's health falls below 0, set it to 0, display hero's health and monster's health, exit since hero lost64 if(h.getHealth() <= 0):65 h.setHealth(0)66 print(h.getName(), 'was defeated by', m.getName())67 print(h.getName() + ':', str(h.getHealth()) + '/' + str(h.maxHealth()))68 print(m.getName() + ':', str(m.getHealth()) + '/' + str(m.maxHealth()))69 sys.exit()70 71 #display hero's and enemy's health after each turn72 print(h.getName() + ':', str(h.getHealth()) + '/' + str(h.maxHealth()))73 print(m.getName() + ':', str(m.getHealth()) + '/' + str(m.maxHealth()))74if __name__ == '__main__':75 fighterList = []76 print('Welcome to Adventure Battle!')77 heroName = input('What is the name of your hero? ')78 if heroName.lower() == 'exit':79 sys.exit()80 #instantiate a hero with the given name and 100 health81 hero = hero(heroName, 100)82 #ask for how many enemies the hero wants to fight83 fighters = input('How many enemies will ' + heroName + ' battle? ')84 valid = False85 if fighters.lower() == 'exit':86 sys.exit()87 else:...
FieldEditor.js
Source:FieldEditor.js
...9 controller: 'Field',10 action : 'save',11 params : {12 pageFileName: this.form.page.pageLink.getFileName(),13 form : this.form.getName(),14 field : this.getName(),15 attr : name,16 value : value17 }18 });19 this.setAttr(name, value);20 return data;21 }22 async deleteData() {23 await FrontHostApp.doHttpRequest({24 controller : 'Field',25 action : 'delete',26 params : {27 pageFileName:this.form.page.pageLink.getFileName(),28 form :this.form.getName(),29 field :this.getName()30 }31 });32 }33 async delete() {34 await this.deleteData();35 this.parent.removeField(this);36 }37 async getView(view) {38 return await FrontHostApp.doHttpRequest({39 controller: 'Field',40 action : 'getView',41 params : {42 view : view,43 page : this.data !== undefined ? this.form.page.getName() : null,44 form : this.data !== undefined ? this.form.getName() : null,45 field: this.data !== undefined ? this.getName() : null46 }47 });48 }49 async saveView(text, view) {50 return await FrontHostApp.doHttpRequest({51 controller: 'Field',52 action : 'saveView',53 params : {54 page : this.form.page.getName(),55 form : this.form.getName(),56 field: this.getName(),57 view : view,58 text : text59 }60 });61 }62 async saveController(text) {63 return await FrontHostApp.doHttpRequest({64 controller: 'Field',65 action : 'saveController',66 params : {67 page : this.form.page.getName(),68 form : this.form.getName(),69 field: this.getName(),70 text : text71 }72 });73 }74 async createView() {75 return await FrontHostApp.doHttpRequest({76 controller: 'Field',77 action : 'createView',78 params : {79 page : this.form.page.getName(),80 form : this.form.getName(),81 field: this.getName(),82 class: this.getClassName()83 }84 });85 }86 async createStyle() {87 return await FrontHostApp.doHttpRequest({88 controller: 'Field',89 action : 'createStyle',90 params : {91 page : this.form.page.getName(),92 form : this.form.getName(),93 field: this.getName(),94 class: this.getClassName()95 }96 });97 }98 async createController() {99 return await FrontHostApp.doHttpRequest({100 controller: 'Field',101 action : 'createController',102 params : {103 page : this.form.page.getName(),104 form : this.form.getName(),105 field: this.getName(),106 class: this.getClassName()107 }108 });109 }110 async changeClass(params) {111 params['page'] = this.form.page.getName();112 params['form'] = this.form.getName();113 params['field'] = this.getName();114 const data = await FrontHostApp.doHttpRequest({115 controller: 'Field',116 action : 'changeClass',117 params : params118 });119 return this.data = data;120 }121 moveUp() {122 return FrontHostApp.doHttpRequest({123 controller : 'Field',124 action : 'moveUp',125 params : {126 pageFileName: this.form.page.pageLink.getFileName(),127 form : this.form.getName(),128 field : this.getName()129 }130 });131 }132 moveDown() {133 return FrontHostApp.doHttpRequest({134 controller : 'Field',135 action : 'moveDown',136 params : {137 pageFileName: this.form.page.pageLink.getFileName(),138 form : this.form.getName(),139 field : this.getName()140 }141 });142 }...
party2_rp.js
Source:party2_rp.js
...7var notify;8function enter(pi) {9 try {10 var em = pi.getEventManager("LudiPQ");11 if (em != null && em.getProperty("stage6_" + (pi.getPortal().getName().substring(2, 4)) + "").equals("1")) {12 if (pi.getPortal().getName() == "pt00" || pi.getPortal().getName() == "pt01" || pi.getPortal().getName() == "pt02") {13 portal = 2;14 notify = true;15 } else if (pi.getPortal().getName() == "pt10" || pi.getPortal().getName() == "pt11" || pi.getPortal().getName() == "pt12") {16 portal = 3;17 notify = true;18 } else if (pi.getPortal().getName() == "pt20" || pi.getPortal().getName() == "pt21" || pi.getPortal().getName() == "pt22") {19 portal = 4;20 notify = true;21 } else if (pi.getPortal().getName() == "pt30" || pi.getPortal().getName() == "pt31" || pi.getPortal().getName() == "pt32") {22 portal = 5;23 notify = true;24 } else if (pi.getPortal().getName() == "pt40" || pi.getPortal().getName() == "pt41" || pi.getPortal().getName() == "pt42") {25 portal = 6;26 notify = true;27 } else if (pi.getPortal().getName() == "pt50" || pi.getPortal().getName() == "pt51" || pi.getPortal().getName() == "pt52") {28 portal = 7;29 notify = true;30 } else if (pi.getPortal().getName() == "pt60" || pi.getPortal().getName() == "pt61" || pi.getPortal().getName() == "pt62") {31 portal = 8;32 notify = true;33 } else if (pi.getPortal().getName() == "pt70" || pi.getPortal().getName() == "pt71" || pi.getPortal().getName() == "pt72") {34 portal = 9;35 notify = true;36 } else if (pi.getPortal().getName() == "pt80" || pi.getPortal().getName() == "pt81" || pi.getPortal().getName() == "pt82") {37 portal = 10;38 notify = true;39 } else if (pi.getPortal().getName() == "pt90" || pi.getPortal().getName() == "pt91" || pi.getPortal().getName() == "pt92") {40 portal = 11;41 notify = true;42 }43 if (notify) {44 var pname = pi.getPortal().getName().substring(2, 4);45 if (em.getProperty(("portal" + (portal - 1))).equals("1")) {46 em.setProperty(("portal" + (portal - 1)), ("" + pname + ""));47 }48 pi.getMap().changeEnvironment("an" + em.getProperty("portal" + (portal - 1)) , 2);49 }50 if (portal != 11) {51 pi.changePortal(portal);52 } else {53 pi.warpParty(pi.getMapId(), 13);54 pi.showEffect(true, "quest/party/clear");55 pi.playSound(true, "Party1/Clear");56 }57 } else {58 pi.warpS(pi.getMapId(), 0);...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!