def lint_view(cls, view_id, filename, code, sections, callback): if view_id in cls.linters: selectors = Linter.get_selectors(view_id) linters = tuple(cls.linters[view_id]) for linter in linters: if not linter.selector: linter.filename = filename linter.pre_lint(code) for sel, linter in selectors: if sel in sections: highlight = Highlight(code, scope=linter.scope, outline=linter.outline) errors = {} for line_offset, left, right in sections[sel]: highlight.shift(line_offset, left) linter.pre_lint(code[left:right], highlight=highlight) for line, error in linter.errors.items(): errors[line + line_offset] = error linter.errors = errors # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0)
def __init__(self, section, x, y): self.elements = list() self.highlight = Highlight() self.x = x self.y = y self.section = section
def lint_view(cls, view_id, filename, code, sections, callback): if view_id in cls.linters: selectors = Linter.get_selectors(view_id) linters = tuple(cls.linters[view_id]) for linter in linters: if not linter.selector: linter.filename = filename linter.pre_lint(code) for sel, linter in selectors: if sel in sections: highlight = Highlight(code, scope=linter.scope, outline=linter.outline) errors = {} for line_offset, left, right in sections[sel]: highlight.shift(line_offset, left) linter.pre_lint(code[left:right], highlight=highlight) for line, error in linter.errors.items(): errors[line+line_offset] = error linter.errors = errors # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0)
def lint_view(cls, view_id, filename, code, sections, callback): if view_id in cls.linters: selectors = Linter.get_selectors(view_id) linters = tuple(cls.linters[view_id]) linter_text = ", ".join(l.name for l in linters) persist.debug("SublimeLint: `%s` as %s" % (filename or "untitled", linter_text)) for linter in linters: if linter.settings.get("disable"): continue if not linter.selector: linter.filename = filename linter.pre_lint(code) for sel, linter in selectors: if sel in sections: highlight = Highlight(code, scope=linter.scope, outline=linter.outline) errors = {} for line_offset, left, right in sections[sel]: highlight.shift(line_offset, left) linter.pre_lint(code[left:right], highlight=highlight) for line, error in linter.errors.items(): errors[line + line_offset] = error linter.errors = errors # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Code-to-Html') self.setWindowIcon(QIcon('pic/icon.png')) # StyleSheet self.setStyleSheet(''' QMainWindow{background-color: qlineargradient(spread: pad, x1:0, y1:0.5, x2:1, y2:0.5, stop:0 rgb(255, 255, 255), stop:1 rgb(150, 150, 150));} ''') # Highlight class self.highlight = Highlight() # ComboBox all_langs = self.highlight.return_all_languages() all_styles = self.highlight.return_all_styles() self.ui.comboBox.addItems(all_langs) self.ui.comboBox_2.addItems(all_styles) # Button self.ui.pushButton.clicked.connect(self.convertEvent)
def code_highlight(self): """ Стилизуем код из файла. :return: Изображение в бинарном виде. """ code2image = Highlight( self.language, style=config.get('highlight').get('style'), line_numbers=config.get('highlight').get('show_line_numbers'), font_size=config.get('highlight').get('font_size'), font_name=config.get('highlight').get('font_name'), line_pad=config.get('highlight').get('line_pad'), background_color=config.get('highlight').get('background_color'), highlight_color=config.get('highlight').get('highlight_color'), window_frame_color=config.get('highlight').get( 'window_frame_color'), bg_from_color=tuple(config.get('highlight').get('bg_from_color')), bg_to_color=tuple(config.get('highlight').get('bg_to_color')), close_circle=config.get('highlight').get('close_circle'), maximize_circle=config.get('highlight').get('maximize_circle'), minimize_circle=config.get('highlight').get('minimize_circle')) image = code2image.to_macos_frame( code2image.prepare_code( self.code, fake_line_numbers=config.get('highlight').get( 'show_fake_line_numbers'), show_title_in_code=self.show_title_in_code, title=self.title, comment_char=self.start_comment_with)) return code2image.to_bytes(image)
def lint_view(cls, view_id, filename, code, sections, callback): if view_id in cls.linters: selectors = Linter.get_selectors(view_id) linters = tuple(cls.linters[view_id]) linter_text = (', '.join(l.name for l in linters)) persist.debug('SublimeLint: `%s` as %s' % (filename or 'untitled', linter_text)) for linter in linters: if linter.settings.get('disable'): continue if not linter.selector: linter.filename = filename linter.pre_lint(code) for sel, linter in selectors: if sel in sections: highlight = Highlight(code, scope=linter.scope, outline=linter.outline) errors = {} for line_offset, left, right in sections[sel]: highlight.shift(line_offset, left) linter.pre_lint(code[left:right], highlight=highlight) for line, error in linter.errors.items(): errors[line + line_offset] = error linter.errors = errors # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0)
def draw(self): pyxel.cls(0) pyxel.circ(pyxel.mouse_x, pyxel.mouse_y, 1, 9) # THE MOUSE Highlight.hbox() npc.draw_npcs() npc.select_npc() npc.move_npc()
def __init__(self, view, syntax, filename=None): self.view = view self.syntax = syntax self.filename = filename if self.regex: self.regex = re.compile(self.regex) self.highlight = Highlight(scope=self.scope)
def __init__(self, locals={}, debug=False): if not isinstance(locals, PythonNamespace): self.locals = dict(PythonNamespace(locals)) else: self.locals = dict(locals) self.debug = debug self.trap = OutputTrap() self.inspector = Inspector() self.highlight = Highlight() self.index = 0
def __init__(self, view, syntax, filename=None): self.view = view self.syntax = syntax self.filename = filename if self.regex: if self.multiline: self.flags |= re.MULTILINE self.regex = re.compile(self.regex, self.flags) self.highlight = Highlight(scope=self.scope)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Code-to-Html') self.setWindowIcon(QIcon('pic/icon.png')) # StyleSheet self.setStyleSheet(''' QMainWindow{background-color: qlineargradient(spread: pad, x1:0, y1:0.5, x2:1, y2:0.5, stop:0 rgb(255, 255, 255), stop:1 rgb(150, 150, 150));} ''') # Highlight class self.highlight = Highlight() # ComboBox all_langs = self.highlight.return_all_languages() all_styles = self.highlight.return_all_styles() self.ui.comboBox.addItems(all_langs) self.ui.comboBox_2.addItems(all_styles) # Button self.ui.pushButton.clicked.connect(self.convertEvent) # Convert the input code to html text def convertEvent(self): code = self.ui.plainTextEdit.toPlainText() code = self.highlightEvent(code) self.ui.textBrowser.setHtml( re.findall("(.*)<textarea readonly id=", code, re.DOTALL)[0]) self.ui.plainTextEdit_2.setPlainText(code) self.ui.plainTextEdit_2.selectAll() self.ui.plainTextEdit_2.copy() # Fresh self.ui.plainTextEdit_2.repaint() self.ui.textBrowser.repaint() # Using highlight class to highlight the code def highlightEvent(self, code): lexer = self.ui.comboBox.currentText() style = self.ui.comboBox_2.currentText() results = self.highlight.highlightEvent(code, style, lexer, self.ui.checkBox.isChecked()) return results
def lint(self, code=None): if not (self.language and self.cmd and self.regex): raise NotImplementedError if code is None: code = Linter.text(self.view) self.highlight = Highlight(code) self.errors = errors = {} if not code: return output = self.communicate(self.cmd, code) print repr(output) for line in output.splitlines(): line = line.strip() match, row, col, message, near = self.match_error(self.regex, line) if match: if row or row is 0: if col or col is 0: self.highlight.range(row, col) elif near: self.highlight.near(row, near) else: self.highlight.line(row) if row in errors: errors[row].append(message) else: errors[row] = [message]
def selectMing( self, ming ) : if self.highlight is not None : self.highlight.getActor().kill() if ming is None : self.highlight = None else : self.highlight = Highlight( ming.getActor() ) self.highlight.createActor().event( "highlight" )
def lint(self, code=None): self.highlight = Highlight(code) self.errors = {} if code is None: code = Linter.text(self.view) if code: self.check(code)
class UI: def __init__(self, section, x, y): self.elements = list() self.highlight = Highlight() self.x = x self.y = y self.section = section def render(self, console: Console): for element in self.elements: element.render(console) if self.highlight is not None: self.highlight.render(console) pass def keydown(self, event: tcod.event.KeyDown): for element in self.elements: element.on_keydown(event) def mousedown(self, x: int, y: int): for element in self.elements: if element.is_mouseover(x, y): element.on_mousedown() elif isinstance(element, Input): element.selected = False element.blink = False def mousemove(self, x: int, y: int): for element in self.elements: if element.is_mouseover(x, y): if element.mouseover == False: element.on_mouseenter() element.mouseover = True else: if element.mouseover == True: element.on_mouseleave() element.mouseover = False def add_element(self, element): element.x = element.x + self.x element.y = element.y + self.y self.elements.append(element)
def __init__(self, graphics, root): # global variables self.k = K() # piece - piece identifier. px, py - piece position(472x472). mx, my - mouse position(472x472) self.data = {"piece": None, "px": 0, "py": 0, "mx": 0, "my": 0} # keeps track of current turn self.color = "token" # true when menu is displayed, else false self.menuOn = False # tkinter root self.root = root # creates window and all images self.graphics = graphics # Canvas from graphics class. Tkinter object, draws images self.canvas = graphics.canvas # functions for special moves. self.specialMoves = SpecialMoves(self.canvas) # contains board and functions pertaining to position self.position = Position(self.canvas, self.specialMoves) self.position.updateBoard() # contains functions for moving pieces self.movement = Movement(self.canvas, self.position) # handles menues self.interface = Interface(graphics) # creates highlights around boxes self.highlight = Highlight(self.canvas, self.position) # finds move for computer player self.cpu = CPU(self.position, self.canvas) # brings up main menu, starts game self.showMain(0)
def get_pretty(self, obj, highlight=None): """Get all information about ``obj`` in pretty form. """ if highlight is None: highlight = Highlight() info = self.get_info(obj) docstring = info['docstring'] if docstring is not None: info['docstring_html'] = highlight.docstring(docstring) source = info['source'] if source is not None: info['source_html'] = highlight.python(source) args = info['args'] if args is not None: info['args_html'] = highlight.python(args) return info
def pre_lint(self, code, highlight=None): self.errors = {} self.highlight = highlight or Highlight( code, scope=self.scope, outline=self.outline) if not code: return # if this linter needs the api, we want to merge back into the main thread # but stall this thread until it's done so we still have the return if self.needs_api: q = Queue() def callback(): q.get() self.lint(code) q.task_done() q.put(1) sublime.set_timeout(callback, 1) q.join() else: self.lint(code)
class Linter: __metaclass__ = Tracker language = '' cmd = () regex = '' multiline = False flags = 0 tab_size = 1 scope = 'keyword' selector = None outline = True needs_api = False languages = {} linters = {} errors = None highlight = None def __init__(self, view, syntax, filename=None): self.view = view self.syntax = syntax self.filename = filename if self.regex: if self.multiline: self.flags |= re.MULTILINE self.regex = re.compile(self.regex, self.flags) self.highlight = Highlight(scope=self.scope) @classmethod def add_subclass(cls, sub, name, attrs): if name: sub.name = name cls.languages[name] = sub @classmethod def assign(cls, view): ''' find a linter for a specified view if possible, then add it to our mapping of view <--> lint class and return it each view has its own linter to make it feasible for linters to store persistent data about a view ''' try: vid = view.id() except RuntimeError: pass settings = view.settings() syn = settings.get('syntax') if not syn: cls.remove(vid) return match = syntax_re.search(syn) if match: syntax, = match.groups() else: syntax = syn if syntax: if vid in cls.linters and cls.linters[vid]: if tuple(cls.linters[vid])[0].syntax == syntax: return linters = set() for name, entry in cls.languages.items(): if entry.can_lint(syntax): linter = entry(view, syntax, view.file_name()) linters.add(linter) if linters: cls.linters[vid] = linters return linters cls.remove(vid) @classmethod def remove(cls, vid): if vid in cls.linters: for linter in cls.linters[vid]: linter.clear() del cls.linters[vid] @classmethod def reload(cls, mod): ''' reload all linters originating from a specific module (follows a module reload) ''' for id, linters in cls.linters.items(): for linter in linters: if linter.__module__ == mod: linter.clear() cls.linters[id].remove(linter) linter = cls.languages[linter.name](linter.view, linter.syntax, linter.filename) cls.linters[id].add(linter) linter.draw() return @classmethod def text(cls, view): return view.substr(sublime.Region(0, view.size())).encode('utf-8') @classmethod def lint_view(cls, view_id, filename, code, sections, callback): if view_id in cls.linters: selectors = Linter.get_selectors(view_id) linters = tuple(cls.linters[view_id]) for linter in linters: if not linter.selector: linter.filename = filename linter.pre_lint(code) for sel, linter in selectors: if sel in sections: highlight = Highlight(code, scope=linter.scope, outline=linter.outline) errors = {} for line_offset, left, right in sections[sel]: highlight.shift(line_offset, left) linter.pre_lint(code[left:right], highlight=highlight) for line, error in linter.errors.items(): errors[line+line_offset] = error linter.errors = errors # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0) @classmethod def get_view(cls, view_id): if view_id in cls.linters: return tuple(cls.linters[view_id])[0].view @classmethod def get_linters(cls, view_id): if view_id in cls.linters: return tuple(cls.linters[view_id]) return () @classmethod def get_selectors(cls, view_id): return [(linter.selector, linter) for linter in cls.get_linters(view_id) if linter.selector] def pre_lint(self, code, highlight=None): self.errors = {} self.highlight = highlight or Highlight(code, scope=self.scope, outline=self.outline) if not code: return # if this linter needs the api, we want to merge back into the main thread # but stall this thread until it's done so we still have the return if self.needs_api: q = Queue() def callback(): q.get() self.lint(code) q.task_done() q.put(1) sublime.set_timeout(callback, 1) q.join() else: self.lint(code) def lint(self, code): if not (self.language and self.cmd and self.regex): raise NotImplementedError output = self.communicate(self.cmd, code) if output: persist.debug('Output:', repr(output)) for match, row, col, message, near in self.find_errors(output): if match: if row or row is 0: if col or col is 0: # adjust column numbers to match the linter's tabs if necessary if self.tab_size > 1: start, end = self.highlight.full_line(row) code_line = code[start:end] diff = 0 for i in xrange(len(code_line)): if code_line[i] == '\t': diff += (self.tab_size - 1) if col - diff <= i: col = i break self.highlight.range(row, col) elif near: self.highlight.near(row, near) else: self.highlight.line(row) self.error(row, message) def draw(self, prefix='lint'): self.highlight.draw(self.view, prefix) def clear(self, prefix='lint'): self.highlight.clear(self.view, prefix) # helper methods @classmethod def can_lint(cls, language): language = language.lower() if cls.language: if language == cls.language: return True elif isinstance(cls.language, (tuple, list)) and language in cls.language: return True else: return False def error(self, line, error): self.highlight.line(line) error = str(error) if line in self.errors: self.errors[line].append(error) else: self.errors[line] = [error] def find_errors(self, output): if self.multiline: errors = self.regex.finditer(output) if errors: for error in errors: yield self.split_match(error) else: yield self.split_match(None) else: for line in output.splitlines(): yield self.match_error(self.regex, line.strip()) def split_match(self, match): if match: items = {'row':None, 'col':None, 'error':'', 'near':None} items.update(match.groupdict()) error, row, col, near = [items[k] for k in ('error', 'line', 'col', 'near')] row = int(row) - 1 if col: col = int(col) - 1 return match, row, col, error, near return match, None, None, '', None def match_error(self, r, line): return self.split_match(r.match(line)) # popen wrappers def communicate(self, cmd, code): return util.communicate(cmd, code) def tmpfile(self, cmd, code, suffix=''): return util.tmpfile(cmd, code, suffix) def tmpdir(self, cmd, files, code): return util.tmpdir(cmd, files, self.filename, code) def popen(self, cmd, env=None): return util.popen(cmd, env)
class Python(Linter): language = 'python' def lint(self, code=None): self.highlight = Highlight(code) self.errors = {} if code is None: code = Linter.text(self.view) if code: self.check(code) def check(self, code, filename='untitled'): stripped_lines = [] good_lines = [] lines = code.split('\n') for i in xrange(len(lines)): line = lines[i] if not line.strip() or line.strip().startswith('#'): stripped_lines.append(i) else: good_lines.append(line) text = '\n'.join(good_lines) errors = check(text, filename) def underlineWord(lineno, word): regex = r'((and|or|not|if|elif|while|in)\s+|[+\-*^%%<>=\(\{])*\s*(?P<underline>[\w\.]*%s[\w]*)' % (word) self.highlight.regex(lineno, regex, word) def underlineImport(lineno, word): linematch = '(from\s+[\w_\.]+\s+)?import\s+(?P<match>[^#;]+)' regex = '(^|\s+|,\s*|as\s+)(?P<underline>[\w]*%s[\w]*)' % word self.highlight.regex(lineno, regex, word, linematch) def underlineForVar(lineno, word): regex = 'for\s+(?P<underline>[\w]*%s[\w*])' % word self.highlight.regex(lineno, regex, word) def underlineDuplicateArgument(lineno, word): regex = 'def [\w_]+\(.*?(?P<underline>[\w]*%s[\w]*)' % word self.highlight.regex(lineno, regex, word) for error in errors: error.lineno -= 1 for i in stripped_lines: if error.lineno >= i: error.lineno += 1 self.error(error.lineno, error) if isinstance(error, OffsetError): self.highlight.range(error.lineno, error.offset) elif isinstance(error, PythonError): pass elif isinstance(error, messages.UnusedImport): underlineImport(error.lineno, error.name) elif isinstance(error, messages.RedefinedWhileUnused): underlineWord(error.lineno, error.name) elif isinstance(error, messages.ImportShadowedByLoopVar): underlineForVar(error.lineno, error.name) elif isinstance(error, messages.ImportStarUsed): underlineImport(error.lineno, '\*') elif isinstance(error, messages.UndefinedName): underlineWord(error.lineno, error.name) elif isinstance(error, messages.UndefinedExport): underlineWord(error.lineno, error.name) elif isinstance(error, messages.UndefinedLocal): underlineWord(error.lineno, error.name) elif isinstance(error, messages.DuplicateArgument): underlineDuplicateArgument(error.lineno, error.name) elif isinstance(error, messages.RedefinedFunction): underlineWord(error.lineno, error.name) elif isinstance(error, messages.LateFutureImport): pass elif isinstance(error, messages.UnusedVariable): underlineWord(error.lineno, error.name) else: print 'SublimeLint (Python): Oops, we missed an error type!'
class Play(PlainSceneDirector) : def __init__(self) : self.limitsLeft = 0 self.limitsRight = 1000 self.limitsBottom = 0 self.limitsTop = 800 self.neighbourhood = StandardNeighbourhood( 80 ) self.scrollSpeed = 4 self.scrollX = 0 self.scrollY = 0 self.inputScrollLeft = Input.find("scrollLeft") self.inputScrollRight = Input.find("scrollRight") self.inputScrollUp = Input.find("scrollUp") self.inputScrollDown = Input.find("scrollDown") self.jobButton = None # The currently selected JobButton self.highlight = None # a Highlight object or None if no Ming is highlighted def loading( self, scene ) : print "Loading gui scene" game.mergeScene("gui") def onActivate(self) : width = game.getWidth() height = game.getHeight() # Adjust the limits, so that they reference the CENTER of the screen # MORE Change to the VISIBLE area i.e. the size of the main view. self.limitsLeft += width/2 self.limitsRight -= width/2 self.limitsTop -= height/2 self.limitsBottom += height/2 def tick(self) : if self.inputScrollLeft.pressed() : self.scrollBy( -self.scrollSpeed, 0 ) elif self.inputScrollRight.pressed() : self.scrollBy( self.scrollSpeed, 0 ) elif self.inputScrollUp.pressed() : self.scrollBy( 0, self.scrollSpeed ) elif self.inputScrollDown.pressed() : self.scrollBy( 0, -self.scrollSpeed ) director.scrollTo( self.scrollX, self.scrollY ) def scrollTo( self, x, y ) : self.scrollX = x self.scrollY = y self.__scrollLimit() def scrollBy( self, dx, dy ) : self.scrollX += dx self.scrollY += dy self.__scrollLimit() def __scrollLimit( self ) : if self.scrollX < self.limitsLeft : self.scrollX = self.limitsLeft if self.scrollX > self.limitsRight : self.scrollX = self.limitsRight if self.scrollY < self.limitsBottom : self.scrollY = self.limitsBottom if self.scrollY > self.limitsTop : self.scrollY = self.limitsTop def pickJob( self, jobButton ) : if self.jobButton is not None : # MORE Unhighlight the old button pass self.jobButton = jobButton # MORE Highlight the button if self.highlight is not None : self.highlight.parent.role.assignJob( jobButton.job ) self.selectMing(None) def selectMing( self, ming ) : if self.highlight is not None : self.highlight.getActor().kill() if ming is None : self.highlight = None else : self.highlight = Highlight( ming.getActor() ) self.highlight.createActor().event( "highlight" ) def onMouseDown( self, event ) : mainView = game.layout.findView("main") mainView.adjustMouse( event ) if event.button == MouseButtonEvent.BUTTON_LEFT : ming = game.findNearestRole( "ming",event.x ,event.y-20 ) #Nearest to their middle, not their feet. if ming is not None and ming.getActor().hitting( event.x, event.y ) : self.selectMing( ming ) else : self.selectMing( None ) mainView.unadjustMouse( event ) def chooseCollisionStrategy( self, actor ) : #return SinglePointCollisionStrategy( actor, self.neighbourhood ) return NeighbourhoodCollisionStrategy( actor, self.neighbourhood ) # Boiler plate code - no need to change this def getProperties(self): return properties # Boiler plate code - no need to change this def getClassName(self): return ClassName( CostumeProperties, self.__module__ + ".py" )
class PythonInterpreter(object): """Customized Python interpreter with two-stage evaluation. """ filename = '<online-lab>' def __init__(self, locals={}, debug=False): if not isinstance(locals, PythonNamespace): self.locals = dict(PythonNamespace(locals)) else: self.locals = dict(locals) self.debug = debug self.trap = OutputTrap() self.inspector = Inspector() self.highlight = Highlight() self.index = 0 def complete(self, source): """Get all completions for an initial source code. """ interrupted = False try: completer = rlcompleter.Completer(self.locals) matches = set([]) state = 0 while True: result = completer.complete(source, state) if result is not None: matches.add(result) state += 1 else: break completions = [] for match in sorted(matches): if match[-1] == '(': match = match[:-1] if '.' in match: name, attrs = match.split('.', 1) else: name, attrs = match, None try: obj = self.locals[name] except KeyError: obj = None else: if attrs is not None: for attr in attrs.split('.'): obj = getattr(obj, attr) if obj is not None: info = self.inspector.get_basic_info(obj) else: info = {'type': 'keyword'} completions.append({ 'match': match, 'info': info, }) except KeyboardInterrupt: completions = None interrupted = True return { 'completions': completions, 'interrupted': interrupted, } def evaluate(self, source): """Evaluate a piece of Python source code. """ source = source.replace('\r', '').rstrip() # XXX: make all this SIGINT aware if '\n' in source: exec_source, eval_source = self.split(source) else: exec_source, eval_source = None, source eval_source += '\n' try: self.compile(eval_source, 'eval') except (OverflowError, SyntaxError, ValueError): if '\n' not in source and self.is_inspect(source): return self.inspect(source) exec_source = source eval_source = None # If in debug mode, then don't setup output trap so that we can # run a debugger (e.g. pdb). Note that stdout and stderr won't # be captured and stored in the resulting dict object. if not self.debug: self.trap.set() try: try: del self.locals['__plots__'] except KeyError: pass interrupted = False traceback = False result = None start = time.clock() try: if exec_source is not None: try: exec_code = self.compile(exec_source, 'exec') except (OverflowError, SyntaxError, ValueError): traceback = self.syntaxerror() eval_source = None else: exec exec_code in self.locals if eval_source is not None: result = eval(eval_source, self.locals) sys.displayhook(result) except SystemExit: raise except KeyboardInterrupt: interrupted = True except: traceback = self.traceback() end = time.clock() try: plots = self.locals['__plots__'] except KeyError: plots = [] self.index += 1 if result is not None: self.locals['_%d' % self.index] = result self.locals['___'] = self.locals.get('__') self.locals['__'] = self.locals.get('_') self.locals['_'] = result result = { 'source': source, 'index': self.index, 'time': end - start, 'out': self.trap.out, 'err': self.trap.err, 'plots': plots, 'traceback': traceback, 'interrupted': interrupted, } if traceback: result['traceback_html'] = self.highlight.traceback(traceback) return result finally: self.trap.reset() def inspect(self, source): """Collect information about a Python object. """ text = source more = False if text.startswith('??'): text = text[2:] more = True if text.endswith('??'): text = text[:-2] more = True if not more: if text.startswith('?'): text = text[1:] if text.endswith('?'): text = text[:-1] text = text.strip() if '.' in text: name, attrs = text.split('.', 1) else: name, attrs = text, None try: obj = self.locals[name] except KeyError: obj = None else: if attrs is not None: for attr in attrs.split('.'): try: obj = getattr(obj, attr) except KeyError: obj = None break if obj is not None: info = self.inspector.get_pretty(obj, self.highlight) else: info = None self.index += 1 return { 'source': source, 'text': text, 'info': info, 'more': more, 'index': self.index, 'interrupted': False, } def is_inspect(self, source): """Return ``True`` if user requested code inspection. """ return source.startswith('?') or source.endswith('?') def split(self, source): """Extract last logical line from multi-line source code. """ string = StringIO(source).readline tokens = tokenize.generate_tokens(string) for tok, _, (n, _), _, _ in reversed(list(tokens)): if tok == tokenize.NEWLINE: lines = source.split('\n') exec_source = '\n'.join(lines[:n]) eval_source = '\n'.join(lines[n:]) return exec_source, eval_source else: return None, source def compile(self, source, mode): """Wrapper over Python's built-in :func:`compile` function. """ return compile(source, self.filename, mode) def traceback(self): """Return nicely formatted most recent traceback. """ type, value, tb = sys.exc_info() return ''.join(traceback.format_exception(type, value, tb.tb_next)) def syntaxerror(self): """Return nicely formatted syntax error. """ type, value, sys.last_traceback = sys.exc_info() sys.last_type = type sys.last_value = value if type is SyntaxError: try: msg, (dummy_filename, lineno, offset, line) = value except: pass else: value = SyntaxError(msg, (self.filename, lineno, offset, line)) sys.last_value = value header = "Traceback (most recent call last):\n" return ''.join([header] + traceback.format_exception_only(type, value))
def highlight_func(self, query_string): if termstyle is None: return lambda x: x highlight = Highlight(query_string) return lambda x: highlight.replace(x, green)
class Game(): def __init__(self, graphics, root): # global variables self.k = K() # piece - piece identifier. px, py - piece position(472x472). mx, my - mouse position(472x472) self.data = {"piece": None, "px": 0, "py": 0, "mx": 0, "my": 0} # keeps track of current turn self.color = "token" # true when menu is displayed, else false self.menuOn = False # tkinter root self.root = root # creates window and all images self.graphics = graphics # Canvas from graphics class. Tkinter object, draws images self.canvas = graphics.canvas # functions for special moves. self.specialMoves = SpecialMoves(self.canvas) # contains board and functions pertaining to position self.position = Position(self.canvas, self.specialMoves) self.position.updateBoard() # contains functions for moving pieces self.movement = Movement(self.canvas, self.position) # handles menues self.interface = Interface(graphics) # creates highlights around boxes self.highlight = Highlight(self.canvas, self.position) # finds move for computer player self.cpu = CPU(self.position, self.canvas) # brings up main menu, starts game self.showMain(0) def mouseClick(self, event): ''' Called when a user generated mouse click event occurs. @param event: Mouse click event generated from Tkinter. Function is binded with event and is called when this event occurs. @post data and originalPosition are initialized to the piece closest to the mouse click event. This piece's image is raised to the top layer. A border is created around the current tile. ''' self.data["piece"] = self.findClosest(event) self.data["mx"] = event.x self.data["my"] = event.y self.updateCoords() self.canvas.lift(self.data["piece"]) self.position.originalPosition = self.getPosition() self.highlight.createBorder(self.getPosition(), self.data) def mouseMove(self, event): ''' Called when a user generated mouse movement event occurs. Does nothing unless data members have been initialized by mouseClick @param event: Mouse movement event generated from Tkinter. Function is binded with event and is called when this event occurs. @post The corresponding piece is moved and a border is created around the current tile. Try block is used to keep piece inside window. ''' self.movement.drag(event, self.data) self.updateCoords() try: self.highlight.createBorder(self.getPosition(), self.data) except TypeError: self.movement.push(self.data) def mouseRelease(self, event): ''' Called when a user generated mouse release event occurs. Places piece and clears data members. @param event: Mouse release event generated from Tkinter. Function is binded with event and is called when this event occurs. @post If in a legal position, piece is moved to the center of the tile and the game updates. Else, piece is moved to original position. Variables are reset. ''' if (self.canMove()): self.movement.snap(self.data) if (self.position.originalPosition != self.getPosition()): self.updateGame() else: self.movement.reset(self.data) self.position.rookMoved = False self.highlight.clearBorder() self.data["piece"] = NONE self.data["mx"] = 0 self.data["my"] = 0 def updateGame(self): ''' Called during mouseRelease. Updates game and changes turn. @post Captured pieces, pieces that have been moved, and the board have all been updated. Special moves and a winner have both been checked for. If multiplayer game, the game changes turn. Else, the computer takes its turn. ''' self.position.capture(self.getPosition(), self.canvas.gettags(self.data["piece"])) self.checkSpecials() self.position.updateMoved(self.data["piece"]) self.position.updateBoard() self.checkWin() if (self.multiPlayer): self.changeTurn() else: if (self.color == "token"): self.unbind() self.setColor() self.bind() self.cpu.takeTurn(self.checkWin, self.graphics.createNewPiece, self.specialMoves.pawns) def findClosest(self, event): ''' Prevents user from grabbing board. Four more locations are attempted if canvas.find_closest() doesn't return a piece. @param event: Tkinter event. event.x and event.y correspond to the location of the mouse click event. The origin is the top left corner, +x is right, and +y is down. @return The identifier of the piece. ''' piece = self.canvas.find_closest(event.x, event.y) tags = self.canvas.gettags(piece) if (len(tags) < 2): pieces = [] piece1 = self.canvas.find_closest(event.x + 20, event.y + 20) tags1 = self.canvas.gettags(piece1) pieces.append((piece1, tags1)) piece2 = self.canvas.find_closest(event.x + 20, event.y - 20) tags2 = self.canvas.gettags(piece2) pieces.append((piece2, tags2)) piece3 = self.canvas.find_closest(event.x - 20, event.y + 20) tags3 = self.canvas.gettags(piece3) pieces.append((piece3, tags3)) piece4 = self.canvas.find_closest(event.x - 20, event.y - 20) tags4 = self.canvas.gettags(piece4) pieces.append((piece4, tags4)) for pair in pieces: if (len(pair[1]) > 2): piece = pair[0] return piece def bind(self): ''' @post Bindings are added for pieces of current color. ''' self.canvas.tag_bind(self.color, "<ButtonPress-1>", self.mouseClick) self.canvas.tag_bind(self.color, "<B1-Motion>", self.mouseMove) self.canvas.tag_bind(self.color, "<ButtonRelease-1>", self.mouseRelease) def unbind(self): ''' @post Bindings are removed for pieces of current color. ''' self.canvas.tag_unbind(self.color, "<ButtonPress-1>") self.canvas.tag_unbind(self.color, "<B1-Motion>") self.canvas.tag_unbind(self.color, "<ButtonRelease-1>") def changeTurn(self): ''' Changes turn for multi-player game. @post Pieces are bound to other players color. ''' self.unbind() self.changeColor() self.bind() def setColor(self): ''' @post Sets color based off of current piece. If single-player game, also sets cpu color. ''' tags = self.canvas.gettags(self.data["piece"]) self.color = tags[1] if (self.singlePlayer): if (self.color == "white"): self.cpu.color = "black" else: self.cpu.color = "white" def changeColor(self): ''' @post Changes color to opposing team. ''' if (self.color == "token"): self.setColor() if (self.color == "white"): self.color = "black" else: self.color = "white" def updateCoords(self): ''' @post The current coordinates of the image are updated. origin - topleft, +x - right(0-472), +y - down(0-472). ''' coords = self.canvas.coords(self.data["piece"]) self.data["px"] = coords[0] self.data["py"] = coords[1] def getPosition(self): ''' @return position.getPosition(), current board position. origin - topleft, +x - right(0-7), +y - down(0-7). ''' return self.position.getPosition(self.data["px"], self.data["py"]) def canMove(self): ''' @post position.canMove() is called. Checks if current piece can move to it's current location. ''' return self.position.canMove( self.canvas.gettags(self.data["piece"]), self.position.getPosition(self.data["px"], self.data["py"])) def checkWin(self): ''' @post interface.checkWin() has been called. ''' self.interface.checkWin(self.unbind, self.disableMenu, self.restart, self.showMain) def checkSpecials(self): ''' @post specialMoves.pawns() is called. Checks for promotion / en passant. ''' pos = self.getPosition() self.specialMoves.pawns(self.position.originalPosition, pos, self.unbind, self.createPiece) def createPiece(self, event): ''' Used when promoting a pawn. Function is binded with mouseClick event in specialmoves.promote() @param event: Tkinter event used to find which piece user clicked on @post A new piece is created, The promotion menu is hidden, and the pieces are rebound. ''' piece = self.canvas.find_closest(event.x, event.y) tags = self.canvas.gettags(piece) self.graphics.createNewPiece(tags, self.getPosition()) self.specialMoves.hide() self.position.updateBoard() self.bind() def showMenu(self, event): ''' @param event: Tkinter event, needed for interace.menu() @post Bindings are removed from pieces and in-game menu is brought up. ''' self.unbind() self.interface.menu(event, self.bind, self.showMenu, self.restart, self.showMain) def disableMenu(self): ''' @post In-game menu can no longer appear. ''' self.root.unbind('<Escape>') def enableMenu(self): ''' @post In-game menu can appear. ''' self.root.bind('<Escape>', self.showMenu) def restart(self, event): ''' Called from interface.menu(). Restarts game. @param event: Tkinter event, needed to bind functions @post Variables and board are reset. ''' self.color = "token" self.bind() self.enableMenu() self.graphics.restart() self.position.updateBoard() def showMain(self, event): ''' Brings up main menu. @param event: Tkinter event, needed to bind function @post Game is reset, bindings are removed, main menu is displayed. ''' self.singlePlayer = False self.multiPlayer = False self.color = "token" self.unbind() self.disableMenu() self.graphics.restart() self.position.updateBoard() self.interface.mainMenu(self.setSinglePlayer, self.setMultiPlayer) def setSinglePlayer(self, event): ''' Called from interface.mainMenu(). Sets up single player game. @param event: Tkinter event, needed to bind functions @post Variables for single player game are set, main menu is hidden, pieces are rebound, and in-game menu are enabled. ''' self.singlePlayer = True self.multiPlayer = False self.interface.hideMain() self.bind() self.enableMenu() def setMultiPlayer(self, event): ''' Called from interface.mainMenu(). Sets up multi player game. @param event: Tkinter event, needed to bind functions @post Variables for mutli player game are set, main menu is hidden, pieces are rebound, and in-game menu are enabled. ''' self.multiPlayer = True self.singlePlayer = False self.interface.hideMain() self.bind() self.enableMenu()
def make_interactive_graph(graph, pos=None, cmap=plt.cm.viridis, edge_cmap=plt.cm.Reds, node_size_factor=5): fig = plt.figure(1, figsize=(8, 6), dpi=100) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) weights = [d["weight"] for (u, v, d) in graph.edges(data=True)] degrees = nx.degree(graph) sizes = [degrees[name] * node_size_factor for name in graph.nodes()] urls = [d["url"] for u, d in graph.nodes(data=True)] if pos is None: pos = nx.spring_layout(graph) nodes = nx.draw_networkx_nodes(graph, pos=pos, node_size=sizes, node_color=sizes, cmap=cmap, alpha=0.3) edges = nx.draw_networkx_edges(graph, pos=pos, edge_color=weights, edge_cmap=edge_cmap, arrows=False, alpha=0.3) tip_div = u"<div style='background: #FFF; border-style: solid; border-width: 1px; padding: 2px;'>{}</div>" html_labels = list() for node in graph.nodes(): neighbors = graph[node] neighbor_list = sorted([(neighbor, graph[node][neighbor]["weight"]) for neighbor in graph[node]], key=lambda tup: tup[1], reverse=True)[:3] list_label = u"<br />".join([ u"{} ({})".format(neighbor[0], neighbor[1]) for neighbor in neighbor_list ]) html_labels.append( tip_div.format(u"<strong>{}</strong><br/><i>{}</i>".format( node, list_label))) line_labels = [ tip_div.format( u"<strong>{}</strong> and <strong>{}</strong> <i>({})</i>".format( u, v, d["weight"])) for (u, v, d) in graph.edges(data=True) ] tooltips = mpld3.plugins.PointHTMLTooltip(nodes, labels=html_labels, voffset=-10, hoffset=10) linetips = mpld3.plugins.PointHTMLTooltip(edges, labels=line_labels, voffset=-5, hoffset=10) mpld3.plugins.connect(fig, ClickInfo(nodes, urls)) mpld3.plugins.connect(fig, Highlight(nodes)) mpld3.plugins.connect(fig, Highlight(edges)) mpld3.plugins.connect(fig, tooltips) mpld3.plugins.connect(fig, linetips) mpld3.enable_notebook() return mpld3.fig_to_html(fig)
class Linter: __metaclass__ = Tracker language = '' cmd = () regex = '' tab_size = 1 scope = 'keyword' selector = None outline = True needs_api = False languages = {} linters = {} errors = None highlight = None def __init__(self, view, syntax, filename=None): self.view = view self.syntax = syntax self.filename = filename if self.regex: self.regex = re.compile(self.regex) self.highlight = Highlight(scope=self.scope) @classmethod def add_subclass(cls, sub, name, attrs): if name: sub.name = name cls.languages[name] = sub @classmethod def assign(cls, view): ''' find a linter for a specified view if possible, then add it to our mapping of view <--> lint class and return it each view has its own linter to make it feasible for linters to store persistent data about a view ''' try: vid = view.id() except RuntimeError: pass settings = view.settings() syn = settings.get('syntax') if not syn: cls.remove(vid) return match = syntax_re.search(syn) if match: syntax, = match.groups() else: syntax = syn if syntax: if vid in cls.linters and cls.linters[vid]: if tuple(cls.linters[vid])[0].syntax == syntax: return linters = set() for name, entry in cls.languages.items(): if entry.can_lint(syntax): linter = entry(view, syntax, view.file_name()) linters.add(linter) if linters: cls.linters[vid] = linters return linters cls.remove(vid) @classmethod def remove(cls, vid): if vid in cls.linters: for linter in cls.linters[vid]: linter.clear() del cls.linters[vid] @classmethod def reload(cls, mod): ''' reload all linters originating from a specific module (follows a module reload) ''' for id, linters in cls.linters.items(): for linter in linters: if linter.__module__ == mod: linter.clear() cls.linters[id].remove(linter) linter = cls.languages[linter.name](linter.view, linter.syntax, linter.filename) cls.linters[id].add(linter) linter.draw() return @classmethod def text(cls, view): return view.substr(sublime.Region(0, view.size())).encode('utf-8') @classmethod def lint_view(cls, view_id, filename, code, sections, callback): if view_id in cls.linters: selectors = Linter.get_selectors(view_id) linters = tuple(cls.linters[view_id]) for linter in linters: if not linter.selector: linter.filename = filename linter.pre_lint(code) for sel, linter in selectors: if sel in sections: highlight = Highlight(code, scope=linter.scope, outline=linter.outline) errors = {} for line_offset, left, right in sections[sel]: highlight.shift(line_offset, left) linter.pre_lint(code[left:right], highlight=highlight) for line, error in linter.errors.items(): errors[line + line_offset] = error linter.errors = errors # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0) @classmethod def get_view(cls, view_id): if view_id in cls.linters: return tuple(cls.linters[view_id])[0].view @classmethod def get_linters(cls, view_id): if view_id in cls.linters: return tuple(cls.linters[view_id]) return () @classmethod def get_selectors(cls, view_id): return [(linter.selector, linter) for linter in cls.get_linters(view_id) if linter.selector] def pre_lint(self, code, highlight=None): self.errors = {} self.highlight = highlight or Highlight( code, scope=self.scope, outline=self.outline) if not code: return # if this linter needs the api, we want to merge back into the main thread # but stall this thread until it's done so we still have the return if self.needs_api: q = Queue() def callback(): q.get() self.lint(code) q.task_done() q.put(1) sublime.set_timeout(callback, 1) q.join() else: self.lint(code) def lint(self, code): if not (self.language and self.cmd and self.regex): raise NotImplementedError output = self.communicate(self.cmd, code) if output: persist.debug('Output:', repr(output)) for line in output.splitlines(): line = line.strip() match, row, col, message, near = self.match_error( self.regex, line) if match: if row or row is 0: if col or col is 0: # adjust column numbers to match the linter's tabs if necessary if self.tab_size > 1: start, end = self.highlight.full_line(row) code_line = code[start:end] diff = 0 for i in xrange(len(code_line)): if code_line[i] == '\t': diff += (self.tab_size - 1) if col - diff <= i: col = i break self.highlight.range(row, col) elif near: self.highlight.near(row, near) else: self.highlight.line(row) self.error(row, message) def draw(self, prefix='lint'): self.highlight.draw(self.view, prefix) def clear(self, prefix='lint'): self.highlight.clear(self.view, prefix) # helper methods @classmethod def can_lint(cls, language): language = language.lower() if cls.language: if language == cls.language: return True elif isinstance(cls.language, (tuple, list)) and language in cls.language: return True else: return False def error(self, line, error): self.highlight.line(line) error = str(error) if line in self.errors: self.errors[line].append(error) else: self.errors[line] = [error] def match_error(self, r, line): match = r.match(line) if match: items = {'row': None, 'col': None, 'error': '', 'near': None} items.update(match.groupdict()) error, row, col, near = [ items[k] for k in ('error', 'line', 'col', 'near') ] row = int(row) - 1 if col: col = int(col) - 1 return match, row, col, error, near return match, None, None, '', None # popen wrappers def communicate(self, cmd, code): return util.communicate(cmd, code) def tmpfile(self, cmd, code, suffix=''): return util.tmpfile(cmd, code, suffix) def tmpdir(self, cmd, files, code): return util.tmpdir(cmd, files, self.filename, code) def popen(self, cmd, env=None): return util.popen(cmd, env)
class Linter: __metaclass__ = Tracker language = "" cmd = () regex = "" languages = {} linters = {} def __init__(self, view, syntax, filename="untitled"): self.view = view self.syntax = syntax self.filename = filename if self.regex: self.regex = re.compile(self.regex) @classmethod def add_subclass(cls, sub, name, attrs): if name: sub.name = name cls.languages[name] = sub @classmethod def assign(cls, view): """ find a linter for a specified view if possible, then add it to our mapping of view <--> lint class and return it each view has its own linter to make it feasible for linters to store persistent data about a view """ id = view.id() settings = view.settings() syn = settings.get("syntax") match = syntax_re.search(syn) if match: syntax, = match.groups() else: syntax = syn if syntax: if id in cls.linters and cls.linters[id]: if tuple(cls.linters[id])[0].syntax == syntax: return linters = set() for entry in cls.languages.values(): if entry.can_lint(syntax): linter = entry(view, syntax) linters.add(linter) if linters: cls.linters[id] = linters else: if id in cls.linters: del cls.linters[id] return linters @classmethod def reload(cls, mod): """ reload all linters originating from a specific module (follows a module reload) """ for id, linters in cls.linters.items(): for linter in linters: if linter.__module__ == mod: cls.linters[id].remove(linter) linter = cls.languages[linter.name](linter.view, linter.syntax) cls.linters[id].add(linter) return @classmethod def text(cls, view): return view.substr(sublime.Region(0, view.size())).encode("utf-8") @classmethod def lint_view(cls, view_id, code, callback): if view_id in cls.linters: linters = tuple(cls.linters[view_id]) for linter in linters: linter.lint(code) # merge our result back to the main thread sublime.set_timeout(lambda: callback(linters[0].view, linters), 0) @classmethod def get_view(self, view_id): if view_id in self.linters: return tuple(self.linters[view_id])[0].view def lint(self, code=None): if not (self.language and self.cmd and self.regex): raise NotImplementedError if code is None: code = Linter.text(self.view) self.highlight = Highlight(code) self.errors = errors = {} if not code: return output = self.communicate(self.cmd, code) print repr(output) for line in output.splitlines(): line = line.strip() match, row, col, message, near = self.match_error(self.regex, line) if match: if row or row is 0: if col or col is 0: self.highlight.range(row, col) elif near: self.highlight.near(row, near) else: self.highlight.line(row) if row in errors: errors[row].append(message) else: errors[row] = [message] def draw(self, prefix="lint"): self.highlight.draw(self.view, prefix) def clear(self, prefix="lint"): self.highlight.clear(self.view, prefix) # helper methods @classmethod def can_lint(cls, language): if language.lower() == cls.language: return True else: return False def error(self, line, error): self.highlight.line(line) error = str(error) if line in self.errors: self.errors[line].append(error) else: self.errors[line] = [error] def match_error(self, r, line): match = r.match(line) if match: items = {"row": None, "col": None, "error": "", "near": None} items.update(match.groupdict()) error, row, col, near = [items[k] for k in ("error", "line", "col", "near")] row = int(row) - 1 return match, row, col, error, near return match, None, None, "", None # popen methods def communicate(self, cmd, code): out = self.popen(cmd).communicate(code) return (out[0] or "") + (out[1] or "") def tmpfile(self, cmd, code, suffix=""): f = tempfile.NamedTemporaryFile(suffix=suffix) f.write(code) f.flush() cmd = tuple(cmd) + (f.name,) out = self.popen(cmd).communicate("") return (out[0] or "") + (out[1] or "") def popen(self, cmd): if isinstance(cmd, basestring): cmd = (cmd,) info = None if os.name == "nt": info = subprocess.STARTUPINFO() info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.wShowWindow = subprocess.SW_HIDE return subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=info )
class PythonInterpreter(object): """Customized Python interpreter with two-stage evaluation. """ filename = '<online-lab>' def __init__(self, locals={}, debug=False): if not isinstance(locals, PythonNamespace): self.locals = dict(PythonNamespace(locals)) else: self.locals = dict(locals) self.debug = debug self.trap = OutputTrap() self.inspector = Inspector() self.highlight = Highlight() self.index = 0 def complete(self, source): """Get all completions for an initial source code. """ interrupted = False try: completer = rlcompleter.Completer(self.locals) matches = set([]) state = 0 while True: result = completer.complete(source, state) if result is not None: matches.add(result) state += 1 else: break completions = [] for match in sorted(matches): if match[-1] == '(': match = match[:-1] if '.' in match: name, attrs = match.split('.', 1) else: name, attrs = match, None try: obj = self.locals[name] except KeyError: obj = None else: if attrs is not None: for attr in attrs.split('.'): obj = getattr(obj, attr) if obj is not None: info = self.inspector.get_basic_info(obj) else: info = {'type': 'keyword'} completions.append({ 'match': match, 'info': info, }) except KeyboardInterrupt: completions = None interrupted = True return { 'completions': completions, 'interrupted': interrupted, } def evaluate(self, source): """Evaluate a piece of Python source code. """ source = source.replace('\r', '').rstrip() # XXX: make all this SIGINT aware if '\n' in source: exec_source, eval_source = self.split(source) else: exec_source, eval_source = None, source eval_source += '\n' try: self.compile(eval_source, 'eval') except (OverflowError, SyntaxError, ValueError): if '\n' not in source and self.is_inspect(source): return self.inspect(source) exec_source = source eval_source = None # If in debug mode, then don't setup output trap so that we can # run a debugger (e.g. pdb). Note that stdout and stderr won't # be captured and stored in the resulting dict object. if not self.debug: self.trap.set() try: try: del self.locals['__plots__'] except KeyError: pass interrupted = False traceback = False result = None start = time.clock() try: if exec_source is not None: try: exec_code = self.compile(exec_source, 'exec') except (OverflowError, SyntaxError, ValueError): traceback = self.syntaxerror() eval_source = None else: exec exec_code in self.locals if eval_source is not None: result = eval(eval_source, self.locals) sys.displayhook(result) except SystemExit: raise except KeyboardInterrupt: traceback = self.traceback() interrupted = True except: traceback = self.traceback() end = time.clock() try: plots = self.locals['__plots__'] except KeyError: plots = [] self.index += 1 if result is not None: self.locals['_%d' % self.index] = result self.locals['___'] = self.locals.get('__') self.locals['__'] = self.locals.get('_') self.locals['_'] = result result = { 'source': source, 'index': self.index, 'time': end - start, 'out': self.trap.out, 'err': self.trap.err, 'plots': plots, 'traceback': traceback, 'interrupted': interrupted, } if traceback: result['traceback_html'] = self.highlight.traceback(traceback) return result finally: self.trap.reset() def inspect(self, source): """Collect information about a Python object. """ text = source more = False if text.startswith('??'): text = text[2:] more = True if text.endswith('??'): text = text[:-2] more = True if not more: if text.startswith('?'): text = text[1:] if text.endswith('?'): text = text[:-1] text = text.strip() if '.' in text: name, attrs = text.split('.', 1) else: name, attrs = text, None try: obj = self.locals[name] except KeyError: obj = None else: if attrs is not None: for attr in attrs.split('.'): try: obj = getattr(obj, attr) except KeyError: obj = None break if obj is not None: info = self.inspector.get_pretty(obj, self.highlight) else: info = None self.index += 1 return { 'source': source, 'text': text, 'info': info, 'more': more, 'index': self.index, 'interrupted': False, } def is_inspect(self, source): """Return ``True`` if user requested code inspection. """ return source.startswith('?') or source.endswith('?') def split(self, source): """Extract last logical line from multi-line source code. """ string = StringIO(source).readline try: tokens = reversed(list(tokenize.generate_tokens(string))) except (OverflowError, SyntaxError, ValueError): return None, source for tok, _, (n, _), _, _ in tokens: if tok == tokenize.NEWLINE: lines = source.split('\n') exec_source = '\n'.join(lines[:n]) eval_source = '\n'.join(lines[n:]) return exec_source, eval_source else: return None, source def compile(self, source, mode): """Wrapper over Python's built-in :func:`compile` function. """ return compile(source, self.filename, mode) def traceback(self): """Return nicely formatted most recent traceback. """ type, value, tb = sys.exc_info() return ''.join(traceback.format_exception(type, value, tb.tb_next)) def syntaxerror(self): """Return nicely formatted syntax error. """ type, value, sys.last_traceback = sys.exc_info() sys.last_type = type sys.last_value = value if type is SyntaxError: try: msg, (dummy_filename, lineno, offset, line) = value except: pass else: value = SyntaxError(msg, (self.filename, lineno, offset, line)) sys.last_value = value header = "Traceback (most recent call last):\n" return ''.join([header] + traceback.format_exception_only(type, value))