Search is not available for this dataset
text
stringlengths
75
104k
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...
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 != "": ...
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. """ ...
def plain(self, markup): """ Strips Wikipedia markup from given text. This creates a "plain" version of the markup, stripping images and references and the like. Does some commonsense maintenance as well, like collapsing multiple spaces. If you specified...
def convert_pre(self, markup): """ Substitutes <pre> to Wikipedia markup by adding a space at the start of a line. """ for m in re.findall(self.re["preformatted"], markup): markup = markup.replace(m, m.replace("\n", "\n ")) markup = re.sub("<pre.*?>\n{0,...
def convert_li(self, markup): """ Subtitutes <li> content to Wikipedia markup. """ for li in re.findall("<li;*?>", markup): markup = re.sub(li, "\n* ", markup) markup = markup.replace("</li>", "") return markup
def convert_table(self, markup): """ Subtitutes <table> content to Wikipedia markup. """ for table in re.findall(self.re["html-table"], markup): wiki = table wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki) wiki = re.sub(r"<tr(.*?)>", "|-\\1", w...
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....
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...
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 [[ ]] ]]). ...
def parse_gallery_images(self, markup): """ Parses images from the <gallery></gallery> section. Images inside <gallery> tags do not have outer "[[" brackets. Add these and then parse again. """ gallery = re.search(self.re["gallery"], markup) ...
def parse_paragraph(self, markup): """ Creates a list from lines of text in a paragraph. Each line of text is a new item in the list, except lists and preformatted chunks (<li> and <pre>), these are kept together as a single chunk. Lists are formatted u...
def parse_paragraph_list(self, markup, indent="\t"): """ Formats bullets and numbering of Wikipedia lists. List items are marked by "*", "#" or ";" at the start of a line. We treat ";" the same as "*", and replace "#" with real numbering (e.g. "2."). Sublists (e...
def connect_paragraph(self, paragraph, paragraphs): """ Create parent/child links to other paragraphs. The paragraphs parameters is a list of all the paragraphs parsed up till now. The parent is the previous paragraph whose depth is less. The parent's c...
def parse_paragraph_references(self, markup): """ Updates references with content from specific paragraphs. The "references", "notes", "external links" paragraphs are double-checked for references. Not all items in the list might have been referenced inside the article...
def parse_paragraphs(self, markup): """ Returns a list of paragraphs in the markup. A paragraph has a title and multiple lines of plain text. A paragraph might have parent and child paragraphs, denoting subtitles or bigger chapters. A paragraph might ha...
def parse_table_row(self, markup, row): """ Parses a row of cells in a Wikipedia table. Cells in the row are separated by "||". A "!" indicates a row of heading columns. Each cell can contain properties before a "|", # e.g. align="right" | Cell 2 (right aligned). ...
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 =...
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 = ...
def parse_references(self, markup): """ Returns a list of references found in the markup. References appear inline as <ref> footnotes, http:// external links, or {{cite}} citations. We replace it with (1)-style footnotes. Additional references data is gathered in ...
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...
def parse_translations(self, markup): """ Returns a dictionary of translations for the page title. A Wikipedia language link looks like: [[af:Rekenaar]]. The parser will also fetch links like "user:" and "media:" but these are stripped against the dictionary of ...
def parse_disambiguation(self, markup): """ Gets the Wikipedia disambiguation page for this article. A Wikipedia disambiguation link refers to other pages with the same title but of smaller significance, e.g. {{dablink|For the IEEE magazine see [[Computer (magazine)]].}...
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. ...
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...
def compliesTo(self, v): """Return whether I am compatible with the given var: - Type should be the same - My value should be inside the given vars' min/max range. """ if self.type == v.type: if self.type == NUMBER: if self.value < self.min o...
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))
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)
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...
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 ...
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 ...
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
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)
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...
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)
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...
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)
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, ...
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...
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, ...
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) ...
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)
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) ...
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...
def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i
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...
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()
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 ...
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
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...
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
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)
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)
def _popToTag(self, name, inclusivePop=True): """Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.""" #print "Popping to %s" % name ...
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)
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...
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)
def handle_entityref(self, ref): """Handle entity references as data, possibly converting known HTML and/or XML entity references to the corresponding Unicode characters.""" data = None if self.convertHTMLEntities: try: data = unichr(name2codepoint[ref...
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) ...
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...
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;'...
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] != '\...
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) ...
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("_", " ")) ...
def _get_center(self): '''Returns the center point of the path, disregarding transforms. ''' x = (self.x + self.width / 2) y = (self.y + self.height / 2) return (x, y)
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...
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...
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...
def do_drawing(self, size, frame, cairo_ctx): ''' Update the backing store from a cairo context and schedule a redraw (expose event) :param size: width, height in pixels of bot :param frame: frame # thar was drawn :param cairo_ctx: cairo context the bot was drawn on ...
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): ...
def iterencode(self, o): """ Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: ...
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...
def _grow(self, generation, rule, angle, length, time=maxint, draw=True): """ Recurse through the system. When a segment is drawn, the LSsytem.segment() method will be called. You can customize this method to create your own visualizations. It takes an optional time parameter. ...
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...
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....
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()
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): ...
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...
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...
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 ...
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...
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...
def add_variables(self): """ Add all widgets to specified vbox :param container: :return: """ for k, v in self.bot._vars.items(): if not hasattr(v, 'type'): raise AttributeError( '%s is not a Shoebot Variable - see https://s...
def update_var(self, name, value): """ :return: success, err_msg_if_failed """ widget = self.widgets.get(name) if widget is None: return False, 'No widget found matching, {}'.format(name) try: if isinstance(widget, Gtk.CheckButton): ...
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...
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()
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] ...
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...
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
def parse_node(node, paths=[], ignore=["pattern"]): """ Recurse the node tree and find drawable tags. Recures all the children in the node. If a child is something we can draw, a line, rect, oval or path, parse it to a PathElement drawable with drawpath() """ # Ignore pat...
def parse_transform(e, path): """ Transform the path according to a defined matrix. Attempts to extract a transform="matrix()|translate()" attribute. Transforms the path accordingly. """ t = get_attribute(e, "transform", default="") for mode in ("matrix", "translate"): ...
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 =...
def download(self, size=SIZE_LARGE, thumbnail=False, wait=60, asynchronous=False): """ Downloads this image to cache. Calling the download() method instantiates an asynchronous URLAccumulator. Once it is done downloading, this image will have its path property set to an...
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
def update(self): """ Interacts with the graph by clicking or dragging nodes. Hovering a node fires the callback function events.hover(). Clicking a node fires the callback function events.click(). """ if self.mousedown: # When not pressing or dragg...
def drag(self, node): """ Drags given node to mouse location. """ dx = self.mouse.x - self.graph.x dy = self.mouse.y - self.graph.y # A dashed line indicates the drag vector. s = self.graph.styles.default self._ctx.nofill() self._ctx.nostroke() ...
def hover(self, node): """ Displays a popup when hovering over a node. """ if self.popup == False: return if self.popup == True or self.popup.node != node: if self.popup_text.has_key(node.id): texts = self.popup_text[node.id] else...
def textpath(self, i): """ Returns a cached textpath of the given text in queue. """ if len(self._textpaths) == i: self._ctx.font(self.font, self.fontsize) txt = self.q[i] if len(self.q) > 1: # Indicate current text (e.g. 5/13...
def update(self): """ Rotates the queued texts and determines display time. """ if self.delay > 0: # It takes a while for the popup to appear. self.delay -= 1; return if self.fi == 0: # Only one text in queue, displayed i...
def draw(self): """ Draws a popup rectangle with a rotating text queue. """ if len(self.q) > 0: self.update() if self.delay == 0: # Rounded rectangle in the given background color. p,...