_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q260100
BezierPath._render_closure
validation
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...
python
{ "resource": "" }
q260101
BezierPath._linepoint
validation
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, ...
python
{ "resource": "" }
q260102
BezierPath._linelength
validation
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)
python
{ "resource": "" }
q260103
BezierPath._curvepoint
validation
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. ...
python
{ "resource": "" }
q260104
BezierPath._segment_lengths
validation
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 ...
python
{ "resource": "" }
q260105
BezierPath._get_length
validation
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...
python
{ "resource": "" }
q260106
BezierPath._get_elements
validation
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
python
{ "resource": "" }
q260107
adjacency
validation
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,...
python
{ "resource": "" }
q260108
get_child_by_name
validation
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...
python
{ "resource": "" }
q260109
sbot_executable
validation
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') ...
python
{ "resource": "" }
q260110
Page._description
validation
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""
python
{ "resource": "" }
q260111
Page._keywords
validation
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: ...
python
{ "resource": "" }
q260112
sorted
validation
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
python
{ "resource": "" }
q260113
unique
validation
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
python
{ "resource": "" }
q260114
clique
validation
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 ...
python
{ "resource": "" }
q260115
cliques
validation
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) ...
python
{ "resource": "" }
q260116
DrawQueueSink.render
validation
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...
python
{ "resource": "" }
q260117
hexDump
validation
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:...
python
{ "resource": "" }
q260118
readLong
validation
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)
python
{ "resource": "" }
q260119
decodeOSC
validation
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...
python
{ "resource": "" }
q260120
CallbackManager.handle
validation
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)
python
{ "resource": "" }
q260121
CallbackManager.dispatch
validation
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...
python
{ "resource": "" }
q260122
CallbackManager.add
validation
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
python
{ "resource": "" }
q260123
find_example_dir
validation
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...
python
{ "resource": "" }
q260124
AsynchronousFileReader.eof
validation
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
python
{ "resource": "" }
q260125
ShoebotProcess.live_source_load
validation
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...
python
{ "resource": "" }
q260126
ShoebotProcess.close
validation
def close(self): """ Close outputs of process. """ self.process.stdout.close() self.process.stderr.close() self.running = False
python
{ "resource": "" }
q260127
ShoebotProcess.get_command_responses
validation
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
python
{ "resource": "" }
q260128
CairoGIBackend.ensure_pycairo_context
validation
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...
python
{ "resource": "" }
q260129
pangocairo_create_context
validation
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...
python
{ "resource": "" }
q260130
is_list
validation
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...
python
{ "resource": "" }
q260131
draw_math
validation
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...
python
{ "resource": "" }
q260132
draw_list
validation
def draw_list(markup, x, y, w, padding=5, callback=None): """ Draws list markup with indentation in NodeBox. Draw list markup at x, y coordinates using indented bullets or numbers. The callback is a command that takes a str and an int. """ try: from web import _ctx except: pa...
python
{ "resource": "" }
q260133
draw_table
validation
def draw_table(table, x, y, w, padding=5): """ This is a very poor algorithm to draw Wikipedia tables in NodeBox. """ try: from web import _ctx except: pass f = _ctx.fill() _ctx.stroke(f) h = _ctx.textheight(" ") + padding*2 row_y = y if table.title != "": ...
python
{ "resource": "" }
q260134
WikipediaPage.parse
validation
def parse(self, light=False): """ Parses data from Wikipedia page markup. The markup comes from Wikipedia's edit page. We parse it here into objects containing plain text. The light version parses only links to other articles, it's faster than a full parse. """ ...
python
{ "resource": "" }
q260135
WikipediaPage.parse_links
validation
def parse_links(self, markup): """ Returns a list of internal Wikipedia links in the markup. # A Wikipedia link looks like: # [[List of operating systems#Embedded | List of embedded operating systems]] # It does not contain a colon, this indicates images, users, languages, etc....
python
{ "resource": "" }
q260136
WikipediaPage.parse_images
validation
def parse_images(self, markup, treshold=6): """ Returns a list of images found in the markup. An image has a pathname, a description in plain text and a list of properties Wikipedia uses to size and place images. # A Wikipedia image looks like: # [[Image:Columb...
python
{ "resource": "" }
q260137
WikipediaPage.parse_balanced_image
validation
def parse_balanced_image(self, markup): """ Corrects Wikipedia image markup. Images have a description inside their link markup that can contain link markup itself, make sure the outer "[" and "]" brackets delimiting the image are balanced correctly (e.g. no [[ ]] ]]). ...
python
{ "resource": "" }
q260138
WikipediaPage.connect_table
validation
def connect_table(self, table, chunk, markup): """ Creates a link from the table to paragraph and vice versa. Finds the first heading above the table in the markup. This is the title of the paragraph the table belongs to. """ k = markup.find(chunk) i =...
python
{ "resource": "" }
q260139
WikipediaPage.parse_tables
validation
def parse_tables(self, markup): """ Returns a list of tables in the markup. A Wikipedia table looks like: {| border="1" |- |Cell 1 (no modifier - not aligned) |- |align="right" |Cell 2 (right aligned) |- |} """ tables = ...
python
{ "resource": "" }
q260140
WikipediaPage.parse_categories
validation
def parse_categories(self, markup): """ Returns a list of categories the page belongs to. # A Wikipedia category link looks like: # [[Category:Computing]] # This indicates the page is included in the given category. # If "Category" is preceded by ":" this indicates a li...
python
{ "resource": "" }
q260141
WikipediaPage.parse_important
validation
def parse_important(self, markup): """ Returns a list of words that appear in bold in the article. Things like table titles are not added to the list, these are probably bold because it makes the layout nice, not necessarily because they are important. ...
python
{ "resource": "" }
q260142
Variable.sanitize
validation
def sanitize(self, val): """Given a Variable and a value, cleans it out""" if self.type == NUMBER: try: return clamp(self.min, self.max, float(val)) except ValueError: return 0.0 elif self.type == TEXT: try: retu...
python
{ "resource": "" }
q260143
isList
validation
def isList(l): """Convenience method that works with all 2.x versions of Python to determine whether or not something is listlike.""" return hasattr(l, '__iter__') \ or (type(l) in (types.ListType, types.TupleType))
python
{ "resource": "" }
q260144
isString
validation
def isString(s): """Convenience method that works with all 2.x versions of Python to determine whether or not something is stringlike.""" try: return isinstance(s, unicode) or isinstance(s, basestring) except NameError: return isinstance(s, str)
python
{ "resource": "" }
q260145
buildTagMap
validation
def buildTagMap(default, *args): """Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.""" built = {} for portion in args: if hasattr(portion, 'items'): #It's a m...
python
{ "resource": "" }
q260146
PageElement.setup
validation
def setup(self, parent=None, previous=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous = previous self.next = None self.previousSibling = None self.nextSibling = None if self.parent and ...
python
{ "resource": "" }
q260147
PageElement.extract
validation
def extract(self): """Destructively rips this element out of the tree.""" if self.parent: try: self.parent.contents.remove(self) except ValueError: pass #Find the two elements that would be next to each other if #this element (and ...
python
{ "resource": "" }
q260148
PageElement._lastRecursiveChild
validation
def _lastRecursiveChild(self): "Finds the last element beneath this object to be parsed." lastChild = self while hasattr(lastChild, 'contents') and lastChild.contents: lastChild = lastChild.contents[-1] return lastChild
python
{ "resource": "" }
q260149
PageElement.findNext
validation
def findNext(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
python
{ "resource": "" }
q260150
PageElement.findAllNext
validation
def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwar...
python
{ "resource": "" }
q260151
PageElement.findNextSibling
validation
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs)
python
{ "resource": "" }
q260152
PageElement.findNextSiblings
validation
def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, s...
python
{ "resource": "" }
q260153
PageElement.findPrevious
validation
def findPrevious(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
python
{ "resource": "" }
q260154
PageElement.findAllPrevious
validation
def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousGenerator, ...
python
{ "resource": "" }
q260155
PageElement.findPreviousSibling
validation
def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findPreviousSiblings, name, attrs, text, **kw...
python
{ "resource": "" }
q260156
PageElement.findPreviousSiblings
validation
def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, ...
python
{ "resource": "" }
q260157
PageElement.findParent
validation
def findParent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _findOne because findParents takes a different # set of arguments. r = None l = self.findParents(name, attrs, 1) ...
python
{ "resource": "" }
q260158
PageElement.findParents
validation
def findParents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs)
python
{ "resource": "" }
q260159
PageElement._findAll
validation
def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name else: # Build a SoupStrainer strainer = SoupStrainer(name, attrs, text, **kwargs) ...
python
{ "resource": "" }
q260160
PageElement.toEncoding
validation
def toEncoding(self, s, encoding=None): """Encodes an object to a string in some encoding, or to Unicode. .""" if isinstance(s, unicode): if encoding: s = s.encode(encoding) elif isinstance(s, str): if encoding: s = s.encode(encodin...
python
{ "resource": "" }
q260161
Tag._invert
validation
def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i
python
{ "resource": "" }
q260162
Tag._convertEntities
validation
def _convertEntities(self, match): """Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.""" x = match.group(1) if self.convertHTMLEntitie...
python
{ "resource": "" }
q260163
Tag.decompose
validation
def decompose(self): """Recursively destroys the contents of this tree.""" contents = [i for i in self.contents] for i in contents: if isinstance(i, Tag): i.decompose() else: i.extract() self.extract()
python
{ "resource": "" }
q260164
Tag.renderContents
validation
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Renders the contents of this tag as a string in the given encoding. If encoding is None, returns a Unicode string..""" s=[] for c in self: text = None ...
python
{ "resource": "" }
q260165
Tag.find
validation
def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.findAll(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r
python
{ "resource": "" }
q260166
Tag.findAll
validation
def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in th...
python
{ "resource": "" }
q260167
Tag._getAttrMap
validation
def _getAttrMap(self): """Initializes a map representation of this tag's attributes, if not already initialized.""" if not getattr(self, 'attrMap'): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap
python
{ "resource": "" }
q260168
BeautifulStoneSoup.convert_charref
validation
def convert_charref(self, name): """This method fixes a bug in Python's SGMLParser.""" try: n = int(name) except ValueError: return if not 0 <= n <= 127 : # ASCII ends at 127, not 255 return return self.convert_codepoint(n)
python
{ "resource": "" }
q260169
BeautifulStoneSoup.isSelfClosingTag
validation
def isSelfClosingTag(self, name): """Returns true iff the given string is the name of a self-closing tag according to this parser.""" return self.SELF_CLOSING_TAGS.has_key(name) \ or self.instanceSelfClosingTags.has_key(name)
python
{ "resource": "" }
q260170
BeautifulStoneSoup._toStringSubclass
validation
def _toStringSubclass(self, text, subclass): """Adds a certain piece of text to the tree as a NavigableString subclass.""" self.endData() self.handle_data(text) self.endData(subclass)
python
{ "resource": "" }
q260171
BeautifulStoneSoup.handle_pi
validation
def handle_pi(self, text): """Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.""" if text[:3] == "xml": text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self...
python
{ "resource": "" }
q260172
BeautifulStoneSoup.handle_charref
validation
def handle_charref(self, ref): "Handle character references as data." if self.convertEntities: data = unichr(int(ref)) else: data = '&#%s;' % ref self.handle_data(data)
python
{ "resource": "" }
q260173
BeautifulStoneSoup.parse_declaration
validation
def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) ...
python
{ "resource": "" }
q260174
BeautifulSoup.start_meta
validation
def start_meta(self, attrs): """Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.""" httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSu...
python
{ "resource": "" }
q260175
UnicodeDammit._subMSChar
validation
def _subMSChar(self, orig): """Changes a MS smart quote character to an XML or HTML entity.""" sub = self.MS_CHARS.get(orig) if type(sub) == types.TupleType: if self.smartQuotesTo == 'xml': sub = '&#x%s;' % sub[1] else: sub = '&%s;'...
python
{ "resource": "" }
q260176
UnicodeDammit._toUnicode
validation
def _toUnicode(self, data, encoding): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ and (data[2:4] != '\...
python
{ "resource": "" }
q260177
UnicodeDammit._detectEncoding
validation
def _detectEncoding(self, xml_data, isHTML=False): """Given a document, tries to detect its XML encoding.""" xml_encoding = sniffed_xml_encoding = None try: if xml_data[:4] == '\x4c\x6f\xa7\x94': # EBCDIC xml_data = self._ebcdic_to_ascii(xml_data) ...
python
{ "resource": "" }
q260178
shoebot_example
validation
def shoebot_example(**shoebot_kwargs): """ Decorator to run some code in a bot instance. """ def decorator(f): def run(): from shoebot import ShoebotInstallError # https://github.com/shoebot/shoebot/issues/206 print(" Shoebot - %s:" % f.__name__.replace("_", " ")) ...
python
{ "resource": "" }
q260179
ShoebotWidget.scale_context_and_center
validation
def scale_context_and_center(self, cr): """ Scale context based on difference between bot size and widget """ bot_width, bot_height = self.bot_size if self.width != bot_width or self.height != bot_height: # Scale up by largest dimension if self.width < sel...
python
{ "resource": "" }
q260180
ShoebotWidget.draw
validation
def draw(self, widget, cr): ''' Draw just the exposed part of the backing store, scaled to fit ''' if self.bot_size is None: # No bot to draw yet. self.draw_default_image(cr) return cr = driver.ensure_pycairo_context(cr) surfa...
python
{ "resource": "" }
q260181
ShoebotWidget.create_rcontext
validation
def create_rcontext(self, size, frame): ''' Creates a recording surface for the bot to draw on :param size: The width and height of bot ''' self.frame = frame width, height = size meta_surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, width, heig...
python
{ "resource": "" }
q260182
JSONEncoder.encode
validation
def encode(self, o): """ Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): ...
python
{ "resource": "" }
q260183
GtkInputDeviceMixin.get_key_map
validation
def get_key_map(self): ''' Return a dict in the form of SHOEBOT_KEY_NAME, GTK_VALUE Shoebot key names look like KEY_LEFT, whereas Gdk uses KEY_Left - Shoebot key names are derived from Nodebox 1, which was a mac app. ''' kdict = {} for gdk_name...
python
{ "resource": "" }
q260184
CairoImageSink._output_file
validation
def _output_file(self, frame): """ If filename was used output a filename, along with multifile numbered filenames will be used. If buff was specified it is returned. :return: Output buff or filename. """ if self.buff: return self.buff elif s...
python
{ "resource": "" }
q260185
CairoImageSink.create_rcontext
validation
def create_rcontext(self, size, frame): """ Called when CairoCanvas needs a cairo context to draw on """ if self.format == 'pdf': surface = cairo.PDFSurface(self._output_file(frame), *size) elif self.format in ('ps', 'eps'): surface = cairo.PSSurface(self....
python
{ "resource": "" }
q260186
CairoImageSink.rendering_finished
validation
def rendering_finished(self, size, frame, cairo_ctx): """ Called when CairoCanvas has rendered a bot """ surface = cairo_ctx.get_target() if self.format == 'png': surface.write_to_png(self._output_file(frame)) surface.finish() surface.flush()
python
{ "resource": "" }
q260187
CairoCanvas.output_closure
validation
def output_closure(self, target, file_number=None): ''' Function to output to a cairo surface target is a cairo Context or filename if file_number is set, then files will be numbered (this is usually set to the current frame number) ''' def output_context(ctx): ...
python
{ "resource": "" }
q260188
UrbanDictionaryDefinition._parse
validation
def _parse(self): """ Strips links from the definition and gathers them in a links property. """ p1 = "\[.*?\](.*?)\[\/.*?\]" p2 = "\[(.*?)\]" self.links = [] for p in (p1,p2): for link in re.findall(p, self.description): self...
python
{ "resource": "" }
q260189
create_canvas
validation
def create_canvas(src, format=None, outputfile=None, multifile=False, buff=None, window=False, title=None, fullscreen=None, show_vars=False): """ Create canvas and sink for attachment to a bot canvas is what draws images, 'sink' is the final consumer of the images :param src: Default...
python
{ "resource": "" }
q260190
create_bot
validation
def create_bot(src=None, grammar=NODEBOX, format=None, outputfile=None, iterations=1, buff=None, window=False, title=None, fullscreen=None, server=False, port=7777, show_vars=False, vars=None, namespace=None): """ Create a canvas and a bot with the same canvas attached to it bot parameters ...
python
{ "resource": "" }
q260191
run
validation
def run(src, grammar=NODEBOX, format=None, outputfile=None, iterations=1, buff=None, window=True, title=None, fullscreen=None, close_window=False, server=False, port=7777, show_vars=False, vars=None, namespac...
python
{ "resource": "" }
q260192
ShoebotEditorWindow.save_as
validation
def save_as(self): """ Return True if the buffer was saved """ chooser = ShoebotFileChooserDialog(_('Save File'), None, Gtk.FileChooserAction.SAVE, (Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT, Gtk.STOCK_C...
python
{ "resource": "" }
q260193
VarWindow.widget_changed
validation
def widget_changed(self, widget, v): ''' Called when a slider is adjusted. ''' # set the appropriate bot var if v.type is NUMBER: self.bot._namespace[v.name] = widget.get_value() self.bot._vars[v.name].value = widget.get_value() ## Not sure if this is how to do this - st...
python
{ "resource": "" }
q260194
VarWindow.var_added
validation
def var_added(self, v): """ var was added in the bot while it ran, possibly by livecoding :param v: :return: """ self.add_variable(v) self.window.set_size_request(400, 35 * len(self.widgets.keys())) self.window.show_all()
python
{ "resource": "" }
q260195
VarWindow.var_deleted
validation
def var_deleted(self, v): """ var was added in the bot :param v: :return: """ widget = self.widgets[v.name] # widgets are all in a single container .. parent = widget.get_parent() self.container.remove(parent) del self.widgets[v.name] ...
python
{ "resource": "" }
q260196
parse
validation
def parse(svg, cached=False, _copy=True): """ Returns cached copies unless otherwise specified. """ if not cached: dom = parser.parseString(svg) paths = parse_node(dom, []) else: id = _cache.id(svg) if not _cache.has_key(id): dom = parser.parseString...
python
{ "resource": "" }
q260197
get_attribute
validation
def get_attribute(element, attribute, default=0): """ Returns XML element's attribute, or default if none. """ a = element.getAttribute(attribute) if a == "": return default return a
python
{ "resource": "" }
q260198
add_color_info
validation
def add_color_info(e, path): """ Expand the path with color information. Attempts to extract fill and stroke colors from the element and adds it to path attributes. """ _ctx.colormode(RGB, 1.0) def _color(hex, alpha=1.0): if hex == "none": return None n =...
python
{ "resource": "" }
q260199
events.copy
validation
def copy(self, graph): """ Returns a copy of the event handler, remembering the last node clicked. """ e = events(graph, self._ctx) e.clicked = self.clicked return e
python
{ "resource": "" }