code
stringlengths
1
18.2k
def inplace_filter(func, sequence): """ Like Python's filter() builtin, but modifies the sequence in place. Example: >>> l = range(10) >>> inplace_filter(lambda x: x > 5, l) >>> l [6, 7, 8, 9] Performance considerations: the function iterates over the sequence, shuffling surviving members down and deleting whatever top...
def inorder(*iterables, **kwargs): """ A generator that yields the values from several ordered iterables in order. Example: >>> x = [0, 1, 2, 3] >>> y = [1.5, 2.5, 3.5, 4.5] >>> z = [1.75, 2.25, 3.75, 4.25] >>> list(inorder(x, y, z)) [0, 1, 1.5, 1.75, 2, 2.25, 2.5, 3, 3.5, 3.75, 4.25, 4.5] >>> list(inorder(x, y, z, key...
1.75] >>> list(inorder(x, y, z, reverse = True)) [4.5, 4.25, 3.75, 3.5, 3, 2.5, 2.25, 2, 1.75, 1.5, 1, 0] >>> list(inorder(x, y, z, key = lambda x: -x)) [4.5, 4.25, 3.75, 3.5, 3, 2.5, 2.25, 2, 1.75, 1.5, 1, 0] NOTE: this function will never reverse the order of elements in the input iterables. If the reverse keyword ar...
default = identity if kwargs: raise TypeError("invalid keyword argument '%s'" % kwargs.keys()[0]) nextvals = {} for iterable in iterables: next = iter(iterable).next try: nextval = next() nextvals[next] = keyfunc(nextval), nextval, next except StopIteration: pass if not nextvals: # all sequences are empty return if rev...
def randindex(lo, hi, n = 1.): """ Yields integers in the range [lo, hi) where 0 <= lo < hi. Each return value is a two-element tuple. The first element is the random integer, the second is the natural logarithm of the probability with which that integer will be chosen. The CDF for the distribution from which the integ...
<= 0: %g" % n) elif n == 1.: # special case for uniform distribution try: lnP = math.log(1. / (hi - lo)) except ValueError: raise ValueError("[lo, hi) domain error") hi -= 1 rnd = random.randint while 1: yield rnd(lo, hi), lnP # CDF evaluated at index boundaries lnP = numpy.arange(lo, hi + 1, dtype = "double")**n lnP -...
index assert index >= lo yield index, lnP[index - lo]
def shift(self, x): """ Return a new segment whose bounds are given by adding x to the segment's upper and lower bounds. """ return tuple.__new__(self.__class__, (self[0] + x, self[1] + x))
def extent(self): """ Return the segment whose end-points denote the maximum and minimum extent of the segmentlist. Does not require the segmentlist to be coalesced. """ if not len(self): raise ValueError("empty list") min, max = self[0] for lo, hi in self: if min > lo: min = lo if max < hi: max = hi return segment(min...
def find(self, item): """ Return the smallest i such that i is the index of an element that wholly contains item. Raises ValueError if no such element exists. Does not require the segmentlist to be coalesced. """ for i, seg in enumerate(self): if item in seg: return i raise ValueError(item)
def intersects_segment(self, other): """ Returns True if the intersection of self and the segment other is not the null set, otherwise returns False. The algorithm is O(log n). Requires the list to be coalesced. """ i = _bisect_left(self, other) return ((i != 0) and (other[0] < self[i-1][1])) or ((i != len(self)) and (...
def intersects(self, other): """ Returns True if the intersection of self and the segmentlist other is not the null set, otherwise returns False. The algorithm is O(n), but faster than explicit calculation of the intersection, i.e. by testing bool(self & other). Requires both lists to be coalesced. """ # if either has ...
def coalesce(self): """ Sort the elements of the list into ascending order, and merge continuous segments into single segments. Segmentlist is modified in place. This operation is O(n log n). """ self.sort() i = j = 0 n = len(self) while j < n: lo, hi = self[j] j += 1 while j < n and hi >= self[j][0]: hi = max(hi, self...
def protract(self, x): """ Execute the .protract() method on each segment in the list and coalesce the result. Segmentlist is modified in place. """ for i in xrange(len(self)): self[i] = self[i].protract(x) return self.coalesce()
def contract(self, x): """ Execute the .contract() method on each segment in the list and coalesce the result. Segmentlist is modified in place. """ for i in xrange(len(self)): self[i] = self[i].contract(x) return self.coalesce()
def shift(self, x): """ Execute the .shift() method on each segment in the list. The algorithm is O(n) and does not require the list to be coalesced nor does it coalesce the list. Segmentlist is modified in place. """ for i in xrange(len(self)): self[i] = self[i].shift(x) return self
def update(self, d): """ From a dictionary of offsets, apply each offset to the corresponding segmentlist. NOTE: it is acceptable for the offset dictionary to contain entries for which there is no matching segmentlist; no error will be raised, but the offset will be ignored. This simplifies the case of updating several...
def copy(self, keys = None): """ Return a copy of the segmentlistdict object. The return value is a new object with a new offsets attribute, with references to the original keys, and shallow copies of the segment lists. Modifications made to the offset dictionary or segmentlists in the object returned by this method wi...
existing one with >>> old = segmentlistdict() >>> new = segmentlistdict(old) This creates a copy of the dictionary, but not of its contents. That is, this creates new with references to the segmentlists in old, therefore changes to the segmentlists in either new or old are reflected in both. The second method is >>> ne...
def map(self, func): """ Return a dictionary of the results of func applied to each of the segmentlist objects in self. Example: >>> x = segmentlistdict() >>> x["H1"] = segmentlist([segment(0, 10)]) >>> x["H2"] = segmentlist([segment(5, 15)]) >>> x.map(lambda l: 12 in l) {'H2': True, 'H1': False} """ return dict((key, ...
def extent_all(self): """ Return the result of running .extent() on the union of all lists in the dictionary. """ segs = tuple(seglist.extent() for seglist in self.values() if seglist) if not segs: raise ValueError("empty list") return segment(min(seg[0] for seg in segs), max(seg[1] for seg in segs))
def keys_at(self, x): """ Return a list of the keys for the segment lists that contain x. Example: >>> x = segmentlistdict() >>> x["H1"] = segmentlist([segment(0, 10)]) >>> x["H2"] = segmentlist([segment(5, 15)]) >>> x.keys_at(12) ['H2'] """ return [key for key, segs in self.items() if x in segs]
def intersects_segment(self, seg): """ Returns True if any segmentlist in self intersects the segment, otherwise returns False. """ return any(value.intersects_segment(seg) for value in self.itervalues())
def intersects(self, other): """ Returns True if there exists a segmentlist in self that intersects the corresponding segmentlist in other; returns False otherwise. See also: .intersects_all(), .all_intersects(), .all_intersects_all() """ return any(key in self and self[key].intersects(value) for key, value in other.it...
def intersects_all(self, other): """ Returns True if each segmentlist in other intersects the corresponding segmentlist in self; returns False if this is not the case, or if other is empty. See also: .intersects(), .all_intersects(), .all_intersects_all() """ return all(key in self and self[key].intersects(value) for k...
def all_intersects_all(self, other): """ Returns True if self and other have the same keys, and each segmentlist intersects the corresponding segmentlist in the other; returns False if this is not the case or if either dictionary is empty. See also: .intersects(), .all_intersects(), .intersects_all() """ return set(sel...
def extend(self, other): """ Appends the segmentlists from other to the corresponding segmentlists in self, adding new segmentslists to self as needed. """ for key, value in other.iteritems(): if key not in self: self[key] = _shallowcopy(value) else: self[key].extend(value)
def contract(self, x): """ Run .contract(x) on all segmentlists. """ for value in self.itervalues(): value.contract(x) return self
def protract(self, x): """ Run .protract(x) on all segmentlists. """ for value in self.itervalues(): value.protract(x) return self
def extract_common(self, keys): """ Return a new segmentlistdict containing only those segmentlists associated with the keys in keys, with each set to their mutual intersection. The offsets are preserved. """ keys = set(keys) new = self.__class__() intersection = self.intersection(keys) for key in keys: dict.__setitem_...
def is_coincident(self, other, keys = None): """ Return True if any segment in any list in self intersects any segment in any list in other. If the optional keys argument is not None, then it should be an iterable of keys and only segment lists for those keys will be considered in the test (instead of raising KeyError,...
else: self = tuple(self.values()) other = tuple(other.values()) # make sure inner loop is smallest if len(self) < len(other): self, other = other, self return any(a.intersects(b) for a in self for b in other)
def intersection(self, keys): """ Return the intersection of the segmentlists associated with the keys in keys. """ keys = set(keys) if not keys: return segmentlist() seglist = _shallowcopy(self[keys.pop()]) for key in keys: seglist &= self[key] return seglist
def update_ids(connection, xmldoc, verbose = False): """ For internal use only. """ # NOTE: it's critical that the xmldoc object be retrieved *before* # the rows whose IDs need to be updated are inserted. The xml # retrieval resets the "last max row ID" values inside the table # objects, so if retrieval of the xmldoc i...
# reset ID mapping for next document dbtables.idmap_reset(connection)
def insert_from_url(url, preserve_ids = False, verbose = False, contenthandler = None): """ Parse and insert the LIGO Light Weight document at the URL into the database with which the content handler is associated. If preserve_ids is False (default), then row IDs are modified during the insert process to prevent collis...
enable/disable ID remapping # orig_DBTable_append = dbtables.DBTable.append if not preserve_ids: try: dbtables.idmap_create(contenthandler.connection) except sqlite3.OperationalError: # assume table already exists pass dbtables.idmap_sync(contenthandler.connection) dbtables.DBTable.append = dbtables.DBTable._remapping_...
# not regular Table instances, but this is not checked. # xmldoc = ligolw_utils.load_url(url, verbose = verbose, contenthandler = contenthandler) # # update references to row IDs and cleanup ID remapping # if not preserve_ids: update_ids(contenthandler.connection, xmldoc, verbose = verbose) finally: dbtables.DBTable.ap...
def insert_from_xmldoc(connection, source_xmldoc, preserve_ids = False, verbose = False): """ Insert the tables from an in-ram XML document into the database at the given connection. If preserve_ids is False (default), then row IDs are modified during the insert process to prevent collisions with IDs already in the dat...
dbtables.idmap_sync(connection) dbtables.DBTable.append = dbtables.DBTable._remapping_append else: dbtables.DBTable.append = dbtables.DBTable._append try: # # create a place-holder XML representation of the target # document so we can pass the correct tree to update_ids(). # note that only tables present in the source ...
connection)) # # copy table element child nodes from source XML tree # for elem in tbl.childNodes: if elem.tagName == ligolw.Stream.tagName: dbtbl._end_of_columns() dbtbl.appendChild(type(elem)(elem.attributes)) # # copy table rows from source XML tree # for row in tbl: dbtbl.append(row) dbtbl._end_of_rows() # # update...
def insert_from_urls(urls, contenthandler, **kwargs): """ Iterate over a sequence of URLs, calling insert_from_url() on each, then build the indexes indicated by the metadata in lsctables.py. See insert_from_url() for a description of the additional arguments. """ verbose = kwargs.get("verbose", False) # # load documen...
def extract(connection, filename, table_names = None, verbose = False, xsl_file = None): """ Convert the database at the given connection to a tabular LIGO Light-Weight XML document. The XML document is written to the file named filename. If table_names is not None, it should be a sequence of strings and only the table...
def append_search_summary(xmldoc, process, shared_object = "standalone", lalwrapper_cvs_tag = "", lal_cvs_tag = "", comment = None, ifos = None, inseg = None, outseg = None, nevents = 0, nnodes = 1): """ Append search summary information associated with the given process to the search summary table in xmldoc. Returns t...
def segmentlistdict_fromsearchsummary_in(xmldoc, program = None): """ Convenience wrapper for a common case usage of the segmentlistdict class: searches the process table in xmldoc for occurances of a program named program, then scans the search summary table for matching process IDs and constructs a segmentlistdict ob...
def segmentlistdict_fromsearchsummary_out(xmldoc, program = None): """ Convenience wrapper for a common case usage of the segmentlistdict class: searches the process table in xmldoc for occurances of a program named program, then scans the search summary table for matching process IDs and constructs a segmentlistdict o...
def common_options(func): """Commonly used command options.""" def parse_preset(ctx, param, value): return PRESETS.get(value, (None, None)) def parse_private(ctx, param, value): return hex_from_b64(value) if value else None func = click.option('--private', default=None, help='Private.', callback=parse_private)(func) fu...
def get_private_and_public(username, password_verifier, private, preset): """Print out server public and private.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) click.secho('Server private: %s' % session.private_b64) click.sec...
def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_public, salt, base64=True) click...
def get_private_and_public(ctx, username, password, private, preset): """Print out server public and private.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) click.secho('Client private: %s' % session.private_b64) click.secho('Client public: %s' % se...
def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) click.secho('Client session key: ...
def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password verifier: %s' % passwo...
def cwd_decorator(func): """ decorator to change cwd to directory containing rst for this function """ def wrapper(*args, **kw): cur_dir = os.getcwd() found = False for arg in sys.argv: if arg.endswith(".rst"): found = arg break if found: directory = os.path.dirname(found) if directory: os.chdir(directory) data = func(...
def to_xml(node, pretty=False): """ convert an etree node to xml """ fout = Sio() etree = et.ElementTree(node) etree.write(fout) xml = fout.getvalue() if pretty: xml = pretty_xml(xml, True) return xml
def pretty_xml(string_input, add_ns=False): """ pretty indent string_input """ if add_ns: elem = "<foo " for key, value in DOC_CONTENT_ATTRIB.items(): elem += ' %s="%s"' % (key, value) string_input = elem + ">" + string_input + "</foo>" doc = minidom.parseString(string_input) if add_ns: s1 = doc.childNodes[0].childNode...
def add_cell(preso, pos, width, height, padding=1, top_margin=4, left_margin=2): """ Add a text frame to current slide """ available_width = SLIDE_WIDTH available_width -= left_margin * 2 available_width -= padding * (width - 1) column_width = available_width / width avail_height = SLIDE_HEIGHT avail_height -= top_marg...
def add_line(preso, x1, y1, x2, y2, width="3pt", color="red"): """ Arrow pointing up to right: context.xml: office:automatic-styles/ <style:style style:name="gr1" style:family="graphic" style:parent-style-name="objectwithoutfill"> <style:graphic-properties draw:marker-end="Arrow" draw:marker-end-width="0.3cm" draw:fill...
"draw:style-name": style.name, "draw:layer": "layout", "svg:x1": x1, "svg:y1": y1, "svg:x2": x2, "svg:y2": y2, } line_node = el("draw:line", attrib=line_attrib) preso.slides[-1]._page.append(line_node)
def add_otp_style(self, zip_odp, style_file): """ takes the slide content and merges in the style_file """ style = zipwrap.Zippier(style_file) for picture_file in style.ls("Pictures"): zip_odp.write(picture_file, style.cat(picture_file, True)) xml_data = style.cat("styles.xml", False) # import pdb;pdb.set_trace() xml_d...
def to_file(self, filename=None, write_style=True): """ >>> p = Preso() >>> z = p.to_file('/tmp/foo.odp') >>> sorted(z.ls('/')) ['META-INF/manifest.xml', 'content.xml', 'meta.xml', 'mimetype', 'settings.xml', 'styles.xml'] """ out = zipwrap.Zippier(filename, "w") out.write("mimetype", self.mime_type) for p in self._pic...
def get_node(self): """ <anim:par smil:begin="next"> <anim:par smil:begin="0s"> <anim:par smil:begin="0s" smil:fill="hold" presentation:node-type="on-click" presentation:preset-class="entrance" presentation:preset-id="ooo-entrance-appear"> <anim:set smil:begin="0s" smil:dur="0.001s" smil:fill="hold" smil:targetElement=...
def update_frame_attributes(self, attrib): """ For positioning update the frame """ if "align" in self.user_defined: align = self.user_defined["align"] if "top" in align: attrib["style:vertical-pos"] = "top" if "right" in align: attrib["style:horizontal-pos"] = "right" return attrib
def update_style(self, mapping): """Use to update fill-color""" default = { "presentation:background-visible": "true", "presentation:background-objects-visible": "true", "draw:fill": "solid", "draw:fill-color": "#772953", "draw:fill-image-width": "0cm", "draw:fill-image-height": "0cm", "presentation:display-footer": "t...
def push_pending_node(self, name, attr): """ pending nodes are for affecting type, such as wrapping content with text:a to make a hyperlink. Anything in pending nodes will be written before the actual text. User needs to remember to pop out of it. """ if self.cur_element is None: self.add_text_frame() self.cur_element....
def add_picture(self, p): """ needs to look like this (under draw:page) <draw:frame draw:style-name="gr2" draw:text-style-name="P2" draw:layer="layout" svg:width="19.589cm" svg:height="13.402cm" svg:x="3.906cm" svg:y="4.378cm"> <draw:image xlink:href="Pictures/10000201000002F800000208188B22AE.png" xlink:type="simple" x...
def _copy(self): """ needs to update page numbers """ ins = copy.copy(self) ins._fire_page_number(self.page_number + 1) return ins
def get_node(self): """return etree Element representing this slide""" # already added title, text frames # add animation chunks if self.animations: anim_par = el("anim:par", attrib={"presentation:node-type": "timing-root"}) self._page.append(anim_par) anim_seq = sub_el( anim_par, "anim:seq", attrib={"presentation:node...
def add_list(self, bl): """ note that this pushes the cur_element, but doesn't pop it. You'll need to do that """ # text:list doesn't like being a child of text:p if self.cur_element is None: self.add_text_frame() self.push_element() self.cur_element._text_box.append(bl.node) style = bl.style_name if style not in self....
def add_table(self, t): """ remember to call pop_element after done with table """ self.push_element() self._page.append(t.node) self.cur_element = t
def update_text(self, mapping): """Iterate over nodes, replace text with mapping""" found = False for node in self._page.iter("*"): if node.text or node.tail: for old, new in mapping.items(): if node.text and old in node.text: node.text = node.text.replace(old, new) found = True if node.tail and old in node.tail: node....
def parent_of(self, name): """ go to parent of node with name, and set as cur_node. Useful for creating new paragraphs """ if not self._in_tag(name): return node = self.cur_node while node.tag != name: node = node.getparent() self.cur_node = node.getparent()
def _is_last_child(self, tagname, attributes=None): """ Check if last child of cur_node is tagname with attributes """ children = self.cur_node.getchildren() if children: result = self._is_node(tagname, attributes, node=children[-1]) return result return False
def _in_tag(self, tagname, attributes=None): """ Determine if we are already in a certain tag. If we give attributes, make sure they match. """ node = self.cur_node while not node is None: if node.tag == tagname: if attributes and node.attrib == attributes: return True elif attributes: return False return True node = n...
def _check_add_node(self, parent, name): """ Returns False if bad to make name a child of parent """ if name == ns("text", "a"): if parent.tag == ns("draw", "text-box"): return False return True
def _add_styles(self, add_paragraph=True, add_text=True): """ Adds paragraph and span wrappers if necessary based on style """ p_styles = self.get_para_styles() t_styles = self.get_span_styles() for s in self.slide.pending_styles: if isinstance(s, ParagraphStyle): p_styles.update(s.styles) elif isinstance(s, TextStyle)...
not self._is_node( ns("text", "span"), {ns("text", "style-name"): text.name} ): # Create text style self.slide._preso.add_style(text) self.add_node("text:span", attrib={"text:style-name": text.name})
def line_break(self): """insert as many line breaks as the insert_line_break variable says """ for i in range(self.slide.insert_line_break): # needs to be inside text:p if not self._in_tag(ns("text", "p")): # we can just add a text:p and no line-break # Create paragraph style first self.add_node(ns("text", "p")) self.a...
def write(self, text, add_p_style=True, add_t_style=True): """ see mixed content http://effbot.org/zone/element-infoset.htm#mixed-content Writing is complicated by requirements of odp to ignore duplicate spaces together. Deal with this by splitting on white spaces then dealing with the '' (empty strings) which would be...
str(num_spaces)}) else: self.add_node("text:s") self.pop_node()
def style_node(self, additional_style_attrib=None): """ generate a style node (for automatic-styles) could specify additional attributes such as 'style:parent-style-name' or 'style:list-style-name' """ style_attrib = {"style:name": self.name, "style:family": self.FAMILY} if additional_style_attrib: style_attrib.update(...
def run_file_operation(outdoc, filenames, use_segment_table, operation, preserve = True): """ Performs an operation (intersect or union) across a set of files. That is, given a set of files each with segment definers DMT-FLAG1, DMT-FLAG2 etc the result is a file where DMT-FLAG1 = (file 1's DMT-FLAG1 operation file 2's ...
intersection for ifo, name, version in segment_definers: if operation == INTERSECT: # If I were feeling especially functional-ist I'd write this # with reduce() result = pycbc_glue.segments.segmentlist([pycbc_glue.segments.segment(-pycbc_glue.segments.infinity(), pycbc_glue.segments.infinity())]) for xmldoc in xmldocs:...
add_to_segment_summary(outdoc, proc_id, seg_def_id, result) # If we're preserving, also load up everything into the output document. if preserve: # Add them to the output document map(lambda x: outdoc.appendChild(x.childNodes[0]), xmldocs) # Merge the ligolw elements and tables ligolw_add.merge_ligolws(outdoc) ligolw_a...
def run_segment_operation(outdoc, filenames, segments, use_segment_table, operation, result_name = 'RESULT', preserve = True): """ Performs an operation (intersect or union) across a set of segments. That is, given a set of files each with segment definers DMT-FLAG1, DMT-FLAG2 etc and a list of segments DMT-FLAG1,DMT-F...
sgmntlist = pycbc_glue.segments.segmentlist([]) for key in keys: sgmntlist |= find_segments(indoc, key, use_segment_table) elif operation == DIFF: sgmntlist = find_segments(indoc, keys[0], use_segment_table) for key in keys[1:]: sgmntlist -= find_segments(indoc, key, use_segment_table) else: raise NameError("%s is not ...
def __setWildcardSymbol(self, value): """self.__wildcardSymbol variable setter""" errors = [] if not value is str and not value.split(): errors.append('wildcardSymbol_ERROR : Symbol : must be char or string!') else: self.__wildcardSymbol = value if errors: view.Tli.showErrors('SymbolError', errors)
def __setParentSymbol(self, value): """self.__parentSymbol variable setter""" errors = [] if not value is str and not value.split(): errors.append('parentSymbol_ERROR : Symbol : must be char or string!') else: self.__parentSymbol = value if errors: view.Tli.showErrors('SymbolError', errors)
def __tableStringParser(self, tableString): """ Will parse and check tableString parameter for any invalid strings. Args: tableString (str): Standard table string with header and decisions. Raises: ValueError: tableString is empty. ValueError: One of the header element is not unique. ValueError: Missing data value. Val...
tableString.split() if len(split) == len(header): decisions.append(split) else: error.append('Row: {}==> missing: {} data'.format( str(i).ljust(4), str(len(header) - len(split)).ljust(2)) ) if error: view.Tli.showErrors('TableStringError', error) else: return [header, decisions]
def __replaceSpecialValues(self, decisions): """ Will replace special values in decisions array. Args: decisions (array of array of str): Standard decision array format. Raises: ValueError: Row element don't have parent value. Returns: New decision array with updated values. """ error = [] for row, line in enumerate(de...
def __toString(self, values): """ Will replace dict values with string values Args: values (dict): Dictionary of values Returns: Updated values dict """ for key in values: if not values[key] is str: values[key] = str(values[key]) return values
def __valueKeyWithHeaderIndex(self, values): """ This is hellper function, so that we can mach decision values with row index as represented in header index. Args: values (dict): Normaly this will have dict of header values and values from decision Return: >>> return() { values[headerName] : int(headerName index in hea...
def __checkDecisionParameters(self, result, **values): """ Checker of decision parameters, it will raise ValueError if finds something wrong. Args: result (array of str): See public decision methods **values (array of str): See public decision methods Raise: ValueError: Result array none. ValueError: Values dict none. ...
is not in header!') elif not values[header].split(): error.append('Variable (' + header + ') in values is empty string') if error: return error
def __getDecision(self, result, multiple=False, **values): """ The main method for decision picking. Args: result (array of str): What values you want to get in return array. multiple (bolean, optional): Do you want multiple result if it finds many maching decisions. **values (dict): What should finder look for, (heade...
if multiple: if machingData: return machingData # Return none if not found (not string so # not found value can be recognized return dict((key, None) for key in result)
def decisionCall(self, callback, result, **values): """ The decision method with callback option. This method will find matching row, construct a dictionary and call callback with dictionary. Args: callback (function): Callback function will be called when decision will be finded. result (array of str): Array of header...
def decision(self, result, **values): """ The decision method with callback option. This method will find matching row, construct a dictionary and call callback with dictionary. Args: callback (function): Callback function will be called when decision will be finded. result (array of str): Array of header string **valu...
def allDecisions(self, result, **values): """ Joust like self.decision but for multiple finded values. Returns: Arrays of arrays of finded elements or if finds only one mach, array of strings. """ data = self.__getDecision(result, multiple=True, **values) data = [data[value] for value in result] if len(data) == 1: retu...
def find_server(region='EU-London', mode=None): """ Returns `(address, token)`, both strings. `mode` is the game mode of the requested server. It can be `'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all". The returned `address` is in `'IP:port'` format. Makes a request to http://m.agar.io to get addre...