def asHtml(self, level): """ redefine html output for this object contents are put in header (usually brand) navigation table used to generate navlist """ div_navbar_main = div.div('navbar-collapse collapse') div_navbar_main.add(self._nav_list(self.navmenu)) div_navbar = div.div('navbar navbar-default').add( div.div('navbar-header').addList(self.contents).add( # mobile navbar ugliness pui.element( 'button', _class='navbar-toggle', type='button', data_toggle='collapse', data_target='.navbar-main' ).add( pui.element('span', _class='icon-bar'), pui.element('span', _class='icon-bar'), pui.element('span', _class='icon-bar'), ) ), div_navbar_main ) return div_navbar.asHtml(level)
def optimize(self, env, compiler): index = self.index.optimize(env, compiler) container = self.container.optimize(env, compiler) if isinstance(index, Atom): if isinstance(container, Atom): return element(container.item[index.item]) elif isinstance(container, RulesDict): return element(container.arity_body_map[index.item]) #try: #return element(container.arity_body_map[index.item]) #except: #return GetItem(container, index) elif isinstance(container, MacroArgs): return container.item[index.item] return GetItem(container, index)
def convertToUnitcell(self): from coor import coor paraDict = self.paraDict s = paraDict['scalingFactor'] a = coor(tuple(paraDict['latticeVectors'][0])) b = coor(tuple(paraDict['latticeVectors'][1])) c = coor(tuple(paraDict['latticeVectors'][2])) speciesNumber = paraDict['speciesNumber'] speciesLabel = paraDict['speciesLabel'] coordinateSystem = paraDict['coordinateSystem'] atomPositions = paraDict['atomPositions'] # Get the total number of atoms specified in poscar atomNumberCount = sum(speciesNumber) # Scale the latticeMatrix a = a * s; b = b * s; c = c * s; # Construct the siteList (Recall that unitcell always use reduced coor) from element import element elementList = [element(speciesLabel[index])\ for index in range(len(speciesLabel))\ for count in range(speciesNumber[index])] if coordinateSystem == 'Direct': reducedCoorList = [coor(tuple(position)) for position in atomPositions] else: raise StandardError("Coordinate system not direct") from atom import atom alist = [atom(element, coor)\ for (element, coor) in zip(elementList, reducedCoorList)] from unitcell import unitcell return unitcell(a, b, c, alist)
def __init__(self): const.__init__(self,'physical'); self.unit = unit.unit('physical.') self.units = self.unit self.constant = constant.constant('physical.', self.units) self.constants = self.constant self.element = element.element('physical.', self.constants, self.units) self.elements = self.element # do some trickery to get modules set to instantiated classes self.unit.__name__ = unit.__name__ sys.modules[unit.__name__]=self.unit sys.modules[units.__name__]=self.unit self.constant.__name__ = constant.__name__ sys.modules[constant.__name__]=self.constant sys.modules[constants.__name__]=self.constant self.element.__name__ = element.__name__ sys.modules[element.__name__]=self.element sys.modules[elements.__name__]=self.element # add in the license file self.license = license # copy over the Quantity module so that the user can reference it. self.base = Quantity
def loadXml(self,node): self.getText(node.childNodes) if node.nodeType!=Node.ELEMENT_NODE: for n in node.childNodes: if n.nodeType==Node.ELEMENT_NODE and n.localName == 'xdl_resource_report': self.loadXml(n) else: for n in node.childNodes: if n.nodeType==Node.ELEMENT_NODE and n.localName == 'pin': el=pin() el.loadXml(n) self.set_pin(el) for n in node.childNodes: if n.nodeType==Node.ELEMENT_NODE and n.localName == 'element': el=element() el.loadXml(n) self.set_element(el) if node.hasAttributes(): attrs=node.attributes attrId='a1' if attrId in attrs.keys(): self.a1=str(attrs[attrId].value) attrId='a0' if attrId in attrs.keys(): self.a0=str(attrs[attrId].value) attrId='a2' if attrId in attrs.keys(): self.a2=str(attrs[attrId].value)
def __init__(self): const.__init__(self, "physical") self.unit = unit.unit("physical.") self.units = self.unit self.constant = constant.constant("physical.", self.units) self.constants = self.constant self.element = element.element("physical.", self.constants, self.units) self.elements = self.element # do some trickery to get modules set to instantiated classes self.unit.__name__ = unit.__name__ sys.modules[unit.__name__] = self.unit sys.modules[units.__name__] = self.unit self.constant.__name__ = constant.__name__ sys.modules[constant.__name__] = self.constant sys.modules[constants.__name__] = self.constant self.element.__name__ = element.__name__ sys.modules[element.__name__] = self.element sys.modules[elements.__name__] = self.element # add in the license file self.license = license # copy over the Quantity module so that the user can reference it. self.base = Quantity # also provide a direct reference to the Quantity class self.Quantity = Quantity.Quantity
def optimize(self, env, compiler): caller = self.caller args = optimize_args(self.args, env, compiler) for arg in args: if not isinstance(arg, Atom): break else: return element(caller.operator_function(*tuple(arg.item for arg in args))) return self.__class__(caller, args)
def __init__(self, title='Web Page', **kwargs): pui.element.__init__(self, 'page', **kwargs) self.title = title self.head.append( pui.element( 'meta', charset='utf-8' ) )
def optimize(self, env, compiler): caller = self.caller args = optimize_args(self.args, env, compiler) for arg in args: if not isinstance(arg, Atom): break else: return element( caller.operator_function(*tuple(arg.item for arg in args))) return self.__class__(caller, args)
def addItem(self, nameOfObejct, Object, x=None, y=None): if x == None: x = 0 if y == None: y = 0 if type(Object) == type(element()): Object = Object.getImage() item = [] item.append(Object) item.append(x) item.append(y) self.m_object[nameOfObejct] = item
def addElementByNode(self, nodeTable, nodeNr1, nodeNr2): # noteTable: list holding all nodes defined # nodeNr1 & nodeNr2 # based on nodeNumbers create an element # step 1: get the 2 nodes Node1 = nodeTable.getNode_by_Nr(nodeNr1) Node2 = nodeTable.getNode_by_Nr(nodeNr2) #step 2: create an element using the element class # remember that setting the first variable to 0 will assign a free elementNr element2add = element(0, Node1, Node2) # step 3: add the element to the elementList using "append" self.elementList.append(element2add)
def asHtml(self): """ redefine html output for this page special case grabs head and tail lists and constructs entire page with doctype """ # get the head/tail before contents duplicated page_head = self._get_head() page_tail = self._get_tail() page_ready = self._get_ready() # construct ready script section ready_script = None if page_ready: scripts = '\n'.join(page_ready.itervalues()) ready_script_func = '\n'.join([ "$(document).ready(function(){", scripts, "});" ]) ready_script = pui.element( 'script', type='text/javascript', html=ready_script_func) # create fake body element body = pui.element('body') body.contents = self.contents body.attributes = self.attributes # construct page with head and body html = pui.element('html').add( pui.element('head').add( pui.element('title', text=self.title), ).addList(page_head) ).add( body.addList(page_tail).add(ready_script) ) return '<!DOCTYPE html>' + html.asHtml() + '\n'
def main(): e0 = element(0) e1 = element(1) e2 = element(2) e3 = element(3) e4 = element(4) e5 = element(5) #Linked list check # ll = linked_list(e1) # ll.append(e2) # ll.append(e3) # ll.append(e5) # print(ll.get_position(3).value) # ll.insert(e4,3) # print(ll.get_position(3).value) # print(ll.get_position(4).value) # ll.insert(e0,0) # print(ll.get_position(0).value) # print(ll.get_position(1).value) # print() # print() # ll.delete(3) # print(ll.get_position(3).value) # print(ll.get_position(4).value) # ll.delete(0) # print(ll.get_position(0).value) #stack check ss = stack(e0) ss.push(e1) ss.push(e2) print(ss.pop()) print(ss.pop())
def _nav_list(self, elements, dropdown=False): ul = pui.element('ul') if dropdown: ul.addClass('dropdown-menu') dropdown_id = dropdown.get_id() ul.attr(role="menu", aria_labelledby=dropdown_id) else: ul.addClass('nav', 'navbar-nav') for item in elements: li = pui.element('li') li.add(item) if item.navmenu: if 'dropdown' in str(type(item)): li.add(self._nav_list(item.navmenu, item)) li.addClass('dropdown') else: li.add(self._nav_list(item.navmenu)) ul.add(li) return ul
def buildDatabase(monFilePath, elementFilePath, attacksFilePath): #open files monFile = open(monFilePath, 'r') elementFile = open(elementFilePath, 'r') attackFile = open(attacksFilePath, 'r') #create monList #ignore first line monFile.readline() #readlines lines = monFile.readlines() monList = [] #split line and append new mon to monList for member in lines: mLineInfo = member.split() monList.append(databaseMon(mLineInfo[0], mLineInfo[1], mLineInfo[2], mLineInfo[3], mLineInfo[4], mLineInfo[5], mLineInfo[6], mLineInfo[7], mLineInfo[8], mLineInfo[9] )) #print ("MonList[3] points: %s" % (monList[3].points)) #create elementList #ignore first line elementFile.readline() #readlines lines = elementFile.readlines() elementList = [] #split line and append new element to elementList for member in lines: eLineInfo = member.split() elementList.append(element(eLineInfo[0], eLineInfo[1], eLineInfo[2] )) #test #for member in elementList: #print ("name: %s strength: %s weakness: %s " %( member.name, member.strength, member.weakness)) #create attackList #ignore first line attackFile.readline() #readlines lines = attackFile.readlines() attackList = [] #split line and append new attack to attackList for member in lines: aLineInfo = member.split() #print"%s %s %s %s %s %s %s "%(aLineInfo[0], aLineInfo[1], aLineInfo[2], aLineInfo[3], aLineInfo[4], aLineInfo[5], aLineInfo[6]) attackList.append(attack(aLineInfo[0], aLineInfo[1], aLineInfo[2], aLineInfo[3], aLineInfo[4], aLineInfo[5], aLineInfo[6])) #test #for member in attackList: #print ("name: %s element: %s : accuracy%s " %( member.name, member.element, member.accuracy)) return monList, elementList, attackList
def __init__(self, rows): if type([]) != type(rows) or len(rows) != 9: raise TypeError, "puzzle(rows) takes 9 rows as an argument" if os.getenv("DEBUG"): self.debugging = True self.rows = [] self.knowns = [] self.givens = [] self.log("starting puzzle") self.indent() self.log("populating rows") for ypos, row in enumerate(rows): this_row = [] self.rows.append(this_row) if type([]) != type(row) or len(row) != 9: raise TypeError, "puzzle(rows) takes 9 rows with 9 integers (or None) in each" for xpos, i in enumerate(row): if i == 0 or (type(i)==type(3) and 0<i<10): e = element(i, self, (xpos,ypos)) this_row.append(e) if i>0: self.givens.append(e) else: raise TypeError, "every element in a puzzle row must be an integer (0-9) or None" for row in self.rows: for e in row: e.row = row self.log("populating cols") self.assign_cols() self.log("populating cels") self.assign_cels() self._before_string = str(self) # after the line below, the puzzle starts solving itself self.log("telling initial knowns: i_am()") self.i_am() self.outdent() self.log("done building puzzle")
def testfunctionTruss(): """ define variables """ n1=node(1,0,0,np.nan,np.nan,np.nan,np.nan) #node 1 of the textbook example n2=node(2,3*12,0,np.nan,np.nan,np.nan,np.nan) #node 2 of the textbook example (feet to inch = *12) n5=node(5,6*12,3*12,np.nan,np.nan,np.nan,np.nan) #node 2 of the textbook example (feet to inch = *12) NT = nodeTable(n1,n2) #enter example of U: length(U) = 2*(highest_node_nr +1), values from the textbook example U = np.array([[0], [0], [0], [0],[-0.00355], [-0.01026], [0], [0], [0.0018], [-0.0114], [0.0024], [-0.0195]]) elementExample = element(0,n2,n5) """ start testing the code """ T = truss(1) T.addExistingElement(elementExample) T.addElementByNode(NT,1,2) T.print_details(False,False) f=plt.figure() T.plotTruss(f,U)
def __init__(self, parent): self.parent = parent self.device = parent.device self.data_layer = parent.data_layer self.apps = parent.apps self.marionette = parent.marionette self.actions = Actions(self.marionette) # Globals used for reporting ... self.errNum = 0 self.start_time = time.time() # Get run details from the OS. self.general = general(self) self.test_num = parent.__module__[5:] self.app = app(self) self.date_and_time = date_and_time(self) self.debug = debug(self) self.element = element(self) self.home = home(self) self.iframe = iframe(self) self.messages = Messages(self) self.network = network(self) self.reporting = reporting(self) self.statusbar = statusbar(self) self.test = test(self) self.visual_tests = visualtests(self) self.marionette.set_search_timeout(10000) self.marionette.set_script_timeout(10000) elapsed = time.time() - self.start_time elapsed = round(elapsed, 0) elapsed = str(datetime.timedelta(seconds=elapsed)) self.reporting.debug( "Initializing 'UTILS' took {} seconds.".format(elapsed)) current_lang = parent.data_layer.get_setting("language.current").split( '-')[0] self.reporting.info( "Current Toolkit language: [{}]".format(current_lang)) try: btn = self.marionette.find_element('id', 'charge-warning-ok') btn.tap() except: pass parent.data_layer.set_setting('screen.automatic-brightness', True)
def launchSudoku(self, base): self.heure = 0 self.minute = 0 self.seconde = 0 self.Pause = True screenReady = elmt.element(0,0,"Ready.png") screenReady.clickable = True screenReady.action = "Ready" self.jeuLayout.listElmtManager[1].addElement(screenReady) self.sudoku = Sudoku(base) self.jeuLayout.listElmtManager[0].elements[0].setText(self.font.render(self.sudoku.stringCompteur, True,(0,0,0))) vie = '' for i in range(self.sudoku.trys): vie = vie + 'O' if i != self.sudoku.trys-1: vie = vie + ' ' self.jeuLayout.listElmtManager[0].elements[1].setText(self.font.render(vie, True,(0,190,0)))
def generateElements(self, domain): tempRow = [] xLength = domain.length / self.numOfXElems yLength = domain.height / self.numOfYElems self.elementalMass = xLength * yLength * domain.depth * domain.density rowIdx = self.numOfYElems - 1 colIdx = self.numOfXElems - 1 for i in range(1, self.numOfEls + 1): tempRow.append( element(self.numOfEls + 1 - i, [rowIdx, colIdx], xLength, yLength)) colIdx -= 1 if i % self.numOfXElems == 0: self.elements.append(tempRow[::-1]) rowIdx -= 1 colIdx = self.numOfXElems - 1 tempRow = []
def __init__(self, parent): self.parent = parent self.device = parent.device self.data_layer = parent.data_layer self.apps = parent.apps self.marionette = parent.marionette self.actions = Actions(self.marionette) # Globals used for reporting ... self.errNum = 0 self.start_time = time.time() # Get run details from the OS. self.general = general(self) self.test_num = parent.__module__[5:] self.app = app(self) self.date_and_time = date_and_time(self) self.debug = debug(self) self.element = element(self) self.home = home(self) self.iframe = iframe(self) self.messages = Messages(self) self.network = network(self) self.reporting = reporting(self) self.statusbar = statusbar(self) self.test = test(self) self.visual_tests = visualtests(self) self.marionette.set_search_timeout(10000) self.marionette.set_script_timeout(10000) elapsed = time.time() - self.start_time elapsed = round(elapsed, 0) elapsed = str(datetime.timedelta(seconds=elapsed)) self.reporting.debug("Initializing 'UTILS' took {} seconds.".format(elapsed)) current_lang = parent.data_layer.get_setting("language.current").split('-')[0] self.reporting.info("Current Toolkit language: [{}]".format(current_lang)) try: btn = self.marionette.find_element('id', 'charge-warning-ok') btn.tap() except: pass parent.data_layer.set_setting('screen.automatic-brightness', True)
def __init__(self, vals): self.__n = len(vals) self.__rows = [] self.__cols = [] self.__eles = [] self.blocks = [] self.isChanged = False self.solved = 0 self.expired = False self.Iterations = 0 self.guesses = 0 for i in range(self.__n): x = subTable(self.__n, self) y = subTable(self.__n, self) z = subTable(self.__n, self) self.__rows.append(x) self.__cols.append(y) self.blocks.append(z) for i in range(self.__n): for j in range(self.__n): k = int((self.__n)**(1 / 2.0)) b = k * (i // k) + (j // k) e = element(self, self.__rows[i], self.__cols[j], self.blocks[b]) if (vals[i][j] != 0): e.setVal(vals[i][j]) self.__rows[i].setVal(j, e) self.__cols[j].setVal(i, e) self.blocks[b].setVal(k * (i % k) + j % k, e) self.__eles.append(e) for i in self.__eles: for n in range(self.__n): if (i.getVal() == 0): if not (i.myRow().contains(n + 1) or i.myCol().contains(n + 1) or i.myBlock().contains(n + 1)): i.markPoss(n + 1)
def init(self): if self.base == 3: self.buttonList = ("[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]", "[8]", "[9]", "backspace") elif self.base == 4: self.buttonList = ("[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]", "[8]", "[9]", "a", "b", "c", "d", "e", "f", "g", "backspace") self.backgroundGrille = elmt.element(0, 0, "case.png") if self.base == 3: self.backgroundGrille.setTexture( pygame.transform.scale(self.backgroundGrille.texture, (440, 440))) self.backgroundGrille.setPosition( 610 - self.backgroundGrille.texture_rect.centerx, 400 - self.backgroundGrille.texture_rect.centery) elif self.base == 4: self.backgroundGrille.setTexture( pygame.transform.scale(self.backgroundGrille.texture, (710, 710))) self.backgroundGrille.setPosition( 760 - self.backgroundGrille.texture_rect.centerx, 400 - self.backgroundGrille.texture_rect.centery) self.initRender()
def initRender(self): self.backgroundManager = elmtManager.elementManager() self.sakuraPetalManager = elmtManager.elementManager() textManager = elmtManager.elementManager() buttonManager = elmtManager.elementManager() buttonManagerSub = elmtManager.elementManager() buttonManagerGrille = elmtManager.elementManager() buttonManagerJeu = elmtManager.elementManager() #====================== Elements à ajouter ===========================# titleBackground = elmt.element(0,0,"sakuraBackground.jpg") titleBackground.texture = pygame.transform.scale(titleBackground.texture,(self.width,self.height)) self.backgroundManager.addElement(titleBackground) jeuBackground = elmt.element(0,0,"sakuraBackground2.jpg") jeuBackground.texture = pygame.transform.scale(jeuBackground.texture,(self.width,self.height)) self.backgroundManager.addElement(jeuBackground) for i in range(50): petal = elmt.element(randint(-500,1000),-50,"sakuraPetal.png") petal.texture = pygame.transform.scale(petal.texture,(40,40)) petal.action = (randint(1,5),randint(1,3),randint(0,600)) self.sakuraPetalManager.addElement(petal) Menutitle = elmt.element(355,230,"title.png") petal.texture = pygame.transform.scale(petal.texture,(40,40)) textManager.elements.append(Menutitle) self.loading = elmt.element(0,0,"loading.png") self.Seppuku = elmt.element(0,0,"Seppuku.png") #====================== Bouttons Home Screen ===========================# buttonPlay = elmt.element(5,330,"button.png") buttonPlay.setText(pygame.font.SysFont("comicsansms", 48).render('Play', True,(0,0,0))) buttonPlay.clickable = True buttonPlay.action = "SubMenu" buttonPlay.hoverable = True buttonManager.addElement(buttonPlay) buttonQuitter = elmt.element(560,330,"button.png") buttonQuitter.setText(self.font.render('Quitter', True,(0,0,0))) buttonQuitter.clickable = True buttonQuitter.action = "Quitter" buttonQuitter.hoverable = True buttonManager.addElement(buttonQuitter) #====================== Bouttons Sous Menu ===========================# buttonNew = elmt.element(5,330,"button.png") buttonNew.setText(self.font.render('Nouveau', True,(0,0,0))) buttonNew.clickable = True buttonNew.action = "Jouer" buttonNew.hoverable = True buttonManagerSub.addElement(buttonNew) buttonLoad = elmt.element(560,330,"button.png") buttonLoad.setText(self.font.render('Charger', True,(0,0,0))) buttonLoad.clickable = True buttonLoad.action = "Charger" buttonLoad.hoverable = True buttonManagerSub.addElement(buttonLoad) # ====================== Bouttons Choix Grille ===========================# buttonNeuf = elmt.element(5, 330, "button.png") buttonNeuf.setText(self.font.render('9x9', True, (0, 0, 0))) buttonNeuf.clickable = True buttonNeuf.action = "Neuf" buttonNeuf.hoverable = True buttonManagerGrille.addElement(buttonNeuf) buttonSeize = elmt.element(560, 330, "button.png") buttonSeize.setText(self.font.render('16x16', True, (0, 0, 0))) buttonSeize.clickable = True buttonSeize.action = "Seize" buttonSeize.hoverable = True buttonManagerGrille.addElement(buttonSeize) #====================== Bouttons Jeu ===========================# otherElmManagerJeu = elmtManager.elementManager() compteur = elmt.element(450,5,"compteur.png") compteur.setText(self.font.render("00:00:00", True,(0,0,0))) otherElmManagerJeu.addElement(compteur) vie = elmt.element(470,95,"compteur.png") vie.setTexture(pygame.transform.scale(vie.texture,(278,74))) vie.setText(self.font.render(vie.action, True,(0,190,0))) otherElmManagerJeu.addElement(vie) buttonVerif = elmt.element(420,620,"buttonRect.png") buttonVerif.setTexture(pygame.transform.scale(buttonVerif.texture,(400,180))) buttonVerif.setText(self.font.render('Verifier', True,(0,0,0))) buttonVerif.clickable = False buttonVerif.hoverable = False buttonVerif.action = "Verif" buttonManagerJeu.addElement(buttonVerif) buttonSauvegarder = elmt.element(100,620,"buttonRect.png") buttonSauvegarder.setTexture(pygame.transform.scale(buttonSauvegarder.texture,(400,180))) buttonSauvegarder.setText(pygame.transform.scale(self.font.render('Sauvegarder', True,(0,0,0)),(150,50))) buttonSauvegarder.clickable = False buttonSauvegarder.hoverable = False buttonSauvegarder.action = "Sauvegarder" buttonManagerJeu.addElement(buttonSauvegarder) buttonPause = elmt.element(740,620,"buttonRect.png") buttonPause.setTexture(pygame.transform.scale(buttonPause.texture,(400,180))) buttonPause.setText(self.font.render('Pause', True,(0,0,0))) buttonPause.clickable = False buttonPause.hoverable = False buttonPause.action = "Pause" buttonPause.clickStateToggle = True buttonManagerJeu.addElement(buttonPause) buttonhtp = elmt.element(120,0) buttonhtp.setText(self.font.render('How to play ?', True,(0,0,0))) buttonhtp.setTexture(pygame.Surface((buttonhtp.text.get_rect().w,buttonhtp.text.get_rect().h),pygame.SRCALPHA)) buttonhtp.clickable = False buttonhtp.hoverable = False buttonhtp.alphaClickable = False buttonhtp.action = "howToPlay" #====================== Bouttons Back to Home ===========================# buttonBack = elmt.element(820,-10,"buttonRect.png") buttonBack.setTexture(pygame.transform.scale(buttonBack.texture,(400,180))) buttonBack.setText(pygame.font.SysFont("comicsansms", 44).render('Menu', True,(0,0,0))) buttonBack.clickable = True buttonBack.action = "Back" buttonBack.hoverable = True buttonManagerSub.addElement(buttonBack) buttonManagerGrille.addElement(buttonBack) buttonManagerJeu.addElement(buttonBack) buttonManagerJeu.addElement(buttonhtp) #====================== Initialisation des Layouts ===========================# self.titleScreen = Lyt.Layout() self.titleScreen.addElmtManager(buttonManager) self.titleScreen.addElmtManager(textManager) self.subMenu = Lyt.Layout() self.subMenu.addElmtManager(buttonManagerSub) self.subMenu.addElmtManager(textManager) self.choixGrille = Lyt.Layout() self.choixGrille.addElmtManager(buttonManagerGrille) self.choixGrille.addElmtManager(textManager) self.jeuLayout = Lyt.Layout() self.jeuLayout.addElmtManager(otherElmManagerJeu) self.jeuLayout.addElmtManager(buttonManagerJeu)
def interface(self): button = str(self.__getattribute__("button")) # check for left click if button == "MouseButton.LEFT": # Initialize file dialogue interface root = tk.Tk() root.withdraw() filepath = filedialog.askopenfilename() if filepath == "": return try: # convert file contents to a dataframe dfs = pd.read_html(filepath) # Clear existing structure g.nodes = [] g.nodeX, g.nodeY, g.nodeColor = [], [], [] g.elements = [] loops = len(g.elementsPlot) for i in range(0, loops): g.elementsPlot.pop(0).remove() g.constraints = [] g.constraintX, g.constraintY, g.constraintColor = [], [], [] g.forces = [] loops = len(g.forcesPlot) for i in range(0, loops): g.forcesPlot.pop(0).remove() g.moments = [] loops = len(g.momentsPlot) for i in range(0, loops): g.momentsPlot.pop(0).remove() # Loop through the dataframe and create the structure table = 0 for i in dfs: if table == 0: for j in i.values: g.nodes.append(node(j[1], j[2], 'b')) g.nodeX.append(g.nodes[len(g.nodes)-1].u) g.nodeY.append(g.nodes[len(g.nodes)-1].v) g.nodeColor.append(g.nodes[len(g.nodes)-1].color) elif table == 1: for j in i.values: g.elements.append(element(g.nodes[int(j[1])], g.nodes[int(j[2])], j[3], j[4], j[5], 'k')) elif table == 2: for j in i.values: g.constraints.append(constraint(g.nodes[int(j[1])], bool(j[2]), bool(j[3]), bool(j[4]), 'y')) g.constraintX.append(g.constraints[len(g.constraints)-1].node.u) g.constraintY.append(g.constraints[len(g.constraints)-1].node.v) g.constraintColor.append(g.constraints[len(g.constraints)-1].color) elif table == 3: for j in i.values: g.forces.append(force(g.nodes[int(j[1])], j[2], j[3], 'darkred')) elif table == 4: for j in i.values: g.moments.append(moment(g.nodes[int(j[1])], j[2], 'darkred')) table += 1 except ValueError: # If the file chosen is not .html or has invalid contents tk.messagebox.showerror(title="File Error", message="Invalid Structure File") # Clear the dataframe dfs = 0
from funcoesTermosol import importa, plota, geraSaida from knot import knot from element import element from structure import structure import numpy as np [knot_numbers, knot_coordinates, element_numbers, incidence, load_numbers, forces, restriction_numbers, restriction] = importa('entry.xlsx') knot_list = [] element_list = [] for i in range(knot_numbers): # melhor codigo do mundo knot_list.append(knot(knot_coordinates[0][i], knot_coordinates[1][i], [forces[2 * i], forces[2*i + 1]])) for i in range(element_numbers): incidence0 = (int(incidence[i][0]) - 1)*2 incidence1 = (int(incidence[i][1]) - 1)*2 element_list.append(element(incidence[i][2], incidence[i][3], [knot_list[int(incidence[i][0]) - 1], knot_list[int(incidence[i][1]) - 1]], [[incidence0, incidence0 + 1], [incidence1, incidence1 + 1]])) object_structure = structure(element_list, knot_numbers, restriction, element_numbers) geraSaida(object_structure.reaction, object_structure.u_vector, object_structure.deformation, object_structure.internal_force, object_structure.tension)
return xDirection, yDirection clock.tick(FPS) window = pygame.display.set_mode((800, 600)) myScreen = Screen(window) knight = pygame.image.load("knight.png") First = pygame.image.load("python_blue.png") Second = pygame.image.load("python_white.png") Final = pygame.image.load("god_emperor_pythonos.png") mySecond = element(Second) myScreen.addItem("mySecond", mySecond) myScreen.addItem("Final", Final, 200, 0) myScreen.addItem("knight", knight, 600, 350) #myScreen.addItem("knight", knight) #myScreen.addItem("Final", Final) #myScreen.itemUpdate("Final", myScreen.getItem("Final").get_width()+800, 200) myScreen.ScreenLoad() pygame.display.update() xcounter = 0 ycounter = 0 game = 1 xDirection = True yDirection = True
def createElement(indices, A, E, I): g.elements.append( element(g.nodes[indices[0]], g.nodes[indices[1]], A, E, I, 'k'))
def run_rhythm(params, constants, verbose=False): '''Runs the main finite element method algorithm for calculating potential values (in mV). Biological parameters are setup for isotropic cardiac tissues. Inputs: params = data dictionary initialised by fill_params constants = constants dictionary; constants defined by Goktepe et .al Returns: data_dict = all computed & updated matrices ''' #time loop for n in constants['time'][1:]: #initalise/update things if n != 0: phi_global = params['phi_global_time'][:, ( n - 1)] #using the 'passed' phi_global frm previous time else: phi_global = params['phi_global'] sys.stdout.write( '\n\n*************************************************************** Starting iterations for n = {}\n\n' .format(n)) sys.stdout.flush() Tol = np.ones((global_matrix_size, 1)) * constants['tol'] #using global matrix size #re-initialise R_phi_global to start while loop params['R_phi_global'] = np.ones(global_matrix_size) while sum(params['R_phi_global']) > sum(Tol): #assymetry test # while sum(abs(params['R_phi_global'])) > sum(Tol): params['phi_step'][n] += 1 if verbose: sys.stdout.write( '\n Redistributing the phi_global the elements for element-level calculations\n\n' ) sys.stdout.flush() #redistribute/initialise things params['phi'][n, :] = global_to_element_21x21( np.zeros(1764), phi_global) params['r'][n, :] = params['r'][(n - 1), :] for z_d in np.arange(0, 1761, 4): nodes = [z_d, (z_d + 1), (z_d + 2), (z_d + 3)] ##assign node values & print variable params = element(nodes, n, params, constants) if verbose: sys.stdout.write( '\n Nodes: {}\n\n Residuals: {}\n\n'.format( nodes, params['R_phi'][z_d:(z_d + 4)])) sys.stdout.flush() #FHN element if z_d == 880: nodes = [z_d, (z_d + 1), (z_d + 2), (z_d + 3)] k = min(nodes) #initalise things to feed into functions r = params['r'] phi = params['phi'] for j in [0, 1, 2, 3]: params['r'][n, (j + k)] = r_FHN(r[(n - 1), (j + k)], phi[n, (j + k)], **constants) params['R_phi'][j + k] = residual_phi_FHN( j, phi, r, nodes, n, **constants) #partial derivative matrix for m in [0, 1, 2, 3]: params['p_phi_R_phi'][(m + k), ( j + k)] = partial_derivative_phi_R_phi_FHN( j, m, phi, r, nodes, n, **constants) if verbose: sys.stdout.write( '\n Nodes: {}\n\n Residuals: {}\n\n'.format( nodes, params['R_phi'][z_d:(z_d + 4)])) sys.stdout.flush() if verbose: sys.stdout.write( '\n\n Assembling 1764 element nodes to 484 global nodes...\n\n' ) sys.stdout.flush() params['R_phi_global'], params[ 'p_phi_R_phi_global'] = element_to_global_21x21( params['R_phi'], params['p_phi_R_phi']) #Newton's iteration for phi phi_global = phi_global - np.matmul( np.linalg.inv(params['p_phi_R_phi_global']), params['R_phi_global']) sys.stdout.write( '\n Maximum value of residual for n = {}: {}'.format( n, max(abs(params['R_phi_global'])))) sys.stdout.flush() params[ 'phi_global_time'][:, n] = phi_global #updates global phi matrix for time loop sys.stdout.write('\n\n\nPassed tol for n = {}'.format(n)) sys.stdout.flush() return params
def __init__(self): # 1、将初始数据读入到matrix_all列表中 self.matrix_all = [] reader = csv.reader(open('data_lvl_four.csv')) y = 0 length = 0 for line in reader: x = 0 length = len(line) for val in line: self.matrix_all.append(element.element(x, y, int(val))) x = x + 1 y = y + 1 # 2、原始数据加工 # 2-1、创建行列表 # 2-2、创建列列表 self.MATRIX_ROW_LENGTH = length self.MATRIX_COLUMN_LENGTH = length self.MATRIX_SQUARE_LENGTH = length if length == 4: self.create_four_lvl() self.init_row_lvl_four() self.init_column_lvl_four() self.init_parts_lvl_four() elif length == 9: self.init_nine_lvl() else: print('wrong data!') quit() print('原始数独数据:') self.matrix_print() print('块数据:') print('0块:') string = '' for i in self.matrix_parts[0].elements: string += ' ' string += str(i.value) string += '(' string += str(i.x) string += str(i.y) string += ')' print(string) print('') print('块数据:') print('1块:') string = '' for i in self.matrix_parts[1].elements: string += ' ' string += str(i.value) string += '(' string += str(i.x) string += str(i.y) string += ')' print(string) print('') print('块数据:') print('2块:') string = '' for i in self.matrix_parts[2].elements: string += ' ' string += str(i.value) string += '(' string += str(i.x) string += str(i.y) string += ')' print(string) print('') print('块数据:') print('3块:') string = '' for i in self.matrix_parts[3].elements: string += ' ' string += str(i.value) string += '(' string += str(i.x) string += str(i.y) string += ')' print(string) print('')
def event(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() return True if self.layoutEnCours == "titleScreen": action = self.titleScreen.event(event) if action == 'Quitter': self.quit() return True if action == 'SubMenu': self.subMenu.listElmtManager[0].elements[2].setPosition(820,-10) self.sound_manager.playOneTime('click') self.layoutEnCours = "SubMenu" elif self.layoutEnCours == "SubMenu": action = self.subMenu.event(event) if action == 'Jouer': self.sound_manager.playOneTime('click') self.layoutEnCours = "ChoixGrille" if action == 'Charger': self.sound_manager.playOneTime('click') self.loading.render(self.screen) pygame.display.flip() ok = self.sudoku.loadMenu() if ok == True: vie = '' self.Pause = True screenReady = elmt.element(0,0,"Ready.png") screenReady.clickable = True screenReady.action = "Ready" self.jeuLayout.listElmtManager[1].addElement(screenReady) for i in range(self.sudoku.trys): vie = vie + 'O' if i != self.sudoku.trys-1: vie = vie + ' ' self.jeuLayout.listElmtManager[0].elements[1].setText(self.font.render(vie, True,(0,190,0))) self.sound_manager.playXTime('vent') self.heure = int(self.sudoku.stringCompteur[0:2]) self.minute = int(self.sudoku.stringCompteur[3:5]) self.seconde = int(self.sudoku.stringCompteur[6:8]) self.jeuLayout.listElmtManager[0].elements[0].setText(self.font.render(self.sudoku.stringCompteur, True,(0,0,0))) if self.sudoku.base == 4: x = 10 y = 200 i = 0 for button in self.jeuLayout.listElmtManager[1].elements: i = i + 1 button.setPosition(x,y) y = y + 130 if i == 4: break self.jeuLayout.listElmtManager[0].elements[1].setPosition(70,130) self.jeuLayout.listElmtManager[0].elements[0].setPosition(50,40) else: self.jeuLayout.listElmtManager[0].elements[0].setPosition(450,5) self.jeuLayout.listElmtManager[0].elements[1].setPosition(470,95) self.jeuLayout.listElmtManager[1].elements[0].setPosition(420,620) self.jeuLayout.listElmtManager[1].elements[1].setPosition(100,620) self.jeuLayout.listElmtManager[1].elements[2].setPosition(740,620) self.layoutEnCours = "Jeu" if action == 'Back': self.sound_manager.playOneTime('click') self.layoutEnCours = 'titleScreen' elif self.layoutEnCours == 'ChoixGrille': action = self.choixGrille.event(event) if action == 'Neuf': self.sound_manager.playOneTime('click') self.loading.render(self.screen) pygame.display.flip() self.launchSudoku(3) self.layoutEnCours = "Jeu" self.sound_manager.playXTime('vent') self.jeuLayout.listElmtManager[0].elements[0].setPosition(450,5) self.jeuLayout.listElmtManager[0].elements[1].setPosition(470,95) self.jeuLayout.listElmtManager[1].elements[0].setPosition(420,620) self.jeuLayout.listElmtManager[1].elements[1].setPosition(100,620) self.jeuLayout.listElmtManager[1].elements[2].setPosition(740,620) if action == 'Seize': self.sound_manager.playOneTime('click') self.loading.render(self.screen) pygame.display.flip() self.launchSudoku(4) self.layoutEnCours = "Jeu" self.sound_manager.playXTime('vent') x = 10 y = 210 i = 0 for button in self.jeuLayout.listElmtManager[1].elements: i = i + 1 button.setPosition(x,y) y= y + 130 if i == 4: break self.jeuLayout.listElmtManager[0].elements[0].setPosition(50,45) self.jeuLayout.listElmtManager[0].elements[1].setPosition(70,135) if action == 'Back': self.sound_manager.playOneTime('click') self.layoutEnCours = 'titleScreen' elif self.layoutEnCours == "Jeu": if not self.timer: self.jeuLayout.listElmtManager[1].elements[4].hoverable = False pygame.time.set_timer( pygame.USEREVENT + 1,1000) self.timer = True action = self.jeuLayout.event(event) if action == 'Ready': self.Pause = False self.sound_manager.playOneTime('hajime') self.jeuLayout.listElmtManager[1].elements.pop() for button in self.jeuLayout.listElmtManager[1].elements: button.clickable = True button.hoverable = True if action == 'howToPlay': self.Pause = True for button in self.jeuLayout.listElmtManager[1].elements: button.clickable = False button.hoverable = False screenTuto = elmt.element(0,0,"tuto.png") screenTuto.clickable = True screenTuto.action = "Tuto" self.jeuLayout.listElmtManager[1].addElement(screenTuto) if action == 'Tuto': self.Pause = False self.jeuLayout.listElmtManager[1].elements.pop() for button in self.jeuLayout.listElmtManager[1].elements: button.clickable = True button.hoverable = True if action == 'Sauvegarder': self.sound_manager.playOneTime('click') self.sudoku.save() if action == 'Verif': if self.sudoku.isFinish(): self.sound_manager.playOneTime('banzai') self.Pause = True Banzai = elmt.element(0,0,"Banzai.png") Banzai.clickable = True Banzai.action = "titleScreen" self.jeuLayout.listElmtManager[0].addElement(Banzai) else: self.sudoku.trys = self.sudoku.trys - 1 self.sudoku.changeCaseState() vie = '' for i in range(self.sudoku.trys): vie = vie + 'O' if i != self.sudoku.trys-1: vie = vie + ' ' self.jeuLayout.listElmtManager[0].elements[1].setText(self.font.render(vie, True,(0,190,0))) if self.sudoku.trys == 0: self.layoutEnCours = "titleScreen" self.jeuLayout.listElmtManager[0].elements[1].render(self.screen) self.Seppuku.render(self.screen) pygame.display.flip() self.sound_manager.playOneTime('seppuku') pygame.time.wait(1000) self.sound_manager.playOneTime('loose') pygame.time.wait(2000) else: self.sound_manager.playOneTime('loose') if action == 'Pause': self.sound_manager.playOneTime('click') if self.Pause == False: self.Pause = True else: self.Pause = False if action == 'Back': self.sound_manager.playOneTime('click') self.layoutEnCours = 'titleScreen' if not self.Pause: self.sudoku.event(event) if action == "titleScreen": self.jeuLayout.listElmtManager[0].elements.pop() self.layoutEnCours = "titleScreen" if event.type == pygame.USEREVENT + 1: if not self.Pause: self.seconde = self.seconde + 1 if self.seconde == 60: self.seconde = 0 self.minute = self.minute + 1 if self.minute == 60: self.minute = 0 self.heure = self.heure + 1 if self.seconde < 10: stringCompteur = '0'+str(self.seconde) else: stringCompteur = str(self.seconde) if self.minute < 10: stringCompteur = '0'+ str(self.minute)+':'+ stringCompteur else: stringCompteur = str(self.minute)+':'+ stringCompteur if self.heure < 10: stringCompteur = '0'+str(self.heure)+':'+ stringCompteur else: stringCompteur = str(self.heure)+':'+ stringCompteur self.sudoku.stringCompteur = stringCompteur self.jeuLayout.listElmtManager[0].elements[0].setText(self.font.render(stringCompteur, True,(0,0,0)))
def __init__(self, theme=None): """ load bootstrap (requires use of page object) see http://bootswatch.com and http://bootstrapcdn.com for themes """ pui.element.__init__(self) bootstrap_cdn = '//netdna.bootstrapcdn.com' bootstrap_version = '3.1.1' bootstrap_css = 'bootstrap.min.css' bootstrap_js = 'bootstrap.min.js' bootstrap_css_url = '/'.join([ bootstrap_cdn, 'bootswatch' if theme else 'bootstrap', bootstrap_version, theme if theme else 'css', bootstrap_css ]) bootstrap_js_url = '/'.join([ bootstrap_cdn, 'bootstrap', bootstrap_version, 'js', bootstrap_js ]) jquery_js_url = '//code.jquery.com/jquery-1.10.1.min.js' self.head.append( pui.element( 'link', rel='stylesheet', href=bootstrap_css_url, type='text/css' ) ) # mobile viewport meta self.head.append( pui.element( 'meta', name="viewport", content="width=device-width, initial-scale=1" ) ) self.tail.append( pui.element( 'script', src=jquery_js_url, ) ) self.tail.append( pui.element( 'script', src=bootstrap_js_url, ) )