def checkCommandLineForAction (): # Check that the user has passed the correct options if opts.tests > 0: cudaBinary = args[0] if not os.path.exists(cudaBinary): Debug.exitMessage("The argument '%s' does not exist" % cudaBinary) elif not os.path.isfile(cudaBinary): Debug.exitMessage("The argument '%s' is not a file" % cudaBinary) elif not os.access(cudaBinary, os.X_OK): Debug.exitMessage("The argument '%s' does not have execute permission" % cudaBinary) # Get the filename of the binary without the path basename = os.path.basename(cudaBinary) basepath = os.path.abspath(os.path.dirname(cudaBinary)) generatedFiles = runCUDAKernel(basepath) doAnalysis(generatedFiles, basename, basepath) elif len(args) > 0: for arg in args: if not arg.endswith(gpgpuFileExt): Debug.exitMessage("Each file must end with a '%s' suffix. You passed '%s'." % (gpgpuFileExt, arg)) basename = os.path.splitext(os.path.basename(args[0]))[0] basepath = os.path.abspath(os.path.dirname(args[0])) doAnalysis(args, basename, basepath) else: Debug.exitMessage("""There are two ways to run this script: 1) Either pass a CUDA binary as an argument and the number of times you want to run the kernel with the -T option; or 2) Pass a number of files that were generated by GPGPU-sim from a previous testing run""")
def choose_prodigy(self, turn): # On récupère l'index index = self.prodigies_order[turn] self.played_prodigy = self.prodigies[index] if settings.VERBOSE: debug.verbose("Player " + str(self.id) + " joue " + self.played_prodigy.name)
def splitTraces (program, generatedFiles): Debug.debugMessage("Splitting traces", 1) allWarpTraces = {} for outfile in generatedFiles: traceFound = False newKernel = False firstTuple = None lastTuple = None Debug.debugMessage("Analysing file '%s'" % outfile, 1) with open(outfile, 'r') as f: for line in f: if line.startswith("NEW KERNEL"): traceFound = True if firstTuple: analyseHWMT(program, firstTuple, lastTuple) firstTuple = None continue if traceFound: SMAndWarp, timingTuple = getLineOfTimingTrace(line) print w = getWarp (allWarpTraces, SMAndWarp) w.appendToTrace(timingTuple) lastTuple = timingTuple if not firstTuple: firstTuple = timingTuple analyseHWMT(program, firstTuple, lastTuple) return allWarpTraces
def draw_fragment_heatmap_animation(self, save=False, type=None): sel_cmd = "select seginfo from deviceinfo" buf = self.db.fetch(sel_cmd) cnt = len(buf) dy1 = 100 fig = plt.figure(figsize=(16, 8), dpi=100) #fig, ax = plt.subplots() ims = [] if cnt > 100: step = int(cnt / 100) + 1 for i in range(0, cnt, step): bb = buf[i] cc = json.loads(bb[0].replace("'", "\""))["z"] dx1 = int(len(cc) / dy1) dd = np.array(cc).reshape(dx1, dy1) ims.append((plt.pcolor(np.arange(0, dy1 + 1, 1), np.arange(dx1, -1, -1), dd, norm=plt.Normalize(0, 999)), )) else: for i in range(cnt): bb = buf[i] cc = json.loads(bb[0].replace("'", "\""))["z"] dx1 = int(len(cc) / dy1) dd = np.array(cc).reshape(dx1, dy1) ims.append((plt.pcolor(np.arange(0, dy1 + 1, 1), np.arange(dx1, -1, -1), dd, norm=plt.Normalize(0, 999)), )) #fig.colorbar(ims) plt.colorbar() im_ani = animation.ArtistAnimation(fig, ims, interval=500, repeat_delay=1000, blit=True) title = self.dev_sn + ": df[" + str(float( '%.2f' % self.storage)) + "] ratio[" + str( float('%.2f' % self.ratio)) + "]" plt.title(title) if save and type == "mp4": Writer = animation.writers['ffmpeg'] writer = Writer(fps=15, metadata=dict(artist=title), bitrate=1800) if save: if type == "mp4": im_ani.save(self.dev_sn + ".mp4", writer=writer) d.d("save mp4 success!") elif type == "gif": im_ani.save(self.dev_sn + ".gif", writer='imagemagick', fps=15) d.d("save gif success!") else: ##no type define, show it replace plt.show() else: plt.show() return
def GetLessions(message, bot): mesg = message.text try: if not message.text in lessions: answ = "Группа не найдена" bot.reply_to(message, answ) return answ = "|№| Группа : " + lessions[mesg].GroupNum + "|" + "\n" i = 0 for lession in lessions[mesg].Lessions: answ += "|" + str(i) + "| " + lession + " |" + "\n" i += 1 pass except: answ = "Error GetLessions \n" answ += traceback.format_exc() Debug.LogError(answ) pass Debug.Log("GetLession for " + mesg + " by " + message.from_user.first_name) bot.reply_to(message, answ)
def test(): log_msg = "%s test example." % debug.comm_get_func_head_info() debug_log.debug_write_log(log_msg) string = "test" log_msg = "%s test example. %s" % (debug.comm_get_func_head_info(), string) debug_log.debug_write_log(log_msg)
def _handle_db_click(self, event): Debug.printe(event, Debug.Level.INFO) item = self._listbox.get(ACTIVE) results = WallTextureDialog(self, populator=WallTextureContainer(self._items[item])) self._remove_texture() self._add_new_texture(results._entries) pass
def use(self, char): Debug.print("Used bow") angle = math.atan2(char.pos.x - pygame.mouse.get_pos()[0], char.pos.y - pygame.mouse.get_pos()[1]) bullet = Entities.Bullet(char.room, -angle - 3.14 / 2, 2, False) bullet.pos = pygame.math.Vector2(char.pos.x + 12, char.pos.y + 12) char.room.entities.append(bullet)
def doConditionScript(self, scriptData): Debug.debug(__name__, '==?= condition script data form : ' + str(scriptData)) tag = scriptData[0] if len(scriptData) > 1: args = scriptData[1] else: args = [] if self.hasScript(tag): if self.getNumScriptArgs(tag) == len(args): scriptFn = self.tagMap[tag] bool = scriptFn(self.world, *args) # temp #bool = False #print '=test= scriptFn type : ', type(scriptFn) #print '=test= scriptFn with world and args type : ', type(scriptFn(self.world, *args)) #print '=test= scriptFn return when eval used : ', eval(scriptFn(self.world, *args)) Debug.debug( __name__, '==== script ' + str(tag) + ' with args ' + str(args) + ' evaluated to be : ' + str(bool)) return bool else: # CONSIDER: exception class print 'ERROR: script \'%s\' takes %d args (%d given)' % ( tag, self.getNumScriptArgs(tag), len(args)) else: print 'ERROR: script name \'%s\' not found in doConditionScript function' % ( tag)
def _selection_operation(self, coords): """ Contextually create or edit a node :param coords: :return: """ # Determine the item ID item = self._get_current_item(coords) self._cache["item"] = item true_coords = self._canvas_to_screen((self._cache["x"], self._cache["y"])) if self._is_node(item): Debug.printi("Node Selected : " + str(item) + " | Launching Editor", Debug.Level.INFO) # Make request from object manager using the tag assigned populator = self._manager.request(DataStore.DATATYPE.NODE, item) updated_node = NodeDialog(self, true_coords[0] + 10, true_coords[1] + 10, populator=populator) # post information to object manager, or let the dialog handle it, or whatever self._manager.inform(DataStore.EVENT.NODE_EDIT, updated_node._entries, item) return if self._is_edge(item): Debug.printi("Edge Selected : " + str(item) + " | Launching Editor", Debug.Level.INFO) # Make a request from the object manager to populate the dialog populator = self._manager.request(DataStore.DATATYPE.EDGE, item) updated_edge = EdgeDialog(self, true_coords[0] + 10, true_coords[1] + 10, populator=populator) # Make sure that information is posted to the object manager self._manager.inform(DataStore.EVENT.EDGE_EDIT, updated_edge._entries, item) return if self._is_object(item): self._edit_object(coords) return
def addSuccessor(self, id): if not id in self.successorIDs: self.successorIDs.append(id) Debug.debug(__name__, "added successor (id=" + str(id) + ") to line (id=" + str(self.id) + ")") return True else: return False
def _delete_object(self, item): if item not in self._object_listing: Debug.printi("Object does not exist to delete", Debug.Level.ERROR) return del self._object_listing[item] self._manager.inform(DataStore.EVENT.OBJECT_DELETE, data_id=item) self._canvas.itemconfig(item, outline="red", fill="black", activeoutline="black", activefill="red")
def _end_node_drag(self, coords): """ Performs actions to complete a node drag operation Validates node location, and other associated object information and updates the cache when a node drag is completed :coords: The coordinates associated with this event """ if self._cache["item"] is None: return # Obtain the final points x = coords[0] y = coords[1] item = self._cache["item"] self._validate_node_position(coords) container = self._manager.request(DataStore.DATATYPE.NODE, item) container.x_coordinate = x container.y_coordinate = y self._manager.inform(DataStore.EVENT.NODE_EDIT, container.empty_container(), self._cache["item"]) Debug.printi("Node " + str(self._cache["item"]) + " has been moved", Debug.Level.INFO) # Clean the cache self._clear_cache(coords)
def _handle_mot(self, m_event, event): """ Callback function to handle movement of the mouse Function updates the mouse location status bar as well as setting cache values to the current location of the mouse :m_event: The specifier for the type of event that has been generated :event: The tk provided event object """ event.x = int(self._canvas.canvasx(event.x)) event.y = int(self._canvas.canvasy(event.y)) self._status.set_text("Mouse X:" + str(event.x) + "\tMouse Y:" + str(event.y)) item = self._get_current_item((event.x, event.y)) if self._is_node(item): Debug.printi("Node: " + str(item), Debug.Level.INFO) if self._is_edge(item): d_x = self._edge_bindings[item].x_start - self._edge_bindings[item].x_end d_y = self._edge_bindings[item].y_start - self._edge_bindings[item].y_end square = (d_x * d_x) + (d_y * d_y) distance = int(math.sqrt(square)) Debug.printi("Edge: " + str(item) + " | Source: " + str(self._edge_bindings[item].item_start) + " | Target: " + str(self._edge_bindings[item].item_end) + " | Length: " + str(distance)) self._cache["x"] = event.x self._cache["y"] = event.y
def createGraphs (program, basepath): import UDrawGraph, ICFGs, Trees, IPGs Debug.debugMessage("Creating data structures", 1) for cfg in program.getCFGs(): functionName = cfg.getName() UDrawGraph.makeUdrawFile (cfg, basepath, "%s.%s" % (functionName, "cfg")) predomTree = Trees.Dominators(cfg, cfg.getEntryID()) reverseg = cfg.getReverseCFG() postdomTree = Trees.Dominators(reverseg, reverseg.getEntryID()) UDrawGraph.makeUdrawFile (predomTree, basepath, "%s.%s" % (functionName, "pre")) UDrawGraph.makeUdrawFile (postdomTree, basepath, "%s.%s" % (functionName, "post")) icfg = ICFGs.ICFG(cfg) icfg.setEntryID() icfg.setExitID() icfg.addExitEntryEdge() program.addICFG(icfg) UDrawGraph.makeUdrawFile (icfg, basepath, "%s.%s" % (functionName, "icfg")) lnt = Trees.LoopNests(icfg, icfg.getEntryID()) program.addLNT(lnt) UDrawGraph.makeUdrawFile (lnt, basepath, "%s.%s" % (functionName, "lnt")) ipg = IPGs.IPG(icfg, lnt) program.addIPG(ipg) icfg.addBranchDivergenceEdges(lnt) ipg.updateWithBranchDivergentPaths() UDrawGraph.makeUdrawFile (icfg, basepath, "%s.%s" % (functionName, "icfg")) UDrawGraph.makeUdrawFile (ipg, basepath, "%s.%s" % (functionName, "ipg"))
def _add_new_wall_pic(self, pic=None): """ Adds a new wall picture to the node definition Launches a dialog, and validates and posts the entered information to the repository for the creation of a new wall picture for the node that is being edited """ # Display the dialogue results = pic if results is None: results = NodePictureDialog(self) results = results._entries item_id = results["name"] item = results # Extract the return values try: self.add_new(item, item_id) except DuplicateListHeapItemException: Debug.printi("Unable to add duplicate picture", Debug.Level.ERROR) return except MaxItemLimitReachedException: Debug.printi("Maximum number of pictures for this room reached", Debug.Level.ERROR) return
def doConditionScript(self, scriptData): Debug.debug(__name__,'==?= condition script data form : '+str(scriptData)) tag = scriptData[0] if len(scriptData) > 1: args = scriptData[1] else: args = [] ##print tag,",",args if self.hasScript(tag): if not self.getNumScriptArgs(tag) == len(args): for ii in range(self.getNumScriptArgs(tag)): print ii if ii > len(args): args.append("") scriptFn = self.tagMap[tag] bool = scriptFn(self.world, *args) # temp #bool = False #print '=test= scriptFn type : ', type(scriptFn) #print '=test= scriptFn with world and args type : ', type(scriptFn(self.world, *args)) #print '=test= scriptFn return when eval used : ', eval(scriptFn(self.world, *args)) Debug.debug(__name__,'==== script '+str(tag)+' with args '+str(args)+ ' evaluated to be : '+str(bool)) return bool ## else: ## # CONSIDER: exception class ## print 'ERROR: script \'%s\' takes %d args (%d given)' %(tag, self.getNumScriptArgs(tag), len(args)) else: print 'ERROR: script name \'%s\' not found in doConditionScript function' %(tag)
def _at_exit_handler(): if not isExited: print("SprintInterface[pid %i] atexit handler, exit() was not called, calling it now" % (os.getpid(),)) exit() print("All threads:") import Debug Debug.dump_all_thread_tracebacks(exclude_self=True)
def updateData(self,evt = None): Debug.debug(__name__,"Data is being Updating") self.editor.fNeedToSave = True #children = self.journalTree.GetChildren(rootItem) parent = self.journalTree.GetRootItem() node, cookie = self.journalTree.GetLastChild(parent) #LEjournalEntries = {} self.editor.journalMgr.reset() while node.IsOk():#for i in range(self.journalTree.GetChildrenCount(rootItem)): name = self.journalTree.GetItemText(node, 0) tag = self.journalTree.GetItemText(node, 1) #print "Tag ", tag #filename = self.journalTree.GetItemText(node, 4) journalEntry = JournalEntry(tag, name) #lines = self.journalTree.GetChildren(node) l, cookie = self.journalTree.GetFirstChild(node) while l.IsOk():#for j in range(self.journalTree.GetChildrenCount(node)): text = self.journalTree.GetItemText(l, 0) endpoint = self.journalTree.GetItemText(l, 2) entryValue = self.journalTree.GetItemText(l,3) journalLine = JournalLine(text,entryValue, endpoint) journalEntry.addJournalLine(journalLine) l = self.journalTree.GetNextSibling(l) self.editor.journalMgr.addJournalEntry(journalEntry) #LEjournalEntries[LEjournalEntry.tag] = LEjournalEntry node = self.journalTree.GetPrevSibling(node)
def start_game(self): # import Debug as db if self.Debug_flag == 0: return 0 else: # 1 = Black, 2 = White print("Starting new Game!") db.show_grid(self.board) print("White move: ") self.make_move(-2, -1, -1) print("Black move: ") self.make_move(-1, -1, -1) player = 2 i = 1 while i <= self.board_size **2: if player == 1: print("Black Move: ", end="") if self.game_won(self.board, self.make_move(1, -1, -1), 1): print("Player 1 won on move", i) exit(1) else: player = 2 else: print("White Move: ", end="") if self.game_won(self.board, self.make_move(2, -1, -1), 2): print("Player 2 won on move", i) exit(2) else: player = 1 i += 1 print("Game is a tie") # Total moves equal entire board space, so game cannot proceed and its a tie exit(0)
def searchBy_Genre(self, searchStr): """ Search the library by Genre Name where searchStr matches the genre name. NB: If searchStr consists of multiple words then ALL words must be found within the genre name to make a match. arguments: searchStr as string "word1 word2..." returns: list [songID1, songID2, ...] of songIDs that match the search criteria """ Debug.out("Searching", len(self.byGenre), "genres") t1 = time.time() wordList = MakeWordlist(searchStr) matchedSongs = [] for genre in self.byGenre: asciiGenre = NiceAscii(genre) matches = [1 for (asciiWord, word) in wordList if asciiWord in asciiGenre or word in genre] if len(matches) == len(wordList): matchedSongs.extend(self.byGenre[genre]) Debug.out(" Found", len(matchedSongs), "songs in", round(time.time()-t1,6), "seconds") return matchedSongs
def add_to_cmake(self): Debug.info(self.name) global _ready if self in _ready: return self.setup_conan() _ready.add(self) Cmake.add_var(self.name + "_PATH", self.path()) if not self.needs_deps(): Debug.info(self.name + " no deps") for dep in self.deps(): self.include_in_cmake(dep) self.link_in_cmake(dep) for dep in self.subdeps(): self.include_in_cmake(dep) for dep in self.all_deps(): dep.add_to_cmake()
def _at_exit_handler(): if not isExited: print("SprintInterface[pid %i] atexit handler, exit() was not called, calling it now" % (os.getpid(),)) exit() print("All threads:") import Debug Debug.dumpAllThreadTracebacks()
def loadFromLog(self, logFile): Debug.out("Loading log " + logFile) if os.path.isfile(logFile): statinfo = os.stat(logFile) if not statinfo.st_size: raise LogError("Log has zero length") else: raise LogError("Log doesn't exist!") try: f = open(logFile, 'r') except IOError as err: raise LogError("Parsing log failed on IOError: " + str(errstr)) t1 = time.time() p = xml.parsers.expat.ParserCreate() p.StartElementHandler = self.start_element p.EndElementHandler = self.end_element p.CharacterDataHandler = self.char_data p.buffer_text = True try: p.ParseFile(f) Debug.out(" Loaded", self.numLoaded, "rows in", round(time.time() - t1,5), "seconds") except IOError as err: raise LogError("Parsing log failed on IOError: " + str(IOError)) except ExpatError as err: raise LogError("Parsing log failed on XML ExpatError: " + str(err)) finally: f.close()
def _load_control_file(file_path): try: control_file = open(file_path) Debug.printi("Control file " + file_path + " successfully loaded", Debug.Level.INFO) return control_file except IOError as e: Debug.printi(e.message, Debug.Level.FATAL)
def searchBy_Title(self, searchStr): """ Search the library by song title where searchStr matches the title. NB: If searchStr consists of multiple words then ALL words must be found within the title to make a match. arguments: searchStr as string "word1 word2..." returns: list [songID1, songID2, ...] of songIDs that match the search criteria """ Debug.out("Searching", len(self.songs), "song titles") t1 = time.time() wordList = MakeWordlist(searchStr) matchedSongs = [] for songID, songData in self.songs.iteritems(): songTitle = songData['title-search'] asciiSongTitle = songData['title-searchAscii'] matches = [1 for (asciiWord, word) in wordList if asciiWord in asciiSongTitle or word in songTitle] if len(matches) == len(wordList): matchedSongs.append(songID) Debug.out(" Found", len(matchedSongs), "songs in", round(time.time()-t1,6), "seconds") return matchedSongs
def setup(compiler=Compiler.get()): if Args.ide: return Debug.info(compiler) Debug.info(compiler.CXX)
def readAirPressure(self): """ Lecture de la pression atmosphérique depuis le BME280 et mise à jour des compteurs de BDD """ val = 0.0 ok = False ts = datetime.datetime.now() # Mise à jour des compteurs self.ex.pool.incrementCountEnvAirPressureNbReadTotal() self.ex.pool.setCountEnvAirPressureReadLastTs(ts) try: # Lecture depuis le BME280, avec deux décimales conservées val = round(self.BME280_I2C.pressure, 2) dbg_msg('MESURE_ENV: PA', '{:.2f}'.format(val)) except Exception as e: Debug.log_exc(e, this_file) self.ex.pool.incrementCountEnvAirPressureNbReadFailed() else: # On conserve la nouvelle mesure ok = True # Mise à jour des compteurs BDD self.ex.pool.incrementCountEnvAirPressureNbReadOk() # Mise à jour valeur instantanée dans la BDD self.ex.pool.updatePaInst(val, ts) return val, ok
def createGraphs(program, basepath): import UDrawGraph, ICFGs, Trees, IPGs Debug.debugMessage("Creating data structures", 1) for cfg in program.getCFGs(): functionName = cfg.getName() UDrawGraph.makeUdrawFile(cfg, basepath, "%s.%s" % (functionName, "cfg")) predomTree = Trees.Dominators(cfg, cfg.getEntryID()) reverseg = cfg.getReverseCFG() postdomTree = Trees.Dominators(reverseg, reverseg.getEntryID()) UDrawGraph.makeUdrawFile(predomTree, basepath, "%s.%s" % (functionName, "pre")) UDrawGraph.makeUdrawFile(postdomTree, basepath, "%s.%s" % (functionName, "post")) icfg = ICFGs.ICFG(cfg) icfg.setEntryID() icfg.setExitID() icfg.addExitEntryEdge() program.addICFG(icfg) UDrawGraph.makeUdrawFile(icfg, basepath, "%s.%s" % (functionName, "icfg")) lnt = Trees.LoopNests(icfg, icfg.getEntryID()) program.addLNT(lnt) UDrawGraph.makeUdrawFile(lnt, basepath, "%s.%s" % (functionName, "lnt")) ipg = IPGs.IPG(icfg, lnt) program.addIPG(ipg) icfg.addBranchDivergenceEdges(lnt) ipg.updateWithBranchDivergentPaths() UDrawGraph.makeUdrawFile(icfg, basepath, "%s.%s" % (functionName, "icfg")) UDrawGraph.makeUdrawFile(ipg, basepath, "%s.%s" % (functionName, "ipg"))
def updateData(self, evt=None): Debug.debug(__name__, "Data is being Updating") self.editor.fNeedToSave = True #children = self.journalTree.GetChildren(rootItem) parent = self.journalTree.GetRootItem() node, cookie = self.journalTree.GetLastChild(parent) #LEjournalEntries = {} self.editor.journalMgr.reset() while node.IsOk( ): #for i in range(self.journalTree.GetChildrenCount(rootItem)): name = self.journalTree.GetItemText(node, 0) tag = self.journalTree.GetItemText(node, 1) #print "Tag ", tag #filename = self.journalTree.GetItemText(node, 4) journalEntry = JournalEntry(tag, name) #lines = self.journalTree.GetChildren(node) l, cookie = self.journalTree.GetFirstChild(node) while l.IsOk( ): #for j in range(self.journalTree.GetChildrenCount(node)): text = self.journalTree.GetItemText(l, 0) endpoint = self.journalTree.GetItemText(l, 2) entryValue = self.journalTree.GetItemText(l, 3) journalLine = JournalLine(text, entryValue, endpoint) journalEntry.addJournalLine(journalLine) l = self.journalTree.GetNextSibling(l) self.editor.journalMgr.addJournalEntry(journalEntry) #LEjournalEntries[LEjournalEntry.tag] = LEjournalEntry node = self.journalTree.GetPrevSibling(node)
def splitTraces(program, generatedFiles): Debug.debugMessage("Splitting traces", 1) allWarpTraces = {} for outfile in generatedFiles: traceFound = False newKernel = False firstTuple = None lastTuple = None Debug.debugMessage("Analysing file '%s'" % outfile, 1) with open(outfile, 'r') as f: for line in f: if line.startswith("NEW KERNEL"): traceFound = True if firstTuple: analyseHWMT(program, firstTuple, lastTuple) firstTuple = None continue if traceFound: SMAndWarp, timingTuple = getLineOfTimingTrace(line) print w = getWarp(allWarpTraces, SMAndWarp) w.appendToTrace(timingTuple) lastTuple = timingTuple if not firstTuple: firstTuple = timingTuple analyseHWMT(program, firstTuple, lastTuple) return allWarpTraces
def checkCommandLineForAction(): # Check that the user has passed the correct options if opts.tests > 0: cudaBinary = args[0] if not os.path.exists(cudaBinary): Debug.exitMessage("The argument '%s' does not exist" % cudaBinary) elif not os.path.isfile(cudaBinary): Debug.exitMessage("The argument '%s' is not a file" % cudaBinary) elif not os.access(cudaBinary, os.X_OK): Debug.exitMessage( "The argument '%s' does not have execute permission" % cudaBinary) # Get the filename of the binary without the path basename = os.path.basename(cudaBinary) basepath = os.path.abspath(os.path.dirname(cudaBinary)) generatedFiles = runCUDAKernel(basepath) doAnalysis(generatedFiles, basename, basepath) elif len(args) > 0: for arg in args: if not arg.endswith(gpgpuFileExt): Debug.exitMessage( "Each file must end with a '%s' suffix. You passed '%s'." % (gpgpuFileExt, arg)) basename = os.path.splitext(os.path.basename(args[0]))[0] basepath = os.path.abspath(os.path.dirname(args[0])) doAnalysis(args, basename, basepath) else: Debug.exitMessage("""There are two ways to run this script: 1) Either pass a CUDA binary as an argument and the number of times you want to run the kernel with the -T option; or 2) Pass a number of files that were generated by GPGPU-sim from a previous testing run""" )
def rm(path): Debug.info("Deleting: " + path) if os.path.exists(path): if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path)
def post( self, event ): if not isinstance( event, TickEvent ): Debug.log( "Event: " + event.name ) # Event is broadcast to all listeners for listener in self.listeners: listener.notify( event )
def createProgram (cfgLines): program = CFGs.Program() cfg = None analyse = False instructions = [] labels = [] for line in cfgLines: if "Summary of basic blocks for" in line: analyse = False assert cfg assert instructions createBasicBlocks(cfg, instructions) addEdges(cfg) setEntryAndExit(cfg) instructions = [] if analyse: analyseLine(line, instructions, labels) if "Printing basic blocks for function" in line: analyse = True lexemes = shlex.split(line) functionName = lexemes[-1][:-1] cfg = CFGs.CFG() cfg.setName(functionName) program.addCFG(cfg) Debug.debugMessage("Found new CFG '%s'" % functionName, 1) return program
def randomSong(self): self.__select("count(*) FROM tags") (count, ) = self.__fetchone() self.__select("url FROM tags LIMIT 1 OFFSET %s" % random.randint(0, int(count)-1)) (url, ) = self.__fetchone() Debug.log("Random song: " + url) return url
def createProgram(cfgLines): program = CFGs.Program() cfg = None analyse = False instructions = [] labels = [] for line in cfgLines: if "Summary of basic blocks for" in line: analyse = False assert cfg assert instructions createBasicBlocks(cfg, instructions) addEdges(cfg) setEntryAndExit(cfg) instructions = [] if analyse: analyseLine(line, instructions, labels) if "Printing basic blocks for function" in line: analyse = True lexemes = shlex.split(line) functionName = lexemes[-1][:-1] cfg = CFGs.CFG() cfg.setName(functionName) program.addCFG(cfg) Debug.debugMessage("Found new CFG '%s'" % functionName, 1) return program
def __init__(self): super(Sprite, self).__init__() global sprite_count sprite_count += 1 Debug.track("Sprite Count", sprite_count)
def postDailySummary(self): '''Posts a daily summary to Twitter''' # Get current minutes from system time currentTime = datetime.now() # create time difference to be used to work out time period timeDiff = timedelta(days=1) # Get current minutes currentHour = currentTime.strftime("%H") # Check if the hours of the time is 00 which means midnight and the current day # has changed if(currentHour == "00" and (self.LAST_DAY_POST == "" or currentTime.strftime("%d") != self.LAST_DAY_POST)): Debug.writeOut("Daily condition met (hour of day:" + currentHour + " == 00 && day:" + currentTime.strftime("%d") + " == " + self.LAST_DAY_POST + "). Posting to Twitter") # Create SQL to get data for tweet sql = " SELECT COALESCE(ROUND(AVG(energy), 2), 0), COALESCE(MAX(energy), 0), COALESCE(ROUND(AVG(temperature), 1), 0) FROM historical_data WHERE date_time >= ADDDATE(NOW(), INTERVAL -1 DAY)" self.LOGGER.debug(sql) # Get statistics from DB stats = MySQL.executeOneUpdate(sql, None) # Create tweet message = (currentTime - timeDiff).strftime("%d-%b-%Y") + " Summary: " + str(stats[0]) +\ "w was used. " +\ "Energy usage peaked at " + str(stats[1]) + "w. " +\ "The average temperature was " + str(stats[2]) + "c." # Save new day of tweet self.LAST_DAY_POST = currentTime.strftime("%d") # Check if tweet should be a Direct Message or just a tweet if self.CONFIG.getBooleanConfig("Twitter", "directMessagePost"): self.postDirectMessage(self.CONFIG.getBooleanConfig("Twitter", "directMessageUser"), message) else: # Post message to twitter self.tweet(message)
def postHourlySummary(self): '''Posts an hourly summary to Twitter''' # Get current system time currentTime = datetime.now() # create time difference to be used to work out time period timeDiff = timedelta(hours=1) # Get current hour currentHour = currentTime.strftime("%H") # If current hour does not match last post hour then it's been a new hour since last post if(currentHour != self.LAST_HOURLY_POST): Debug.writeOut("Hourly condtion met (" + currentHour + " != " + self.LAST_HOURLY_POST + "). Posting to Twitter") # Create SQL to get data for tweet sql = "SELECT COALESCE(ROUND(AVG(energy), 2), 0), " +\ "COALESCE(MAX(energy), 0), COALESCE(ROUND(AVG(temperature), 1), 0) " +\ "FROM historical_data WHERE date_time >= ADDDATE(NOW(), INTERVAL -1 HOUR)" self.LOGGER.debug(sql) # Get statistics from DB stats = MySQL.executeOneUpdate(sql, None) # Create tweet message = (currentTime - timeDiff).strftime("%H:%M") + "-" + currentTime.strftime("%H:%M") +\ " Summary: " + str(stats[0]) + "w was used." +\ " Energy usage peaked at " + str(stats[1]) + "w" +\ ". The average temperature was " + str(stats[2]) + "c." # Check if tweet should be a Direct Message or just a tweet if self.CONFIG.getBooleanConfig("Twitter", "directMessagePost"): self.postDirectMessage(self.CONFIG.getBooleanConfig("Twitter", "directMessageUser"), message) else: # Post message to twitter self.tweet(message) # Set last hourly post to current hour self.LAST_HOURLY_POST = currentHour
def setupWxPaint(self): self.bitmap = wx.Bitmap("bitmap") #self.canvasPanel.AddChild(self.bitmap) Debug.debug(__name__, str(self.terrain.asset.getFullFilename().getExtension())) self.bitmap.LoadFile( self.terrain.asset.getFullFilename().toOsSpecific(), wx.BITMAP_TYPE_ANY)
def validate(event, data): if DEBUG: return True, "" try: return DataValidator().VALIDATE_MAP[event](data) except KeyError as error: Debug.printi(error.message, Debug.Level.FATAL)
def notify( self, event ): if isinstance( event, KeyboardInputEvent ): # Handle keyboard input # Check controllable actor's maps try: Debug.log( "Keyboard: %s" % event.data.unicode ) except: Debug.log( "Keyboard: %s" % event.data.key )
def os(): if is_linux: return "Linux" if is_mac: return "macOS" if is_windows: return "Windows" Debug.not_implemented()
def __addIpoints (self): for bb in self: address, instr = bb.getFirstInstruction() vertexID = self.getNextVertexID () ipoint = Vertices.Ipoint(vertexID, address) self.vertices[vertexID] = ipoint Debug.debugMessage("Adding Ipoint %d with ID %s" % (vertexID, hex(address)), 4) self.__linkIpoint(bb, ipoint)
def UpdateWithoutTg(): try: parse(get_html(site)) pass except: Debug.LogError(traceback.format_exc()) return Debug.Log("Updating lessions")
def setPlayerChoice(self,n): #[antonjs] temp Debug.debug(__name__,'setPlayerChoice called') '''pass the player's choice to ConversationMgr''' self.world.conversationMgr.playResponse(n) self.syncedWithConvoMgr = False
def init(isClient): Globals.isClient = isClient Debug.init() if not isClient: if not Logfile.init(startMsg=VERSION_STRING): return False return Globals.init()
def copyfile(srcfile, dstfile): if not os.path.isfile(srcfile): print("%s not exist!" + srcfile) else: fpath, fname = os.path.split(dstfile) if not os.path.exists(fpath): os.makedirs(fpath) shutil.copyfile(srcfile, dstfile) d.d("copy " + srcfile + "-> " + dstfile)
def use(self, char): Debug.print("Used " + self.name) self.rect = char.interact_rect() for entity in char.room.entities: if not isinstance(entity, GameBase.Character): continue if entity is not char and entity.get_collision().colliderect( self.rect): entity.hurt(char, self.dmg)
def addSuccessor(self, id): if not id in self.successorIDs: self.successorIDs.append(id) Debug.debug( __name__, 'added successor (id=' + str(id) + ') to line (id=' + str(self.id) + ')') return True else: return False
def toWorkflow(self, device, wf): Debug.write("Action->Workflow: " + self.Title) wf.add_item( title=self.Title, subtitle=str(self.Subtitle), autocomplete=DomoticzHelpers.CreateQuery(None if self.Device == None else self.Device.Room, self.Device, self), valid=False, icon=self.Icon )
def interact(self): check = self.interact_rect() for entity in self.room.entities: if entity.can_interact(self) and check.colliderect( entity.get_collision()): Debug.print("Interact w/ " + entity.__class__.__name__) entity.on_interact(self) break
def __init__(self, name, target, args, kwargs, stopevt, delay=0): threading.Thread.__init__(self) self.stopevt = stopevt self.name = name self.target = target self.args = args self.kwargs = kwargs self.delay = delay d.init()
def root_dir(path='.'): _path = path print(_path) while not File.is_root(_path): if has_cmake_file(_path): if not has_parent_cmake_files(_path): return File.full_path(_path) _path += "/.." Debug.throw("CMake root directory not found for path: " + File.full_path(path))
def __addIpoints(self): for bb in self: address, instr = bb.getFirstInstruction() vertexID = self.getNextVertexID() ipoint = Vertices.Ipoint(vertexID, address) self.vertices[vertexID] = ipoint Debug.debugMessage( "Adding Ipoint %d with ID %s" % (vertexID, hex(address)), 4) self.__linkIpoint(bb, ipoint)
def _display_img(self): """ Display a loaded image in a dialog """ if self._file_path is None: Debug.printi("No picture has been loaded to preview", Debug.Level.ERROR) return photo = self._open_img(self._file_path) ImageViewDialog(self._parent, self._file_name, photo)
def __init__(self, cfg): Debug.debugMessage(cfg, 10) CFGs.CFG.__init__(self) self.__branchDivergentEdges = [] self.setName(cfg.getName()) for bb in cfg: bbID = bb.getVertexID() self.vertices[bbID] = copy.deepcopy(bb) self.__addIpoints()
def on_openButton_clicked(self, checked): Debug.printCall(self, checked) fileDialogue = QtGui.QFileDialog(self, "Select a campaign", os.getcwd(), "DSV files (*.csv *.txt)") fileDialogue.setAcceptMode(QtGui.QFileDialog.AcceptOpen) fileDialogue.setFileMode(QtGui.QFileDialog.ExistingFile) fileDialogue.setViewMode(QtGui.QFileDialog.Detail) if fileDialogue.exec_() == QtGui.QDialog.Accepted: fileName = fileDialogue.selectedFiles()[0] self.fileNameEdit.setText(fileName)
def call(call): Debug.log("DCOP call: " + call) f = os.popen("dcop amarok %s" % call) result = f.read() if f.close() is not None: raise Error result = result.strip() Debug.log("DCOP response: " + result) return result