Search is not available for this dataset
text
stringlengths
75
104k
def call_good_cb(self): """ If good_cb returns True then keep it :return: """ with LiveExecution.lock: if self.good_cb and not self.good_cb(): self.good_cb = None
def run_context(self): """ Context in which the user can run the source in a custom manner. If no exceptions occur then the source will move from 'tenuous' to 'known good'. >>> with run_context() as (known_good, source, ns): >>> ... exec source in ns >>> ... n...
def cohesion(self, d=100): """ Boids move towards the flock's centre of mass. The centre of mass is the average position of all boids, not including itself (the "perceived centre"). """ vx = vy = vz = 0 for b in self.boids: ...
def separation(self, r=10): """ Boids keep a small distance from other boids. Ensures that boids don't collide into each other, in a smoothly accelerated motion. """ vx = vy = vz = 0 for b in self.boids: if b != self: ...
def alignment(self, d=5): """ Boids match velocity with other boids. """ vx = vy = vz = 0 for b in self.boids: if b != self: vx, vy, vz = vx+b.vx, vy+b.vy, vz+b.vz n = len(self.boids)-1 vx, vy, vz = vx/n, vy/n, vz/n ...
def limit(self, max=30): """ The speed limit for a boid. Boids can momentarily go very fast, something that is impossible for real animals. """ if abs(self.vx) > max: self.vx = self.vx/abs(self.vx)*max if abs(self.vy) > max...
def _angle(self): """ Returns the angle towards which the boid is steering. """ from math import atan, pi, degrees a = degrees(atan(self.vy/self.vx)) + 360 if self.vx < 0: a += 180 return a
def goal(self, x, y, z, d=50.0): """ Tendency towards a particular place. """ return (x-self.x)/d, (y-self.y)/d, (z-self.z)/d
def constrain(self): """ Cages the flock inside the x, y, w, h area. The actual cage is a bit larger, so boids don't seem to bounce of invisible walls (they are rather "encouraged" to stay in the area). If a boid touches the ground level, it may...
def update(self, shuffled=True, cohesion=100, separation=10, alignment=5, goal=20, limit=30): """ Calculates the next motion frame for the flock. """ # Shuffling the list of boids ens...
def iterscan(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is None...
def copy(self, graph): """ Returns a copy of the layout for the given graph. """ l = self.__class__(graph, self.n) l.i = 0 return l
def create(iterations=1000, distance=1.0, layout=LAYOUT_SPRING, depth=True): """ Returns a new graph with predefined styling. """ #global _ctx _ctx.colormode(_ctx.RGB) g = graph(iterations, distance, layout) # Styles for different types of nodes. s = style.style ...
def can_reach(self, node, traversable=lambda node, edge: True): """ Returns True if given node can be reached over traversable edges. To enforce edge direction, use a node==edge.node1 traversable. """ if isinstance(node, str): node = self.graph[node] ...
def copy(self, empty=False): """ Create a copy of the graph (by default with nodes and edges). """ g = graph(self.layout.n, self.distance, self.layout.type) g.layout = self.layout.copy(g) g.styles = self.styles.copy(g) g.events = self.events.copy(g) ...
def clear(self): """ Remove nodes and edges and reset the layout. """ dict.clear(self) self.nodes = [] self.edges = [] self.root = None self.layout.i = 0 self.alpha = 0
def add_node(self, id, radius=8, style=style.DEFAULT, category="", label=None, root=False, properties={}): """ Add node from id and return the node object. """ if self.has_key(id): return self[id] if not isinstance(style, str) ...
def add_edge(self, id1, id2, weight=0.0, length=1.0, label="", properties={}): """ Add weighted (0.0-1.0) edge between nodes, creating them if necessary. The weight represents the importance of the connection (not the cost). """ if id1 == id2: return None ...
def remove_node(self, id): """ Remove node with given id. """ if self.has_key(id): n = self[id] self.nodes.remove(n) del self[id] # Remove all edges involving id and all links to it. for e in list(self.edges): ...
def remove_edge(self, id1, id2): """ Remove edges between nodes with given id's. """ for e in list(self.edges): if id1 in (e.node1.id, e.node2.id) and \ id2 in (e.node1.id, e.node2.id): e.node1.links.remove(e.node2) e.n...
def edge(self, id1, id2): """ Returns the edge between the nodes with given id1 and id2. """ if id1 in self and \ id2 in self and \ self[id2] in self[id1].links: return self[id1].links.edge(id2) return None
def update(self, iterations=10): """ Iterates the graph layout and updates node positions. """ # The graph fades in when initially constructed. self.alpha += 0.05 self.alpha = min(self.alpha, 1.0) # Iterates over the graph's layout. # Each s...
def offset(self, node): """ Returns the distance from the center to the given node. """ x = self.x + node.x - _ctx.WIDTH/2 y = self.y + node.y - _ctx.HEIGHT/2 return x, y
def draw(self, dx=0, dy=0, weighted=False, directed=False, highlight=[], traffic=None): """ Layout the graph incrementally. The graph is drawn at the center of the canvas. The weighted and directed parameters visualize edge weight and direction. The highlight specifies ...
def prune(self, depth=0): """ Removes all nodes with less or equal links than depth. """ for n in list(self.nodes): if len(n.links) <= depth: self.remove_node(n.id)
def betweenness_centrality(self, normalized=True): """ Calculates betweenness centrality and returns an node id -> weight dictionary. Node betweenness weights are updated in the process. """ bc = proximity.brandes_betweenness_centrality(self, normalized) for id, w in bc.iteritems...
def eigenvector_centrality(self, normalized=True, reversed=True, rating={}, start=None, iterations=100, tolerance=0.0001): """ Calculates eigenvector centrality and returns an node id -> weight dictionary. Node eigenvalue weights are updated in the process. """ ...
def nodes_by_betweenness(self, treshold=0.0): """ Returns nodes sorted by betweenness centrality. Nodes with a lot of passing traffic will be at the front of the list. """ nodes = [(n.betweenness, n) for n in self.nodes if n.betweenness > treshold] nodes.sort(); nodes.reverse() ...
def nodes_by_eigenvalue(self, treshold=0.0): """ Returns nodes sorted by eigenvector centrality. Nodes with a lot of incoming traffic will be at the front of the list """ nodes = [(n.eigenvalue, n) for n in self.nodes if n.eigenvalue > treshold] nodes.sort(); nodes.reverse() ...
def nodes_by_category(self, category): """ Returns nodes with the given category attribute. """ return [n for n in self.nodes if n.category == category]
def crown(self, depth=2): """ Returns a list of leaves, nodes connected to leaves, etc. """ nodes = [] for node in self.leaves: nodes += node.flatten(depth-1) return cluster.unique(nodes)
def _density(self): """ The number of edges in relation to the total number of possible edges. """ return 2.0*len(self.edges) / (len(self.nodes) * (len(self.nodes)-1))
def load(self, id): """ Rebuilds the graph around the given node id. """ self.clear() # Root node. self.add_node(id, root=True) # Directly connected nodes have priority. for w, id2 in self.get_links(id): self.add_edge(id, id...
def click(self, node): """ Callback from graph.events when a node is clicked. """ if not self.has_node(node.id): return if node == self.root: return self._dx, self._dy = self.offset(node) self.previous = self.root.id self.load(node.id)
def bezier_arc(x1, y1, x2, y2, start_angle=0, extent=90): """ Compute a cubic Bezier approximation of an elliptical arc. (x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The coordinate system has coordinates that increase to the right and down. Angles, measured in degress, start w...
def angle(x1, y1, x2, y2): """ The angle in degrees between two vectors. """ sign = 1.0 usign = (x1*y2 - y1*x2) if usign < 0: sign = -1.0 num = x1*x2 + y1*y2 den = hypot(x1,y1) * hypot(x2,y2) ratio = min(max(num/den, -1.0), 1.0) return sign * degrees(acos(ratio))
def transform_from_local(xp, yp, cphi, sphi, mx, my): """ Transform from the local frame to absolute space. """ x = xp * cphi - yp * sphi + mx y = xp * sphi + yp * cphi + my return (x,y)
def elliptical_arc_to(x1, y1, rx, ry, phi, large_arc_flag, sweep_flag, x2, y2): """ An elliptical arc approximated with Bezier curves or a line segment. Algorithm taken from the SVG 1.1 Implementation Notes: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes """ # Basic normalizati...
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...
def set_bot(self, bot): ''' Bot must be set before running ''' self.bot = bot self.sink.set_bot(bot)
def settings(self, **kwargs): ''' Pass a load of settings into the canvas ''' for k, v in kwargs.items(): setattr(self, k, v)
def size_or_default(self): ''' If size is not set, otherwise set size to DEFAULT_SIZE and return it. This means, only the first call to size() is valid. ''' if not self.size: self.size = self.DEFAULT_SIZE return self.size
def set_size(self, size): ''' Size is only set the first time it is called Size that is set is returned ''' if self.size is None: self.size = size return size else: return self.size
def snapshot(self, target, defer=True, file_number=None): ''' Ask the drawqueue to output to target. target can be anything supported by the combination of canvas implementation and drawqueue implmentation. If target is not supported then an exception is thrown. ''' ...
def flush(self, frame): ''' Passes the drawqueue to the sink for rendering ''' self.sink.render(self.size_or_default(), frame, self._drawqueue) self.reset_drawqueue()
def overlap(self, x1, y1, x2, y2, r=5): """ Returns True when point 1 and point 2 overlap. There is an r treshold in which point 1 and point 2 are considered to overlap. """ if abs(x2-x1) < r and abs(y2-y1) < r: return True ...
def reflect(self, x0, y0, x, y): """ Reflects the point x, y through origin x0, y0. """ rx = x0 - (x-x0) ry = y0 - (y-y0) return rx, ry
def angle(self, x0, y0, x1, y1): """ Calculates the angle between two points. """ a = degrees( atan((y1-y0) / (x1-x0+0.00001)) ) + 360 if x1-x0 < 0: a += 180 return a
def coordinates(self, x0, y0, distance, angle): """ Calculates the coordinates of a point from the origin. """ x = x0 + cos(radians(angle)) * distance y = y0 + sin(radians(angle)) * distance return Point(x, y)
def contains_point(self, x, y, d=2): """ Returns true when x, y is on the path stroke outline. """ if self.path != None and len(self.path) > 1 \ and self.path.contains(x, y): # If all points around the mouse are also part of the path, # this mean...
def insert_point(self, x, y): """ Inserts a point on the path at the mouse location. We first need to check if the mouse location is on the path. Inserting point is time intensive and experimental. """ try: bezier = _ctx.ximport("b...
def update(self): """ Update runs each frame to check for mouse interaction. Alters the path by allowing the user to add new points, drag point handles and move their location. Updates are automatically stored as SVG in the given filename. """ ...
def draw(self): """ Draws the editable path and interface elements. """ # Enable interaction. self.update() x, y = mouse() # Snap to grid when enabled. # The grid is enabled with the TAB key. if self.show_grid: ...
def draw_freehand(self): """ Freehand sketching. """ if _ctx._ns["mousedown"]: x, y = mouse() if self.show_grid: x, y = self.grid.snap(x, y) if self.freehand_move == True: cmd = MOVETO...
def export_svg(self): """ Exports the path as SVG. Uses the filename given when creating this object. The file is automatically updated to reflect changes to the path. """ d = "" if len(self._points) > 0: d += "M "+s...
def download(self, size=SIZE_XLARGE, thumbnail=False, wait=60, asynchronous=False): """ Downloads this image to cache. Calling the download() method instantiates an asynchronous URLAccumulator that will fetch the image's URL from Flickr. A second process then downloads ...
def gtk_mouse_button_down(self, widget, event): ''' Handle right mouse button clicks ''' if self.menu_enabled and event.button == 3: menu = self.uimanager.get_widget('/Save as') menu.popup(None, None, None, None, event.button, event.time) else: super(ShoebotWi...
def show_variables_window(self): """ Show the variables window. """ if self.var_window is None and self.bot._vars: self.var_window = VarWindow(self, self.bot, '%s variables' % (self.title or 'Shoebot')) self.var_window.window.connect("destroy", self.var_window_clo...
def hide_variables_window(self): """ Hide the variables window """ if self.var_window is not None: self.var_window.window.destroy() self.var_window = None
def var_window_closed(self, widget): """ Called if user clicked close button on var window :param widget: :return: """ # TODO - Clean up the menu handling stuff its a bit spagetti right now self.action_group.get_action('vars').set_active(False) self.show_v...
def schedule_snapshot(self, format): """ Tell the canvas to perform a snapshot when it's finished rendering :param format: :return: """ bot = self.bot canvas = self.bot.canvas script = bot._namespace['__file__'] if script: filename = os...
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def do_fullscreen(self, widget): """ Widget Action to Make the window fullscreen and update the bot. """ self.fullscreen() self.is_fullscreen = True # next lines seem to be needed for window switching really to # fullscreen mode before reading it's size values ...
def do_unfullscreen(self, widget): """ Widget Action to set Windowed Mode. """ self.unfullscreen() self.is_fullscreen = False self.bot._screen_ratio = None
def do_window_close(self, widget, data=None): """ Widget Action to Close the window, triggering the quit event. """ publish_event(QUIT_EVENT) if self.has_server: self.sock.close() self.hide_variables_window() self.destroy() self.window_open ...
def do_toggle_fullscreen(self, action): """ Widget Action to Toggle fullscreen from the GUI """ is_fullscreen = action.get_active() if is_fullscreen: self.fullscreen() else: self.unfullscreen()
def do_toggle_play(self, action): """ Widget Action to toggle play / pause. """ # TODO - move this into bot controller # along with stuff in socketserver and shell if self.pause_speed is None and not action.get_active(): self.pause_speed = self.bot._speed ...
def do_toggle_variables(self, action): """ Widget Action to toggle showing the variables window. """ self.show_vars = action.get_active() if self.show_vars: self.show_variables_window() else: self.hide_variables_window()
def main_iteration(self): """ Called from main loop, if your sink needs to handle GUI events do it here. Check any GUI flags then call Gtk.main_iteration to update things. """ if self.show_vars: self.show_variables_window() else: self.hide...
def _set_initial_defaults(self): '''Set the default values. Called at __init__ and at the end of run(), do that new draw loop iterations don't take up values left over by the previous one.''' DEFAULT_WIDTH, DEFAULT_HEIGHT = self._canvas.DEFAULT_SIZE self.WIDTH = self._namespace.g...
def _mouse_pointer_moved(self, x, y): '''GUI callback for mouse moved''' self._namespace['MOUSEX'] = x self._namespace['MOUSEY'] = y
def _key_pressed(self, key, keycode): '''GUI callback for key pressed''' self._namespace['key'] = key self._namespace['keycode'] = keycode self._namespace['keydown'] = True
def _makeInstance(self, clazz, args, kwargs): '''Creates an instance of a class defined in this document. This method sets the context of the object to the current context.''' inst = clazz(self, *args, **kwargs) return inst
def _makeColorableInstance(self, clazz, args, kwargs): """ Create an object, if fill, stroke or strokewidth is not specified, get them from the _canvas :param clazz: :param args: :param kwargs: :return: """ kwargs = dict(kwargs) fill = kw...
def color(self, *args): ''' :param args: color in a supported format. :return: Color object containing the color. ''' return self.Color(mode=self.color_mode, color_range=self.color_range, *args)
def grid(self, cols, rows, colSize=1, rowSize=1, shuffled=False): """Returns an iterator that contains coordinate tuples. The grid can be used to quickly create grid-like structures. A common way to use them is: for x, y in grid(10,10,12,12): rect(x,y, 10,10) ...
def snapshot(self, target=None, defer=None, autonumber=False): '''Save the contents of current surface into a file or cairo surface/context :param filename: Can be a filename or a Cairo surface. :param defer: If true, buffering/threading may be employed however output will not be immediate. ...
def show(self, format='png', as_data=False): '''Returns an Image object of the current surface. Used for displaying output in Jupyter notebooks. Adapted from the cairo-jupyter project.''' from io import BytesIO b = BytesIO() if format == 'png': from IPython.display...
def ximport(self, libName): ''' Import Nodebox libraries. The libraries get _ctx, which provides them with the nodebox API. :param libName: Library name to import ''' # from Nodebox lib = __import__(libName) self._namespace[libName] = lib ...
def size(self, w=None, h=None): '''Set the canvas size Only the first call will actually be effective. :param w: Width :param h: height ''' if not w: w = self._canvas.width if not h: h = self._canvas.height if not w and not h: ...
def speed(self, framerate=None): '''Set animation framerate. :param framerate: Frames per second to run bot. :return: Current framerate of animation. ''' if framerate is not None: self._speed = framerate self._dynamic = True else: retu...
def set_callbacks(self, **kwargs): ''' Set callbacks for input events ''' for name in self.SUPPORTED_CALLBACKS: func = kwargs.get(name, getattr(self, name)) setattr(self, name, func)
def complement(clr): """ Returns the color and its complement in a list. """ clr = color(clr) colors = colorlist(clr) colors.append(clr.complement) return colors
def complementary(clr): """ Returns a list of complementary colors. The complement is the color 180 degrees across the artistic RYB color wheel. The list contains darker and softer contrasting and complementing colors. """ clr = color(clr) colors = colorlist(clr) # A contrastin...
def split_complementary(clr): """ Returns a list with the split complement of the color. The split complement are the two colors to the left and right of the color's complement. """ clr = color(clr) colors = colorlist(clr) clr = clr.complement colors.append(clr.rotate_ryb(-30).light...
def left_complement(clr): """ Returns the left half of the split complement. A list is returned with the same darker and softer colors as in the complementary list, but using the hue of the left split complement instead of the complement itself. """ left = split_complementary(clr)[1] co...
def right_complement(clr): """ Returns the right half of the split complement. """ right = split_complementary(clr)[2] colors = complementary(clr) colors[3].h = right.h colors[4].h = right.h colors[5].h = right.h colors = colorlist( colors[0], colors[2], colors[1], colors[5]...
def analogous(clr, angle=10, contrast=0.25): """ Returns colors that are next to each other on the wheel. These yield natural color schemes (like shades of water or sky). The angle determines how far the colors are apart, making it bigger will introduce more variation. The contrast determines t...
def monochrome(clr): """ Returns colors in the same hue with varying brightness/saturation. """ def _wrap(x, min, threshold, plus): if x - min < threshold: return x + plus else: return x - min colors = colorlist(clr) c = clr.copy() c.brightness = _wr...
def triad(clr, angle=120): """ Returns a triad of colors. The triad is made up of this color and two other colors that together make up an equilateral triangle on the artistic color wheel. """ clr = color(clr) colors = colorlist(clr) colors.append(clr.rotate_ryb(angle).lighten(0.1))...
def tetrad(clr, angle=90): """ Returns a tetrad of colors. The tetrad is made up of this color and three other colors that together make up a cross on the artistic color wheel. """ clr = color(clr) colors = colorlist(clr) c = clr.rotate_ryb(angle) if clr.brightness < 0.5: c...
def compound(clr, flip=False): """ Roughly the complement and some far analogs. """ def _wrap(x, min, threshold, plus): if x - min < threshold: return x + plus else: return x - min d = 1 if flip: d = -1 clr = color(clr) colors = colorlist(clr) ...
def outline(path, colors, precision=0.4, continuous=True): """ Outlines each contour in a path with the colors in the list. Each contour starts with the first color in the list, and ends with the last color in the list. Because each line segment is drawn separately, works only with corner-mode...
def guess_name(clr): """ Guesses the shade and hue name of a color. If the given color is named in the named_colors list, return that name. Otherwise guess its nearest hue and shade range. """ clr = Color(clr) if clr.is_transparent: return "transparent" if clr.is_black: return "black" ...
def shader(x, y, dx, dy, radius=300, angle=0, spread=90): """ Returns a 0.0 - 1.0 brightness adjusted to a light source. The light source is positioned at dx, dy. The returned float is calculated for x, y position (e.g. an oval at x, y should have this brightness). The radius influences the st...
def aggregated(cache=DEFAULT_CACHE): """ A dictionary of all aggregated words. They keys in the dictionary correspond to subfolders in the aggregated cache. Each key has a list of words. Each of these words is the name of an XML-file in the subfolder. The XML-file contains color information harvest...
def search_engine(query, top=5, service="google", license=None, cache=os.path.join(DEFAULT_CACHE, "google")): """ Return a color aggregate from colors and ranges parsed from the web. T. De Smedt, http://nodebox.net/code/index.php/Prism """ # Check if we have cached information firs...
def morguefile(query, n=10, top=10): """ Returns a list of colors drawn from a morgueFile image. With the Web library installed, downloads a thumbnail from morgueFile and retrieves pixel colors. """ from web import morguefile images = morguefile.search(query)[:top] path = choice(images...
def str_to_rgb(self, str): """ Returns RGB values based on a descriptive string. If the given str is a named color, return its RGB values. Otherwise, return a random named color that has str in its name, or a random named color which name appears in str. Specific suffixes (-is...
def rotate_ryb(self, angle=180): """ Returns a color rotated on the artistic RYB color wheel. An artistic color wheel has slightly different opposites (e.g. purple-yellow instead of purple-lime). It is mathematically incorrect but generally assumed to provide better complementa...