code
stringlengths
1
18.2k
def as_id_dict(self): """ Return table as a dictionary mapping experiment_id, time_slide_id, veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id. """ d = {} for row in self: if row.experiment_id not in d: d[row.experiment_id] = {} if (row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) in...
def get_expr_summ_id(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None): """ Return the expr_summ_id for the row in the table whose experiment_id, time_slide_id, veto_def_name, and datatype match the given. If sim_proc_id, will retrieve the injection run matching that sim_proc_id. If a mat...
def write_experiment_summ(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None ): """ Writes a single entry to the experiment_summ table. This can be used for either injections or non-injection experiments. However, it is recommended that this only be used for injection experiments; for non-i...
def write_non_injection_summary(self, experiment_id, time_slide_dict, veto_def_name, write_all_data = True, write_playground = True, write_exclude_play = True, return_dict = False): """ Method for writing a new set of non-injection experiments to the experiment summary table. This ensures that for every entry in the ex...
is slide @veto_def_name: the name of the vetoes applied @write_all_data: if set to True, writes a zero-lag row who's datatype column is set to 'all_data' @write_playground: same, but datatype is 'playground' @write_exclude_play: same, but datatype is 'exclude_play' @return_dict: if set to true, returns an id_dict of th...
def add_nevents(self, experiment_summ_id, num_events, add_to_current = True): """ Add num_events to the nevents column in a specific entry in the table. If add_to_current is set to False, will overwrite the current nevents entry in the row with num_events. Otherwise, default is to add num_events to the current value. N...
def get_experiment_summ_ids( self, coinc_event_id ): """ Gets all the experiment_summ_ids that map to a given coinc_event_id. """ experiment_summ_ids = [] for row in self: if row.coinc_event_id == coinc_event_id: experiment_summ_ids.append(row.experiment_summ_id) if len(experiment_summ_ids) == 0: raise ValueError("'%s'...
def get_column(self, column): """@returns: an array of column values for each row in the table @param column: name of column to return @returntype: numpy.ndarray """ if column.lower() == 'q': return self.get_q else: return self.getColumnByName(column).asarray()
def ifocut(self, ifo, inplace=False): """ Return a SnglInspiralTable with rows from self having IFO equal to the given ifo. If inplace, modify self directly, else create a new table and fill it. """ if inplace: iterutils.inplace_filter(lambda row: row.ifo == ifo, self) return self else: ifoTrigs = self.copy() ifoTrigs....
def getslide(self,slide_num): """ Return the triggers with a specific slide number. @param slide_num: the slide number to recover (contained in the event_id) """ slideTrigs = self.copy() slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num) return slideTrigs
def get_id_parts(self): """ Return the three pieces of the int_8s-style sngl_inspiral event_id. """ int_event_id = int(self.event_id) a = int_event_id // 1000000000 slidenum = (int_event_id % 1000000000) // 100000 b = int_event_id % 100000 return int(a), int(slidenum), int(b)
def get_slide_number(self): """ Return the slide-number for this trigger """ a, slide_number, b = self.get_id_parts() if slide_number > 5000: slide_number = 5000 - slide_number return slide_number
def get_null_snr(self): """ Get the coherent Null SNR for each row in the table. """ null_snr_sq = self.get_coinc_snr()**2 - self.get_column('snr')**2 null_snr_sq[null_snr_sq < 0] = 0. return null_snr_sq**(1./2.)
def get_sigmasqs(self, instruments=None): """ Return dictionary of single-detector sigmas for each row in the table. """ if len(self): if not instruments: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) return dict((ifo, self.get_sigmasq(ifo))\ for ifo in instruments) else: return dict()
def get_sngl_snrs(self, instruments=None): """ Get the single-detector SNRs for each row in the table. """ if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_snr(ifo))\ for ifo in instruments)
def get_sngl_chisqs(self, instruments=None): """ Get the single-detector \chi^2 for each row in the table. """ if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_chisq(ifo))\ for ifo in instrum...
def get_sngl_bank_chisqs(self, instruments=None): """ Get the single-detector \chi^2 for each row in the table. """ if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_bank_chisq(ifo))\ for ifo ...
def get_sngl_cont_chisqs(self, instruments=None): """ Get the single-detector \chi^2 for each row in the table. """ if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sngl_cont_chisq(ifo))\ for ifo ...
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): """ Get the BestNR statistic for each row in the table """ return [row.get_bestnr(index=index, nhigh=nhigh, null_snr_threshold=null_snr_threshold, null_grad_thresh=null_grad_thresh, null_grad_val=null_grad...
def get_null_snr(self): """ Get the coherent Null SNR for this row. """ null_snr_sq = (numpy.asarray(self.get_sngl_snrs().values())**2)\ .sum() - self.snr**2 if null_snr_sq < 0: return 0 else: return null_snr_sq**(1./2.)
def get_sngl_snrs(self): """ Return a dictionary of single-detector SNRs for this row. """ return dict((ifo, self.get_sngl_snr(ifo)) for ifo in\ instrument_set_from_ifos(self.ifos))
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): """ Return the BestNR statistic for this row. """ # weight SNR by chisq bestnr = self.get_new_snr(index=index, nhigh=nhigh, column="chisq") if len(self.get_ifos()) < 3: return bestnr # recontour null SNR t...
def get(self, segment_def_id = None): """ Return a segmentlist object describing the times spanned by the segments carrying the given segment_def_id. If segment_def_id is None then all segments are returned. Note: the result is not coalesced, the segmentlist contains the segments as they appear in the table. """ if seg...
def as_dict(self): """ Return a ditionary mapping time slide IDs to offset dictionaries. """ d = {} for row in self: if row.time_slide_id not in d: d[row.time_slide_id] = offsetvector.offsetvector() if row.instrument in d[row.time_slide_id]: raise KeyError("'%s': duplicate instrument '%s'" % (row.time_slide_id, row.ins...
def append_offsetvector(self, offsetvect, process): """ Append rows describing an instrument --> offset mapping to this table. offsetvect is a dictionary mapping instrument to offset. process should be the row in the process table on which the new time_slide table rows will be blamed (or any object with a process_id at...
def get_time_slide_id(self, offsetdict, create_new = None, superset_ok = False, nonunique_ok = False): """ Return the time_slide_id corresponding to the offset vector described by offsetdict, a dictionary of instrument/offset pairs. If the optional create_new argument is None (the default), then the table must contain ...
newly created) matching offset vector. If the optional superset_ok argument is False (the default) then an offset vector in the table is considered to "match" the requested offset vector only if they contain the exact same set of instruments. If the superset_ok argument is True, then an offset vector in the table is co...
vector. If the optional nonunique_ok is True then the return value is the ID of one of the matching offset vectors selected at random. """ # look for matching offset vectors if superset_ok: ids = [id for id, slide in self.as_dict().items() if offsetdict == dict((instrument, offset) for instrument, offset in slide.items...
that's OK, create new vector, return its ID return self.append_offsetvector(offsetdict, create_new)
def get_coinc_def_id(self, search, search_coinc_type, create_new = True, description = None): """ Return the coinc_def_id for the row in the table whose search string and search_coinc_type integer have the values given. If a matching row is not found, the default behaviour is to create a new row and return the ID assig...
type) = ('%s', %d) is not unique" % (search, search_coinc_type)) if len(rows) > 0: return rows[0].coinc_def_id # coinc type not found in table if not create_new: raise KeyError((search, search_coinc_type)) row = self.RowType() row.coinc_def_id = self.get_next_id() row.search = search row.search_coinc_type = search_coin...
def apply_to_segmentlist(self, seglist): """ Apply our low and high windows to the segments in a segmentlist. """ for i, seg in enumerate(seglist): seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window)
def synchronizeLayout(primary, secondary, surface_size): """Synchronizes given layouts by normalizing height by using max height of given layouts to avoid transistion dirty effects. :param primary: Primary layout used. :param secondary: Secondary layout used. :param surface_size: Target surface size on which layout wil...
def draw_key(self, surface, key): """Default drawing method for key. Draw the key accordingly to it type. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ if isinstance(key, VSpaceKey): self.draw_space_key(surface, key) elif isinstance(key, VBackKey): self.draw_back_key(sur...
def draw_character_key(self, surface, key, special=False): """Default drawing method for key. Key is drawn as a simple rectangle filled using this cell style background color attribute. Key value is printed into drawn cell using internal font. :param surface: Surface background should be drawn in. :param key: Target ke...
def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.value = u'\u21ea' self.draw_character_key(surface, key, True)
def draw_special_char_key(self, surface, key): """Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'#' if key.is_activated(): key.value = u'Ab' self.draw_character_key(surface, key, True)
def is_touched(self, position): """Hit detection method. Indicates if this key has been hit by a touch / click event at the given position. :param position: Event position. :returns: True is the given position collide this key, False otherwise. """ return position[0] >= self.position[0] and position[0] <= self.position...
def add_key(self, key, first=False): """Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end. """ if first: self.keys = [key] + self.keys else: self.keys.append(key) if isinstance(key, VSpaceKey): self.space = k...
def set_size(self, position, size, padding): """Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param position: Position of this row. :param size: Size of th...
def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_keys = [VBackKey()] if self.allow_uppercase: special_keys.append(VUp...
def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the layout model is empty. """ r = len(self.rows)...
def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position = (0, surface_size[1] - self.size[1]) y = self.position[1]...
def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0
def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value = key.value.upper() else: key.value = key.value.lower()
def get_key_at(self, position): """Retrieves if any key is located at the given position :param position: Position to check key at. :returns: The located key if any at the given position, None otherwise. """ for row in self.rows: if position in row: for key in row.keys: if key.is_touched(position): return key return No...
def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: self.renderer.draw_key(self.surface, key)
def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate()
def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate()
def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: self.on_key_down(key) elif event.type == MOUSEBUTTONUP: self.on_key_up() elif event.typ...
def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key)
def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) self.last_pressed = None
def same_player(self, other): """ Compares name and color. Returns True if both are owned by the same player. """ return self.name == other.name \ and self.color == other.color
def reset(self): """ Clears the `cells` and leaderboards, and sets all corners to `0,0`. """ self.cells.clear() self.leaderboard_names.clear() self.leaderboard_groups.clear() self.top_left.set(0, 0) self.bottom_right.set(0, 0)
def reset(self): """ Clears `nick` and `own_ids`, sets `center` to `world.center`, and then calls `cells_changed()`. """ self.own_ids.clear() self.nick = '' self.center = self.world.center self.cells_changed()
def cells_changed(self): """ Calculates `total_size`, `total_mass`, `scale`, and `center`. Has to be called when the controlled cells (`own_ids`) change. """ self.total_size = sum(cell.size for cell in self.own_cells) self.total_mass = sum(cell.mass for cell in self.own_cells) self.scale = pow(min(1.0, 64.0 / self.tota...
def visible_area(self): """ Calculated like in the official client. Returns (top_left, bottom_right). """ # looks like zeach has a nice big screen half_viewport = Vec(1920, 1080) / 2 / self.scale top_left = self.world.center - half_viewport bottom_right = self.world.center + half_viewport return top_left, bottom_right
def has_segment_tables(xmldoc, name = None): """ Return True if the document contains a complete set of segment tables. Returns False otherwise. If name is given and not None then the return value is True only if the document's segment tables, if present, contain a segment list by that name. """ try: names = lsctables....
def segmenttable_get_by_name(xmldoc, name): """ Retrieve the segmentlists whose name equals name. The result is a segmentlistdict indexed by instrument. The output of this function is not coalesced, each segmentlist contains the segments as found in the segment table. NOTE: this is a light-weight version of the .get_by...
dict((row.segment_def_id, row.instruments) for row in def_table if row.name == name) # # populate result segmentlistdict object from segment_def_map table # and index # instruments = set(instrument for instruments in instrument_index.values() for instrument in instruments) result = segments.segmentlistdict((instrument,...
def sort(self, *args): """ Sort the internal segment lists. The optional args are passed to the .sort() method of the segment lists. This can be used to control the sort order by providing an alternate comparison function. The default is to sort by start time with ties broken by end time. """ self.valid.sort(*args) sel...
def insert_from_segwizard(self, fileobj, instruments, name, version = None, comment = None): """ Parse the contents of the file object fileobj as a segwizard-format segment list, and insert the result as a new list of "active" segments into this LigolwSegments object. A new entry will be created in the segment_definer ...
def insert_from_segmentlistdict(self, seglists, name, version = None, comment = None, valid=None): """ Insert the segments from the segmentlistdict object seglists as a new list of "active" segments into this LigolwSegments object. The dictionary's keys are assumed to provide the instrument name for each segment list. ...
def optimize(self): """ Identifies segment lists that differ only in their instruments --- they have the same valid and active segments, the same name, version and the same comment --- and then deletes all but one of them, leaving just a single list having the union of the instruments. """ self.sort() segment_lists = d...
def get_by_name(self, name, clip_to_valid = False): """ Retrieve the active segmentlists whose name equals name. The result is a segmentlistdict indexed by instrument. All segmentlist objects within it will be copies of the contents of this object, modifications will not affect the contents of this object. If clip_to_v...
ValueError("multiple '%s' segmentlists for instrument '%s'" % (name, instrument)) result[instrument] = segs.copy() return result
def finalize(self, process_row = None): """ Restore the LigolwSegmentList objects to the XML tables in preparation for output. All segments from all segment lists are inserted into the tables in time order, but this is NOT behaviour external applications should rely on. This is done simply in the belief that it might a...
self.segment_def_table.sync_next_id() self.segment_table.sync_next_id() self.segment_sum_table.sync_next_id() # # put all segment lists in time order # self.sort() # # generator function to convert segments into row objects, # each paired with the table to which the row is to be # appended # def row_generator(segs, tar...
segment_def_row.instruments = ligolw_segment_list.instruments segment_def_row.name = ligolw_segment_list.name segment_def_row.version = ligolw_segment_list.version segment_def_row.comment = ligolw_segment_list.comment self.segment_def_table.append(segment_def_row) row_generators.append(row_generator(ligolw_segment_list...
def add_graph(self, rhs_graph): """ Adds a graph to self.g :param rhs_graph: the graph to add :return: itself """ rhs_graph = self.__substitute_names_in_graph(rhs_graph) self.g = self.__merge_graphs(self.g, rhs_graph) return self
def set(self, code): """ Executes the code and apply it to the self.g :param code: the LISP code to execute :return: True/False, depending on the result of the LISP code """ if self.update: self.vertices_substitution_dict, self.edges_substitution_dict, self.match_info\ = self.match.get_variables_substitution_dictionari...
def delete_list(self, variables): """ Deletes a list of vertices/edges from self.g :param variables: the names of the variables to delete :return: """ variables = set(self.__substitute_names_in_list(variables)) self.update = False self.g.delete_vertices(self.g.vs.select(name_in=variables)) self.g.delete_edges(self.g.es...
def build_variables(self, variable_placeholders): """ :param variables: The list of vertices/edges to return :return: a dict where the keys are the names of the variables to return, the values are the JSON of the properties of these variables """ variables = self.__substitute_names_in_list(variable_placeholders) attrib...
def get_lock(lockfile): """ Tries to write a lockfile containing the current pid. Excepts if the lockfile already contains the pid of a running process. Although this should prevent a lock from being granted twice, it can theoretically deny a lock unjustly in the unlikely event that the original process is gone but ano...
check for a pid therein pidfile.seek(0) pidfile_pid = pidfile.readline().strip() if pidfile_pid.isdigit(): if pycbc_glue.utils.pid_exists(int(pidfile_pid)): raise RuntimeError, ("pidfile %s contains pid (%s) of a running " "process" % (lockfile, pidfile_pid)) else: print ("pidfile %s contains stale pid %s; writing new ...
def confirm_lock(lockfile): """ Confirm that the given lockfile contains our pid. Should be entirely unecessary, but paranoia always served me well. """ pidfile = open(lockfile, "r") pidfile_pid = pidfile.readline().strip() pidfile.close() if int(pidfile_pid) != os.getpid(): raise RuntimeError, ("pidfile %s contains pi...
def _argsdicts( args, mydict ): """A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1.""" if len( args ) == 0: args = None, elif len( args ) == 1: args = _totuple( args[0] ) else: raise Exception( "We should have never gotten here." ) mykeys = list( mydict.key...
thisarg, thisdict
def _totuple( x ): """Utility stuff to convert string, int, long, float, None or anything to a usable tuple.""" if isinstance( x, basestring ): out = x, elif isinstance( x, ( int, long, float ) ): out = str( x ), elif x is None: out = None, else: out = tuple( x ) return out
def escape( text, newline=False ): """Escape special html characters.""" if isinstance( text, basestring ): if '&' in text: text = text.replace( '&', '&amp;' ) if '>' in text: text = text.replace( '>', '&gt;' ) if '<' in text: text = text.replace( '<', '&lt;' ) if '\"' in text: text = text.replace( '\"', '&quot;' ) if ...
def unescape( text ): """Inverse of escape.""" if isinstance( text, basestring ): if '&amp;' in text: text = text.replace( '&amp;', '&' ) if '&gt;' in text: text = text.replace( '&gt;', '>' ) if '&lt;' in text: text = text.replace( '&lt;', '<' ) if '&quot;' in text: text = text.replace( '&quot;', '\"' ) return text
def render( self, tag, single, between, kwargs ): """Append the actual tags to content.""" out = "<%s" % tag for key, value in list( kwargs.items( ) ): if value is not None: # when value is None that means stuff like <... checked> key = key.strip('_') # strip this so class_ will mean class, etc. if key == 'http_equiv':...
out if self.parent is not None: self.parent.content.append( out ) else: return out
def close( self ): """Append a closing tag unless element has only opening tag.""" if self.tag in self.parent.twotags: self.parent.content.append( "</%s>" % self.tag ) elif self.tag in self.parent.onetags: raise ClosingError( self.tag ) elif self.parent.mode == 'strict_html' and self.tag in self.parent.deptags: raise D...
def open( self, **kwargs ): """Append an opening tag.""" if self.tag in self.parent.twotags or self.tag in self.parent.onetags: self.render( self.tag, False, None, kwargs ) elif self.mode == 'strict_html' and self.tag in self.parent.deptags: raise DeprecationError( self.tag )
def init( self, lang='en', css=None, metainfo=None, title=None, header=None, footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None, base=None ): """This method is used for complete documents with appropriate doctype, encoding, title, etc information. For an HTML/XML snippet omit this metho...
of the <body> element as <body key='value' ... > (ignored in xml mode) script -- dictionary containing src:type pairs, <script type='text/type' src=src></script> or a list of [ 'src1', 'src2', ... ] in which case 'javascript' is assumed for all title -- the title of the document as a string to be inserted into a title ...
to first line of the document as <?xml version='1.0' encoding='myencoding' ?> in xml mode (ignored in html mode) doctype -- the document type string, defaults to <!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'> in html mode (ignored in xml mode)""" self._full = True if self.mode == 'strict_html' or self....
bodyattrs is not None: self.body( **bodyattrs ) else: self.body( ) if header is not None: self.content.append( header ) if footer is not None: self.footer.append( footer ) elif self.mode == 'xml': if doctype is None: if encoding is not None: doctype = "<?xml version='1.0' encoding='%s' ?>" % encoding else: doctype = "<...
def css( self, filelist ): """This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.""" if isinstance( filelist, basestring ): self.link( href=filelist, rel='stylesheet', type='text/css', media='all' ) else: for file in filelist: self.link( href=file, rel='s...
def metainfo( self, mydict ): """This convenience function is only useful for html. It adds meta information via the <meta> element, the argument is a dictionary of the form { 'name':'content' }.""" if isinstance( mydict, dict ): for name, content in list( mydict.items( ) ): self.meta( name=name, content=content ) else...
def scripts( self, mydict ): """Only useful in html, mydict is dictionary of src:type pairs or a list of script sources [ 'src1', 'src2', ... ] in which case 'javascript' is assumed for type. Will be rendered as <script type='text/type' src=src></script>""" if isinstance( mydict, dict ): for src, type in list( mydict.i...
def MultiIter(*sequences): """ A generator for iterating over the elements of multiple sequences simultaneously. With N sequences given as input, the generator yields all possible distinct N-tuples that contain one element from each of the input sequences. Example: >>> x = MultiIter([0, 1, 2], [10, 11]) >>> list(x) [(0...
12) >>> for x in MultiIter(*map(range, lengths)): ... pass ... runs approximately 5 times faster if the lengths list is reversed. """ if len(sequences) > 1: # FIXME: this loop is about 5% faster if done the other # way around, if the last list is iterated over in the # inner loop. but there is code, like snglcoinc.py i...
def choices(vals, n): """ A generator for iterating over all choices of n elements from the input sequence vals. In each result returned, the original order of the values is preserved. Example: >>> x = choices(["a", "b", "c"], 2) >>> list(x) [('a', 'b'), ('a', 'c'), ('b', 'c')] The order of combinations in the output s...
(('a', 'c'), ('1', '3')), (('b', 'c'), ('2', '3'))] Furthermore, the order of combinations in the output sequence is such that if the input list has n elements, and one constructs the combinations choices(input, m), then each combination in choices(input, n-m).reverse() contains the elements discarded in forming the co...
""" if n == len(vals): yield tuple(vals) elif n > 1: n -= 1 for i, v in enumerate(vals[:-n]): v = (v,) for c in choices(vals[i+1:], n): yield v + c elif n == 1: for v in vals: yield (v,) elif n == 0: yield () else: # n < 0 raise ValueError(n)
def uniq(iterable): """ Yield the unique items of an iterable, preserving order. http://mail.python.org/pipermail/tutor/2002-March/012930.html Example: >>> x = uniq([0, 0, 2, 6, 2, 0, 5]) >>> list(x) [0, 2, 6, 5] """ temp_dict = {} for e in iterable: if e not in temp_dict: yield temp_dict.setdefault(e, e)
def nonuniq(iterable): """ Yield the non-unique items of an iterable, preserving order. If an item occurs N > 0 times in the input sequence, it will occur N-1 times in the output sequence. Example: >>> x = nonuniq([0, 0, 2, 6, 2, 0, 5]) >>> list(x) [0, 2, 0] """ temp_dict = {} for e in iterable: if e in temp_dict: yiel...
def flatten(sequence, levels = 1): """ Example: >>> nested = [[1,2], [[3]]] >>> list(flatten(nested)) [1, 2, [3]] """ if levels == 0: for x in sequence: yield x else: for x in sequence: for y in flatten(x, levels - 1): yield y