def drop_privs(): try: new_uid = int(os.getenv('SUDO_UID')) new_gid = int(os.getenv('SUDO_GID')) except TypeError: # they were running directly from a root user and didn't have # sudo env variables print """[!] WARNING: Couldn't drop privileges! To avoid this error, run from a non-root user. You may also use sudo, from a non-root user. Continue? (y/n)""", if raw_input().lower()[0] == 'y': return die() debug.info('Dropping privileges to uid: {}, gid: {}'.format(new_uid, new_gid)) # drop group before user, because otherwise you're not privileged enough # to drop group os.setgroups([]) os.setregid(new_gid, new_gid) os.setreuid(new_uid, new_uid) # check to make sure we can't re-escalate try: os.seteuid(0) print '[!] WARNING: Failed to drop privileges! Continue? (y/n)', if raw_input().lower()[0] != 'y': die() except OSError: return
def __init__(self): super(Cache_current_playlist, self).__init__(qobuz.path.cache, 'current-playlist', None, False) self.data = None self.set_cache_refresh(-1) info(self, "Cache duration: " + str(self.cache_refresh)) self.fetch_data()
def __init__(self, savevar, systems, delay, faction, numenemies, dyntype='', fgname='', greetingText=["Hello there, smuggler. Prepare to die!", "The price on your head is big enough that I missed my lunch."], directions=[], destination='', AdjustFaction=True): directions_mission.directions_mission.__init__ (self, savevar, directions, destination) debug.info('Ambush: Starting') if type(faction) != tuple and type(faction) != list: self.faction=(faction,) else: self.faction=faction if type(systems) != tuple and type(systems) != list: self.systems=(systems,) else: self.systems=systems if type(numenemies) != tuple and type(numenemies) != list: self.numenemies=(numenemies,) else: self.numenemies=numenemies if type(dyntype) != tuple and type(dyntype) != list: self.dyntype=(dyntype,) else: self.dyntype=dyntype if type(fgname) != tuple and type(fgname) != list: self.fgname=(fgname,) else: self.fgname=fgname self.greetingText = greetingText self.cp = VS.getCurrentPlayer() debug.debug("Ambush: self.cp = %s" % (self.cp)) self.delay = delay self.privateSetupPlayer() if type(AdjustFaction) != tuple and type(AdjustFaction) != list: self.AdjustFaction = (AdjustFaction,) else: self.AdjustFaction = AdjustFaction
def LoadLastMission(): global lastMission which=lastMission if which in last_constructor and which in last_args: if last_constructor[which]==None: if type(last_args[which])==str: VS.LoadNamedMissionScript(which, last_args[which]) else: VS.LoadNamedMissionScript(which, repr(last_args[which])+"()") else: cons=last_constructor[which] if type(cons)!=str: cons=cons.__name__ if type(last_args[which])==str: VS.LoadNamedMissionScript(which, '#\nimport '+cons+'\n'+cons+'.'+cons+last_args[which]) else: VS.LoadNamedMissionScript(which, '#\nimport '+cons+'\n'+cons+'.'+cons+repr(last_args[which])) del last_args[which] del last_constructor[which] else: debug.info('No last mission with name "'+str(which)+'"') if which in last_briefing[0]: del last_briefing[0][which] if which in last_briefing[1]: del last_briefing[1][which] lastMission=None
def precondition(self, playernum): for blah in self.precond: debug.info(blah) if (not quest.findQuest (playernum,blah)): return 0 debug.info("quest_surplus_factory.precondition success") return 1
def _add_tracks(self, playlist_id, nodes): if len(nodes) < 1: warn(self, 'Empty list...') return False step = 50 start = 0 numtracks = len(nodes) if numtracks > 1000: notifyH('Qobuz', 'Max tracks per playlist reached (1000)' '\nSkipping %s tracks' % (numtracks - 1000), 'icon-error-256') numtracks = 1000 while start < numtracks: if (start + step) > numtracks: step = numtracks - start str_tracks = '' info(self, "Adding tracks start: %s, end: %s" % (start, start + step)) for i in range(start, start + step): node = nodes[i] if node.nt != Flag.TRACK: warn(self, "Not a Node_track node") continue str_tracks += '%s,' % (str(node.nid)) if not api.playlist_addTracks( playlist_id=playlist_id, track_ids=str_tracks): return False start += step return True
def get_events(self): """ Method: get_events Description: 取得数据同步Event Parameter: 无 Return: Others: """ sync_events = [] db_query = self.__connection.get_active_query() with db_query: fields = [] for attr in self.__FIELDS: fields.append('"%s"' % attr.name) sub_sql = 'SELECT %s FROM user_sync.%s ORDER BY "priority" DESC, "id" ASC' % (','.join(fields), self.__TABLE_NAME) sql = 'SELECT rownum, s.* FROM (%s) s WHERE rownum <= %d' % (sub_sql, EVENT_BATCH_COUNT) debug.info(sql) events_cursor = db_query.select_cursor(sql) debug.info('result: %d' % events_cursor.rowcount) for event in events_cursor: sync_event = self.__get_OraSyncEvent()() sync_event.from_db_record(event) sync_events.append(sync_event) return sync_events
def getPlayerUnboundDifficulty (playa): global unbounddiff debug.debug('unbound diff '+str(unbounddiff)+' player '+str(playa)) if (playa>=len(unbounddiff)): debug.info('Error: no difficulty set') return 0 return unbounddiff[playa]
def look_for (fg, faction, numships,myunit, pos, gcd,newship=[None]): i=0 debug.debug("VS.getUnit (%d)" % (i)) un = VS.getUnit (i) while (not un.isNull()): i+=1 debug.debug("VS.getUnit (%d)" % (i)) un = VS.getUnit (i) i-=1 #now our i is on the last value while ((i>=0) and (numships>0)): debug.debug("VS.getUnit (%d)" % (i)) un = VS.getUnit (i) if (not un.isNull()): if (unOrTupleDistance(un,myunit,1)>gcd ): fac = un.getFactionName () fgname = un.getFlightgroupName () name = un.getName () if ((fg==fgname) and (fac==faction)): if (numships>0): if (vsrandom.random()<0.75): pos=move_to (un,pos) numships-=1 newship[0]=un debug.info("TTYmoving %s to current area" % (name)) else: #toast 'im! un.Kill() debug.info("TTYaxing %s" % (name)) i-=1 return (numships,pos)
def start(self): """ Starts the modules, views classes. Arguments: - self: The main object pointer. """ if self.cfg is None: self.cfg = settings.load() if not self.dbusd.start(): self.httpd.start() if self.cfg.getboolean("main", "startCam"): # Lets start the module idm = pocv.get_idm(self.cfg.get("main", "algorithm")) self.idm = idm.Module(self) self.idm.set_capture(self.cfg.getint("cam", "inputDevIndex")) gobject.timeout_add(10, self.update_frame) gobject.timeout_add(10, self.update_pointers) debug.info("mousetrap", "Idm loaded and started") # Lets build the interface self.itf = MainGui(self) self.itf.build_interface() self.itf.load_addons() debug.info("mousetrap", "MouseTrap's Interface Builded and Loaded") gobject.threads_init() self.loop.run()
def launch_new_wave(self): un = VS.getPlayer() if (vsrandom.randrange(0,4)==0): if (un): currentsystem = VS.getSystemFile() numadj=VS.GetNumAdjacentSystems(currentsystem) if (numadj): cursys=VS.GetAdjacentSystem(currentsystem,vsrandom.randrange(0,numadj)) else: cursys = 'enigma_sector/heavens_gate' debug.info("TJ: jumping to "+cursys) un.JumpTo(cursys) else: debug.info("TJ: jumping to [ERROR: you are null]") side = vsrandom.randrange(0,2) faction="confed" ai = vsrandom.randrange(0,6) if (0 and ai==0): ai = "printhello.py" else: ai = "default" if (side==0): faction=faction_ships.get_enemy_of("confed") else: faction=faction_ships.get_friend_of("confed") launched = launch.launch_wave_around_unit ("Shadow",faction,faction_ships.getRandomFighter(faction),ai,vsrandom.randrange(1,10),100.0,2000.0,VS.getPlayer(),'') if (vsrandom.randrange(0,10)==0): launch.launch_wave_around_unit ("ShadowCap",faction,faction_ships.getRandomCapitol(faction),ai,1,2000.0,4000.0,VS.getPlayer(),'')
def launch_types_around ( fg, faction, typenumbers, ai, radius, myunit, garbage_collection_distance,logo,fgappend=''): pos = whereTo(radius, myunit) nr_ships=0 for t in typenumbers: nr_ships+=t[1] debug.info("launch_types_around: before"+str(nr_ships)) retcontainer=[None] if (fgappend=='' and nr_ships>1): (nr_ships,pos) = look_for (fg,faction,nr_ships-1,myunit,pos,garbage_collection_distance,retcontainer) nr_ships+=1 debug.info("launch_types_around: after "+str(nr_ships)+ str(retcontainer)) count=0 ret=retcontainer[0] found=0 for tn in typenumbers: num = tn[1] if num>nr_ships: num=nr_ships for i in range(num): newship=[None] pos = LaunchNext (fg,faction,tn[0], ai, pos,logo,newship,fgappend) if (i==0 and found==0): ret=newship[0] found=1 nr_ships-=num if (nr_ships==0): return ret return ret
def SpawnShips(self): debug.info("spawning\n %s" % (debug.pp(self.names))) playa = VS.getPlayer() if (playa): for n in self.names: if (len(n) > 0): self.winglist += [self.SpawnShip(playa, n)]
def mpl(list,newsituation,forcechange): global situation debug.info("SITUATION IS "+str( situation)+" force change "+str(forcechange) + " bool "+ str(forcechange or newsituation!=situation)) if (forcechange or newsituation!=situation): debug.info("SITUATION IS RESET TO "+str( newsituation)) situation=newsituation VS.musicPlayList(list)
def start(self): """Poet server control shell.""" debug.info('Entering control shell') self.conn = PoetSocket(self.s.accept()[0]) print 'Welcome to posh, the Poet Shell!' print 'Running `help\' will give you a list of supported commands.' while True: try: argv = raw_input(POSH_PROMPT).split() if not argv: continue if argv[0] in self.builtins: self.builtins[argv[0]](argv) elif argv[0] in module.server_commands: try: module.server_commands[argv[0]](self, argv) except Exception as e: self.info(str(e.args)) else: self.info('{}: command not found'.format(argv[0])) # see comment above for self.continue_ for why this is here if not self.continue_: break except KeyboardInterrupt: print continue except EOFError: print break self.conn.send('fin') debug.info('Exiting control shell')
def Execute(self): VS.PythonAI.Execute(self); if quest_contraband_truck.truck_exit == 1: if self.got_target == 0: self.GetParent().SetTarget(universe.getRandomJumppoint()) self.trucktarget = (self.GetParent()).GetTarget() self.XMLScript ("++afterburn-turntowards.xml") self.AddReplaceLastOrder(1) self.got_target = 1 # starts him afterburning to target if self.timer == 0: self.timer = VS.GetGameTime() debug.info("Timer Set") elif self.timer + 30 < VS.GetGameTime() and self.autoed == 0: self.GetParent().ActivateJumpDrive(1) self.GetParent().AutoPilotTo(self.trucktarget,1) self.autoed = 1 elif self.timer + 5 < VS.GetGameTime(): self.MoveTo(self.trucktarget.Position(),1) self.AddReplaceLastOrder(1) # elif self.timer + 60 < VS.GetGameTime(): # gets him to auto to the jump and jump out # self.GetParent().ActivateJumpDrive(1) debug.info(self.GetParent().getMinDis(self.trucktarget.Position())) return 1
def Check(self): dead=not self.un if (not dead): dead = self.un.GetHull()<=0 if (dead): debug.info("Uunit died") if (VS.systemInMemory (self.starsystem)): if fg_util.RemoveShipFromFG(self.fgname,self.faction,self.type)!=0: if (VS.getPlayerX(0)): debug.info("unit died for real") if (VS.GetRelation(self.faction,VS.getPlayerX(0).getFactionName())>0): dynamic_battle.rescuelist[self.starsystem]=(self.faction,"Shadow",faction_ships.get_enemy_of(self.faction)) debug.info("friend in trouble") global dnewsman_ numships = updatePlayerKillList(0,self.faction) debug.info("num ships killed: "+numships) if ((numships>0 and VS.getPlayer()) or fg_util.NumShipsInFG(self.fgname,self.faction)==0): #generate news here fg killed IRL varList=[str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_DESTROYED,dnewsman_.STAGE_END,"unknown",self.faction,dnewsman_.SUCCESS_WIN,str(dynamic_battle.getImportanceOfType(self.type)),self.starsystem,dnewsman_.KEYWORD_DEFAULT,"unknown","unknown",self.fgname,self.type] if (numships>0 and VS.getPlayer()): varList=[str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_DESTROYED,dnewsman_.STAGE_END,VS.getPlayer().getFactionName(),self.faction,dnewsman_.SUCCESS_WIN,str(dynamic_battle.getImportanceOfType(self.type)),self.starsystem,dnewsman_.KEYWORD_DEFAULT,VS.getPlayer().getFlightgroupName(),VS.getPlayer().getName(),self.fgname,self.type] dnewsman_.writeDynamicString(varList) debug.info("news about unit dying") else: fg_util.LandShip(self.fgname,self.faction,self.type) return 0 else: sys=self.un.getUnitSystemFile() if (len(sys)): self.starsystem=sys return 1
def ReadBaseNameList(faction): bnl=[] debug.info('reading base names '+str(faction)) filename = 'universe/fgnames/'+faction+'.txt' try: f = open (filename,'r') bnl = f.readlines() f.close() except: try: f = open ('../'+filename,'r') bnl = f.readlines() f.close() except: try: f = open ('../universe/names.txt','r') bnl = f.readlines() f.close() except: try: f = open ('universe/names.txt','r') bnl = f.readlines() f.close() except: global genericalphabet bnl=genericalphabet for i in range(len(bnl)): bnl[i]=bnl[i].rstrip()#.decode('utf8','ignore') import vsrandom vsrandom.shuffle(bnl) return bnl
def fetch(self, Dir, lvl, whiteFlag, blackFlag): limit = getSetting('pagination_limit', isInt=True) self.data = None query = self.query if not query: from gui.util import Keyboard k = Keyboard('', 'My %s' % self.search_type) k.doModal() if not k.isConfirmed(): return False query = k.getText() query.strip() info(self, 'search_type: %s, query: %s' % (self.search_type, query)) source = self.source kwargs = {'query': query, 'limit': limit, } if source is not None: kwargs['source'] = source data = None self.data = data if self.search_type == 'albums': data = api.get('/collection/getAlbums', **kwargs) elif self.search_type == 'artists': data = api.get('/collection/getArtists', **kwargs) elif self.search_type == 'tracks': data = api.get('/collection/getTracks', **kwargs) # try: # self.data = data['items'] # return True # except Exception as e: # warn(self, 'Exception: %s' % e) self.data = data return False
def Win (self,un,terminate): self.SetVar(1) VS.IOmessage (0,"bounty mission",self.mplay,"[Computer] #00ff00Bounty Mission Accomplished!") un.addCredits(self.cred) if (terminate): debug.info("you win bounty mission!") VS.terminateMission(1)
def mkdir(self, dir): if not os.path.isdir(dir): try: os.makedirs(dir) except: warn("Cannot create directory: " + dir) exit(2) info(self, "Directory created: " + dir)
def getNode(self, nam=str()): """Returns the required Node, if it exists.""" name = str(nam) if name == str(): name = self.ROOT_KEY if name in self.nodes: return self.nodes[name] debug.info("Error: Node with name \'%s\' does not exist." % (name))
def Lose (self,terminate): VS.AdjustRelation(self.you.getFactionName(),self.faction,-.02,1) VS.IOmessage(0,"rescue_mission",self.mplay,"#ff0000Credit agency reports that you have failed the mission.") if len(self.donevar): quest.removeQuest(int(self.mplay[1:]),self.donevar,-1) if (terminate): debug.info("lose plunder mission") VS.terminateMission(0)
def __init__(self, categories, priceratio, quantratio, ships, planets, precondition=()): debug.info("initing quest_surplus_factory") self.ships=ships self.planets=planets self.priceratio=priceratio self.quantratio=quantratio self.categories=categories self.precond=precondition quest.quest_factory.__init__ (self,"quest_surplus")
def launchBases(sys): import universe debug.info('launching bases for '+sys) fac = VS.GetGalaxyFaction(sys) fgs = BaseFG (fac,sys) sig_units = universe.significantUnits() shipcount=zeros(len(sig_units)) for fg in fgs: launchBase(fg[0],fg[1],fac,sys,sig_units,shipcount)
def endbriefing(self): debug.info("ending briefing") del self.jump_ani del self.rnd_y del self.added_warp del self.brief_stage del self.begintime del self.faction del self.brief_you
def LaunchNav (self,i,playa): debug.info("launching %d" % i) if (i==0): launch.launch_wave_around_unit("BadGuys","aera","lekra","default",3,100,1000,playa) self.moveTrans(self.nav[0]) elif (i==1): if (self.launched[0]): self.moveTrans(self.nav[1]) launch.launch_wave_around_unit("BadGuys","aera","kyta","default",2,100,1000,playa)
def GenerateEnemies(self, jp, you): count = 0 VS.addObjective("Protect %s from %s" % (jp.getName(), self.faction)) self.objective = VS.addObjective( "Destroy All %s Hostiles" % self.faction) VS.setCompleteness(self.objective, 0.0) debug.info("quantity "+str(self.quantity)) while (count < self.quantity): L = launch.Launch() if self.dynatkfg == "": atkfg = "Shadow" else: atkfg = self.dynatkfg L.fg = atkfg L.dynfg = "" if count == 0: L.fgappend = "" else: L.fgappend = "_"+str(count) if (self.dynatktype == ''): L.type = faction_ships.getRandomFighter(self.faction) else: L.type = self.dynatktype L.ai = "default" L.num = 1 L.minradius = 20000.0 L.maxradius = 25000.0 try: L.minradius *= faction_ships.launch_distance_factor L.maxradius *= faction_ships.launch_distance_factor except: pass L.faction = self.faction launched = L.launch(you) if (count == 0): self.you.SetTarget(launched) if (1): launched.SetTarget(jp) else: launched.SetTarget(you) if (self.dedicatedattack): launched.setFgDirective('B') self.attackers += [launched] count += 1 if (self.respawn == 0 and len(self.attackers) > 0): self.respawn = 1 import universe universe.greet( self.greetingText, self.attackers[0], you, self.dyndeffg) else: VS.IOmessage(0, "escort mission", self.mplay, "Eliminate all %s ships here" % self.faction) VS.IOmessage(0, "escort mission", self.mplay, "You must protect %s." % jp.getName()) self.quantity = 0
def registerItem(self, category, item): list = [] if category in self._categories: list = self._categories[category] else: self._categories[category] = list list.append(item) debug.info("Registered plugin {0} in {1}", (item.__class__.__name__, category), "plugins")
def moveUnitTo(un,place,radius): where=place.LocalPosition() debug.info("moving "+un.getName() +" to "+place.getName()) prsize=place.rSize(); prp = VS.getPlanetRadiusPercent() if (place.isPlanet()): prsize*=1+prp where=(where[0]+un.rSize()+prsize+radius,where[1],where[2]); un.SetPosition(VS.SafeEntrancePoint(where,un.rSize())) return un
def run(): # Kill the splash screen if active stop_splash_service() # Get supplied command line arguments commandArgs = args() if commandArgs.terminal_mode and sys.stdin.isatty(): height, width = os.popen('stty size', 'r').read().split() termMatrix = TermMatrix() termMatrix.width = int(width) termMatrix.height = int(height) matrix = Matrix(termMatrix) else: # Check for led configuration arguments matrixOptions = led_matrix_options(commandArgs) matrixOptions.drop_privileges = False # Initialize the matrix matrix = Matrix(RGBMatrix(options=matrixOptions)) #Riff to add loading screen here loading = Loading(matrix) loading.render() # Read scoreboard options from config.json if it exists config = ScoreboardConfig("config", commandArgs, (matrix.width, matrix.height)) data = Data(config) #If we pass the logging arguments on command line, override what's in the config.json, else use what's in config.json (color will always be false in config.json) if commandArgs.logcolor and commandArgs.loglevel != None: debug.set_debug_status(config, logcolor=commandArgs.logcolor, loglevel=commandArgs.loglevel) elif not commandArgs.logcolor and commandArgs.loglevel != None: debug.set_debug_status(config, loglevel=commandArgs.loglevel) elif commandArgs.logcolor and commandArgs.loglevel == None: debug.set_debug_status(config, logcolor=commandArgs.logcolor, loglevel=config.loglevel) else: debug.set_debug_status(config, loglevel=config.loglevel) # Print some basic info on startup debug.info("{} - v{} ({}x{})".format(SCRIPT_NAME, SCRIPT_VERSION, matrix.width, matrix.height)) if data.latlng is not None: debug.info(data.latlng_msg) else: debug.error("Unable to find your location.") # Event used to sleep when rendering # Allows Web API (coming in V2) and pushbutton to cancel the sleep # Will also allow for weather alert to interrupt display board if you want sleepEvent = threading.Event() # Start task scheduler, used for UpdateChecker and screensaver, forecast, dimmer and weather scheduler = BackgroundScheduler() scheduler.start() # Any tasks that are scheduled go below this line # Make sure we have a valid location for the data.latlng as the geocode can return a None # If there is no valid location, skip the weather boards #Create EC data feed handler if data.config.weather_enabled or data.config.wxalert_show_alerts: if data.config.weather_data_feed.lower( ) == "ec" or data.config.wxalert_alert_feed.lower() == "ec": try: data.ecData = ECData(coordinates=(data.latlng)) except Exception as e: debug.error( "Unable to connect to EC, try running again in a few minutes" ) sys.exit(0) if data.config.weather_enabled: if data.config.weather_data_feed.lower() == "ec": ecWxWorker(data, scheduler) elif data.config.weather_data_feed.lower() == "owm": owmweather = owmWxWorker(data, scheduler) else: debug.error( "No valid weather providers selected, skipping weather feed") data.config.weather_enabled = False if data.config.wxalert_show_alerts: if data.config.wxalert_alert_feed.lower() == "ec": ecalert = ecWxAlerts(data, scheduler, sleepEvent) elif data.config.wxalert_alert_feed.lower() == "nws": nwsalert = nwsWxAlerts(data, scheduler, sleepEvent) else: debug.error( "No valid weather alerts providers selected, skipping alerts feed" ) data.config.weather_show_alerts = False if data.config.weather_forecast_enabled and data.config.weather_enabled: wxForecast(data, scheduler) # # Run check for updates against github on a background thread on a scheduler # if commandArgs.updatecheck: data.UpdateRepo = commandArgs.updaterepo checkupdate = UpdateChecker(data, scheduler, commandArgs.ghtoken) if data.config.dimmer_enabled: dimmer = Dimmer(data, matrix, scheduler) screensaver = None if data.config.screensaver_enabled: screensaver = screenSaver(data, matrix, sleepEvent, scheduler) if data.config.screensaver_motionsensor: motionsensor = Motion(data, matrix, sleepEvent, scheduler, screensaver) motionsensorThread = threading.Thread(target=motionsensor.run, args=()) motionsensorThread.daemon = True motionsensorThread.start() if data.config.pushbutton_enabled: pushbutton = PushButton(data, matrix, sleepEvent) pushbuttonThread = threading.Thread(target=pushbutton.run, args=()) pushbuttonThread.daemon = True pushbuttonThread.start() MainRenderer(matrix, data, sleepEvent).render()
def func_test(self, bank_num): import sram import tech debug.info(1, "Testing timing for sample 1bit, 16words SRAM with 1 bank") OPTS.check_lvsdrc = False OPTS.use_pex = True s = sram.sram(word_size=OPTS.word_size, num_words=OPTS.num_words, num_banks=OPTS.num_banks, name="test_sram1") OPTS.check_lvsdrc = True OPTS.use_pex = False tempspice = OPTS.openram_temp + "temp.sp" tempgds = OPTS.openram_temp + "temp.gds" s.sp_write(tempspice) s.gds_write(tempgds) self.assertFalse(verify.run_drc(s.name, tempgds)) self.assertFalse(verify.run_lvs(s.name, tempgds, tempspice)) self.assertFalse( verify.run_pex(s.name, tempgds, tempspice, output=OPTS.openram_temp + "temp_pex.sp")) import sp_file stimulus_file = OPTS.openram_temp + "stimulus.sp" a_stimulus = sp_file.sp_file(stimulus_file) self.write_stimulus(a_stimulus) simulator_file = OPTS.openram_temp + "simulator.sp" a_simulator = sp_file.sp_file(simulator_file) self.write_simulator(a_simulator) result_file = OPTS.openram_temp + "result" import os if OPTS.spice_name == "hspice": cmd = "hspice -mt 2 -i {0} > {1} ".format(simulator_file, result_file) else: cmd = "ngspice -b -i {0} > {1} ".format(simulator_file, result_file) os.system(cmd) import re sp_result = open(result_file, "r") contents = sp_result.read() key = "vr1" val = re.search(r"{0}(\s*)=(\s*)(\d*(.).*)(\s*)(from)".format(key), contents) val = val.group(3) value1 = float(self.convert_voltage_unit(val)) key = "vr2" val = re.search(r"{0}(\s*)=(\s*)(\d*(.).*)(\s*)(from)".format(key), contents) val = val.group(3) value2 = float(self.convert_voltage_unit(val)) self.assertTrue(round(value1) > 0.5 * tech.spice["supply_voltage"]) self.assertTrue(round(value2) < 0.5 * tech.spice["supply_voltage"]) OPTS.check_lvsdrc = True
def print_lvs_stats(): debug.info(1,"LVS runs: {0}".format(num_lvs_runs))
def run_pex(name, gds_name, sp_name, output=None, final_verification=False): """Run pex on a given top-level name which is implemented in gds_name and sp_name. """ global num_pex_runs num_pex_runs += 1 debug.warning("PEX using magic not implemented.") return 1 from tech import drc if output == None: output = name + ".pex.netlist" # check if lvs report has been done # if not run drc and lvs if not os.path.isfile(name + ".lvs.report"): run_drc(name, gds_name) run_lvs(name, gds_name, sp_name) """ 2. magic can perform extraction with the following: #!/bin/sh rm -f $1.ext rm -f $1.spice magic -dnull -noconsole << EOF tech load SCN3ME_SUBM.30 #scalegrid 1 2 gds rescale no gds polygon subcell true gds warning default gds read $1 extract ext2spice scale off ext2spice quit -noprompt EOF """ pex_rules = drc["xrc_rules"] pex_runset = { 'pexRulesFile': pex_rules, 'pexRunDir': OPTS.openram_temp, 'pexLayoutPaths': gds_name, 'pexLayoutPrimary': name, #'pexSourcePath' : OPTS.openram_temp+"extracted.sp", 'pexSourcePath': sp_name, 'pexSourcePrimary': name, 'pexReportFile': name + ".lvs.report", 'pexPexNetlistFile': output, 'pexPexReportFile': name + ".pex.report", 'pexMaskDBFile': name + ".maskdb", 'cmnFDIDEFLayoutPath': name + ".def", } # write the runset file f = open(OPTS.openram_temp + "pex_runset", "w") for k in sorted(pex_runset.iterkeys()): f.write("*{0}: {1}\n".format(k, pex_runset[k])) f.close() # run pex cwd = os.getcwd() os.chdir(OPTS.openram_temp) errfile = "{0}{1}.pex.err".format(OPTS.openram_temp, name) outfile = "{0}{1}.pex.out".format(OPTS.openram_temp, name) cmd = "{0} -gui -pex {1}pex_runset -batch 2> {2} 1> {3}".format(OPTS.pex_exe, OPTS.openram_temp, errfile, outfile) debug.info(2, cmd) os.system(cmd) os.chdir(cwd) # also check the output file f = open(outfile, "r") results = f.readlines() f.close() # Errors begin with "ERROR:" test = re.compile("ERROR:") stdouterrors = list(filter(test.search, results)) for e in stdouterrors: debug.error(e.strip("\n")) out_errors = len(stdouterrors) debug.check(os.path.isfile(output),"Couldn't find PEX extracted output.") return out_errors
def runTest(self): globals.init_openram("config_20_{0}".format(OPTS.tech_name)) OPTS.check_lvsdrc = False OPTS.spice_name = "hspice" OPTS.analytical_delay = False # This is a hack to reload the characterizer __init__ with the spice version import characterizer reload(characterizer) from characterizer import delay if not OPTS.spice_exe: debug.error("Could not find {} simulator.".format(OPTS.spice_name), -1) import sram debug.info(1, "Testing timing for sample 1bit, 16words SRAM with 1 bank") s = sram.sram(word_size=OPTS.word_size, num_words=OPTS.num_words, num_banks=OPTS.num_banks, name="sram1") OPTS.check_lvsdrc = True tempspice = OPTS.openram_temp + "temp.sp" s.sp_write(tempspice) probe_address = "1" * s.addr_size probe_data = s.word_size - 1 debug.info( 1, "Probe address {0} probe data {1}".format(probe_address, probe_data)) d = delay.delay(s, tempspice) import tech loads = [tech.spice["FF_in_cap"] * 4] slews = [tech.spice["rise_time"] * 2] data = d.analyze(probe_address, probe_data, slews, loads) #print data if OPTS.tech_name == "freepdk45": golden_data = { 'read1_power': 0.0345742, 'read0_power': 0.03526189999999999, 'write0_power': 0.0270014, 'delay1': [0.0573107], 'delay0': [0.07055809999999998], 'min_period': 0.234, 'write1_power': 0.0376625, 'slew0': [0.0284344], 'slew1': [0.0189185] } elif OPTS.tech_name == "scn3me_subm": golden_data = { 'read1_power': 11.2474, 'read0_power': 11.3148, 'write0_power': 6.9064, 'delay1': [1.0298], 'delay0': [1.4102], 'min_period': 4.063, 'write1_power': 11.6964, 'slew0': [1.3118], 'slew1': [0.9816656] } else: self.assertTrue(False) # other techs fail # Check if no too many or too few results self.assertTrue(len(data.keys()) == len(golden_data.keys())) # Check each result for k in data.keys(): if type(data[k]) == list: for i in range(len(data[k])): self.isclose(data[k][i], golden_data[k][i], 0.15) else: self.isclose(data[k], golden_data[k], 0.15) # reset these options OPTS.check_lvsdrc = True OPTS.analytical_delay = True reload(characterizer) globals.end_openram()
def bidir_search(self, correct_value, mode): """ This will perform a bidirectional search for either setup or hold times. It starts with the feasible priod and looks a half period beyond or before it depending on whether we are doing setup or hold. """ # NOTE: The feasible bound is always feasible. This is why they are different for setup and hold. # The clock will always be offset by 2*period from the start, so we want to look before and after # this time. They are also unbalanced so that the average won't be right on the clock edge in the # first iteration. if mode == "SETUP": feasible_bound = 1.25*self.period infeasible_bound = 2.5*self.period else: infeasible_bound = 1.5*self.period feasible_bound = 2.75*self.period # Initial check if reference feasible bound time passes for correct_value, if not, we can't start the search! self.write_stimulus(mode=mode, target_time=feasible_bound, correct_value=correct_value) stimuli.run_sim() ideal_clk_to_q = ch.convert_to_float(ch.parse_output("timing", "clk2q_delay")) setuphold_time = ch.convert_to_float(ch.parse_output("timing", "setup_hold_time")) debug.info(2,"*** {0} CHECK: {1} Ideal Clk-to-Q: {2} Setup/Hold: {3}".format(mode, correct_value,ideal_clk_to_q,setuphold_time)) if type(ideal_clk_to_q)!=float or type(setuphold_time)!=float: debug.error("Initial hold time fails for data value feasible bound {0} Clk-to-Q {1} Setup/Hold {2}".format(feasible_bound,ideal_clk_to_q,setuphold_time),2) if mode == "SETUP": # SETUP is clk-din, not din-clk setuphold_time *= -1e9 else: setuphold_time *= 1e9 passing_setuphold_time = setuphold_time debug.info(2,"Checked initial {0} time {1}, data at {2}, clock at {3} ".format(mode, setuphold_time, feasible_bound, 2*self.period)) #raw_input("Press Enter to continue...") while True: target_time = (feasible_bound + infeasible_bound)/2 self.write_stimulus(mode=mode, target_time=target_time, correct_value=correct_value) debug.info(2,"{0} value: {1} Target time: {2} Infeasible: {3} Feasible: {4}".format(mode, correct_value, target_time, infeasible_bound, feasible_bound)) stimuli.run_sim() clk_to_q = ch.convert_to_float(ch.parse_output("timing", "clk2q_delay")) setuphold_time = ch.convert_to_float(ch.parse_output("timing", "setup_hold_time")) if type(clk_to_q)==float and (clk_to_q<1.1*ideal_clk_to_q) and type(setuphold_time)==float: if mode == "SETUP": # SETUP is clk-din, not din-clk setuphold_time *= -1e9 else: setuphold_time *= 1e9 debug.info(2,"PASS Clk-to-Q: {0} Setup/Hold: {1}".format(clk_to_q,setuphold_time)) passing_setuphold_time = setuphold_time feasible_bound = target_time else: debug.info(2,"FAIL Clk-to-Q: {0} Setup/Hold: {1}".format(clk_to_q,setuphold_time)) infeasible_bound = target_time #raw_input("Press Enter to continue...") if ch.relative_compare(feasible_bound, infeasible_bound, error_tolerance=0.001): debug.info(3,"CONVERGE {0} vs {1}".format(feasible_bound,infeasible_bound)) break debug.info(2,"Converged on {0} time {1}.".format(mode,passing_setuphold_time)) return passing_setuphold_time
def runTest(self): globals.init_openram("config_20_{0}".format(OPTS.tech_name)) OPTS.spice_name = "ngspice" OPTS.analytical_delay = False OPTS.netlist_only = True # This is a hack to reload the characterizer __init__ with the spice version from importlib import reload import characterizer reload(characterizer) from characterizer import delay from sram import sram from sram_config import sram_config c = sram_config(word_size=1, num_words=16, num_banks=1) c.words_per_row = 1 c.recompute_sizes() debug.info(1, "Testing timing for sample 1bit, 16words SRAM with 1 bank") s = sram(c, name="sram1") tempspice = OPTS.openram_temp + "temp.sp" s.sp_write(tempspice) probe_address = "1" * s.s.addr_size probe_data = s.s.word_size - 1 debug.info( 1, "Probe address {0} probe data bit {1}".format( probe_address, probe_data)) corner = (OPTS.process_corners[0], OPTS.supply_voltages[0], OPTS.temperatures[0]) d = delay(s.s, tempspice, corner) import tech loads = [tech.spice["msflop_in_cap"] * 4] slews = [tech.spice["rise_time"] * 2] data, port_data = d.analyze(probe_address, probe_data, slews, loads) #Combine info about port into all data data.update(port_data[0]) if OPTS.tech_name == "freepdk45": golden_data = { 'delay_bl': [0.2003652], 'delay_br': [0.198698], 'delay_hl': [0.2108836], 'delay_lh': [0.2108836], 'leakage_power': 0.001564799, 'min_period': 0.508, 'read0_power': [0.43916689999999997], 'read1_power': [0.4198608], 'slew_hl': [0.0455126], 'slew_lh': [0.0455126], 'volt_bl': [0.6472883], 'volt_br': [1.114024], 'write0_power': [0.40681890000000004], 'write1_power': [0.4198608] } elif OPTS.tech_name == "scn4m_subm": golden_data = { 'delay_bl': [1.3937359999999999], 'delay_br': [1.2596429999999998], 'delay_hl': [1.5747600000000002], 'delay_lh': [1.5747600000000002], 'leakage_power': 0.00195795, 'min_period': 3.281, 'read0_power': [14.92874], 'read1_power': [14.369810000000001], 'slew_hl': [0.49631959999999997], 'slew_lh': [0.49631959999999997], 'volt_bl': [4.132618], 'volt_br': [5.573099], 'write0_power': [13.79953], 'write1_power': [14.369810000000001] } else: self.assertTrue(False) # other techs fail # Check if no too many or too few results self.assertTrue(len(data.keys()) == len(golden_data.keys())) self.assertTrue(self.check_golden_data(data, golden_data, 0.25)) globals.end_openram()
def print_attr(self): """Prints a list of attributes for the current layout object""" debug.info( 0, "|==============================================================================|" ) debug.info( 0, "|========= LIST OF OBJECTS (Rects) FOR: " + self.attr["name"]) debug.info( 0, "|==============================================================================|" ) for obj in self.objs: debug.info( 0, "layer={0} : offset={1} : size={2}".format( obj.layerNumber, obj.offset, obj.size)) debug.info( 0, "|==============================================================================|" ) debug.info( 0, "|========= LIST OF INSTANCES FOR: " + self.attr["name"]) debug.info( 0, "|==============================================================================|" ) for inst in self.insts: debug.info( 0, "name={0} : mod={1} : offset={2}".format( inst.name, inst.mod.name, inst.offset))
def isapproxdiff(self, f1, f2, error_tolerance=0.001): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name Return value: True if the files are the same, False otherwise. """ import re import debug with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2: while True: b1 = fp1.readline() b2 = fp2.readline() #print "b1:",b1, #print "b2:",b2, # 1. Find all of the floats using a regex numeric_const_pattern = r""" [-+]? # optional sign (?: (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc | (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc ) # followed by optional exponent part if desired (?: [Ee] [+-]? \d+ ) ? """ rx = re.compile(numeric_const_pattern, re.VERBOSE) b1_floats=rx.findall(b1) b2_floats=rx.findall(b2) debug.info(3,"b1_floats: "+str(b1_floats)) debug.info(3,"b2_floats: "+str(b2_floats)) # 2. Remove the floats from the string for f in b1_floats: b1=b1.replace(str(f),"",1) for f in b2_floats: b2=b2.replace(str(f),"",1) #print "b1:",b1, #print "b2:",b2, # 3. Check if remaining string matches if b1 != b2: self.fail("MISMATCH Line: {0}\n!=\nLine: {1}".format(b1,b2)) # 4. Now compare that the floats match if len(b1_floats)!=len(b2_floats): self.fail("MISMATCH Length {0} != {1}".format(len(b1_floats),len(b2_floats))) for (f1,f2) in zip(b1_floats,b2_floats): if not self.relative_compare(float(f1),float(f2),error_tolerance): self.fail("MISMATCH Float {0} != {1}".format(f1,f2)) if not b1 and not b2: return
def route(self): # Create names for the nets for the graphs nets = [] index = 0 # print(self.netlist) for pin_list in self.netlist: nets.append( channel_net("n{}".format(index), pin_list, self.vertical)) index += 1 # Create the (undirected) horizontal constraint graph hcg = collections.OrderedDict() for net1 in nets: for net2 in nets: if net1.name == net2.name: continue if net1.segment_overlap(net2): try: hcg[net1.name].add(net2.name) except KeyError: hcg[net1.name] = set([net2.name]) try: hcg[net2.name].add(net1.name) except KeyError: hcg[net2.name] = set([net1.name]) # Initialize the vertical conflict graph (vcg) # and make a list of all pins vcg = collections.OrderedDict() # print("Nets:") # for net_name in nets: # print(net_name, [x.name for x in nets[net_name]]) # Find the vertical pin conflicts # FIXME: O(n^2) but who cares for now if self.vertical: pitch = self.horizontal_nonpref_pitch else: pitch = self.vertical_nonpref_pitch for net in nets: vcg[net.name] = set() for net1 in nets: for net2 in nets: # Skip yourself if net1.name == net2.name: continue if net1.pins_overlap(net2, pitch): vcg[net2.name].add(net1.name) # Check if there are any cycles net1 <---> net2 in the VCG # Some of the pins may be to the left/below the channel offset, # so adjust if this is the case self.min_value = min([n.min_value for n in nets]) self.max_value = min([n.max_value for n in nets]) if self.vertical: real_channel_offset = vector(self.offset.x, min(self.min_value, self.offset.y)) else: real_channel_offset = vector(min(self.min_value, self.offset.x), self.offset.y) current_offset = real_channel_offset # Sort nets by left edge value nets.sort() while len(nets) > 0: current_offset_value = current_offset.y if self.vertical else current_offset.x # from pprint import pformat # print("VCG:\n", pformat(vcg)) # for name,net in vcg.items(): # print(name, net.min_value, net.max_value, net.conflicts) # print(current_offset) # get a route from conflict graph with empty fanout set for net in nets: # If it has no conflicts and the interval is to the right of the current offset in the track if net.min_value >= current_offset_value and len( vcg[net.name]) == 0: # print("Routing {}".format(net.name)) # Add the trunk routes from the bottom up for # horizontal or the left to right for vertical if self.vertical: self.add_vertical_trunk_route( net.pins, current_offset, self.vertical_nonpref_pitch) current_offset = vector( current_offset.x, net.max_value + self.horizontal_nonpref_pitch) else: self.add_horizontal_trunk_route( net.pins, current_offset, self.horizontal_nonpref_pitch) current_offset = vector( net.max_value + self.vertical_nonpref_pitch, current_offset.y) # Remove the net from other constriants in the VCG vcg = self.remove_net_from_graph(net.name, vcg) nets.remove(net) break else: # If we made a full pass and the offset didn't change... current_offset_value = current_offset.y if self.vertical else current_offset.x initial_offset_value = real_channel_offset.y if self.vertical else real_channel_offset.x if current_offset_value == initial_offset_value: debug.info( 0, "Channel offset: {}".format(real_channel_offset)) debug.info(0, "Current offset: {}".format(current_offset)) debug.info(0, "VCG {}".format(str(vcg))) debug.info(0, "HCG {}".format(str(hcg))) for net in nets: debug.info( 0, "{0} pin: {1}".format(net.name, str(net.pins))) if self.parent: debug.info(0, "Saving vcg.gds") self.parent.gds_write("vcg.gds") debug.error("Cyclic VCG in channel router.", -1) # Increment the track and reset the offset to the start (like a typewriter) if self.vertical: current_offset = vector( current_offset.x + self.horizontal_nonpref_pitch, real_channel_offset.y) else: current_offset = vector( real_channel_offset.x, current_offset.y + self.vertical_nonpref_pitch) # Return the size of the channel if self.vertical: self.width = current_offset.x + self.horizontal_nonpref_pitch - self.offset.x self.height = self.max_value + self.vertical_nonpref_pitch - self.offset.y else: self.width = self.max_value + self.horizontal_nonpref_pitch - self.offset.x self.height = current_offset.y + self.vertical_nonpref_pitch - self.offset.y
def runTest(self): OPENRAM_HOME = os.path.abspath(os.environ.get("OPENRAM_HOME")) globals.init_openram("{0}/tests/config_{1}".format( OPENRAM_HOME, OPTS.tech_name)) debug.info( 1, "Testing top-level front-end openram.py with 2-bit, 16 word SRAM.") out_file = "testsram" out_path = "/tmp/testsram_{0}_{1}_{2}".format(OPTS.tech_name, getpass.getuser(), os.getpid()) # make sure we start without the files existing if os.path.exists(out_path): shutil.rmtree(out_path, ignore_errors=True) self.assertEqual(os.path.exists(out_path), False) try: os.makedirs(out_path, 0o0750) except OSError as e: if e.errno == 17: # errno.EEXIST os.chmod(out_path, 0o0750) # specify the same verbosity for the system call options = "" for i in range(OPTS.debug_level): options += " -v" if OPTS.spice_name: options += " -s {}".format(OPTS.spice_name) # Always perform code coverage if OPTS.coverage == 0: debug.warning( "Failed to find coverage installation. This can be installed with pip3 install coverage" ) exe_name = "{0}/openram.py ".format(OPENRAM_HOME) else: exe_name = "coverage run -p {0}/openram.py ".format(OPENRAM_HOME) config_name = "{0}config_{1}_front_end.py".format( OPENRAM_HOME + "/tests/", OPTS.tech_name) cmd = "{0} -n -o {1} -p {2} {3} {4} 2>&1 > {5}/output.log".format( exe_name, out_file, out_path, options, config_name, out_path) debug.info(1, cmd) os.system(cmd) # assert an error until we actually check a result for extension in ["v", "lef", "sp", "gds"]: filename = "{0}/{1}.{2}".format(out_path, out_file, extension) debug.info(1, "Checking for file: " + filename) self.assertEqual(os.path.exists(filename), True) # Make sure there is any .lib file import glob files = glob.glob('{0}/*.lib'.format(out_path)) self.assertTrue(len(files) > 0) # Make sure there is any .html file if os.path.exists(out_path): datasheets = glob.glob('{0}/*html'.format(out_path)) self.assertTrue(len(datasheets) > 0) # grep any errors from the output output_log = open("{0}/output.log".format(out_path), "r") output = output_log.read() output_log.close() self.assertEqual(len(re.findall('ERROR', output)), 0) self.assertEqual(len(re.findall('WARNING', output)), 0) # now clean up the directory if OPTS.purge_temp: if os.path.exists(out_path): shutil.rmtree(out_path, ignore_errors=True) self.assertEqual(os.path.exists(out_path), False) globals.end_openram()
#!/usr/bin/env python # IRC Cryptocurrency Exchange (IRCCEX) # Developed by acidvegas in Python # https://git.supernets.org/acidvegas/irccex # irccex.py import os import sys sys.dont_write_bytecode = True os.chdir(sys.path[0] or '.') sys.path += ('core','modules') import debug debug.setup_logger() debug.info() if not debug.check_version(3): debug.error_exit('Python 3 is required!') if debug.check_privileges(): debug.error_exit('Do not run as admin/root!') import irc irc.Bot.run()
def __init__(self, name="cell_6t"): design.design.__init__(self, name) debug.info(2, "Create bitcell object") self.width = bitcell.chars["width"] self.height = bitcell.chars["height"]
def clear_blockages(self): """ Clear all blockages on the grid. """ debug.info(3, "Clearing all blockages") self.rg.clear_blockages()
def run_lvs(cell_name, gds_name, sp_name, final_verification=False): """Run LVS check on a given top-level name which is implemented in gds_name and sp_name. Final verification will ensure that there are no remaining virtual conections. """ global num_lvs_runs num_lvs_runs += 1 # Copy file to local dir if it isn't already if os.path.dirname(gds_name)!=OPTS.openram_temp.rstrip('/'): shutil.copy(gds_name, OPTS.openram_temp) if os.path.dirname(sp_name)!=OPTS.openram_temp.rstrip('/'): shutil.copy(sp_name, OPTS.openram_temp) write_netgen_script(cell_name) (outfile, errfile, resultsfile) = run_script(cell_name, "lvs") total_errors = 0 # check the result for these lines in the summary: try: f = open(resultsfile, "r") except FileNotFoundError: debug.error("Unable to load LVS results from {}".format(resultsfile),1) results = f.readlines() f.close() # Look for the results after the final "Subcircuit summary:" # which will be the top-level netlist. final_results = [] for line in reversed(results): if "Subcircuit summary:" in line: break else: final_results.insert(0,line) # There were property errors in any module. test = re.compile("Property errors were found.") propertyerrors = list(filter(test.search, results)) total_errors += len(propertyerrors) # Require pins to match? # Cell pin lists for pnand2_1.spice and pnand2_1 altered to match. # test = re.compile(".*altered to match.") # pinerrors = list(filter(test.search, results)) # if len(pinerrors)>0: # debug.warning("Pins altered to match in {}.".format(cell_name)) #if len(propertyerrors)>0: # debug.warning("Property errors found, but not checking them.") # Netlists do not match. test = re.compile("Netlists do not match.") incorrect = list(filter(test.search, final_results)) total_errors += len(incorrect) # Netlists match uniquely. test = re.compile("match uniquely.") correct = list(filter(test.search, final_results)) # Fail if they don't match. Something went wrong! if len(correct) == 0: total_errors += 1 if total_errors>0: # Just print out the whole file, it is short. for e in results: debug.info(1,e.strip("\n")) debug.error("{0}\tLVS mismatch (results in {1})".format(cell_name,resultsfile)) else: debug.info(1, "{0}\tLVS matches".format(cell_name)) return total_errors
def analyze_pins(self, pin_name): """ Analyze the shapes of a pin and combine them into pin_groups which are connected. """ debug.info(2, "Analyzing pin groups for {}.".format(pin_name)) pin_set = self.pins[pin_name] # This will be a list of pin tuples that overlap overlap_list = [] # Sort the rectangles into a list with lower/upper y coordinates bottom_y_coordinates = [(x.by(), x, "bottom") for x in pin_set] top_y_coordinates = [(x.uy(), x, "top") for x in pin_set] y_coordinates = bottom_y_coordinates + top_y_coordinates y_coordinates.sort(key=lambda x: x[0]) # Map the pins to the lower indices bottom_index_map = {x[1]: i for i, x in enumerate(y_coordinates) if x[2] == "bottom"} # top_index_map = {x[1]: i for i, x in enumerate(y_coordinates) if x[2] == "bottom"} # Sort the pin list by x coordinate pin_list = list(pin_set) pin_list.sort(key=lambda x: x.lx()) # for shapes in x order for pin in pin_list: # start at pin's lower y coordinate bottom_index = bottom_index_map[pin] compared_pins = set() for i in range(bottom_index, len(y_coordinates)): compare_pin = y_coordinates[i][1] # Don't overlap yourself if pin == compare_pin: continue # Done when we encounter any shape above the pin if compare_pin.by() > pin.uy(): break # Don't double compare the same pin twice if compare_pin in compared_pins: continue compared_pins.add(compare_pin) # If we overlap, add them to the list if pin.overlaps(compare_pin): overlap_list.append((pin, compare_pin)) # Initial unique group assignments group_id = {} gid = 1 for pin in pin_list: group_id[pin] = gid gid += 1 for p in overlap_list: (p1, p2) = p for pin in pin_list: if group_id[pin] == group_id[p2]: group_id[pin] = group_id[p1] # For each pin add it to it's group group_map = {} for pin in pin_list: gid = group_id[pin] if gid not in group_map: group_map[gid] = pin_group(name=pin_name, pin_set=[], router=self) # We always add it to the first set since they are touching group_map[gid].pins.add(pin) self.pin_groups[pin_name] = list(group_map.values())
def print_drc_stats(): debug.info(1,"DRC runs: {0}".format(num_drc_runs))
def getAlerts(self): params = {'point': '{0},{1}'.format(self.lat, self.lon)} #while True: try: debug.info("Checking NWS weather alerts") nws = noaa.NOAA().alerts(active=1, **params) self.network_issues = False except Exception as err: debug.error(err) self.network_issues = True pass #print (nws) if not self.network_issues: nwsalerts = [] for alert in nws['features']: nwsalerts.append(alert['properties']) _state = len(nwsalerts) debug.info("Number of alerts is " + str(_state)) if _state > 0: _attributes = {} _attributes['alerts'] = sorted( nwsalerts, key=self.sortedbyurgencyandseverity) _attributes['urgency'] = _attributes['alerts'][0][ 'urgency'] if _state > 0 else None _attributes['event_severity'] = _attributes['alerts'][0][ 'severity'] if _state > 0 else None _attributes['event'] = _attributes['alerts'][0][ 'event'] if _state > 0 else None _attributes['description'] = _attributes['alerts'][0][ 'description'] if _state > 0 else None _attributes['headline'] = _attributes['alerts'][0][ 'headline'] if _state > 0 else None _attributes['instruction'] = _attributes['alerts'][0][ 'instruction'] if _state > 0 else None _attributes['effective'] = _attributes['alerts'][0][ 'effective'] if _state > 0 else None _attributes['expires'] = _attributes['alerts'][0][ 'expires'] if _state > 0 else None _attributes['alerts_string'] = json.dumps( _attributes['alerts']) # Build up the weather alert string # urgency (Immediate, Expected, Future, Unknown) # severity severity level(minor, moderate, severe, extreme) # if self.data.config.wx_alert_nws_show_expire: warn_date = _attributes['expires'] else: warn_date = _attributes['effective'] #Convert to date for display warn_datetime = datetime.datetime.strptime( warn_date, self.alert_date_format) if self.time_format == "%H:%M": wx_alert_time = warn_datetime.strftime("%m/%d %H:%M") else: wx_alert_time = warn_datetime.strftime("%m/%d %I:%M %p") #Strip out the string at end of string for the title if "Warning" in _attributes['event']: wx_alert_title = _attributes['event'][:-(len(" Warning"))] wx_type = "warning" elif "Watch" in _attributes['event']: wx_alert_title = _attributes['event'][:-(len(" Watch"))] wx_type = "watch" elif "Advisory" in _attributes['event']: wx_alert_title = _attributes['event'][:-(len(" Advisory"))] wx_type = "advisory" else: wx_alert_title = _attributes['event'] wx_type = "statement" # Only create an alert for Immediate and Expected? if wx_type != "statement": self.data.wx_alerts = [ wx_alert_title, wx_type, wx_alert_time, _attributes['urgency'], _attributes['event_severity'] ] # Only interrupt the first time if self.weather_alert == 0 and self.data.wx_updated: self.data.wx_alert_interrupt = True self.sleepEvent.set() self.weather_alert += 1 debug.info(self.data.wx_alerts) else: self.data.wx_alert_interrupt = False self.weather_alert = 0 self.data.wx_alerts = [] debug.info("No active NWS alerts in your area") else: self.data.wx_alert_interrupt = False self.weather_alert = 0 self.data.wx_alerts = [] debug.info("No active NWS alerts in your area")
def print_pex_stats(): debug.info(1,"PEX runs: {0}".format(num_pex_runs))
def run_drc(name, gds_name, final_verification=False): """Run DRC check on a given top-level name which is implemented in gds_name.""" global num_drc_runs num_drc_runs += 1 from tech import drc drc_rules = drc["drc_rules"] drc_runset = OPTS.openram_temp + name + ".rsf" drc_log_file = "{0}{1}.log".format(OPTS.openram_temp, name) # write the runset file # the runset file contains all the options to run Assura # different processes may require different options f = open(drc_runset, "w") f.write("avParameters(\n") f.write(" ?flagDotShapes t\n") f.write(" ?flagMalformed t\n") f.write(" ?flagPathNonManhattanSeg all\n") f.write(" ?flagPathShortSegments endOnlySmart\n") f.write(" ?maintain45 nil\n") f.write(" ?combineNearCollinearEdges nil\n") f.write(")\n") f.write("\n") f.write("avParameters(\n") f.write(" ?inputLayout ( \"gds2\" \"{}\" )\n".format(gds_name)) f.write(" ?cellName \"{}\"\n".format(name)) f.write(" ?workingDirectory \"{}\"\n".format(OPTS.openram_temp)) f.write(" ?rulesFile \"{}\"\n".format(drc_rules)) f.write(" ?set ( \"GridCheck\" )\n") f.write(" ?avrpt t\n") f.write(")\n") f.close() # run drc cwd = os.getcwd() os.chdir(OPTS.openram_temp) cmd = "assura {0} 2> {1} 1> {2}".format(drc_runset, drc_log_file, drc_log_file) debug.info(1, cmd) os.system(cmd) os.chdir(cwd) # count and report errors errors = 0 try: f = open(OPTS.openram_temp + name + ".err", "r") except: debug.error("Unable to retrieve DRC results file.", 1) results = f.readlines() f.close() for line in results: if re.match("Rule No.", line): if re.search("# INFO:", line) == None: errors = errors + 1 debug.info(1, line) if errors > 0: debug.error("Errors: {}".format(errors)) return errors
if type(OPTS.config.num_banks) != int: debug.error("{0} is not an integer in config file.".format( OPTS.config.num_banks)) if not OPTS.config.tech_name: debug.error("Tech name must be specified in config file.") word_size = OPTS.config.word_size num_words = OPTS.config.num_words num_banks = OPTS.config.num_banks if (OPTS.out_name == ""): OPTS.out_name = "sram_{0}_{1}_{2}_{3}".format(word_size, num_words, num_banks, OPTS.tech_name) debug.info(1, "Output file is " + OPTS.out_name + ".(sp|gds|v|lib|lef)") print "Technology: %s" % (OPTS.tech_name) print "Word size: {0}\nWords: {1}\nBanks: {2}".format(word_size, num_words, num_banks) # only start importing modules after we have the config file import calibre import sram print "Start: ", datetime.datetime.now() # import SRAM test generation s = sram.sram(word_size=word_size, num_words=num_words, num_banks=num_banks,
def run_lvs(name, gds_name, sp_name, final_verification=False): """Run LVS check on a given top-level name which is implemented in gds_name and sp_name. """ global num_lvs_runs num_lvs_runs += 1 from tech import drc lvs_rules = drc["lvs_rules"] lvs_runset = OPTS.openram_temp + name + ".rsf" # The LVS compare rules must be defined in the tech file for Assura. lvs_compare = drc["lvs_compare"] # Define the must-connect names for disconnected LVS nets for Assura lvs_bindings = drc["lvs_bindings"] lvs_log_file = "{0}{1}.log".format(OPTS.openram_temp, name) # Needed when FET models are sub-circuits if drc.has_key("lvs_subcircuits"): lvs_sub_file = drc["lvs_subcircuits"] else: lvs_sub_file = "" # write the runset file # the runset file contains all the options to run Assura # different processes may require different options f = open(lvs_runset, "w") f.write("avParameters(\n") f.write(" ?inputLayout ( \"gds2\" \"{}\" )\n".format(gds_name)) f.write(" ?cellName \"{}\"\n".format(name)) f.write(" ?workingDirectory \"{}\"\n".format(OPTS.openram_temp)) f.write(" ?rulesFile \"{}\"\n".format(lvs_rules)) f.write(" ?autoGrid nil\n") f.write(" ?avrpt t\n") # The below options vary greatly between processes and cell-types f.write(" ?set (\"NO_SUBC_IN_GRLOGIC\")\n") f.write(")\n") f.write("\n") c = open(lvs_compare, "r") lines = c.read() c.close f.write(lines) f.write("\n") f.write("avCompareRules(\n") f.write(" schematic(\n") # Needed when FET models are sub-circuits if os.path.isfile(lvs_sub_file): f.write(" genericDevice(emptySubckt)\n") f.write(" netlist( spice \"{}\" )\n".format(lvs_sub_file)) f.write(" netlist( spice \"{}\" )\n".format(sp_name)) f.write(" )\n") f.write(" layout(\n") # Separate gnd shapes are sometimes not connected by metal, so this connects by name # The use of this option is not recommended for final DRC f.write(" joinNets( root \"gnd\" \"gnd*\" ) \n") f.write(" )\n") f.write(" bindingFile( \"{}\" )\n".format(lvs_bindings)) f.write(")\n") f.write("\n") f.write("avLVS()\n") f.close() # run lvs cwd = os.getcwd() os.chdir(OPTS.openram_temp) cmd = "assura {0} 2> {1} 1> {2}".format(lvs_runset, lvs_log_file, lvs_log_file) debug.info(1, cmd) os.system(cmd) os.chdir(cwd) errors = 0 try: f = open(OPTS.openram_temp + name + ".csm", "r") except: debug.error("Unable to retrieve LVS results file.", 1) results = f.readlines() f.close() for line in results: if re.search("errors", line): errors = errors + 1 debug.info(1, line) elif re.search("Schematic and Layout", line): debug.info(1, line) return errors
def warn(self,strin): debug.info(strin)
def run(self): # self.waiting.emit() debug.info("connecting to rfid Scanner Server...") self.socket = context.socket(zmq.REQ) try: self.socket.connect("tcp://192.168.1.183:4689") debug.info("connected.") except: debug.info(str(sys.exc_info())) self.socket.send_multipart(["CAPTURE",self.slNo]) # slNo = self.socket.recv() # debug.info "Received sl.No: " + slNo try: ack = self.socket.recv() debug.info(ack) self.ackReceived.emit(ack) except: debug.info(str(sys.exc_info())) self.socket.close() if (self.socket.closed == True): debug.info("Capture Socket closed.")
def IsFinished(): global traverser for i in range(len(traverser)-1,-1,-1): if IsEnd(traverser[i].node): del traverser[i] return len(traverser)>0 for iter in campaigns.campaigns: import verify_missions verify_missions.campaign_name[iter.name]=1 traverser.append(Traverser(iter)) debug.info(len(traverser)) while len(traverser): IsFinished() progress=False variables=[] for i in range(len(traverser)): var=traverser[i].Update(variables) if (type(var)==type([])): variables=var progress=True if not progress and len(traverser): debug.info("Deadlock ") break
def __render_off_day(self): debug.info('ping_day_off') self._draw_off_day() time.sleep(21600) #sleep 6 hours
def _draw_game(self): self.data.refresh_overview() overview = self.data.overview home_score = overview['home_score'] away_score = overview['away_score'] while True: # Refresh the data if self.data.needs_refresh: debug.info('Refresh game overview') self.data.refresh_overview() self.data.needs_refresh = False if self.data.overview != 0: overview = self.data.overview # Use This code if you want the goal animation to run only for your fav team's goal # if self.data.fav_team_id == overview['home_team_id']: # if overview['home_score'] > home_score: # self._draw_goal() # else: # if overview['away_score'] > away_score: # self._draw_goal() # Use this code if you want the goal animation to run for both team's goal. # Run the goal animation if there is a goal. if overview['home_score'] > home_score or overview[ 'away_score'] > away_score: # audio possible insertion point self._draw_goal() # Prepare the data score = '{}-{}'.format(overview['away_score'], overview['home_score']) period = overview['period'] time_period = overview['time'] # Set the position of the information on screen. time_period_pos = center_text( self.font_mini.getsize(time_period)[0], 32) score_position = center_text(self.font.getsize(score)[0], 32) period_position = center_text( self.font_mini.getsize(period)[0], 32) # Set the position of each logo on screen. away_team_logo_pos = self.screen_config.team_logos_pos[str( overview['away_team_id'])]['away'] home_team_logo_pos = self.screen_config.team_logos_pos[str( overview['home_team_id'])]['home'] # Open the logo image file away_team_logo = Image.open('logos/{}.png'.format( self.data.get_teams_info[ overview['away_team_id']]['abbreviation'])) home_team_logo = Image.open('logos/{}.png'.format( self.data.get_teams_info[ overview['home_team_id']]['abbreviation'])) # Draw the text on the Data image. self.draw.multiline_text((score_position, 15), score, fill=(255, 255, 255), font=self.font, align="center") self.draw.multiline_text((period_position, -1), period, fill=(255, 255, 255), font=self.font_mini, align="center") self.draw.multiline_text((time_period_pos, 5), time_period, fill=(255, 255, 255), font=self.font_mini, align="center") # Put the data on the canvas self.canvas.SetImage(self.image, 0, 0) # Put the images on the canvas self.canvas.SetImage(away_team_logo.convert("RGB"), away_team_logo_pos["x"], away_team_logo_pos["y"]) self.canvas.SetImage(home_team_logo.convert("RGB"), home_team_logo_pos["x"], home_team_logo_pos["y"]) # Load the canvas on screen. self.canvas = self.matrix.SwapOnVSync(self.canvas) # Refresh the Data image. self.image = Image.new('RGB', (self.width, self.height)) self.draw = ImageDraw.Draw(self.image) # Check if the period is over if self.data.get_end_of_period(): debug.info('End of Period check successful') self.draw_end_of_period() # Check if the game is over if overview['game_status'] == 6 or overview['game_status'] == 7: debug.info('GAME OVER') break # Save the scores. away_score = overview['away_score'] home_score = overview['home_score'] self.data.needs_refresh = True time.sleep(60) else: # (Need to make the screen run on it's own) If connection to the API fails, show bottom red line and refresh in 1 min. self.draw.line((0, 0) + (self.width, 0), fill=128) self.canvas = self.matrix.SwapOnVSync(self.canvas) time.sleep(60) # sleep for 1 min
def isapproxdiff(self, filename1, filename2, error_tolerance=0.001): """Compare two files. Arguments: filename1 -- First file name filename2 -- Second file name Return value: True if the files are the same, False otherwise. """ import re import debug numeric_const_pattern = r""" [-+]? # optional sign (?: (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc | (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc ) # followed by optional exponent part if desired (?: [Ee] [+-]? \d+ ) ? """ rx = re.compile(numeric_const_pattern, re.VERBOSE) fp1 = open(filename1, 'rb') fp2 = open(filename2, 'rb') mismatches = 0 line_num = 0 while True: line_num += 1 line1 = fp1.readline().decode('utf-8') line2 = fp2.readline().decode('utf-8') #print("line1:",line1) #print("line2:",line2) # 1. Find all of the floats using a regex line1_floats = rx.findall(line1) line2_floats = rx.findall(line2) debug.info(3, "line1_floats: " + str(line1_floats)) debug.info(3, "line2_floats: " + str(line2_floats)) # 2. Remove the floats from the string for f in line1_floats: line1 = line1.replace(f, "", 1) for f in line2_floats: line2 = line2.replace(f, "", 1) #print("line1:",line1) #print("line2:",line2) # 3. Convert to floats rather than strings line1_floats = [float(x) for x in line1_floats] line2_floats = [float(x) for x in line1_floats] # 4. Check if remaining string matches if line1 != line2: if mismatches == 0: debug.error( "Mismatching files:\nfile1={0}\nfile2={1}".format( filename1, filename2)) mismatches += 1 debug.error("MISMATCH Line ({0}):\n{1}\n!=\n{2}".format( line_num, line1.rstrip('\n'), line2.rstrip('\n'))) # 5. Now compare that the floats match elif len(line1_floats) != len(line2_floats): if mismatches == 0: debug.error( "Mismatching files:\nfile1={0}\nfile2={1}".format( filename1, filename2)) mismatches += 1 debug.error("MISMATCH Line ({0}) Length {1} != {2}".format( line_num, len(line1_floats), len(line2_floats))) else: for (float1, float2) in zip(line1_floats, line2_floats): relative_diff = self.relative_diff(float1, float2) check = relative_diff <= error_tolerance if not check: if mismatches == 0: debug.error( "Mismatching files:\nfile1={0}\nfile2={1}". format(filename1, filename2)) mismatches += 1 debug.error( "MISMATCH Line ({0}) Float {1} != {2} diff: {3:.1f}%" .format(line_num, float1, float2, relative_diff * 100)) # Only show the first 10 mismatch lines if not line1 and not line2 or mismatches > 10: fp1.close() fp2.close() return mismatches == 0 # Never reached return False
import debug import faction_ships import math stattable = {} def lg(num): return math.log(1 + num) / math.log(2) for i in faction_ships.stattableexp: tuple = faction_ships.stattableexp[i] stattable[i] = (tuple[0], tuple[1], lg(tuple[2]), lg(tuple[3]), lg(tuple[4])) stattable[i + '.blank'] = (tuple[0], tuple[1] * .5, lg(tuple[2]) * .5, lg(tuple[3]) * .5, lg(tuple[4]) * .5) debug.info(stattable)
import debug SCRIPT_NAME = "MLB LED Scoreboard" SCRIPT_VERSION = "4.0.1" # Get supplied command line arguments args = args() args.led_rows = 32 args.led_cols = 64 # Check for led configuration arguments matrixOptions = led_matrix_options(args) # Initialize the matrix matrix = RGBMatrix(options=matrixOptions) # Print some basic info on startup debug.info("{} - v{} ({}x{})".format(SCRIPT_NAME, SCRIPT_VERSION, matrix.width, matrix.height)) # Read scoreboard options from config.json if it exists config = ScoreboardConfig("config", matrix.width, matrix.height) debug.set_debug_status(config) # Create a new data object to manage the MLB data # This will fetch initial data from MLB data = Data(config) MainRenderer(matrix, data).render()