def redrawAllScene2(self, screen): LargeTree.generate(LargeTree, screen, self.scrollX) Stone.generate(Stone, screen, self.width, self.height, self.scrollX, self.snowed) Waterfall.generate(Waterfall, screen, self.scrollX) Bush.generate(Bush, screen, self.scrollX) for rabbit in Rabbit.rabbits: rabbit.draw(screen, self.scrollX) Bridge.generate(Bridge, screen, self.scrollX) MediumTree.generate(MediumTree, screen, self.scrollX) for bird in Bird.birds: bird.draw(screen, self.scrollX) if self.scrollX > -800: screen.blit(self.rightArrow, self.rightArrowRect) if self.scrollX < 800: screen.blit(self.leftArrow, self.leftArrowRect) #snow if self.snowed == True: for snowflake in self.snowflakes: screen.blit(self.snowflake, snowflake) #bloom instruction if self.currSeason == 0 or self.currSeason == 1: pixel = pygame.font.Font('Pixeled.ttf', 15) instructionSurf = pixel.render("CLICK ON TREES TO MAKE THEM BLOOM", True, (255, 255, 255)) instructionRect = instructionSurf.get_rect() instructionRect.center = (self.width / 2, 775) screen.blit(instructionSurf, instructionRect) elif self.currSeason == 2 or self.currSeason == 3: pixel = pygame.font.Font('Pixeled.ttf', 15) instructionSurf = pixel.render( "CLICK ON TREES TO MAKE THE LEAVES FALL", True, (255, 255, 255)) instructionRect = instructionSurf.get_rect() instructionRect.center = (self.width / 2, 775) screen.blit(instructionSurf, instructionRect) #menu bar screen.blit(self.menuBar, self.menuPos) if self.menuExpanded == True: screen.blit(self.seasonBar, self.seaPos) screen.blit(self.mydrawings, self.mydrawingsPos) if self.arrowShow == True: screen.blit(self.arrow, self.arrowPos) if self.seasonExpanded == True: screen.blit(self.spring, self.springPos) screen.blit(self.summer, self.summerPos) screen.blit(self.autumn, self.autumnPos) screen.blit(self.winter, self.winterPos) if self.currSeason == 0: screen.blit(self.spring1, self.springPos) elif self.currSeason == 1: screen.blit(self.summer1, self.summerPos) elif self.currSeason == 2: screen.blit(self.autumn1, self.autumnPos) elif self.currSeason == 3: screen.blit(self.winter1, self.winterPos) screen.blit(self.makeitsnow, self.makePos) if self.currSeason == 3: screen.blit(self.makeitsnow, self.makePos)
def verify_priority(self): if Bridge.bridge().bridge_priority != Priority.NONE: if self.car_direction != Bridge.bridge().bridge_priority: if Bridge.bridge_priority_semaphore._value == 0: Bridge.bridge_priority_semaphore.acquire() else: if Bridge.bridge_priority_semaphore._value == 1: Bridge.bridge_priority_semaphore.acquire()
def initialize(self, editableEntries): self.bridge = Bridge() areaDict = self.bridge.getAreaDictionary() self._tpc = TextProductCommon() self._tpc.setUp(areaDict) # List that will hold the ProductPart entries to be # displayed in the Product Editor. # Since this is just a sample format, no editableParts # are defined currently. if editableEntries: self.editableParts = editableEntries else: self.editableParts = []
class PARDMemoryCtrl(MemObject): type = 'PARDMemoryCtrl' cxx_header = "mem/pard_mem_ctrl.hh" port = SlavePort("Slave port") # Internal DRAM Controller # - TODO: Maybe we should use multiple DRAMCtrl? memories = Param.AbstractMemory("Internal memories") # Internal bus that connect all DRAMCtrl together _internal_bus = NoncoherentXBar() internal_bus = Param.NoncoherentXBar(_internal_bus, "Internal Bus") _internal_bridge = Bridge() internal_bridge = Param.Bridge(_internal_bridge, "Internal bridge") # Master port to access DRAMCtrl internal_port = MasterPort("Master port connect to internal bus") def attachDRAM(self): self.internal_port = self.internal_bridge.slave self.internal_bridge.master = self.internal_bus.slave #for mem in self.memories: # self.internal_bus.master = mem.port self.internal_bus.master = self.memories.port
def test_bridge_total_weight(): tollbridge = Bridge() mb = Motorbike("abc", 182) lorry = Lorry("abc", 5000) tollbridge.add_vehicle(mb) tollbridge.add_vehicle(lorry) assert tollbridge.calculate_total_weight() == 5182
def redrawAllScene1(self, screen): LargeTree.generate(LargeTree, screen, self.scrollX) Stone.generate(Stone, screen, self.width, self.height, self.scrollX, self.snowed) Waterfall.generate(Waterfall, screen, self.scrollX) Bush.generate(Bush, screen, self.scrollX) Bridge.generate(Bridge, screen, self.scrollX) MediumTree.generate(MediumTree, screen, self.scrollX) #snow if self.snowed == True: for snowflake in self.snowflakes: screen.blit(self.snowflake, snowflake) if self.showInstruction == True: pixel = pygame.font.Font('Pixeled.ttf', 15) instructionSurf = pixel.render("PRESS 'SPACE' TO ADD ANIMALS", True, (255, 255, 255)) instructionRect = instructionSurf.get_rect() instructionRect.center = (self.width / 2, 775) screen.blit(instructionSurf, instructionRect) if self.showNavigation == True: screen.blit(self.navigation, self.navRect) if self.scrollX > -800: screen.blit(self.rightArrow, self.rightArrowRect) if self.scrollX < 800: screen.blit(self.leftArrow, self.leftArrowRect) screen.blit(self.menuBar, self.menuPos) if self.menuExpanded == True: screen.blit(self.seasonBar, self.seaPos) if self.arrowShow == True: screen.blit(self.arrow, self.arrowPos) if self.seasonExpanded == True: screen.blit(self.spring, self.springPos) screen.blit(self.summer, self.summerPos) screen.blit(self.autumn, self.autumnPos) screen.blit(self.winter, self.winterPos) if self.currSeason == 0: screen.blit(self.spring1, self.springPos) elif self.currSeason == 1: screen.blit(self.summer1, self.summerPos) elif self.currSeason == 2: screen.blit(self.autumn1, self.autumnPos) elif self.currSeason == 3: screen.blit(self.winter1, self.winterPos) if self.currSeason == 3: screen.blit(self.makeitsnow, self.makePos)
def executeConfiguredQuery(geometryCollection, siteID, queryName): bridge = Bridge() spatialQueries = bridge.getSpatialQueries() query = spatialQueries[queryName] if query is None: raise Exception("No spatial query with name ", queryName, " is configured") constraints = query.get('constraints', {}) sortBy = query.get('sortBy', []) returnFields = query.get('returnFields', ['name']) maxResults = query.get('maxResults', None) if 'cwa' not in constraints: constraints['cwa'] = siteID return retrievePoints(geometryCollection, query['tableName'], constraints, sortBy, returnFields, maxResults)
def config_bridge(self, cfg): """ :type cfg: BridgeDef :return: Bridge """ b = Bridge(cfg.name, self.get_host(cfg.host) if cfg.host != '' else self, cfg.options.split(' ') if cfg.options != '' else [], cfg.ip_list) self.bridges[cfg.name] = b return b
def initialize(self, editableEntries): self.bridge = Bridge() areaDict = self.bridge.getAreaDictionary() self._tpc = TextProductCommon() self._tpc.setUp(areaDict) self._issueTime = self.productDict.get('issueTime') self._runMode = self.productDict.get('runMode') self._testMode = self._runMode in ['Practice', 'Test'] # List that will hold the Product Part entries to be # displayed in the Product Editor. # Since this is just a sample format, no editableParts # are defined. if editableEntries: self.editableParts = editableEntries else: self.editableParts = [] # Setup the Time Zones self.timezones = [] segments = self.productDict.get('segments') for segment in segments: self.timezones += segment.get('timeZones')
def _attach_bridges(self, system, mem_range, ext_ranges): self.mem2cls = Bridge(delay='1ns', ranges=mem_range) self.mem2cls.master = self.local_bus.slave self.mem2cls.slave = system.membus.master
class TheCPU(InOrderCPU): type = "TheCPU" turbodec = CoProcessor() sfetch_port = MasterPort("Instruction Port") agu_port = MasterPort("AGU Data Port") csuext_port = MasterPort("CSU DMA external Port") csuint_port = MasterPort("CSU DMA internal Port") biu0_port = MasterPort("BIU0 Port") biu1_port = MasterPort("BIU1 Port") biu2_port = MasterPort("BIU2 Port") mfetch_port = MasterPort("MPU Instruction Port") turbo_port = MasterPort("Turbo decoder Port") ibus = PriorityBus() mibus = PriorityBus() dbus = NoncoherentBus() d2d01_bridge = Bridge() d2d23_bridge = Bridge() d2d45_bridge = Bridge() dbus01 = PriorityBus() dbus23 = PriorityBus() dbus45 = PriorityBus() # Port buses agu_bus = NoncoherentBus() csuext_bus = NoncoherentBus() csuint_bus = NoncoherentBus() #hiobus = NoncoherentBus() im2sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='100ps') mim2sys_bridge = MIMBridge(req_size=2, queue_delay='1001ps', req_delay='0ps') dm02sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='1001ps') dm12sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='1001ps') dm22sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='1001ps') dm32sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='1001ps') dm42sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='1001ps') dm52sys_bridge = DMBridge(req_size=1, queue_delay='2000ps', req_delay='1001ps') a2i_bridge = Bridge() a2d_bridge = Bridge() a2s_bridge = Bridge(ranges=[AddrRange(0x40400000, 0x407FFFFF)]) c2i_bridge = Bridge() c2mi_bridge = Bridge() c2d_bridge = Bridge() c2c_bridge = Bridge(ranges=[AddrRange(0x0, 0xFFFFFFF)]) c2ddr0_bridge = Bridge(ranges=[AddrRange(0x60000000, 0x6FFFFFFF)]) c2ddr1_bridge = Bridge(ranges=[AddrRange(0x70000000, 0x7FFFFFFF)]) c2ddr2_bridge = Bridge(ranges=[AddrRange(0x80000000, 0x9FFFFFFF)]) c2ddr3_bridge = Bridge(ranges=[AddrRange(0xA0000000, 0xBFFFFFFF)]) def connectAllPorts(self, system_bus, cbus, sbus, ddr0bus, ddr1bus, ddr2bus, ddr3bus): # declare all internal buses # The order of the ports connetions SHALL NOT be changed, because it determines # the priority of each master port on the PriorityBuses # spu fetching port self.sfetch_port = self.ibus.slave # mpu fetching port self.mfetch_port = self.mibus.slave # biu port self.biu0_port = self.dbus01.slave self.biu1_port = self.dbus23.slave self.biu2_port = self.dbus45.slave # turbo decoder port self.turbo_port = self.dbus.slave # agu port self.a2i_bridge.ranges = [ AddrRange(0x0 + self.cpu_id.value * 0x1000000, 0x1FFFFF + self.cpu_id.value * 0x1000000) ] self.a2d_bridge.ranges = [ AddrRange(0x400000 + self.cpu_id.value * 0x1000000, 0xFFFFFF + self.cpu_id.value * 0x1000000) ] self.agu_port = self.agu_bus.slave self.agu_bus.master = self.a2i_bridge.slave self.a2i_bridge.master = self.ibus.slave self.agu_bus.master = self.a2d_bridge.slave self.a2d_bridge.master = self.dbus.slave self.agu_bus.master = self.a2s_bridge.slave self.a2s_bridge.master = sbus.slave self.agu_bus.master = self.turbodec.cop #agu_bus.slave = sbus.master #self.agu_bus.slave = system_bus.master # csu import port self.c2i_bridge.ranges = [ AddrRange(0x0 + self.cpu_id.value * 0x1000000, 0x1FFFFF + self.cpu_id.value * 0x1000000) ] self.c2mi_bridge.ranges = [ AddrRange(0x200000 + self.cpu_id.value * 0x1000000, 0x3FFFFF + self.cpu_id.value * 0x1000000) ] self.c2d_bridge.ranges = [ AddrRange(0x400000 + self.cpu_id.value * 0x1000000, 0xFFFFFF + self.cpu_id.value * 0x1000000) ] self.csuint_port = self.csuint_bus.slave self.csuint_bus.master = self.c2i_bridge.slave self.c2i_bridge.master = self.ibus.slave self.csuint_bus.master = self.c2mi_bridge.slave self.c2mi_bridge.master = self.mibus.slave self.csuint_bus.master = self.c2d_bridge.slave self.c2d_bridge.master = self.dbus.slave # csu export port self.csuext_port = self.csuext_bus.slave self.csuext_bus.master = self.c2c_bridge.slave self.c2c_bridge.master = cbus.slave self.csuext_bus.master = self.c2ddr0_bridge.slave self.c2ddr0_bridge.master = ddr0bus.slave self.csuext_bus.master = self.c2ddr1_bridge.slave self.c2ddr1_bridge.master = ddr1bus.slave self.csuext_bus.master = self.c2ddr2_bridge.slave self.c2ddr2_bridge.master = ddr2bus.slave self.csuext_bus.master = self.c2ddr3_bridge.slave self.c2ddr3_bridge.master = ddr3bus.slave #csu_bus.slave = hiobus.master # im self.ibus.master = self.im2sys_bridge.slave self.im2sys_bridge.master = system_bus.slave # mim self.mibus.master = self.mim2sys_bridge.slave self.mim2sys_bridge.master = system_bus.slave # dm self.dbus.master = self.d2d01_bridge.slave self.dbus.master = self.d2d23_bridge.slave self.dbus.master = self.d2d45_bridge.slave self.d2d01_bridge.master = self.dbus01.slave self.d2d23_bridge.master = self.dbus23.slave self.d2d45_bridge.master = self.dbus45.slave self.dm02sys_bridge.ranges = [ AddrRange(0x400000 + self.cpu_id.value * 0x1000000, 0x5FFFFF + self.cpu_id.value * 0x1000000) ] self.dm12sys_bridge.ranges = [ AddrRange(0x600000 + self.cpu_id.value * 0x1000000, 0x7FFFFF + self.cpu_id.value * 0x1000000) ] self.dm22sys_bridge.ranges = [ AddrRange(0x800000 + self.cpu_id.value * 0x1000000, 0x9FFFFF + self.cpu_id.value * 0x1000000) ] self.dm32sys_bridge.ranges = [ AddrRange(0xA00000 + self.cpu_id.value * 0x1000000, 0xBFFFFF + self.cpu_id.value * 0x1000000) ] self.dm42sys_bridge.ranges = [ AddrRange(0xC00000 + self.cpu_id.value * 0x1000000, 0xDFFFFF + self.cpu_id.value * 0x1000000) ] self.dm52sys_bridge.ranges = [ AddrRange(0xE00000 + self.cpu_id.value * 0x1000000, 0xFFFFFF + self.cpu_id.value * 0x1000000) ] self.d2d01_bridge.ranges = self.dm02sys_bridge.ranges self.d2d01_bridge.ranges += self.dm12sys_bridge.ranges self.d2d23_bridge.ranges = self.dm22sys_bridge.ranges self.d2d23_bridge.ranges += self.dm32sys_bridge.ranges self.d2d45_bridge.ranges = self.dm42sys_bridge.ranges self.d2d45_bridge.ranges += self.dm52sys_bridge.ranges self.dbus01.master = self.dm02sys_bridge.slave self.dbus01.master = self.dm12sys_bridge.slave self.dbus23.master = self.dm22sys_bridge.slave self.dbus23.master = self.dm32sys_bridge.slave self.dbus45.master = self.dm42sys_bridge.slave self.dbus45.master = self.dm52sys_bridge.slave self.dm02sys_bridge.master = system_bus.slave self.dm12sys_bridge.master = system_bus.slave self.dm22sys_bridge.master = system_bus.slave self.dm32sys_bridge.master = system_bus.slave self.dm42sys_bridge.master = system_bus.slave self.dm52sys_bridge.master = system_bus.slave
def __init__(self): self.bridge = Bridge()
def build(key): if key[0] == "G": if len(key) > 1: return Grass(key[1]) else: return Grass(None) if key[0] == "M": if len(key) > 1: return Mountain(key[1]) else: return Mountain(None) if key[0] == "F": if len(key) > 1: return Forest(key[1]) else: return Forest(None) if key[0] == "W": if len(key) > 1: return Wall(key[1]) else: return Wall(None) if key[0] == "~": if len(key) > 1: return Water(key[1]) else: return Water(None) if key[0] == "S": if len(key) > 1: return Sand(key[1]) else: return Sand(None) if key[0] == "E": if len(key) > 1: return MetalWall(key[1]) else: return MetalWall(None) if key[0] == "T": if len(key) > 1: return MetalFloor(key[1]) else: return MetalFloor(None) if key[0] == "P": if len(key) > 1: return Plating(key[1]) else: return Plating(None) if key[0] == ".": if len(key) > 1: return Void(key[1]) else: return Void(None) if key[0] == "O": if len(key) > 1: return WoodFloor(key[1]) else: return WoodFloor(None) if key[0] == "L": if len(key) > 1: return WoodFloorDam(key[1]) else: return WoodFloorDam(None) if key[0] == "B": if len(key) > 1: return Bridge(key[1]) else: return Bridge(None) if key[0] == "-": if len(key) > 1: return BridgeTop(key[1]) else: return BridgeTop(None) if key[0] == "+": if len(key) > 1: return BridgeBot(key[1]) else: return BridgeBot(None)
def free_bridge_from_priority(self): if Bridge.bridge().bridge_priority != Priority.NONE: if self.car_direction == Bridge.bridge().bridge_priority: if Bridge.bridge_priority_semaphore._value == 0: Bridge.bridge_priority_semaphore.release()
#Import neccecary Bridge class and plotting class from Bridge import Bridge import matplotlib.pyplot as plt #Choose the size we want for our bridges N = 176 #Get a set of 100 random bridges of size N bridges = [Bridge(size=N) for i in range(100)] #Give plot a snazzy title plt.suptitle("Simple Random Bridges before repeated addition") #Itterate through bridges and plot them for num in range(100): #"cd" into the correct subplot plt.subplot(10, 10, num + 1) #Remove the (honestly distracting) numbers next to graphs plt.xticks([]) plt.yticks([]) #Plot the "bodies" (i.e actual numbers) of the bridges plt.plot(bridges[num].body) #Finish this first graph by rendering it plt.show() #Go through each bridge and do the repeated addition algorithm 10,000 times [bridge.intervalItter(reps=100) for bridge in bridges] #Do the same process as before, just with this new data plt.suptitle("Simple Random Bridges after repeated addition") for num in range(100):
from Bridge import Bridge files = { "object0001": { "type": "com.symphony.hackathon.bitweaver", "version": "1.0", "data":[] } } bridge = Bridge("bot.user21", "https://develop2.symphony.com", "https://develop2-api.symphony.com:8444","") #bridge.renameRoom("RoDOROntj7QfyTZWQu1WoH___pxU3hyxdA", "New name for the chatRoom !", "Done by bot19") #bridge.renameRoom("RoDOROntj7QfyTZWQu1WoH___pxU3hyxdA","12345678901234567890123456789012345678901234567890","room 2") print(bridge.getUserStreamsInCsvFormat())
#Import neccecary Bridge class from Bridge import Bridge #Make a random bridge of size 20 B = Bridge(size=20) #Print the bridge print(B) #Update the bridge B.itter(reps=20) #Print the updated bridge print(B)
class Format(FormatTemplate.Formatter): def initialize(self, editableEntries): self.bridge = Bridge() areaDict = self.bridge.getAreaDictionary() self._tpc = TextProductCommon() self._tpc.setUp(areaDict) self._issueTime = self.productDict.get('issueTime') self._runMode = self.productDict.get('runMode') self._testMode = self._runMode in ['Practice', 'Test'] # List that will hold the Product Part entries to be # displayed in the Product Editor. # Since this is just a sample format, no editableParts # are defined. if editableEntries: self.editableParts = editableEntries else: self.editableParts = [] # Setup the Time Zones self.timezones = [] segments = self.productDict.get('segments') for segment in segments: self.timezones += segment.get('timeZones') def execute(self, productDict, editableEntries): self.productDict = productDict self.initialize(editableEntries) product = self.createTwitterProduct() return [product], self.editableParts def createTwitterProduct(self): text = '' segments = self.productDict['segments'] size = len(segments) index = 0 for segment in segments: sections = segment.get('sections') for section in sections: text += self.createAttribution(section) # CTAs are segment level text += self.addCTAs(segment) # Add break between segments if (index + 1 < size): text += '\n\n' index += 1 text += self.createOfficeTag(self.productDict.get('siteID')) return self._tpc.linebreak(text, 69) def createAttribution(self, sectionDict): vtecRecord = sectionDict.get('vtecRecord') hazName = self._tpc.hazardName(vtecRecord.get('hdln'), self._testMode, False) action = vtecRecord.get('act') if action == 'COR': action = vtecRecord.get('prevAct') # Endtime for all hazards in the section will be the same. hazard = sectionDict.get('hazardEvents')[0] endTime = hazard.get('endTime') endTimePhrase = ' until ' + endTime.strftime( '%l%M %p %Z').strip() + '.' areaPhrase = self.createAreaPhrase(sectionDict) attribution = hazName if action == 'NEW': attribution += ' issued for ' + areaPhrase + endTimePhrase elif action == 'CON': attribution += ' remains in effect for ' + areaPhrase + endTimePhrase elif action == 'EXT': attribution += ' has been extended for ' + areaPhrase + endTimePhrase elif action in ['EXA', 'EXB']: attribution += ' has been expanded to include ' + areaPhrase + endTimePhrase elif action == 'CAN': attribution += ' has been cancelled for ' + areaPhrase + '.' elif action == 'EXP': expTimeCurrent = self._issueTime if vtecRecord.get('endTime') <= expTimeCurrent: attribution += ' has expired for ' + areaPhrase + '.' else: timeWords = self._tpc.getTimingPhrase(vtecRecord, [], expTimeCurrent, timeZones=self.timezones) attribution += ' will expire ' + timeWords + ' for ' + areaPhrase + '.' return attribution def createAreaPhrase(self, sectionDict): areaPhrase = '' vtecRecord = sectionDict.get('vtecRecord') counter = 0 size = len(vtecRecord.get('id', [])) for ugc in vtecRecord.get('id', []): areaPhrase += self._tpc.getInformationForUGC(ugc, 'entityName') if size > 1: if counter < size - 2: areaPhrase += ', ' elif counter < size - 1: areaPhrase += ' and ' counter += 1 if size > 1: areaPhrase += ' counties' else: areaPhrase += ' county' return areaPhrase def addCTAs(self, segmentDict): callsToAction = self._tpc.getVal(segmentDict, 'callsToAction', None) if callsToAction and callsToAction != '': ctaText = '\n\n' ctaText += callsToAction.rstrip() return ctaText return '' def createOfficeTag(self, siteID): officeTag = ' #' + siteID return officeTag
def post(self, streamId): self.application.bridge.sendMessageToStream('hello', streamId, self.entitydata) entityDataAll = { "recommend": { "object0001": { "type": "com.symphony.hackathon.bitweaver", "version": "1.0", "data": [] } } } bridge = Bridge("bot.user21", "https://develop2.symphony.com", "https://develop2-api.symphony.com:8444", "") duplicateId = '' class WhoRequestHandler(RequestHandler): voteslip = """ <style> form div.box { display: inline-block; margin: 10px } .btn-info { color: #fff;
def main(): bridgegame = Bridge() bridgegame.deal() bridgegame.show_hands() bridgegame.show_hands_cards() bridgegame.show_hands_values() bridgegame.show_hands_distributions() bridgegame.read_rules() return
# ----------------------------------------------------------------------------- # Copyright (c) Ben Kuster 2016, all rights reserved. # # Created: 2016-09-16 # Version: 0.1 # Purpose: Entrypoint # ----------------------------------------------------------------------------- import argparse from Bridge import Bridge parser = argparse.ArgumentParser(description='Read a city GMLm, export CSG') parser.add_argument('--id', help='the GML ID of the bridge model to extract', required=True) parser.add_argument('--gml', help='the GML file name', required=True) parser.add_argument('--csg', help='output file name', required=True) args = parser.parse_args() bridge = Bridge(args.id, '3') bridge.parse(args.gml) bridge.write(args.csg)
class Format(FormatTemplate.Formatter): def initialize(self, editableEntries): self.bridge = Bridge() areaDict = self.bridge.getAreaDictionary() self._tpc = TextProductCommon() self._tpc.setUp(areaDict) # List that will hold the ProductPart entries to be # displayed in the Product Editor. # Since this is just a sample format, no editableParts # are defined currently. if editableEntries: self.editableParts = editableEntries else: self.editableParts = [] def execute(self, productDict, editableEntries): ''' Returns an html formatted string and a map of editable parts that is currently blank for this format. @param productDict: dictionary values @return: Returns the html string and map of editable parts ''' self.productDict = productDict self.initialize(editableEntries) htmlProduct = self.createHTMLProduct() return [htmlProduct], self.editableParts def createHTMLProduct(self): html = "<!DOCTYPE html>\n" html += "<html>\n" html += self.createHTMLHead() html += self.createHTMLBody() html += "</html>\n" file = self.writeToFile(html) return file + '\n\n' + html def createHTMLHead(self): html = "<head>\n<script src=\" http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false\"></script>" html += "<script>\n" html += "var x=new google.maps.LatLng(41.3, 263.9);" idx = 0 polygonPointLists = self.getPolygonPointLists() for polygon in polygonPointLists: idx = 0 for lon, lat in polygon: if (lon < 0): lon = lon + 360 html += 'var point' + str( idx) + '=new google.maps.LatLng(' + str(lat) + ',' + str( lon) + ');' idx = idx + 1 html += "function initialize() {\n" html += "var mapProp = {\n" html += " center:x, zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP };\n" html += "var map=new google.maps.Map(document.getElementById(\"googleMap\"), mapProp);\n" html += "var points=[\n" for i in range(idx): html += 'point' + str(i) if i < idx - 1: html += ',' html += "];" html += "var polygon=new google.maps.Polygon({ path:points, strokeColor:\"#0000FF\",\n" html += " strokeOpacity:0.8, strokeWeight:2, fillColor:\"#0000FF\", fillOpacity:0.4 });\n" html += "polygon.setMap(map); }\n" html += "google.maps.event.addDomListener(window, 'load', initialize);\n" html += "</script></head>\n" return html def createHTMLBody(self): html = "<body>\n" html += self.createHTMLTable(html) html += "</body>" return html def createHTMLTable(self, html): html += "<table border=\"1\" style=\"width:100%\">\n" # First Row is just the productName in a Header html += "<tr>\n" html += "<th colspan=\"2\">" + self.productDict[ 'productName'] + "</th>\n" html += "</tr>\n" # Second Row is the LegacyText and googleMap html += "<tr>\n" html += "<td rowspan=\"2\">\n" # Add the legacy text using <pre> to retain formatting html += "<pre>" + self.getLegacyText() + "</pre>\n" html += "</td>\n" impactedLocationsHTML = self.addImpactedLocationsToTable() # Add the google map if impactedLocationsHTML: html += "<td>\n" html += "<div id=\"googleMap\" style=\"width:800px;height:580px;\"></div>\n" html += "</td>\n" html += "</tr>\n" #Add 3rd row for locations html += impactedLocationsHTML else: # No locations so span 2 rows html += "<td rowspan=\"2\">\n" html += "<div id=\"googleMap\" style=\"width:800px;height:580px;\"></div>\n" html += "</td>\n" html += "</tr>\n" html += "</table>\n" return html def getLegacyText(self): productCategory = self.productDict.get('productCategory') # Added try block since ESF Formatter is not in baseline yet. try: # Import the correct legacy formatter if productCategory == 'FFA': import Legacy_FFA_Formatter legacyFormatter = Legacy_FFA_Formatter.Format() elif productCategory == 'FFW_FFS': import Legacy_FFW_FFS_Formatter legacyFormatter = Legacy_FFW_FFS_Formatter.Format() elif productCategory == 'FLW_FLS': import Legacy_FLW_FLS_Formatter legacyFormatter = Legacy_FLW_FLS_Formatter.Format() elif productCategory == 'ESF': import Legacy_ESF_Formatter legacyFormatter = Legacy_ESF_Formatter.Format() else: return 'There is no product formatter for this hazard type: ' + productCategory legacyText = legacyFormatter.execute(self.productDict, self.editableParts)[0][0] except: legacyText = 'Error running legacy formatter.' return legacyText def getPolygonPointLists(self): polygonPointLists = [] segments = self.productDict.get('segments') for segment in segments: sections = segment.get('sections') for section in sections: for hazard in section.get('hazardEvents', []): for geometry in hazard.get('geometry'): if geometry.geom_type == HazardConstants.SHAPELY_POLYGON: polygonPointLists.append( list(geometry.exterior.coords)) elif geometry.geom_type == HazardConstants.SHAPELY_POINT or geometry.geom_type == HazardConstants.SHAPELY_LINE: polygonPointLists.append(list(geometry.coords)) else: for geo in geometry: if geo.geom_type == HazardConstants.SHAPELY_POINT: continue else: polygonPointLists.append( list(geo.exterior.coords)) return polygonPointLists def addImpactedLocationsToTable(self): addToTable = False html = '' cityList = [] for segment in self.productDict.get('segments', []): for section in segment.get('sections', []): for hazard in section.get('hazardEvents', []): if hazard.get('citiesListFlag', False): cityList.extend(hazard.get('cityList', [])) addToTable = True if addToTable: html += "<tr>\n" html += "<td>\n" html += "<pre> Impacted cities include: </pre>\n" # Create the html list html += "<ul style=\"list-style-type:disc\">\n" for city in cityList: html += "<li>" + city + "</li>\n" html += "</ul>\n" html += "</td>\n" html += "</tr>\n" return html def writeToFile(self, html): seconds = int(time.time()) file = '/tmp/' + self.productDict.get('productCategory') + '_' + str( seconds) + '.html' f = open(file, 'w') f.write(html) f.close() return file
def initScene1(self): season = self.seasons[self.currSeason] #reset everything before changing the season Stone.backStones = [] Stone.middleStones = [] Stone.frontStones = [] Stone.dims = [] Stone.stoneSurface = dict() Stone.backSurface = dict() Stone.middleSurface = dict() Stone.frontSurface = dict() Tree.mediumTrees = [] Tree.bushes = [] Tree.largeTrees = [] Bridge.bridges = [] Waterfall.waterfalls = [] #generate stones for corner in Stone.cornerData: if corner[1] <= self.height / 3: layer = 0 h = random.randint(500, 800) w = random.randint(50, 100) for dim in range(random.randint(0, 4)): length = random.randint(5, w // 3) dimx = random.randint(corner[0], corner[0] + w * 2 // 3) dimy = 790 - h Stone.dims.append((length, dimx, dimy)) Stone.backStones.append((corner[0], 800, w, h, layer)) #add to surface dictionary for i in range(corner[0], corner[0] + w): Stone.stoneSurface[i] = 789 - h Stone.backSurface[i] = 789 - h elif corner[1] <= self.height * 2 / 3: layer = 1 h = random.randint(100, 500) w = random.randint(100, 150) for dim in range(random.randint(0, 4)): length = random.randint(5, w // 3) dimx = random.randint(corner[0], corner[0] + w * 2 // 3) dimy = 790 - h Stone.dims.append((length, dimx, dimy)) for i in range(corner[0], corner[0] + w): Stone.stoneSurface[i] = 789 - h Stone.middleSurface[i] = 789 - h Stone.middleStones.append((corner[0], 800, w, h, layer)) else: layer = 2 h = random.randint(20, 100) w = random.randint(50, 150) for dim in range(random.randint(0, 4)): length = random.randint(5, w // 3) dimx = random.randint(corner[0], corner[0] + w * 2 // 3) dimy = 790 - h Stone.dims.append((length, dimx, dimy)) for i in range(corner[0], corner[0] + w): Stone.stoneSurface[i] = 789 - h Stone.frontSurface[i] = 789 - h Stone.frontStones.append((corner[0], 800, w, h, layer)) #trees for tree in Tree.mediumTreeData: a = tree[0] + 800 b = Stone.stoneSurface.get(a, 800) if b != 800: Tree.mediumTrees.append(MediumTree(a, b, season)) x = tree[0] y = Stone.stoneSurface.get(x, 800) Tree.mediumTrees.append(MediumTree(x, y, season)) c = tree[0] - 800 d = Stone.stoneSurface.get(c, 800) if d != 800: Tree.mediumTrees.append(MediumTree(c, d, season)) for bush in Tree.bushData: a = bush[0] + 800 b = Stone.stoneSurface.get(a, 800) if b != 800: Tree.bushes.append(Bush(a, b, season)) x = bush[0] y = Stone.stoneSurface.get(x, 800) Tree.bushes.append(Bush(x, y, season)) c = bush[0] - 800 d = Stone.stoneSurface.get(c, 800) if d != 800: Tree.bushes.append(Bush(c, d, season)) for largeTree in Tree.largeTreeData: x = largeTree[0] y = 800 height = random.randint(300, 600) Tree.largeTrees.append(LargeTree(x, y, height, season)) Tree.largeTrees.append(LargeTree(x + 800, y, height, season)) Tree.largeTrees.append(LargeTree(x - 800, y, height, season)) #identify biggest gap gapOriginX,gapDestinationX,gapOriginY,gapDestinationY =\ Stone.findBiggestGap(Stone,Stone.stoneSurface) #setup back stones for waterfall self.backStoneX = gapOriginX + (gapOriginX - gapDestinationX) / 2 self.backStoneH = random.randint(500, 800) self.backStoneW = random.randint(50, 100) Stone.backStones.append( (self.backStoneX, 800, self.backStoneW, self.backStoneH, 0)) self.middleStoneX = self.backStoneX + 30 self.middleStoneH = random.randint(100, 500) self.middleStoneW = random.randint(100, 150) Stone.middleStones.append( (self.middleStoneX, 800, self.middleStoneW, self.middleStoneH, 1)) self.frontStoneX = self.middleStoneX + 30 self.frontStoneH = random.randint(20, 100) self.frontStoneW = random.randint(50, 150) Stone.frontStones.append( (self.frontStoneX, 800, self.frontStoneW, self.frontStoneH, 2)) Waterfall.waterfalls.append(Waterfall(self.backStoneX,800-self.backStoneH,\ self.backStoneW,self.backStoneH,self.middleStoneX,800-self.middleStoneH,\ self.middleStoneW,self.middleStoneH,self.frontStoneX,800-self.frontStoneH, self.frontStoneW,self.frontStoneH)) #identify bridge gaps #back if Stone.findBiggestGap(Stone, Stone.backSurface) != None: backX1,backX2,backY1,backY2 =\ Stone.findBiggestGap(Stone,Stone.backSurface) Bridge.bridges.append(\ Bridge(backX1,backX2,backY1,backY2)) #middle if Stone.findBiggestGap(Stone, Stone.middleSurface) != None: middleX1,middleX2,middleY1,middleY2 =\ Stone.findBiggestGap(Stone,Stone.middleSurface) Bridge.bridges.append(\ Bridge(middleX1,middleX2,middleY1,middleY2)) #front if Stone.findBiggestGap(Stone, Stone.frontSurface) != None: frontX1,frontX2,frontY1,frontY2 =\ Stone.findBiggestGap(Stone,Stone.frontSurface) Bridge.bridges.append(\ Bridge(frontX1,frontX2,frontY1,frontY2)) #instruction self.showInstruction = False self.showNavigation = True self.timer = 0 self.leftArrow = pygame.image.load('menu/leftarrow.png') self.rightArrow = pygame.image.load('menu/rightarrow.png') self.leftArrowRect = self.leftArrow.get_rect() self.rightArrowRect = self.rightArrow.get_rect() self.leftArrowRect.center = (50, self.height / 2) self.rightArrowRect.center = (1230, self.height / 2) self.navigation = pygame.image.load('menu/lookaround.png') self.navRect = self.navigation.get_rect() self.navRect.center = (self.width / 2, 30) #menubar self.menuBar = pygame.image.load('menu/menu.png') self.menuPos = (1150, 20) self.menuExpanded = False self.seasonBar = pygame.image.load('menu/seasons.png') self.seaPos = (960, 20) self.seasonExpanded = False self.arrow = pygame.image.load('menu/downarrow.png') self.arrowPos = (1055, 75) self.arrowShow = False self.spring = pygame.image.load('menu/spring.png') self.spring1 = pygame.image.load('menu/spring1.png') self.springPos = (960, 70) self.summer = pygame.image.load('menu/summer.png') self.summer1 = pygame.image.load('menu/summer1.png') self.summerPos = (960, 120) self.autumn = pygame.image.load('menu/autumn.png') self.autumn1 = pygame.image.load('menu/autumn1.png') self.autumnPos = (960, 170) self.winter = pygame.image.load('menu/winter.png') self.winter1 = pygame.image.load('menu/winter1.png') self.winterPos = (960, 220) self.makeitsnow = pygame.image.load('menu/makeitsnow.png') self.makePos = (20, 20) self.snowed = False #snow self.snowDensity = 30 self.snowSpeed = 10 self.snowflakes = [] self.snowflake = pygame.image.load('menu/snowflake.png') for i in range(self.snowDensity): snowX = random.randint(0, 1280) snowY = random.randint(0, 800) self.snowflakes.append((snowX, snowY))
class ComputeUnit(MemObject): type = 'ComputeUnit' cxx_class = 'ComputeUnit' cxx_header = 'gpu-compute/compute_unit.hh' wavefronts = VectorParam.Wavefront('Number of wavefronts') wfSize = Param.Int(64, 'Wavefront size (in work items)') num_SIMDs = Param.Int(4, 'number of SIMD units per CU') spbypass_pipe_length = Param.Int(4, 'vector ALU Single Precision bypass '\ 'latency') dpbypass_pipe_length = Param.Int(8, 'vector ALU Double Precision bypass '\ 'latency') issue_period = Param.Int(4, 'number of cycles per issue period') num_global_mem_pipes = Param.Int(1, 'number of global memory pipes per CU') num_shared_mem_pipes = Param.Int(1, 'number of shared memory pipes per CU') n_wf = Param.Int(1, 'Number of wavefront slots per SIMD') mem_req_latency = Param.Int(9, "Latency for request from the cu to ruby. "\ "Represents the pipeline to reach the TCP and "\ "specified in GPU clock cycles") mem_resp_latency = Param.Int(9, "Latency for responses from ruby to the "\ "cu. Represents the pipeline between the TCP "\ "and cu as well as TCP data array access. "\ "Specified in GPU clock cycles") system = Param.System(Parent.any, "system object") cu_id = Param.Int('CU id') vrf_to_coalescer_bus_width = Param.Int(32, "VRF->Coalescer data bus width "\ "in bytes") coalescer_to_vrf_bus_width = Param.Int(32, "Coalescer->VRF data bus width "\ "in bytes") memory_port = VectorMasterPort("Port to the memory system") translation_port = VectorMasterPort('Port to the TLB hierarchy') sqc_port = MasterPort("Port to the SQC (I-cache") sqc_tlb_port = MasterPort("Port to the TLB for the SQC (I-cache)") perLaneTLB = Param.Bool(False, "enable per-lane TLB") prefetch_depth = Param.Int(0, "Number of prefetches triggered at a time"\ "(0 turns off prefetching)") prefetch_stride = Param.Int(1, "Fixed Prefetch Stride (1 means next-page)") prefetch_prev_type = Param.PrefetchType('PF_PHASE', "Prefetch the stride "\ "from last mem req in lane of "\ "CU|Phase|Wavefront") execPolicy = Param.String("OLDEST-FIRST", "WF execution selection policy") xactCasMode = Param.Bool(False, "Behavior of xact_cas_load magic instr.") debugSegFault = Param.Bool(False, "enable debugging GPU seg faults") functionalTLB = Param.Bool(False, "Assume TLB causes no delay") localMemBarrier = Param.Bool(False, "Assume Barriers do not wait on "\ "kernel end") countPages = Param.Bool(False, "Generate per-CU file of all pages touched "\ "and how many times") global_mem_queue_size = Param.Int( 256, "Number of entries in the global " "memory pipeline's queues") local_mem_queue_size = Param.Int( 256, "Number of entries in the local " "memory pipeline's queues") ldsBus = Bridge() # the bridge between the CU and its LDS ldsPort = MasterPort("The port that goes to the LDS") localDataStore = Param.LdsState("the LDS for this CU") vector_register_file = VectorParam.VectorRegisterFile("Vector register "\ "file") out_of_order_data_delivery = Param.Bool( False, "enable OoO data delivery" " in the GM pipeline")
def run(self): direita = Direction.RIGHT esquerda = Direction.LEFT Bridge.new_bridge(direita) Bridge_Handler.new_handler() bridge_handler = Bridge_Handler.bridge_handler() ''' bridge_handler.append_car_to_bridge(1, 13, esquerda) bridge_handler.append_car_to_bridge(2, 12, esquerda) bridge_handler.append_car_to_bridge(3, 20, esquerda) bridge_handler.append_car_to_bridge(4, 6, esquerda) bridge_handler.append_car_to_bridge(5, 35, esquerda) bridge_handler.append_car_to_bridge(6, 35, esquerda) bridge_handler.append_car_to_bridge(7, 35, esquerda) bridge_handler.append_car_to_bridge(8, 35, esquerda) bridge_handler.append_car_to_bridge(9, 35, esquerda) bridge_handler.append_car_to_bridge(0, 15, esquerda) bridge_handler.begin_bridge() ''' while self.screen.running == True: start_time = time.time() self.screen.update() for event in pygame.event.get(): if event.type == pygame.QUIT: self.screen.running = False if event.type == pygame.MOUSEBUTTONDOWN: self.screen.verify_input_clicked(event) if self.screen.btn_criar_carro.collidepoint(event.pos): self.screen.create_car() if self.screen.btn_deletar_carro.collidepoint(event.pos): self.screen.delete_car() if self.screen.btn_ponte.collidepoint(event.pos): self.screen.set_bridge_priority() if event.type == pygame.KEYDOWN: self.screen.get_keyboard_input(event) if self.screen.active_travessia: colort = self.screen.color_inputA else: colort = self.screen.color_inputB if self.screen.active_espera: colore = self.screen.color_inputA else: colore = self.screen.color_inputB if self.screen.active_direcao: colord = self.screen.color_inputA else: colord = self.screen.color_inputB if self.screen.active_deletar: colordel = self.screen.color_inputA else: colordel = self.screen.color_inputB if self.screen.active_ponte: colorpon = self.screen.color_inputA else: colorpon = self.screen.color_inputB pygame.draw.rect(self.screen.screen, colort, self.screen.txt_box_travessia, 2) pygame.draw.rect(self.screen.screen, colore, self.screen.txt_box_espera, 2) pygame.draw.rect(self.screen.screen, colord, self.screen.txt_box_direcao, 2) pygame.draw.rect(self.screen.screen, colordel, self.screen.txt_box_deletar, 2) pygame.draw.rect(self.screen.screen, colorpon, self.screen.txt_box_ponte, 2) pygame.draw.rect(self.screen.screen, self.screen.color_buttons, self.screen.btn_criar_carro) pygame.draw.rect(self.screen.screen, self.screen.color_buttons, self.screen.btn_deletar_carro) pygame.draw.rect(self.screen.screen, self.screen.color_buttons, self.screen.btn_ponte) text_direcao_ponte = self.screen.base_font.render( self.screen.txt_direcao_ponte, True, (255, 255, 255)) text_travessia = self.screen.base_font.render( self.screen.txt_tempo_travessia, True, (255, 255, 255)) text_espera = self.screen.base_font.render( self.screen.txt_tempo_espera, True, (255, 255, 255)) text_direcao = self.screen.base_font.render( self.screen.txt_direcao, True, (255, 255, 255)) text_travessia_in = self.screen.base_font.render( self.screen.txt_input_travessia, True, (255, 255, 255)) text_espera_in = self.screen.base_font.render( self.screen.txt_input_espera, True, (255, 255, 255)) text_direcao_in = self.screen.base_font.render( self.screen.txt_input_direcao, True, (255, 255, 255)) text_deletar_in = self.screen.base_font.render( self.screen.txt_input_deletar, True, (255, 255, 255)) text_ponte_in = self.screen.base_font.render( self.screen.txt_input_ponte, True, (255, 255, 255)) text_ponte = self.screen.base_font.render(self.screen.txt_ponte, True, (255, 255, 255)) text_criar = self.screen.base_font.render( self.screen.txt_criar_carro, True, (255, 255, 255)) text_definir = self.screen.base_font.render( self.screen.txt_btn_ponte, True, (255, 255, 255)) text_deletar = self.screen.base_font.render( self.screen.txt_deletar_carro, True, (255, 255, 255)) text_instr_d = self.screen.font_instr.render( self.screen.txt_instruction_del, True, (255, 255, 255)) text_instr_d2 = self.screen.font_instr.render( self.screen.txt_instruction_del2, True, (255, 255, 255)) text_instr_di = self.screen.font_instr.render( self.screen.txt_instruction_dir, True, (255, 255, 255)) text_instr_po = self.screen.font_instr.render( self.screen.txt_instruction_dir, True, (255, 255, 255)) text_instr_tr = self.screen.font_instr.render( self.screen.txt_instruction_travessia, True, (255, 255, 255)) text_instr_es = self.screen.font_instr.render( self.screen.txt_instruction_espera, True, (255, 255, 255)) erro = self.screen.base_font.render(self.screen.txt_erro, True, (255, 255, 255)) self.screen.screen.blit(text_travessia, (self.screen.txt_box_travessia.x - 200, self.screen.txt_box_travessia.y + 8)) self.screen.screen.blit(text_espera, (self.screen.txt_box_espera.x - 200, self.screen.txt_box_espera.y + 8)) self.screen.screen.blit(text_direcao, (self.screen.txt_box_direcao.x - 200, self.screen.txt_box_direcao.y + 8)) self.screen.screen.blit(text_travessia_in, (self.screen.txt_box_travessia.x + 5, self.screen.txt_box_travessia.y + 8)) self.screen.screen.blit(text_espera_in, (self.screen.txt_box_espera.x + 5, self.screen.txt_box_espera.y + 8)) self.screen.screen.blit(text_direcao_in, (self.screen.txt_box_direcao.x + 5, self.screen.txt_box_direcao.y + 8)) self.screen.screen.blit(text_criar, (self.screen.btn_criar_carro.x + 12, self.screen.btn_criar_carro.y + 8)) self.screen.screen.blit(text_deletar_in, (self.screen.txt_box_deletar.x + 5, self.screen.txt_box_deletar.y + 8)) self.screen.screen.blit( text_deletar, (self.screen.btn_deletar_carro.x + 5, self.screen.btn_deletar_carro.y + 8)) #bot�ozinho self.screen.screen.blit(text_deletar, (self.screen.txt_box_deletar.x - 0, self.screen.txt_box_deletar.y - 65)) self.screen.screen.blit(text_instr_d, (self.screen.txt_box_deletar.x - 0, self.screen.txt_box_deletar.y - 40)) self.screen.screen.blit(text_instr_d2, (self.screen.txt_box_deletar.x - 0, self.screen.txt_box_deletar.y - 25)) self.screen.screen.blit(text_instr_di, (self.screen.txt_box_direcao.x - 200, self.screen.txt_box_direcao.y + 25)) self.screen.screen.blit(text_ponte_in, (self.screen.txt_box_ponte.x + 5, self.screen.txt_box_ponte.y + 8)) self.screen.screen.blit(text_ponte, (self.screen.txt_box_ponte.x, self.screen.txt_box_ponte.y - 65)) self.screen.screen.blit(text_instr_po, (self.screen.txt_box_ponte.x, self.screen.txt_box_ponte.y - 30)) self.screen.screen.blit(text_instr_tr, (self.screen.txt_box_travessia.x - 200, self.screen.txt_box_travessia.y + 26)) self.screen.screen.blit(text_instr_es, (self.screen.txt_box_espera.x - 200, self.screen.txt_box_espera.y + 26)) self.screen.screen.blit( text_definir, (self.screen.btn_ponte.x + 32, self.screen.btn_ponte.y + 8)) self.screen.screen.blit(erro, (400, 650)) self.screen.screen.blit(text_direcao_ponte, (450, 100)) self.screen.txt_box_direcao.w = max( 90, text_direcao_in.get_width() + 10) self.screen.txt_box_ponte.w = max(90, text_ponte_in.get_width() + 10) pygame.display.update() try: #print("FPS: ", 1.0 / (time.time() - start_time)) #print(Bridge.left_mutex._value,Bridge.right_mutex._value,Bridge.bridge_semaphore._value,Bridge.number_of_left,Bridge.number_of_right) pass except: pass pygame.quit() sys.exit()
import mido from Bridge import Bridge from Synth import Moog from itertools import permutations import random bridge = Bridge() lights = bridge.lights moog = Moog() #Temp. Disgusting I KNOW. lights = bridge.lights # lightz = list(set().union(permutations(lights, 1),permutations(lights, 2),permutations(lights, 3), permutations(lights, 4))) bridge.set_saturation(254) bridge.set_brightness(0) with mido.open_input() as inport: for message in inport: if (message.type == 'note_on'): moog.add_note(message) # current_hue = bridge.get_state(lights[1])['hue'] # print(current_hue + (moog.get_note_difference() * 200)) # bridge.set_hue(current_hue + (moog.get_note_difference() * 20)) bridge.set_on(True) elif (message.type == 'note_off'): moog.remove_note(message) if(moog.empty_notes()): bridge.set_on(False) elif (moog.cutoff(message)): bridge.set_hue(message.value * 500) moog.set_cutoff(message.value)
def bridge(): yield Bridge()
class ComputeUnit(MemObject): type = 'ComputeUnit' cxx_class = 'ComputeUnit' cxx_header = 'gpu-compute/compute_unit.hh' wavefronts = VectorParam.Wavefront('Number of wavefronts') # Wavefront size is 64. This is configurable, however changing # this value to anything other than 64 will likely cause errors. wf_size = Param.Int(64, 'Wavefront size (in work items)') num_SIMDs = Param.Int(4, 'number of SIMD units per CU') num_scalar_cores = Param.Int(1, 'number of Scalar cores per CU') num_scalar_mem_pipes = Param.Int(1, 'number of Scalar memory pipelines '\ 'per CU') simd_width = Param.Int(16, 'width (number of lanes) per SIMD unit') operand_network_length = Param.Int(1, 'number of pipe stages of operand '\ 'network') spbypass_pipe_length = Param.Int(4, 'vector ALU Single Precision bypass '\ 'latency') dpbypass_pipe_length = Param.Int(4, 'vector ALU Double Precision bypass '\ 'latency') scalar_pipe_length = Param.Int(1, 'number of pipe stages per scalar ALU') issue_period = Param.Int(4, 'number of cycles per issue period') vrf_gm_bus_latency = Param.Int(1, 'number of cycles per use of VRF to '\ 'GM bus') srf_scm_bus_latency = Param.Int(1, 'number of cycles per use of SRF '\ 'to Scalar Mem bus') vrf_lm_bus_latency = Param.Int(1, 'number of cycles per use of VRF to '\ 'LM bus') num_global_mem_pipes = Param.Int(1, 'number of global memory pipes per CU') num_shared_mem_pipes = Param.Int(1, 'number of shared memory pipes per CU') n_wf = Param.Int(10, 'Number of wavefront slots per SIMD') mem_req_latency = Param.Int(50, "Latency for request from the cu to ruby. "\ "Represents the pipeline to reach the TCP "\ "and specified in GPU clock cycles") mem_resp_latency = Param.Int(50, "Latency for responses from ruby to the "\ "cu. Represents the pipeline between the "\ "TCP and cu as well as TCP data array "\ "access. Specified in GPU clock cycles") system = Param.System(Parent.any, "system object") cu_id = Param.Int('CU id') vrf_to_coalescer_bus_width = Param.Int(64, "VRF->Coalescer data bus "\ "width in bytes") coalescer_to_vrf_bus_width = Param.Int(64, "Coalescer->VRF data bus "\ "width in bytes") memory_port = VectorMasterPort("Port to the memory system") translation_port = VectorMasterPort('Port to the TLB hierarchy') sqc_port = MasterPort("Port to the SQC (I-cache") sqc_tlb_port = MasterPort("Port to the TLB for the SQC (I-cache)") scalar_port = MasterPort("Port to the scalar data cache") scalar_tlb_port = MasterPort("Port to the TLB for the scalar data cache") perLaneTLB = Param.Bool(False, "enable per-lane TLB") prefetch_depth = Param.Int(0, "Number of prefetches triggered at a time"\ "(0 turns off prefetching)") prefetch_stride = Param.Int(1, "Fixed Prefetch Stride (1 means next-page)") prefetch_prev_type = Param.PrefetchType('PF_PHASE', "Prefetch the stride "\ "from last mem req in lane of "\ "CU|Phase|Wavefront") execPolicy = Param.String("OLDEST-FIRST", "WF execution selection policy") debugSegFault = Param.Bool(False, "enable debugging GPU seg faults") functionalTLB = Param.Bool(False, "Assume TLB causes no delay") localMemBarrier = Param.Bool(False, "Assume Barriers do not wait on "\ "kernel end") countPages = Param.Bool(False, "Generate per-CU file of all pages "\ "touched and how many times") scalar_mem_queue_size = Param.Int(32, "Number of entries in scalar "\ "memory pipeline's queues") global_mem_queue_size = Param.Int( 256, "Number of entries in the global " "memory pipeline's queues") local_mem_queue_size = Param.Int( 256, "Number of entries in the local " "memory pipeline's queues") max_wave_requests = Param.Int(64, "number of pending vector memory "\ "requests per wavefront") max_cu_tokens = Param.Int(4, "Maximum number of tokens, i.e., the number"\ " of instructions that can be sent to coalescer") ldsBus = Bridge() # the bridge between the CU and its LDS ldsPort = MasterPort("The port that goes to the LDS") localDataStore = Param.LdsState("the LDS for this CU") vector_register_file = VectorParam.VectorRegisterFile("Vector register "\ "file") scalar_register_file = VectorParam.ScalarRegisterFile("Scalar register "\ "file") out_of_order_data_delivery = Param.Bool( False, "enable OoO data delivery" " in the GM pipeline") register_manager = Param.RegisterManager("Register Manager") fetch_depth = Param.Int( 2, 'number of i-cache lines that may be ' 'buffered in the fetch unit.')
#Import neccecary Bridge class and plotting class from Bridge import Bridge import matplotlib.pyplot as plt from numpy import log #Itterate through all the values of 2n wanting to be tested, and then compute their mean for n in range(1, 176): #Set the size of the SRB to be N=2n N = 2 * n #Generate the random bridge B = Bridge(size=N) #Perform repeated addition 10,000 times, to get to a "limiting bridge" B.itter(reps=10000) #Choose how many Bridges will be in the sample taken sampleSize = 1000 #Initialize the sum of maximums in the sample maxes = 0 for i in range(sampleSize): #Repeatedly add 100 times to get a new bridge B.itter(reps=100) #Add the maximum absolute value of this bridge to our running tally maxes += B.maximum() #Make this an average by dividing by our sample size norm = maxes / sampleSize #Print out the mean obtained print(str(N) + ": " + str(norm)) #Data I obtained after running this file #data=[1.0,1.126,1.277,1.4,1.514,1.606,1.658,1.78,1.832,1.885,1.954,2.022,2.008,2.064,2.099,2.173,2.178,2.197,2.237,2.261,2.29,2.349,2.323,2.326,2.339,2.397,2.408,2.444,2.429,2.415,2.48,2.472,2.449,2.503,2.516,2.524,2.543,2.536,2.621,2.622,2.585,2.612,2.612,2.622,2.658,2.67,2.695,2.634,2.676,2.674,2.728,2.732,2.69,2.7,2.681,2.695,2.726,2.759,2.706,2.751,2.777,2.75,2.797,2.757,2.801,2.828,2.8,2.788,2.832,2.824,2.807,2.817,2.853,2.844,2.847,2.841,2.829,2.869,2.867,2.875,2.887,2.921,2.894,2.939,2.894,2.894,2.922,2.94,2.883,2.935,2.923,2.971,2.963,2.958,2.949,2.972,2.959,2.967,2.961,3.021,2.985,2.986,2.986,2.972,2.962,3.016,3.008,3.023,2.989,3.037,3.054,3.035,3.018,3.093,3.05,3.051,3.046,3.045,3.081,3.073,3.035,3.072,3.054,3.052,3.131,3.073,3.087,3.087,3.12,3.086,3.095,3.08,3.144,3.129,3.153,3.087,3.101,3.078,3.126,3.15,3.074,3.108,3.127,3.093,3.137,3.126,3.173,3.139,3.195,3.153,3.214,3.171,3.177,3.161,3.145,3.179,3.229,3.201,3.178,3.222,3.172,3.226,3.148,3.189,3.184,3.219,3.237,3.211,3.202,3.225,3.201,3.224,3.205,3.2,3.189] #The code used to graph this data """xaxis=[2*(n+1) for n in range(len(data))]
class MapsDatabaseAccessor(object): def __init__(self): self.bridge = Bridge() def _extract_poly_coords(self, geom): if geom.type == 'Polygon': exterior_coords = geom.exterior.coords[:] interior_coords = [] for int in geom.interiors: interior_coords += int.coords[:] elif geom.type == 'MultiPolygon': exterior_coords = [] interior_coords = [] for part in geom: epc = self._extract_poly_coords(part) # Recursive call exterior_coords += epc['exterior_coords'] interior_coords += epc['interior_coords'] else: raise ValueError('Unhandled geometry type: ' + repr(geom.type)) return { 'exterior_coords': exterior_coords, 'interior_coords': interior_coords } def getPolygonNames(self, tablename, locationField="name", columns=[]): req = DataAccessLayer.newDataRequest() req.setDatatype("maps") table = "mapdata." + tablename req.addIdentifier("table", table) req.addIdentifier("geomField", "the_geom") req.addIdentifier("locationField", locationField) locNames = DataAccessLayer.getAvailableLocationNames(req) return list(locNames) def getPolygonDict(self, tablename, siteID, locationField="name", columns=[]): req = DataAccessLayer.newDataRequest() req.setDatatype("maps") table = "mapdata." + tablename req.addIdentifier("table", table) req.addIdentifier("geomField", "the_geom") req.addIdentifier("locationField", locationField) req.addIdentifier("cwa", siteID) if columns: req.setParameters(columns) retGeoms = DataAccessLayer.getGeometryData(req) retDict = {} for retGeom in retGeoms: id = retGeom.getLocationName() if id: poly = self._extract_poly_coords(retGeom.getGeometry()) formattedPoly = [list(c) for c in poly['exterior_coords']] retDict[id] = formattedPoly return retDict # We now consolidate the dam specific metadata with the non-dam specific # metadata and do any variable substitutions that are possible completely # internally. def getDamInundationMetadata(self, damName, addGeneric=False): if not isinstance(damName, str): # This would only happen if the data from the recommender # was somehow corrupted. For now we are letting clients # report this condition if necessary. return None allDamInundationMetadata = self.bridge.getDamMetaData() if allDamInundationMetadata == None: # This represents a serious error because there should always at # least be some default non-dam specific metadata in base. tb = traceback.format_stack() sys.stderr.write( "\nUNEXPECTED CONDITION!!! None returned from Bridge:getDamMetaData()\n" ) for tbentry in tb[:-1]: sys.stderr.write(tbentry) sys.stderr.write(tb[-1].split('\n')[0] + "\n\n") return None damInundationMetadata = allDamInundationMetadata.get(damName) # Returning None is the expected behavior if nothing for this dam and # requester does not want the generic dam info included. if not addGeneric: return damInundationMetadata genericMetadata = allDamInundationMetadata.get("Dam") if genericMetadata == None: # This represents a serious error because there should always at # least be some default non-dam specific metadata in base. tb = traceback.format_stack() sys.stderr.write( "\nUNEXPECTED CONDITION!!! No non-dam specific metadata available.\n" ) for tbentry in tb[:-1]: sys.stderr.write(tbentry) sys.stderr.write(tb[-1].split('\n')[0] + "\n\n") return damInundationMetadata if damInundationMetadata == None: # This most often happens if the dam is in mapdata.daminundation # SQL table with no associated metadata in DamMetaData.py. For now # we are letting clients report this condition if necessary. # We can still fold the dam name into the generic metadata. damInundationMetadata = {} riverName = '|* riverName *|' cityInfo = '|* downstream town*|' else: riverName = damInundationMetadata.get("riverName", '|* riverName *|') cityInfo = damInundationMetadata.get("cityInfo", '|* downstream town*|') for k in genericMetadata.keys(): if k in damInundationMetadata: continue v = genericMetadata[k] v = v.replace("${damName}", damName) v = v.replace("${riverName}", riverName) v = v.replace("${cityInfo}", cityInfo) damInundationMetadata[k] = v return damInundationMetadata def getAllDamInundationMetadata(self): return self.bridge.getDamMetaData() def getBurnScarMetadata(self, burnscarName): burnScarAreaMetadata = self.bridge.getBurnScarMetaData() return burnScarAreaMetadata.get(burnscarName) def getAllBurnScarMetadata(self): return self.bridge.getBurnScarMetaData()