Search is not available for this dataset
text stringlengths 75 104k |
|---|
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 lea... |
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) + clr.b * factor
a = self.a * (1 - factor) + clr.a * factor
return Color(... |
def distance(self, clr):
"""
Returns the Euclidean distance between two colors (0.0-1.0).
Consider colors arranged on the color wheel:
- hue is the angle of a color along the center
- saturation is the distance of a color from the center
- brightness is the elevation of ... |
def swatch(self, x, y, w=35, h=35, roundness=0):
"""
Rectangle swatch for this color.
"""
_ctx.fill(self)
_ctx.rect(x, y, w, h, roundness) |
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
... |
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:
... |
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.
... |
def copy(self):
""" Returns a deep copy of the list.
"""
return ColorList(
[color(clr.r, clr.g, clr.b, clr.a, mode="rgb") for clr in self],
name=self.name,
tags=self.tags
) |
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
for clr in self:
if clr.r + clr.g + clr.b... |
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:
r += clr.r
g += clr.g
b += clr.b
a += clr.alpha
r /= len(self)
g /= len(self)
b /= l... |
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.
... |
def _sorted_copy(self, comparison, reversed=False):
"""
Returns a sorted copy with the colors arranged according to the given comparison.
"""
sorted = self.copy()
_list.sort(sorted, comparison)
if reversed:
_list.reverse(sorted)
return sorted |
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 s... |
def reverse(self):
"""
Returns a reversed copy of the list.
"""
colors = ColorList.copy(self)
_list.reverse(colors)
return colors |
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()
... |
def swatch(self, x, y, w=35, h=35, padding=0, roundness=0):
"""
Rectangle swatches for all the colors in the list.
"""
for clr in self:
clr.swatch(x, y, w, h, roundness)
y += h + padding |
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 = ... |
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.... |
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... |
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)
c... |
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 yo... |
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 an... |
def _weight_by_hue(self):
"""
Returns a list of (hue, ranges, total weight, normalized total weight)-tuples.
ColorTheme is made up out of (color, range, weight) tuples.
For consistency with XML-output in the old Prism format
(i.e. <color>s made up of <shade>s) we need a group
... |
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>
Not... |
def _save(self):
"""
Saves the color information in the cache as XML.
"""
if not os.path.exists(self.cache):
os.makedirs(self.cache)
path = os.path.join(self.cache, self.name + ".xml")
f = open(path, "w")
f.write(self.xml)
f.close() |
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 (... |
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 = sum([w for clr, rng... |
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()
for clr, rng, weight in self.ranges:
if wei... |
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.na... |
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).
""... |
def fseq(self, client, message):
"""
fseq messages associate a unique frame id with a set of set
and alive messages
"""
client.last_frame = client.current_frame
client.current_frame = message[3] |
def objs(self):
"""
Returns a generator list of tracked objects which are recognized with
this profile and are in the current session.
"""
for obj in self.objects.itervalues():
if obj.sessionid in self.sessions:
yield obj |
def _append_element(self, render_func, pe):
'''
Append a render function and the parameters to pass
an equivilent PathElement, or the PathElement itself.
'''
self._render_funcs.append(render_func)
self._elements.append(pe) |
def _get_bounds(self):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._bounds:
return self._bounds
record_surface = cairo.RecordingSurface(cairo.CONTE... |
def contains(self, x, y):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._bounds:
return self._bounds
record_surface = cairo.RecordingSurface(cairo.CO... |
def _get_center(self):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._center:
return self._center
# get the center point
(x1, y1, x2, y2) = s... |
def _render_closure(self):
'''Use a closure so that draw attributes can be saved'''
fillcolor = self.fill
strokecolor = self.stroke
strokewidth = self.strokewidth
def _render(cairo_ctx):
'''
At the moment this is based on cairo.
TODO: Need to... |
def _get_contours(self):
"""
Returns a list of contours in the path, as BezierPath objects.
A contour is a sequence of lines and curves separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours: the inner circle and the outer circle.
"""
# O... |
def _locate(self, t, segments=None):
""" Locates t on a specific segment in the path.
Returns (index, t, PathElement)
A path is a combination of lines and curves (segments).
The returned index indicates the start of the segment that contains point t.
The returned ... |
def point(self, t, segments=None):
"""
Returns the PathElement at time t (0.0-1.0) on the path.
Returns coordinates for point at t on the path.
Gets the length of the path, based on the length of each curve and line in the path.
Determines in what segment t falls... |
def points(self, amount=100, start=0.0, end=1.0, segments=None):
""" Returns an iterator with a list of calculated points for the path.
To omit the last point on closed paths: end=1-1.0/amount
"""
# Originally from nodebox-gl
if len(self._elements) == 0:
raise Pat... |
def _linepoint(self, t, x0, y0, x1, y1):
""" Returns coordinates for point at t on the line.
Calculates the coordinates of x and y for a point at t on a straight line.
The t parameter is a number between 0.0 and 1.0,
x0 and y0 define the starting point of the line,
... |
def _linelength(self, x0, y0, x1, y1):
""" Returns the length of the line.
"""
# Originally from nodebox-gl
a = pow(abs(x0 - x1), 2)
b = pow(abs(y0 - y1), 2)
return sqrt(a + b) |
def _curvepoint(self, t, x0, y0, x1, y1, x2, y2, x3, y3, handles=False):
""" Returns coordinates for point at t on the spline.
Calculates the coordinates of x and y for a point at t on the cubic bezier spline,
and its control points, based on the de Casteljau interpolation algorithm.
... |
def _curvelength(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
""" Returns the length of the spline.
Integrates the estimated length of the cubic bezier spline defined by x0, y0, ... x3, y3,
by adding the lengths of lineair lines between points at t.
The number of points is de... |
def _segment_lengths(self, relative=False, n=20):
""" Returns a list with the lengths of each segment in the path.
"""
# From nodebox_gl
lengths = []
first = True
for el in self._get_elements():
if first is True:
close_x, close_y = el.x, el.y
... |
def _get_length(self, segmented=False, precision=10):
""" Returns the length of the path.
Calculates the length of each spline in the path, using n as a number of points to measure.
When segmented is True, returns a list containing the individual length of each spline
as valu... |
def _get_elements(self):
'''
Yields all elements as PathElements
'''
for index, el in enumerate(self._elements):
if isinstance(el, tuple):
el = PathElement(*el)
self._elements[index] = el
yield el |
def depth_first_search(root, visit=lambda node: False, traversable=lambda node, edge: True):
""" Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs... |
def adjacency(graph, directed=False, reversed=False, stochastic=False, heuristic=None):
""" An edge weight map indexed by node id's.
A dictionary indexed by node id1's in which each value is a
dictionary of connected node id2's linking to the edge weight.
If directed, edges go from id1 to id2,... |
def brandes_betweenness_centrality(graph, normalized=True):
""" Betweenness centrality for nodes in the graph.
Betweenness centrality is a measure of the number of shortests paths that pass through a node.
Nodes in high-density areas will get a good score.
The algorithm is Brandes' betweennes... |
def eigenvector_centrality(graph, normalized=True, reversed=True, rating={},
start=None, iterations=100, tolerance=0.0001):
""" Eigenvector centrality for nodes in the graph (like Google's PageRank).
Eigenvector centrality is a measure of the importance of a node in a directed n... |
def examples_menu(root_dir=None, depth=0):
"""
:return: xml for menu, [(bot_action, label), ...], [(menu_action, label), ...]
"""
# pre 3.12 menus
examples_dir = ide_utils.get_example_dir()
if not examples_dir:
return "", [], []
root_dir = root_dir or examples_dir
file_tmpl = '... |
def mk_examples_menu(text, root_dir=None, depth=0):
"""
:return: base_item, rel_paths
"""
# 3.12+ menus
examples_dir = ide_utils.get_example_dir()
if not examples_dir:
return None, []
root_dir = root_dir or examples_dir
file_actions = []
menu = Gio.Menu.new()
b... |
def get_child_by_name(parent, name):
"""
Iterate through a gtk container, `parent`,
and return the widget with the name `name`.
"""
# http://stackoverflow.com/questions/2072976/access-to-widget-in-gtk
def iterate_children(widget, name):
if widget.get_name() == name:
return wi... |
def venv_has_script(script):
"""
:param script: script to look for in bin folder
"""
def f(venv):
path=os.path.join(venv, 'bin', script)
if os.path.isfile(path):
return True
return f |
def is_venv(directory, executable='python'):
"""
:param directory: base directory of python environment
"""
path=os.path.join(directory, 'bin', executable)
return os.path.isfile(path) |
def vw_envs(filter=None):
"""
:return: python environments in ~/.virtualenvs
:param filter: if this returns False the venv will be ignored
>>> vw_envs(filter=venv_has_script('pip'))
"""
vw_root=os.path.abspath(os.path.expanduser(os.path.expandvars('~/.virtualenvs')))
venvs=[]
for direc... |
def sbot_executable():
"""
Find shoebot executable
"""
gsettings=load_gsettings()
venv = gsettings.get_string('current-virtualenv')
if venv == 'Default':
sbot = which('sbot')
elif venv == 'System':
# find system python
env_venv = os.environ.get('VIRTUAL_ENV')
... |
def _description(self):
""" Returns the meta description in the page.
"""
meta = self.find("meta", {"name":"description"})
if isinstance(meta, dict) and \
meta.has_key("content"):
return meta["content"]
else:
return u"" |
def _keywords(self):
""" Returns the meta keywords in the page.
"""
meta = self.find("meta", {"name":"keywords"})
if isinstance(meta, dict) and \
meta.has_key("content"):
keywords = [k.strip() for k in meta["content"].split(",")]
else:
... |
def links(self, external=True):
""" Retrieves links in the page.
Returns a list of URL's.
By default, only external URL's are returned.
External URL's starts with http:// and point to another
domain than the domain the page is on.
"""
... |
def sorted(list, cmp=None, reversed=False):
""" Returns a sorted copy of the list.
"""
list = [x for x in list]
list.sort(cmp)
if reversed: list.reverse()
return list |
def unique(list):
""" Returns a copy of the list without duplicates.
"""
unique = []; [unique.append(x) for x in list if x not in unique]
return unique |
def flatten(node, distance=1):
""" Recursively lists the node and its links.
Distance of 0 will return the given [node].
Distance of 1 will return a list of the node and all its links.
Distance of 2 will also include the linked nodes' links, etc.
"""
# When you pass a graph i... |
def subgraph(graph, id, distance=1):
""" Creates the subgraph of the flattened node with given id (or list of id's).
Finds all the edges between the nodes that make up the subgraph.
"""
g = graph.copy(empty=True)
if isinstance(id, (FunctionType, LambdaType)):
# id can also be ... |
def clique(graph, id):
""" Returns the largest possible clique for the node with given id.
"""
clique = [id]
for n in graph.nodes:
friend = True
for id in clique:
if n.id == id or graph.edge(n.id, id) == None:
friend = False
break
... |
def cliques(graph, threshold=3):
""" Returns all the cliques in the graph of at least the given size.
"""
cliques = []
for n in graph.nodes:
c = clique(graph, n.id)
if len(c) >= threshold:
c.sort()
if c not in cliques:
cliques.append(c)
... |
def partition(graph):
""" Splits unconnected subgraphs.
For each node in the graph, make a list of its id and all directly connected id's.
If one of the nodes in this list intersects with a subgraph,
they are all part of that subgraph.
Otherwise, this list is part of a new subgraph.
Re... |
def render(self, size, frame, drawqueue):
'''
Calls implmentation to get a render context,
passes it to the drawqueues render function
then calls self.rendering_finished
'''
r_context = self.create_rcontext(size, frame)
drawqueue.render(r_context)
self.ren... |
def batch(vars, oldvars, ns):
"""
Context manager to only update listeners
at the end, in the meantime it doesn't
matter what intermediate state the vars
are in (they can be added and removed)
>>> with VarListener.batch()
... pass
"""
snapshot... |
def hexDump(bytes):
"""Useful utility; prints the string in hexadecimal"""
for i in range(len(bytes)):
sys.stdout.write("%2x " % (ord(bytes[i])))
if (i+1) % 8 == 0:
print repr(bytes[i-7:i+1])
if(len(bytes) % 8 != 0):
print string.rjust("", 11), repr(bytes[i-len(bytes)%8:... |
def readLong(data):
"""Tries to interpret the next 8 bytes of the data
as a 64-bit signed integer."""
high, low = struct.unpack(">ll", data[0:8])
big = (long(high) << 32) + low
rest = data[8:]
return (big, rest) |
def OSCBlob(next):
"""Convert a string into an OSC Blob,
returning a (typetag, data) tuple."""
if type(next) == type(""):
length = len(next)
padded = math.ceil((len(next)) / 4.0) * 4
binary = struct.pack(">i%ds" % (padded), length, next)
tag = 'b'
else:
tag ... |
def OSCArgument(next):
"""Convert some Python types to their
OSC binary representations, returning a
(typetag, data) tuple."""
if type(next) == type(""):
OSCstringLength = math.ceil((len(next)+1) / 4.0) * 4
binary = struct.pack(">%ds" % (OSCstringLength), next)
tag = "s"
el... |
def parseArgs(args):
"""Given a list of strings, produces a list
where those strings have been parsed (where
possible) as floats or integers."""
parsed = []
for arg in args:
print arg
arg = arg.strip()
interpretation = None
try:
interpretation = float(arg)... |
def decodeOSC(data):
"""Converts a typetagged OSC message to a Python list."""
table = {"i":readInt, "f":readFloat, "s":readString, "b":readBlob}
decoded = []
address, rest = readString(data)
typetags = ""
if address == "#bundle":
time, rest = readLong(rest)
# decoded.append(addr... |
def append(self, argument, typehint = None):
"""Appends data to the message,
updating the typetags based on
the argument's type.
If the argument is a blob (counted string)
pass in 'b' as typehint."""
if typehint == 'b':
binary = OSCBlob(argument)
else... |
def getBinary(self):
"""Returns the binary message (so far) with typetags."""
address = OSCArgument(self.address)[1]
typetags = OSCArgument(self.typetags)[1]
return address + typetags + self.message |
def handle(self, data, source = None):
"""Given OSC data, tries to call the callback with the
right address."""
decoded = decodeOSC(data)
self.dispatch(decoded, source) |
def dispatch(self, message, source = None):
"""Sends decoded OSC data to an appropriate calback"""
msgtype = ""
try:
if type(message[0]) == str:
# got a single message
address = message[0]
self.callbacks[address](message)
el... |
def add(self, callback, name):
"""Adds a callback to our set of callbacks,
or removes the callback with name if callback
is None."""
if callback == None:
del self.callbacks[name]
else:
self.callbacks[name] = callback |
def find_example_dir():
"""
Find examples dir .. a little bit ugly..
"""
# Replace %s with directory to check for shoebot menus.
code_stub = textwrap.dedent("""
from pkg_resources import resource_filename, Requirement, DistributionNotFound
try:
print(resource_filename(Requirement.par... |
def run(self):
"""
The body of the tread: read lines and put them on the queue.
"""
try:
for line in iter(self._fd.readline, False):
if line is not None:
if self._althandler:
if self._althandler(line):
... |
def eof(self):
"""
Check whether there is no more content to expect.
"""
return (not self.is_alive()) and self._queue.empty() or self._fd.closed |
def live_source_load(self, source):
"""
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
"""
source = source.rstrip('\n... |
def send_command(self, cmd, *args):
"""
:param cmd:
:param args:
:return:
"""
# Test in python 2 and 3 before modifying (gedit2 + 3)
if True:
# Create a CommandResponse using a cookie as a unique id
cookie = str(uuid.uuid4())
re... |
def close(self):
"""
Close outputs of process.
"""
self.process.stdout.close()
self.process.stderr.close()
self.running = False |
def get_output(self):
"""
:yield: stdout_line, stderr_line, running
Generator that outputs lines captured from stdout and stderr
These can be consumed to output on a widget in an IDE
"""
if self.process.poll() is not None:
self.close()
yield Non... |
def get_command_responses(self):
"""
Get responses to commands sent
"""
if not self.response_queue.empty():
yield None
while not self.response_queue.empty():
line = self.response_queue.get()
if line is not None:
yield line |
def sort_by_preference(options, prefer):
"""
:param options: List of options
:param prefer: Prefered options
:return:
Pass in a list of options, return options in 'prefer' first
>>> sort_by_preference(["cairo", "cairocffi"], ["cairocffi"])
["cairocffi", "cairo"]
"""
if not prefer:
... |
def get_driver_options():
"""
Interpret env var as key=value
:return:
"""
options = os.environ.get("SHOEBOT_GRAPHICS")
if not options:
return {}
try:
return dict([kv.split('=') for kv in options.split()])
except ValueError:
sys.stderr.write("Bad option format.\n"... |
def import_libs(self, module_names, impl_name):
"""
Loop through module_names,
add has_.... booleans to class
set ..._impl to first successful import
:param module_names: list of module names to try importing
:param impl_name: used in error output if no modules succeed... |
def ensure_pycairo_context(self, ctx):
"""
If ctx is a cairocffi Context convert it to a PyCairo Context
otherwise return the original context
:param ctx:
:return:
"""
if self.cairocffi and isinstance(ctx, self.cairocffi.Context):
from shoebot.util.ca... |
def pangocairo_create_context(cr):
"""
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
"""
# TODO move this to core.backend
try:
return PangoCairo.create_context(cr)
except KeyError a... |
def _get_center(self):
'''Returns the center point of the path, disregarding transforms.
'''
w, h = self.layout.get_pixel_size()
x = (self.x + w / 2)
y = (self.y + h / 2)
return x, y |
def is_list(str):
""" Determines if an item in a paragraph is a list.
If all of the lines in the markup start with a "*" or "1."
this indicates a list as parsed by parse_paragraphs().
It can be drawn with draw_list().
"""
for chunk in str.split("\n"):
chunk = chunk.replace... |
def is_math(str):
""" Determines if an item in a paragraph is a LaTeX math equation.
Math equations are wrapped in <math></math> tags.
They can be drawn as an image using draw_math().
"""
str = str.strip()
if str.startswith("<math>") and str.endswith("</math>"):
retur... |
def draw_math(str, x, y, alpha=1.0):
""" Uses mimetex to generate a GIF-image from the LaTeX equation.
"""
try: from web import _ctx
except: pass
str = re.sub("</{0,1}math>", "", str.strip())
img = mimetex.gif(str)
w, h = _ctx.imagesize(img)
_ctx.image(img, x, y, alpha=alp... |
def textwidth(str):
"""textwidth() reports incorrectly when lineheight() is smaller than 1.0
"""
try: from web import _ctx
except: pass
l = _ctx.lineheight()
_ctx.lineheight(1)
w = _ctx.textwidth(str)
_ctx.lineheight(l)
return w |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.