INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parse multiple definitions and yield them.
def parse_definitions(self, class_, all=False): """Parse multiple definitions and yield them.""" while self.current is not None: self.log.debug( "parsing definition list, current token is %r (%s)", self.current.kind, self.current.value, ...
Parse the __all__ definition in a module.
def parse_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == "__all__" self.consume(tk.NAME) if self.current.value != "=": raise AllError("Could not evaluate contents of __all__. ") self.consume(tk.OP) if self.current.value...
Parse a module ( and its children ) and return a Module object.
def parse_module(self): """Parse a module (and its children) and return a Module object.""" self.log.debug("parsing module.") start = self.line docstring = self.parse_docstring() children = list(self.parse_definitions(Module, all=True)) assert self.current is None, self.c...
Verify the current token is of type kind and equals value.
def check_current(self, kind=None, value=None): """Verify the current token is of type `kind` and equals `value`.""" msg = textwrap.dedent( """ Unexpected token at line {self.line}: In file: {self.filename} Got kind {self.current.kind!r} Got value {self.curren...
Parse a from x import y statement.
def parse_from_import_statement(self): """Parse a 'from x import y' statement. The purpose is to find __future__ statements. """ self.log.debug("parsing from/import statement.") is_future_import = self._parse_from_import_source() self._parse_from_import_names(is_future_i...
Parse the y part in a from x import y statement.
def _parse_from_import_names(self, is_future_import): """Parse the 'y' part in a 'from x import y' statement.""" if self.current.value == "(": self.consume(tk.OP) expected_end_kinds = (tk.OP,) else: expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER) while...
Use docutils to check docstrings are valid RST.
def run(self): """Use docutils to check docstrings are valid RST.""" # Is there any reason not to call load_source here? if self.err is not None: assert self.source is None msg = "%s%03i %s" % ( rst_prefix, rst_fail_load, "F...
Load the source for the specified file.
def load_source(self): """Load the source for the specified file.""" if self.filename in self.STDIN_NAMES: self.filename = "stdin" if sys.version_info[0] < 3: self.source = sys.stdin.read() else: self.source = TextIOWrapper(sys.stdin.bu...
Converts CIE Lab to RGB components. First we have to convert to XYZ color space. Conversion involves using a white point in this case D65 which represents daylight illumination. Algorithms adopted from: http:// www. easyrgb. com/ math. php
def lab_to_rgb(l, a, b): """ Converts CIE Lab to RGB components. First we have to convert to XYZ color space. Conversion involves using a white point, in this case D65 which represents daylight illumination. Algorithms adopted from: http://www.easyrgb.com/math.php """ ...
Returns the darkest swatch. Knowing the contract between a light and a dark swatch can help us decide how to display readable typography.
def _darkest(self): """ Returns the darkest swatch. Knowing the contract between a light and a dark swatch can help us decide how to display readable typography. """ rgb, n = (1.0, 1.0, 1.0), 3.0 for r,g,b in self: if r+g+b ...
Parses a theme from XML returned by Kuler. Gets the theme s id label and swatches. All of the swatches are converted to RGB. If we have a full description for a theme id in cache parse that to get tags associated with the theme.
def parse_theme(self, xml): """ Parses a theme from XML returned by Kuler. Gets the theme's id, label and swatches. All of the swatches are converted to RGB. If we have a full description for a theme id in cache, parse that to get tags associated with the theme....
Create socket and set listening options: param host:: param port:: param handler:: return:
def create_listening_socket(host, port, handler): """ Create socket and set listening options :param host: :param port: :param handler: :return: """ sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(1) ...
Asynchronous connection listener. Starts a handler for each connection.
def listener(self, sock, *args): '''Asynchronous connection listener. Starts a handler for each connection.''' conn, addr = sock.accept() f = conn.makefile(conn) self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO) print(_("Connected")) GObject.io_add_watch(...
Asynchronous connection handler. Processes each line from the socket.
def handler(self, conn, *args): ''' Asynchronous connection handler. Processes each line from the socket. ''' # lines from cmd.Cmd self.shell.stdout.write(self.shell.prompt) line = self.shell.stdin.readline() if not len(line): line = 'EOF' ...
Trusted commands cannot be run remotely
def trusted_cmd(f): """ Trusted commands cannot be run remotely :param f: :return: """ def run_cmd(self, line): if self.trusted: f(self, line) else: print("Sorry cannot do %s here." % f.__name__[3:]) global trusted_cmds trusted_cmds.add(f.__name_...
print response if cookie is set then print that each line: param args:: param keep: if True more output is to come: param cookie: set a custom cookie if set to None then self. cookie will be used. if set to False disables cookie output entirely: return:
def print_response(self, input='', keep=False, *args, **kwargs): """ print response, if cookie is set then print that each line :param args: :param keep: if True more output is to come :param cookie: set a custom cookie, if set to 'None' then self.cookie wi...
Escape newlines in any responses
def do_escape_nl(self, arg): """ Escape newlines in any responses """ if arg.lower() == 'off': self.escape_nl = False else: self.escape_nl = True
Enable or disable prompt: param arg: on|off: return:
def do_prompt(self, arg): """ Enable or disable prompt :param arg: on|off :return: """ if arg.lower() == 'off': self.response_prompt = '' self.prompt = '' return elif arg.lower() == 'on': self.prompt = PROMPT ...
rewind
def do_speed(self, speed): """ rewind """ if speed: try: self.bot._speed = float(speed) except Exception as e: self.print_response('%s is not a valid framerate' % speed) return self.print_response('Speed: %s ...
Attempt to restart the bot.
def do_restart(self, line): """ Attempt to restart the bot. """ self.bot._frame = 0 self.bot._namespace.clear() self.bot._namespace.update(self.bot._initial_namespace)
Toggle pause
def do_pause(self, line): """ Toggle pause """ # along with stuff in socketserver and shell if self.pause_speed is None: self.pause_speed = self.bot._speed self.bot._speed = 0 self.print_response('Paused') else: self.bot._sp...
Resume playback if bot is paused
def do_play(self, line): """ Resume playback if bot is paused """ if self.pause_speed is None: self.bot._speed = self.pause_speed self.pause_speed = None self.print_response("Play")
Go to specific frame: param line:: return:
def do_goto(self, line): """ Go to specific frame :param line: :return: """ self.print_response("Go to frame %s" % line) self.bot._frame = int(line)
rewind
def do_rewind(self, line): """ rewind """ self.print_response("Rewinding from frame %s to 0" % self.bot._frame) self.bot._frame = 0
List bot variables and values
def do_vars(self, line): """ List bot variables and values """ if self.bot._vars: max_name_len = max([len(name) for name in self.bot._vars]) for i, (name, v) in enumerate(self.bot._vars.items()): keep = i < len(self.bot._vars) - 1 s...
load filename = ( file ) load base64 = ( base64 encoded )
def do_load_base64(self, line): """ load filename=(file) load base64=(base64 encoded) Send new code to shoebot. If it does not run successfully shoebot will attempt to role back. Editors can enable livecoding by sending new code as it is edited. """ coo...
Exit shell and shoebot
def do_exit(self, line): """ Exit shell and shoebot """ if self.trusted: publish_event(QUIT_EVENT) self.print_response('Bye.\n') return True
Make the current window fullscreen
def do_fullscreen(self, line): """ Make the current window fullscreen """ self.bot.canvas.sink.trigger_fullscreen_action(True) print(self.response_prompt, file=self.stdout)
Un - fullscreen the current window
def do_windowed(self, line): """ Un-fullscreen the current window """ self.bot.canvas.sink.trigger_fullscreen_action(False) print(self.response_prompt, file=self.stdout)
Exit shell and shoebot
def do_EOF(self, line): """ Exit shell and shoebot Alias for exit. """ print(self.response_prompt, file=self.stdout) return self.do_exit(line)
Show help on all commands.
def do_help(self, arg): """ Show help on all commands. """ print(self.response_prompt, file=self.stdout) return cmd.Cmd.do_help(self, arg)
Set a variable.
def do_set(self, line): """ Set a variable. """ try: name, value = [part.strip() for part in line.split('=')] if name not in self.bot._vars: self.print_response('No such variable %s enter vars to see available vars' % name) return ...
Allow commands to have a last parameter of cookie = somevalue
def precmd(self, line): """ Allow commands to have a last parameter of 'cookie=somevalue' TODO somevalue will be prepended onto any output lines so that editors can distinguish output from certain kinds of events they have sent. :param line: :return: """...
Draw a daisy at x y
def drawdaisy(x, y, color='#fefefe'): """ Draw a daisy at x, y """ # save location, size etc _ctx.push() # save fill and stroke _fill =_ctx.fill() _stroke = _ctx.stroke() sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0 # draw stalk _ctx.strokewidth(sc * 2.0) _ctx.s...
http:// www. swharden. com/ blog/ 2009 - 01 - 21 - signal - filtering - with - python/ #comment - 16801
def fft_bandpassfilter(data, fs, lowcut, highcut): """ http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801 """ fft = np.fft.fft(data) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft.copy() # Zero out fft coefficie...
Produces a nicer graph I m not sure if this is correct
def flatten_fft(scale=1.0): """ Produces a nicer graph, I'm not sure if this is correct """ _len = len(audio.spectrogram) for i, v in enumerate(audio.spectrogram): yield scale * (i * v) / _len
Produces a nicer graph I m not sure if this is correct
def scaled_fft(fft, scale=1.0): """ Produces a nicer graph, I'm not sure if this is correct """ data = np.zeros(len(fft)) for i, v in enumerate(fft): data[i] = scale * (i * v) / NUM_SAMPLES return data
Grab contents of doc and return it
def get_source(self, doc): """ Grab contents of 'doc' and return it :param doc: The active document :return: """ start_iter = doc.get_start_iter() end_iter = doc.get_end_iter() source = doc.get_text(start_iter, end_iter, False) return source
Create the gtk. TextView used for shell output
def _create_view(self, name="shoebot-output"): """ Create the gtk.TextView used for shell output """ view = gtk.TextView() view.set_editable(False) fontdesc = pango.FontDescription("Monospace") view.modify_font(fontdesc) view.set_name(name) buff = view.get_buffe...
Create the gtk. TextView inside a Gtk. ScrolledWindow: return: container text_view
def _create_view(self, name="shoebot-output"): """ Create the gtk.TextView inside a Gtk.ScrolledWindow :return: container, text_view """ text_view = Gtk.TextView() text_view.set_editable(False) fontdesc = Pango.FontDescription("Monospace") text_view.modif...
URI filename or string -- > stream This function lets you define parsers that take any input source ( URL pathname to local or network file or actual data as a string ) and deal with it in a uniform manner. Returned object is guaranteed to have all the basic stdio read methods ( read readline readlines ). Just. close (...
def openAnything(source, searchpaths=None): """URI, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have...
load XML input source return parsed XML document - a URL of a remote XML file ( http:// diveintopython. org/ kant. xml ) - a filename of a local XML file ( ~/ diveintopython/ common/ py/ kant. xml ) - standard input ( - ) - the actual XML document as a string: param searchpaths: optional searchpaths if file is used.
def _load(self, source, searchpaths=None): """load XML input source, return parsed XML document - a URL of a remote XML file ("http://diveintopython.org/kant.xml") - a filename of a local XML file ("~/diveintopython/common/py/kant.xml") - standard input ("-") - the actual ...
load context - free grammar
def loadGrammar(self, grammar, searchpaths=None): """load context-free grammar""" self.grammar = self._load(grammar, searchpaths=searchpaths) self.refs = {} for ref in self.grammar.getElementsByTagName("ref"): self.refs[ref.attributes["id"].value] = ref
load source
def loadSource(self, source, searchpaths=None): """load source""" self.source = self._load(source, searchpaths=searchpaths)
guess default source of the current grammar The default source will be one of the <ref > s that is not cross - referenced. This sounds complicated but it s not. Example: The default source for kant. xml is <xref id = section/ > because section is the one <ref > that is not <xref > d anywhere in the grammar. In most gra...
def getDefaultSource(self): """guess default source of the current grammar The default source will be one of the <ref>s that is not cross-referenced. This sounds complicated but it's not. Example: The default source for kant.xml is "<xref id='section'/>", because ...
reset output buffer re - parse entire source file and return output Since parsing involves a good deal of randomness this is an easy way to get new output without having to reload a grammar file each time.
def refresh(self): """reset output buffer, re-parse entire source file, and return output Since parsing involves a good deal of randomness, this is an easy way to get new output without having to reload a grammar file each time. """ self.reset() s...
choose a random child element of a node This is a utility method used by do_xref and do_choice.
def randomChildElement(self, node): """choose a random child element of a node This is a utility method used by do_xref and do_choice. """ choices = [e for e in node.childNodes if e.nodeType == e.ELEMENT_NODE] chosen = random.choice(choices) ...
parse a single XML node A parsed XML document ( from minidom. parse ) is a tree of nodes of various types. Each node is represented by an instance of the corresponding Python class ( Element for a tag Text for text data Document for the top - level document ). The following statement constructs the name of a class meth...
def parse(self, node): """parse a single XML node A parsed XML document (from minidom.parse) is a tree of nodes of various types. Each node is represented by an instance of the corresponding Python class (Element for a tag, Text for text data, Document for the top...
parse a text node The text of a text node is usually added to the output buffer verbatim. The one exception is that <p class = sentence > sets a flag to capitalize the first letter of the next word. If that flag is set we capitalize the text and reset the flag.
def parse_Text(self, node): """parse a text node The text of a text node is usually added to the output buffer verbatim. The one exception is that <p class='sentence'> sets a flag to capitalize the first letter of the next word. If that flag is set, we capitalize...
parse an element An XML element corresponds to an actual tag in the source: <xref id =... > <p chance =... > <choice > etc. Each element type is handled in its own method. Like we did in parse () we construct a method name based on the name of the element ( do_xref for an <xref > tag etc. ) and call the method.
def parse_Element(self, node): """parse an element An XML element corresponds to an actual tag in the source: <xref id='...'>, <p chance='...'>, <choice>, etc. Each element type is handled in its own method. Like we did in parse(), we construct a method name based...
handle <xref id =... > tag An <xref id =... > tag is a cross - reference to a <ref id =... > tag. <xref id = sentence/ > evaluates to a randomly chosen child of <ref id = sentence >.
def do_xref(self, node): """handle <xref id='...'> tag An <xref id='...'> tag is a cross-reference to a <ref id='...'> tag. <xref id='sentence'/> evaluates to a randomly chosen child of <ref id='sentence'>. """ id = node.attributes["id"].value se...
handle <p > tag The <p > tag is the core of the grammar. It can contain almost anything: freeform text <choice > tags <xref > tags even other <p > tags. If a class = sentence attribute is found a flag is set and the next word will be capitalized. If a chance = X attribute is found there is an X% chance that the tag wil...
def do_p(self, node): """handle <p> tag The <p> tag is the core of the grammar. It can contain almost anything: freeform text, <choice> tags, <xref> tags, even other <p> tags. If a "class='sentence'" attribute is found, a flag is set and the next word will be cap...
Replaces HTML special characters by readable characters.
def replace_entities(ustring, placeholder=" "): """Replaces HTML special characters by readable characters. As taken from Leif K-Brooks algorithm on: http://groups-beta.google.com/group/comp.lang.python """ def _repl_func(match): try: if match.group(1): # Numeric characte...
Returns a connection to a url which you can read ().
def open(url, wait=10): """ Returns a connection to a url which you can read(). When the wait amount is exceeded, raises a URLTimeout. When an error occurs, raises a URLError. 404 errors specifically return a HTTP404NotFound. """ # If the url is a URLParser, get any POST parameters. post...
Returns True when the url generates a 404 Not Found error.
def not_found(url, wait=10): """ Returns True when the url generates a "404 Not Found" error. """ try: connection = open(url, wait) except HTTP404NotFound: return True except: return False return False
Determine the MIME - type of the document behind the url.
def is_type(url, types=[], wait=10): """ Determine the MIME-type of the document behind the url. MIME is more reliable than simply checking the document extension. Returns True when the MIME-type starts with anything in the list of types. """ # Types can also be a single string for convenience. ...
Build requirements based on flags
def requirements(debug=True, with_examples=True, with_pgi=None): """ Build requirements based on flags :param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere :param with_examples: :return: """ reqs = list(BASE_REQUIREMENTS) if with_pgi is None: with_pgi = ...
Draws a image form path in x y and resize it to width height dimensions.
def image(self, path, x, y, width=None, height=None, alpha=1.0, data=None, draw=True, **kwargs): '''Draws a image form path, in x,y and resize it to width, height dimensions. ''' return self.Image(path, x, y, width, height, alpha, data, **kwargs)
Draw a rectangle from x y of width height.
def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs): ''' Draw a rectangle from x, y of width, height. :param startx: top left x-coordinate :param starty: top left y-coordinate :param width: height Size of rectangle. :roundness: Corner roundness defa...
Set the current rectmode.
def rectmode(self, mode=None): ''' Set the current rectmode. :param mode: CORNER, CENTER, CORNERS :return: rectmode if mode is None or valid. ''' if mode in (self.CORNER, self.CENTER, self.CORNERS): self.rectmode = mode return self.rectmode ...
Set the current ellipse drawing mode.
def ellipsemode(self, mode=None): ''' Set the current ellipse drawing mode. :param mode: CORNER, CENTER, CORNERS :return: ellipsemode if mode is None or valid. ''' if mode in (self.CORNER, self.CENTER, self.CORNERS): self.ellipsemode = mode return...
Draw a circle: param x: x - coordinate of the top left corner: param y: y - coordinate of the top left corner: param diameter: Diameter of circle.: param draw: Draw immediately ( defaults to True set to False to inhibit drawing ): return: Path object representing circle
def circle(self, x, y, diameter, draw=True, **kwargs): '''Draw a circle :param x: x-coordinate of the top left corner :param y: y-coordinate of the top left corner :param diameter: Diameter of circle. :param draw: Draw immediately (defaults to True, set to False to inhibit drawin...
Draw an arrow.
def arrow(self, x, y, width, type=NORMAL, draw=True, **kwargs): '''Draw an arrow. Arrows can be two types: NORMAL or FORTYFIVE. :param x: top left x-coordinate :param y: top left y-coordinate :param width: width of arrow :param type: NORMAL or FORTYFIVE :draw: ...
Draws a star.
def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs): '''Draws a star. ''' # Taken from Nodebox. self.beginpath(**kwargs) self.moveto(startx, starty + outer) for i in range(1, int(2 * points)): angle = i * pi / points ...
: param image: Image to draw: param x: optional x coordinate ( default is image. x ): param y: optional y coordinate ( default is image. y ): return:
def drawimage(self, image, x=None, y=None): """ :param image: Image to draw :param x: optional, x coordinate (default is image.x) :param y: optional, y coordinate (default is image.y) :return: """ if x is None: x = image.x if y is None: ...
Move relatively to the last point.
def relmoveto(self, x, y): '''Move relatively to the last point.''' if self._path is None: raise ShoebotError(_("No current path. Use beginpath() first.")) self._path.relmoveto(x, y)
Draw a line using relative coordinates.
def rellineto(self, x, y): '''Draw a line using relative coordinates.''' if self._path is None: raise ShoebotError(_("No current path. Use beginpath() first.")) self._path.rellineto(x, y)
Draws a curve relatively to the last point.
def relcurveto(self, h1x, h1y, h2x, h2y, x, y): '''Draws a curve relatively to the last point. ''' if self._path is None: raise ShoebotError(_("No current path. Use beginpath() first.")) self._path.relcurveto(h1x, h1y, h2x, h2y, x, y)
Constructs a path between the given list of points.
def findpath(self, points, curvature=1.0): """Constructs a path between the given list of points. Interpolates the list of points and determines a smooth bezier path betweem them. The curvature parameter offers some control on how separate segments are stitched together: ...
Set the current transform mode.
def transform(self, mode=None): ''' Set the current transform mode. :param mode: CENTER or CORNER''' if mode: self._canvas.mode = mode return self._canvas.mode
Translate the current position by ( xt yt ) and optionally set the transform mode.
def translate(self, xt, yt, mode=None): ''' Translate the current position by (xt, yt) and optionally set the transform mode. :param xt: Amount to move horizontally :param yt: Amount to move vertically :mode: Set the transform mode to CENTER or CORNER ''' ...
Set a scale at which to draw objects.
def scale(self, x=1, y=None): ''' Set a scale at which to draw objects. 1.0 draws objects at their natural size :param x: Scale on the horizontal plane :param y: Scale on the vertical plane ''' if not y: y = x if x == 0: # Cairo b...
Sets a fill color applying it to new paths.
def fill(self, *args): '''Sets a fill color, applying it to new paths. :param args: color in supported format ''' if args is not None: self._canvas.fillcolor = self.color(*args) return self._canvas.fillcolor
Set a stroke color applying it to new paths.
def stroke(self, *args): '''Set a stroke color, applying it to new paths. :param args: color in supported format ''' if args is not None: self._canvas.strokecolor = self.color(*args) return self._canvas.strokecolor
Stop applying strokes to new paths.
def nostroke(self): ''' Stop applying strokes to new paths. :return: stroke color before nostroke was called. ''' c = self._canvas.strokecolor self._canvas.strokecolor = None return c
Set the stroke width.
def strokewidth(self, w=None): '''Set the stroke width. :param w: Stroke width. :return: If no width was specified then current width is returned. ''' if w is not None: self._canvas.strokewidth = w else: return self._canvas.strokewidth
Set the font to be used with new text instances.
def font(self, fontpath=None, fontsize=None): '''Set the font to be used with new text instances. :param fontpath: path to truetype or opentype font. :param fontsize: size of font :return: current current fontpath (if fontpath param not set) Accepts TrueType and OpenType files....
Set or return size of current font.
def fontsize(self, fontsize=None): ''' Set or return size of current font. :param fontsize: Size of font. :return: Size of font (if fontsize was not specified) ''' if fontsize is not None: self._canvas.fontsize = fontsize else: return self...
Draws a string of text according to current font settings.
def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs): ''' Draws a string of text according to current font settings. :param txt: Text to output :param x: x-coordinate of the top left corner :param y: y-coordinate of the top left corner ...
Returns the height of a string of text according to the current font settings.
def textheight(self, txt, width=None): '''Returns the height of a string of text according to the current font settings. :param txt: string to measure :param width: width of a line of text in a block ''' w = width return self.textmetrics(txt, width=w)[1]
Graph background color.
def graph_background(s): """ Graph background color. """ if s.background == None: s._ctx.background(None) else: s._ctx.background(s.background) if s.depth: try: clr = colors.color(s.background).darker(0.2) p = s._ctx.rect(0, 0, s._ctx.WIDTH, s._ct...
Visualization of traffic - intensive nodes ( based on their centrality ).
def graph_traffic(s, node, alpha=1.0): """ Visualization of traffic-intensive nodes (based on their centrality). """ r = node.__class__(None).r r += (node.weight+0.5) * r * 5 s._ctx.nostroke() if s.traffic: s._ctx.fill( s.traffic.r, s.traffic.g, ...
Visualization of a default node.
def node(s, node, alpha=1.0): """ Visualization of a default node. """ if s.depth: try: colors.shadow(dx=5, dy=5, blur=10, alpha=0.5*alpha) except: pass s._ctx.nofill() s._ctx.nostroke() if s.fill: s._ctx.fill( s.fill.r, s.fill.g, ...
Visualization of a node s id.
def node_label(s, node, alpha=1.0): """ Visualization of a node's id. """ if s.text: #s._ctx.lineheight(1) s._ctx.font(s.font) s._ctx.fontsize(s.fontsize) s._ctx.nostroke() s._ctx.fill( s.text.r, s.text.g, s.text.b, ...
Visualization of the edges in a network.
def edges(s, edges, alpha=1.0, weighted=False, directed=False): """ Visualization of the edges in a network. """ p = s._ctx.BezierPath() if directed and s.stroke: pd = s._ctx.BezierPath() if weighted and s.fill: pw = [s._ctx.BezierPath() for i in range(11)...
Visualization of a single edge between two nodes.
def edge(s, path, edge, alpha=1.0): """ Visualization of a single edge between two nodes. """ path.moveto(edge.node1.x, edge.node1.y) if edge.node2.style == BACK: path.curveto( edge.node1.x, edge.node2.y, edge.node2.x, edge.node2.y, ...
Visualization of the label accompanying an edge.
def edge_label(s, edge, alpha=1.0): """ Visualization of the label accompanying an edge. """ if s.text and edge.label != "": s._ctx.nostroke() s._ctx.fill( s.text.r, s.text.g, s.text.b, s.text.a * alpha*0.75 ) s._ctx...
Visualization of a shortest path between two nodes.
def path(s, graph, path): """ Visualization of a shortest path between two nodes. """ def end(n): r = n.r * 0.35 s._ctx.oval(n.x-r, n.y-r, r*2, r*2) if path and len(path) > 1 and s.stroke: s._ctx.nofill() s._ctx.stroke( s.stroke.r, s.stroke.g, ...
Creates a new style which inherits from the default style or any other style which name is supplied to the optional template parameter.
def create(self, stylename, **kwargs): """ Creates a new style which inherits from the default style, or any other style which name is supplied to the optional template parameter. """ if stylename == "default": self[stylename] = style(stylename, self._ctx, **kwargs) ...
Returns a copy of all styles and a copy of the styleguide.
def copy(self, graph): """ Returns a copy of all styles and a copy of the styleguide. """ s = styles(graph) s.guide = self.guide.copy(graph) dict.__init__(s, [(v.name, v.copy()) for v in self.values()]) return s
Check the rules for each node in the graph and apply the style.
def apply(self): """ Check the rules for each node in the graph and apply the style. """ sorted = self.order + self.keys() unique = []; [unique.append(x) for x in sorted if x not in unique] for node in self.graph.nodes: for s in unique: if self.has_key...
Returns a copy of the styleguide for the given graph.
def copy(self, graph): """ Returns a copy of the styleguide for the given graph. """ g = styleguide(graph) g.order = self.order dict.__init__(g, [(k, v) for k, v in self.iteritems()]) return g
Decode a JSON document from s ( a str or unicode beginning with a JSON document ) and return a 2 - tuple of the Python representation and the index in s where the document ended.
def raw_decode(self, s, **kw): """ Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a str...
Opens the socket and binds to the given host and port. Uses SO_REUSEADDR to be as robust as possible.
def open_socket(self): """ Opens the socket and binds to the given host and port. Uses SO_REUSEADDR to be as robust as possible. """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) se...
Loads all possible TUIO profiles and returns a dictionary with the profile addresses as keys and an instance of a profile as the value
def load_profiles(self): """ Loads all possible TUIO profiles and returns a dictionary with the profile addresses as keys and an instance of a profile as the value """ _profiles = {} for name, klass in inspect.getmembers(profiles): if inspect.isclass(klass) a...
Tells the connection manager to receive the next 1024 byte of messages to analyze.
def update(self): """ Tells the connection manager to receive the next 1024 byte of messages to analyze. """ try: self.manager.handle(self.socket.recv(1024)) except socket.error: pass
Gets called by the CallbackManager if a new message was received
def callback(self, *incoming): """ Gets called by the CallbackManager if a new message was received """ message = incoming[0] if message: address, command = message[0], message[2] profile = self.get_profile(address) if profile is not None: ...
copytree that works even if folder already exists
def copytree(src, dst, symlinks=False, ignore=None): """ copytree that works even if folder already exists """ # http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth if not os.path.exists(dst): os.makedirs(dst) sh...
Serialize obj to a JSON formatted str.
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """ Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types ...
Returns a Google web query formatted as a GoogleSearch list object.
def search(q, start=0, wait=10, asynchronous=False, cached=False): """ Returns a Google web query formatted as a GoogleSearch list object. """ service = GOOGLE_SEARCH return GoogleSearch(q, start, service, "", wait, asynchronous, cached)