_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q260000 | graph.add_node | validation | 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) and style.__dict__.has_key["name"]:
style = style.name
| python | {
"resource": ""
} |
q260001 | graph.remove_node | validation | 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):
if n in (e.node1, e.node2):
if n in e.node1.links:
| python | {
"resource": ""
} |
q260002 | graph.remove_edge | validation | 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 | python | {
"resource": ""
} |
q260003 | graph.edge | validation | 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 \
| python | {
"resource": ""
} |
q260004 | graph.update | validation | 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 step the graph's bounds are recalculated
# and a number of iterations are processed,
# more and more as the layout progresses.
| python | {
"resource": ""
} |
q260005 | graph.offset | validation | def offset(self, node):
""" Returns the distance from the center to the given node.
"""
| python | {
"resource": ""
} |
q260006 | graph.draw | validation | 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 list of connected nodes.
The path will be colored according to the "highlight" style.
Clicking and dragging events are monitored.
"""
self.update()
# Draw the graph background.
s = self.styles.default
s.graph_background(s)
# Center the graph on the canvas.
_ctx.push()
_ctx.translate(self.x+dx, self.y+dy)
# Indicate betweenness centrality.
if traffic:
if isinstance(traffic, bool):
traffic = 5
for n in self.nodes_by_betweenness()[:traffic]:
| python | {
"resource": ""
} |
q260007 | graph.prune | validation | def prune(self, depth=0):
""" Removes all nodes with less or equal links than depth.
| python | {
"resource": ""
} |
q260008 | graph.betweenness_centrality | validation | def betweenness_centrality(self, normalized=True):
""" Calculates betweenness centrality and returns an node id -> weight dictionary.
Node betweenness weights are updated in the process.
| python | {
"resource": ""
} |
q260009 | graph.eigenvector_centrality | validation | 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.
"""
| python | {
"resource": ""
} |
q260010 | graph.nodes_by_betweenness | validation | def nodes_by_betweenness(self, treshold=0.0):
""" Returns nodes sorted by betweenness centrality.
Nodes with a lot of passing traffic will be | python | {
"resource": ""
} |
q260011 | graph.nodes_by_eigenvalue | validation | def nodes_by_eigenvalue(self, treshold=0.0):
""" Returns nodes sorted by eigenvector centrality.
Nodes with a lot of incoming traffic will | python | {
"resource": ""
} |
q260012 | graph.nodes_by_category | validation | def nodes_by_category(self, category):
""" Returns nodes with the given category attribute.
"""
| python | {
"resource": ""
} |
q260013 | graph.crown | validation | def crown(self, depth=2):
""" Returns a list of leaves, nodes connected to leaves, etc.
| python | {
"resource": ""
} |
q260014 | graph._density | validation | def _density(self):
""" The number of edges in relation to the total number of possible edges.
"""
| python | {
"resource": ""
} |
q260015 | xgraph.load | validation | 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, id2, weight=w)
if len(self) > self.max:
break
# Now get all the other nodes in the cluster.
for w, id2, links in self.get_cluster(id):
for id3 in links:
| python | {
"resource": ""
} |
q260016 | xgraph.click | validation | def click(self, node):
""" Callback from graph.events when a node is clicked.
"""
if not self.has_node(node.id): return | python | {
"resource": ""
} |
q260017 | bezier_arc | validation | 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 with 0 to the right (the positive X axis)
and increase counter-clockwise.
The arc extends from start_angle to start_angle+extent.
I.e. start_angle=0 and extent=180 yields an openside-down semi-circle.
The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)
such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and
(x3, y3) as their respective Bezier control points.
"""
x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2)
if abs(extent) <= 90:
frag_angle = float(extent)
nfrag = 1
else:
nfrag = int(ceil(abs(extent)/90.))
if nfrag == 0:
warnings.warn('Invalid value for extent: %r' % extent)
return []
frag_angle = float(extent) / nfrag
x_cen = (x1+x2)/2.
y_cen = (y1+y2)/2.
rx = (x2-x1)/2.
ry = (y2-y1)/2.
half_angle = radians(frag_angle) / 2
kappa = abs(4. / 3. * (1. - cos(half_angle)) / sin(half_angle))
if frag_angle < 0: | python | {
"resource": ""
} |
q260018 | angle | validation | 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) * | python | {
"resource": ""
} |
q260019 | transform_from_local | validation | def transform_from_local(xp, yp, cphi, sphi, mx, my):
""" Transform from the local frame to absolute space.
"""
x = xp * cphi | python | {
"resource": ""
} |
q260020 | Canvas.set_bot | validation | def set_bot(self, bot):
''' Bot must be set before running '''
| python | {
"resource": ""
} |
q260021 | Canvas.settings | validation | def settings(self, **kwargs):
'''
Pass a load of settings into the canvas
'''
| python | {
"resource": ""
} |
q260022 | Canvas.size_or_default | validation | def size_or_default(self):
'''
If size is not set, otherwise set size to DEFAULT_SIZE
and return it.
| python | {
"resource": ""
} |
q260023 | Canvas.set_size | validation | 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:
| python | {
"resource": ""
} |
q260024 | Canvas.snapshot | validation | 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.
'''
| python | {
"resource": ""
} |
q260025 | Canvas.flush | validation | def flush(self, frame):
'''
Passes the drawqueue to the sink for rendering
| python | {
"resource": ""
} |
q260026 | BezierPathEditor.overlap | validation | 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.
| python | {
"resource": ""
} |
q260027 | BezierPathEditor.reflect | validation | def reflect(self, x0, y0, x, y):
""" Reflects the point x, y through origin x0, y0.
"""
| python | {
"resource": ""
} |
q260028 | BezierPathEditor.angle | validation | def angle(self, x0, y0, x1, y1):
""" Calculates the angle between two points.
"""
| python | {
"resource": ""
} |
q260029 | BezierPathEditor.coordinates | validation | def coordinates(self, x0, y0, distance, angle):
""" Calculates the coordinates of a point from the | python | {
"resource": ""
} |
q260030 | BezierPathEditor.contains_point | validation | 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 means we are somewhere INSIDE the path.
# Only points near the edge (i.e. on the outline stroke)
# should propagate.
if not self.path.contains(x+d, y) \
or not self.path.contains(x, y+d) \
| python | {
"resource": ""
} |
q260031 | BezierPathEditor.insert_point | validation | 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("bezier")
except:
from nodebox.graphics import bezier
# Do a number of checks distributed along the path.
# Keep the one closest to the actual mouse location.
# Ten checks works fast but leads to imprecision in sharp corners
# and curves closely located next to each other.
# I prefer the slower but more stable approach.
n = 100
closest = None
dx0 = float("inf")
dy0 = float("inf")
for i in range(n):
t = float(i)/n
pt = self.path.point(t)
dx = abs(pt.x-x)
dy = abs(pt.y-y)
if dx+dy <= dx0+dy0:
dx0 = dx
dy0 = dy
closest = t
# Next, scan the area around the approximation.
# If the closest point is located at 0.2 on the path,
# we need to scan between 0.1 and 0.3 for a better
# approximation. If 1.5 was the best guess, scan
# 1.40, 1.41 ... 1.59 and so on.
# Each decimal precision takes 20 iterations.
decimals = [3,4]
for d in decimals:
d = 1.0/pow(10,d)
for i in range(20):
t = closest-d + float(i)*d*0.1
if t < 0.0: t = 1.0+t
if t > 1.0: t = t-1.0
pt = self.path.point(t)
| python | {
"resource": ""
} |
q260032 | BezierPathEditor.draw_freehand | validation | 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
self.freehand_move = False
else:
cmd = LINETO
# Add a new LINETO to the path,
# except when starting to draw,
# then a MOVETO is added to the path.
pt = PathElement()
if cmd != MOVETO:
pt.freehand = True # Used when mixed with curve drawing.
else:
pt.freehand = False
pt.cmd = cmd
pt.x = x
pt.y = y
pt.ctrl1 = Point(x,y)
pt.ctrl2 = Point(x,y)
self._points.append(pt)
| python | {
"resource": ""
} |
q260033 | BezierPathEditor.export_svg | validation | 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 "+str(self._points[0].x)+" "+str(self._points[0].y)+" "
for pt in self._points:
if pt.cmd == MOVETO:
d += "M "+str(pt.x)+" "+str(pt.y)+" "
elif pt.cmd == LINETO:
d += "L "+str(pt.x)+" "+str(pt.y)+" "
elif pt.cmd == CURVETO:
d += "C "
d += str(pt.ctrl1.x)+" "+str(pt.ctrl1.y)+" "
d += str(pt.ctrl2.x)+" "+str(pt.ctrl2.y)+" "
d += str(pt.x)+" "+str(pt.y)+" "
c = "rgb("
| python | {
"resource": ""
} |
q260034 | ShoebotWindow.gtk_mouse_button_down | validation | def gtk_mouse_button_down(self, widget, event):
''' Handle right mouse button clicks '''
if self.menu_enabled and event.button == 3:
| python | {
"resource": ""
} |
q260035 | ShoebotWindow.show_variables_window | validation | 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 | python | {
"resource": ""
} |
q260036 | ShoebotWindow.hide_variables_window | validation | def hide_variables_window(self):
"""
Hide the variables window
"""
if self.var_window is not None:
| python | {
"resource": ""
} |
q260037 | ShoebotWindow.trigger_fullscreen_action | validation | def trigger_fullscreen_action(self, fullscreen):
"""
Toggle fullscreen from outside the GUI,
| python | {
"resource": ""
} |
q260038 | ShoebotWindow.do_fullscreen | validation | 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
while Gtk.events_pending():
| python | {
"resource": ""
} |
q260039 | ShoebotWindow.do_unfullscreen | validation | def do_unfullscreen(self, widget):
"""
Widget Action to set Windowed Mode.
"""
| python | {
"resource": ""
} |
q260040 | ShoebotWindow.do_window_close | validation | 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:
| python | {
"resource": ""
} |
q260041 | ShoebotWindow.do_toggle_fullscreen | validation | def do_toggle_fullscreen(self, action):
"""
Widget Action to Toggle fullscreen from the GUI
"""
is_fullscreen | python | {
"resource": ""
} |
q260042 | ShoebotWindow.do_toggle_variables | validation | def do_toggle_variables(self, action):
"""
Widget Action to toggle showing the variables window.
| python | {
"resource": ""
} |
q260043 | ShoebotWindow.main_iteration | validation | 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_variables_window()
| python | {
"resource": ""
} |
q260044 | Bot._mouse_pointer_moved | validation | def _mouse_pointer_moved(self, x, y):
'''GUI callback for mouse moved'''
| python | {
"resource": ""
} |
q260045 | Bot._key_pressed | validation | def _key_pressed(self, key, keycode):
'''GUI callback for key pressed'''
self._namespace['key'] = key
| python | {
"resource": ""
} |
q260046 | Bot._makeInstance | validation | def _makeInstance(self, clazz, args, kwargs):
'''Creates an instance of a class defined in this document.
This method sets the context of | python | {
"resource": ""
} |
q260047 | Bot._makeColorableInstance | validation | 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 = kwargs.get('fill', self._canvas.fillcolor)
| python | {
"resource": ""
} |
q260048 | Bot.show | validation | 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 import Image
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.WIDTH, self.HEIGHT)
| python | {
"resource": ""
} |
q260049 | Bot.ximport | validation | 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 | python | {
"resource": ""
} |
q260050 | Bot.size | validation | 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:
| python | {
"resource": ""
} |
q260051 | Bot.speed | validation | 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:
| python | {
"resource": ""
} |
q260052 | InputDeviceMixin.set_callbacks | validation | def set_callbacks(self, **kwargs):
''' Set callbacks for input events '''
for name in self.SUPPORTED_CALLBACKS:
func | python | {
"resource": ""
} |
q260053 | complement | validation | def complement(clr):
"""
Returns the color and its complement in a list.
"""
clr = color(clr)
colors = | python | {
"resource": ""
} |
q260054 | complementary | validation | 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 contrasting color: much darker or lighter than the original.
c = clr.copy()
if clr.brightness > 0.4:
c.brightness = 0.1 + c.brightness * 0.25
else:
c.brightness = 1.0 - c.brightness * 0.25
colors.append(c)
# A soft supporting color: lighter and less saturated.
c = clr.copy()
c.brightness = 0.3 + c.brightness
c.saturation = 0.1 + c.saturation * 0.3
colors.append(c)
# A contrasting complement: very dark or very light. | python | {
"resource": ""
} |
q260055 | split_complementary | validation | 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
| python | {
"resource": ""
} |
q260056 | left_complement | validation | 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]
colors = complementary(clr)
colors[3].h = left.h
| python | {
"resource": ""
} |
q260057 | right_complement | validation | 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
| python | {
"resource": ""
} |
q260058 | analogous | validation | 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 the darkness/lightness of
| python | {
"resource": ""
} |
q260059 | triad | validation | 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 | python | {
"resource": ""
} |
q260060 | tetrad | validation | 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.brightness += 0.2
else:
| python | {
"resource": ""
} |
q260061 | compound | validation | 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)
c = clr.rotate_ryb(30 * d)
c.brightness = _wrap(clr.brightness, 0.25, 0.6, 0.25)
colors.append(c)
c = clr.rotate_ryb(30 * d)
| python | {
"resource": ""
} |
q260062 | outline | validation | 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 transforms.
"""
# The count of points in a given path/contour.
def _point_count(path, precision):
return max(int(path.length * precision * 0.5), 10)
# The total count of points in the path.
n = sum([_point_count(contour, precision) for contour in path.contours])
# For a continuous gradient,
# we need to calculate a subrange in the list of colors
# for each contour to draw colors from.
contour_i = 0
contour_n = len(path.contours) - 1
if contour_n == 0: continuous = False
i = 0
for contour in path.contours:
if not continuous: i = 0
# The number of points for each contour.
j = _point_count(contour, precision)
first = True
for pt in contour.points(j):
if first:
first = False
| python | {
"resource": ""
} |
q260063 | guess_name | validation | 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"
if clr.is_white: return "white"
if clr.is_black: return "black"
for name in named_colors:
try:
r, g, b = named_colors[name]
except:
| python | {
"resource": ""
} |
q260064 | shader | validation | 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 strength of the light,
angle and spread control the direction of the light.
"""
if angle != None:
radius *= 2
# Get the distance and angle between point and light source.
d = sqrt((dx - x) ** 2 + (dy - y) ** 2)
a = degrees(atan2(dy - y, dx - x)) + 180
# If no angle is defined,
# light is emitted evenly in all directions
# and carries as far as the defined radius
# (e.g. like a radial gradient).
if d <= radius:
d1 = 1.0 * d / radius
else:
d1 = 1.0
if angle is None:
return 1 - d1
# Normalize the light's direction and spread
# between 0 and 360.
angle = 360 - angle % 360
spread = max(0, min(spread, 360))
if spread == 0:
return 0.0
# Objects that fall within the spreaded direction
| python | {
"resource": ""
} |
q260065 | aggregated | validation | 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 harvested from the web
(or handmade).
"""
global _aggregated_name, _aggregated_dict
if _aggregated_name != cache:
_aggregated_name = cache
_aggregated_dict = {}
for path in glob(os.path.join(cache, "*")):
| python | {
"resource": ""
} |
q260066 | morguefile | validation | 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 | python | {
"resource": ""
} |
q260067 | Color.str_to_rgb | validation | 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 (-ish, -ed, -y and -like) are recognised
as well, for example, if you need a random variation of "red"
you can use reddish (or greenish, yellowy, etc.)
"""
| python | {
"resource": ""
} |
q260068 | Color.rotate_ryb | validation | 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 complementary colors.
http://en.wikipedia.org/wiki/RYB_color_model
"""
h = self.h * 360
angle = angle % 360
# Approximation of Itten's RYB color wheel.
# In HSB, colors hues range from 0-360.
# However, on the artistic color wheel these are not evenly distributed.
# The second tuple value contains the actual distribution.
wheel = [
(0, 0), (15, 8),
(30, 17), (45, 26),
(60, 34), (75, 41),
(90, 48), (105, 54),
(120, 60), (135, 81),
(150, 103), (165, 123),
(180, 138), (195, 155),
(210, 171), (225, 187),
(240, 204), (255, 219),
(270, 234), (285, 251),
(300, 267), (315, 282),
(330, 298), (345, 329),
(360, 0)
]
# Given a hue, find out under what angle it is
# located on the artistic color wheel.
for i in _range(len(wheel) - 1):
x0, y0 = wheel[i]
x1, y1 = wheel[i + 1]
if y1 < y0:
y1 += 360
if y0 <= h <= y1:
| python | {
"resource": ""
} |
q260069 | Color.nearest_hue | validation | def nearest_hue(self, primary=False):
""" Returns the name of the nearest named hue.
For example,
if you supply an indigo color (a color between blue and violet),
the return value is "violet". If primary is set to True,
the return value is "purple".
Primary colors leave out the fuzzy lime, teal,
cyan, azure and violet hues.
"""
if self.is_black:
return "black"
elif self.is_white:
return "white"
| python | {
"resource": ""
} |
q260070 | Color.blend | validation | def blend(self, clr, factor=0.5):
"""
Returns a mix of two colors.
"""
r = self.r * (1 - factor) + clr.r * factor
g = self.g * (1 - factor) + clr.g * factor
b = self.b * (1 - factor) + | python | {
"resource": ""
} |
q260071 | Color.swatch | validation | def swatch(self, x, y, w=35, h=35, roundness=0):
"""
Rectangle swatch for this color.
"""
| python | {
"resource": ""
} |
q260072 | ColorList.image_to_rgb | validation | def image_to_rgb(self, path, n=10):
"""
Returns a list of colors based on pixel values in the image.
The Core Image library must be present to determine pixel colors.
F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05
"""
from PIL import Image
img = Image.open(path)
p = img.getdata()
f = lambda p: choice(p)
for i in _range(n):
| python | {
"resource": ""
} |
q260073 | ColorList.context_to_rgb | validation | def context_to_rgb(self, str):
""" Returns the colors that have the given word in their context.
For example, the word "anger" appears
in black, orange and red contexts,
so the list will contain those three colors.
"""
matches = []
for clr in context:
tags = context[clr]
for tag in tags:
| python | {
"resource": ""
} |
q260074 | ColorList._context | validation | def _context(self):
"""
Returns the intersection of each color's context.
Get the nearest named hue of each color,
and finds overlapping tags in each hue's colors.
For example, a list containing yellow, deeppink and olive
yields: femininity, friendship, happiness, joy.
"""
tags1 = None
for clr in self:
overlap = []
if clr.is_black:
name = "black"
elif clr.is_white:
name = "white"
elif clr.is_grey:
name = "grey"
else:
name = clr.nearest_hue(primary=True)
if name == "orange" and clr.brightness < 0.6:
name = | python | {
"resource": ""
} |
q260075 | ColorList.copy | validation | def copy(self):
""" Returns a deep copy of the list.
"""
return ColorList(
[color(clr.r, clr.g, clr.b, clr.a, mode="rgb") for | python | {
"resource": ""
} |
q260076 | ColorList._darkest | validation | def _darkest(self):
"""
Returns the darkest color from the list.
Knowing the contrast between a light and a dark swatch
can help us decide how to display readable typography.
"""
min, n = (1.0, 1.0, 1.0), 3.0
| python | {
"resource": ""
} |
q260077 | ColorList._average | validation | def _average(self):
"""
Returns one average color for the colors in the list.
"""
r, g, b, a = 0, 0, 0, 0
for clr in self:
| python | {
"resource": ""
} |
q260078 | ColorList.sort_by_distance | validation | def sort_by_distance(self, reversed=False):
"""
Returns a list with the smallest distance between two neighboring colors.
The algorithm has a factorial complexity so it may run slow.
"""
if len(self) == 0: return ColorList()
# Find the darkest color in the list.
root = self[0]
for clr in self[1:]:
if clr.brightness < root.brightness:
root = clr
# Remove the darkest color from the stack,
# put it in the sorted list as starting element.
| python | {
"resource": ""
} |
q260079 | ColorList._sorted_copy | validation | def _sorted_copy(self, comparison, reversed=False):
"""
Returns a sorted copy with the colors arranged according to the | python | {
"resource": ""
} |
q260080 | ColorList.cluster_sort | validation | def cluster_sort(self, cmp1="hue", cmp2="brightness", reversed=False, n=12):
"""
Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.
If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).
The resulting list will not contain n even slices:
n is used rather to slice up the cmp1 property of the colors,
e.g. cmp1=brightness and n=3 will cluster colors by brightness >= 0.66, 0.33, 0.0
"""
sorted = self.sort(cmp1)
clusters = ColorList()
d = 1.0
| python | {
"resource": ""
} |
q260081 | ColorList.reverse | validation | def reverse(self):
"""
Returns a reversed copy of the list.
"""
colors | python | {
"resource": ""
} |
q260082 | ColorList.repeat | validation | def repeat(self, n=2, oscillate=False, callback=None):
"""
Returns a list that is a repetition of the given list.
When oscillate is True,
moves from the end back to the beginning,
and then from the beginning to the end, and so on.
"""
colorlist = ColorList()
| python | {
"resource": ""
} |
q260083 | ColorList.swatch | validation | def swatch(self, x, y, w=35, h=35, padding=0, roundness=0):
"""
Rectangle swatches for all the colors in the list.
"""
| python | {
"resource": ""
} |
q260084 | ColorList.swarm | validation | def swarm(self, x, y, r=100):
"""
Fancy random ovals for all the colors in the list.
"""
sc = _ctx.stroke(0, 0, 0, 0)
sw = _ctx.strokewidth(0)
_ctx.push()
_ctx.transform(_ctx.CORNER)
_ctx.translate(x, y)
for i in _range(r * 3):
clr = choice(self).copy()
clr.alpha -= 0.5 * random()
_ctx.fill(clr)
clr = choice(self)
_ctx.stroke(clr)
| python | {
"resource": ""
} |
q260085 | Gradient._interpolate | validation | def _interpolate(self, colors, n=100):
""" Returns intermediary colors for given list of colors.
"""
gradient = []
for i in _range(n):
l = len(colors) - 1
x = int(1.0 * i / n * l)
x = min(x + 0, l)
y = min(x + 1, l)
base = 1.0 * n / l * x
d = (i - base) / (1.0 * n / l)
r = colors[x].r * (1 - d) + colors[y].r * d
| python | {
"resource": ""
} |
q260086 | Gradient._cache | validation | def _cache(self):
"""
Populates the list with a number of gradient colors.
The list has Gradient.steps colors that interpolate between
the fixed base Gradient.colors.
The spread parameter controls the midpoint of the gradient,
you can shift it right and left. A separate gradient is
calculated for each half and then glued together.
"""
n = self.steps
# Only one color in base list.
if len(self._colors) == 1:
ColorList.__init__(self, [self._colors[0] for i in _range(n)])
return
# Expand the base list so we can chop more accurately.
colors = self._interpolate(self._colors, 40)
# Chop into left half and right half.
| python | {
"resource": ""
} |
q260087 | ColorRange.copy | validation | def copy(self, clr=None, d=0.0):
"""
Returns a copy of the range.
Optionally, supply a color to get a range copy
limited to the hue of that color.
"""
cr = ColorRange()
cr.name = self.name
cr.h = deepcopy(self.h)
cr.s = deepcopy(self.s)
cr.b = deepcopy(self.b)
cr.a = | python | {
"resource": ""
} |
q260088 | ColorRange.color | validation | def color(self, clr=None, d=0.035):
"""
Returns a color with random values in the defined h, s b, a ranges.
If a color is given, use that color's hue and alpha,
and generate its saturation and brightness from the shade.
The hue is varied with the given d.
In this way you could have a "warm" color range
that returns all kinds of warm colors.
When a red color is given as parameter it would generate
all kinds of warm red colors.
"""
# Revert to grayscale for black, white and grey hues.
if clr != None and not isinstance(clr, Color):
clr = color(clr)
if clr != None and not self.grayscale:
if clr.is_black: return self.black.color(clr, d)
if clr.is_white: return self.white.color(clr, d)
if clr.is_grey: return choice(
(self.black.color(clr, d), self.white.color(clr, d))
)
h, s, b, a = self.h, self.s, self.b, self.a
| python | {
"resource": ""
} |
q260089 | ColorRange.contains | validation | def contains(self, clr):
"""
Returns True if the given color is part of this color range.
Check whether each h, s, b, a component of the color
falls within the defined range for that component.
If the given color is grayscale,
checks against the definitions for black and white.
"""
if not isinstance(clr, Color):
return False
if not isinstance(clr, _list):
clr = [clr]
for clr in clr:
if clr.is_grey and not self.grayscale:
return (self.black.contains(clr) or \
| python | {
"resource": ""
} |
q260090 | ColorTheme._xml | validation | def _xml(self):
"""
Returns the color information as XML.
The XML has the following structure:
<colors query="">
<color name="" weight="" />
<rgb r="" g="" b="" />
<shade name="" weight="" />
</color>
</colors>
Notice that ranges are stored by name and retrieved in the _load()
method with the shade() command - and are thus expected to be
shades (e.g. intense, warm, ...) unless the shade() command would
return any custom ranges as well. This can be done by appending custom
| python | {
"resource": ""
} |
q260091 | ColorTheme._save | validation | def _save(self):
"""
Saves the color information in the cache as XML.
"""
if not os.path.exists(self.cache):
os.makedirs(self.cache)
| python | {
"resource": ""
} |
q260092 | ColorTheme._load | validation | def _load(self, top=5, blue="blue", archive=None, member=None):
"""
Loads a theme from aggregated web data.
The data must be old-style Prism XML: <color>s consisting of <shade>s.
Colors named "blue" will be overridden with the blue parameter.
archive can be a file like object (e.g. a ZipFile)
and will be used along with 'member' if specified.
"""
if archive is None:
path = os.path.join(self.cache, self.name + ".xml")
xml = open(path).read()
else:
assert member is not None
xml = archive.read(member)
dom = parseString(xml).documentElement
attr = lambda e, a: e.attributes[a].value
for e in dom.getElementsByTagName("color")[:top]:
w = float(attr(e, "weight"))
try:
rgb = e.getElementsByTagName("rgb")[0]
clr = color(
float(attr(rgb, "r")),
float(attr(rgb, "g")),
| python | {
"resource": ""
} |
q260093 | ColorTheme.color | validation | def color(self, d=0.035):
"""
Returns a random color within the theme.
Fetches a random range (the weight is taken into account,
so ranges with a bigger weight have a higher chance of propagating)
and hues it with the associated color.
"""
s | python | {
"resource": ""
} |
q260094 | ColorTheme.colors | validation | def colors(self, n=10, d=0.035):
"""
Returns a number of random colors from the theme.
"""
s = sum([w for clr, rng, w in self.ranges])
colors = colorlist()
for i in _range(n):
r = random()
| python | {
"resource": ""
} |
q260095 | ColorTheme.recombine | validation | def recombine(self, other, d=0.7):
"""
Genetic recombination of two themes using cut and splice technique.
"""
a, b = self, other
d1 = max(0, min(d, 1))
d2 = d1
c = ColorTheme(
name=a.name[:int(len(a.name) * d1)] +
b.name[int(len(b.name) * d2):],
ranges=a.ranges[:int(len(a.ranges) * d1)] +
b.ranges[int(len(b.ranges) * d2):],
top=a.top,
| python | {
"resource": ""
} |
q260096 | ColorTheme.swatch | validation | def swatch(self, x, y, w=35, h=35, padding=4, roundness=0, n=12, d=0.035, grouped=None):
"""
Draws a weighted swatch with approximately n columns and rows.
When the grouped parameter is True, colors are grouped in blocks of the same hue
(also see the _weight_by_hue() method).
"""
if grouped is None: # should be True or False
grouped = self.group_swatches
# If we dont't need to make groups,
# just display an individual column for each weight
# in the (color, range, weight) tuples.
if not grouped:
s = sum([wgt for clr, rng, wgt in self.ranges])
for clr, rng, wgt in self.ranges:
cols = max(1, int(wgt / s * n))
for i in _range(cols):
rng.colors(clr, n=n, d=d).swatch(x, y, w, h, padding=padding, roundness=roundness)
| python | {
"resource": ""
} |
q260097 | TuioProfile.fseq | validation | def fseq(self, client, message):
"""
fseq messages associate a unique frame id with a set | python | {
"resource": ""
} |
q260098 | TuioProfile.objs | validation | def objs(self):
"""
Returns a generator list of tracked objects which are recognized with
this profile and are in the current session.
"""
| python | {
"resource": ""
} |
q260099 | BezierPath._append_element | validation | def _append_element(self, render_func, pe):
'''
Append a render function and the parameters to pass
an equivilent PathElement, or the PathElement itself.
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.