code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self.name == other.name \
and self.color == other.color | def same_player(self, other) | Compares name and color.
Returns True if both are owned by the same player. | 5.103254 | 4.549098 | 1.121817 |
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 the `cells` and leaderboards, and sets all corners to `0,0`. | 4.491981 | 3.010336 | 1.492186 |
self.own_ids.clear()
self.nick = ''
self.center = self.world.center
self.cells_changed() | def reset(self) | Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`. | 16.982515 | 2.419326 | 7.019523 |
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.total_size), 0.4) \
if self.total_size > 0 else 1.0
if self.own_ids:
left = min(cell.pos.x for c... | def cells_changed(self) | Calculates `total_size`, `total_mass`, `scale`, and `center`.
Has to be called when the controlled cells (`own_ids`) change. | 2.321463 | 1.827906 | 1.270012 |
# 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 visible_area(self) | Calculated like in the official client.
Returns (top_left, bottom_right). | 7.028711 | 6.084659 | 1.155153 |
try:
names = lsctables.SegmentDefTable.get_table(xmldoc).getColumnByName("name")
lsctables.SegmentTable.get_table(xmldoc)
lsctables.SegmentSumTable.get_table(xmldoc)
except (ValueError, KeyError):
return False
return name is None or name in names | 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. | 4.891604 | 4.625626 | 1.057501 |
#
# find required tables
#
def_table = lsctables.SegmentDefTable.get_table(xmldoc)
seg_table = lsctables.SegmentTable.get_table(xmldoc)
#
# segment_def_id --> instrument names mapping but only for
# segment_definer entries bearing the requested name
#
instrument_index = dict((row.segment_def_id, row.inst... | 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_name() method
of the LigolwSegments cl... | 4.133265 | 3.855981 | 1.07191 |
self.valid.sort(*args)
self.active.sort(*args) | 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. | 6.755734 | 9.258779 | 0.729657 |
self.add(LigolwSegmentList(active = segmentsUtils.fromsegwizard(fileobj, coltype = LIGOTimeGPS), instruments = instruments, name = name, version = version, comment = comment)) | 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
table for the segment list, and instruments, name and
comment are used to populate the... | 16.811125 | 8.651583 | 1.943127 |
for instrument, segments in seglists.items():
if valid is None:
curr_valid = ()
else:
curr_valid = valid[instrument]
self.add(LigolwSegmentList(active = segments, instruments = set([instrument]), name = name, version = version, comment = comment, valid = curr_valid)) | 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. A
new entry will be created in the segment_definer table for
the segment lists, and the dic... | 4.920895 | 3.355125 | 1.46668 |
self.sort()
segment_lists = dict(enumerate(self))
for target, source in [(idx_a, idx_b) for (idx_a, seglist_a), (idx_b, seglist_b) in iterutils.choices(segment_lists.items(), 2) if seglist_a.valid == seglist_b.valid and seglist_a.active == seglist_b.active and seglist_a.name == seglist_b.name and seglist_a.ver... | 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. | 3.453909 | 2.43237 | 1.419977 |
result = segments.segmentlistdict()
for seglist in self:
if seglist.name != name:
continue
segs = seglist.active
if clip_to_valid:
# do not use in-place intersection
segs = segs & seglist.valid
for instrument in seglist.instruments:
if instrument in result:
raise ValueError("mult... | 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_valid is True then the
segmentlists will be i... | 4.315224 | 3.019806 | 1.428974 |
if process_row is not None:
process_id = process_row.process_id
elif self.process is not None:
process_id = self.process.process_id
else:
raise ValueError("must supply a process row to .__init__()")
#
# ensure ID generators are synchronized with table contents
#
self.segment_def_table.sync_n... | 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 assist in
constructing well balanc... | 2.96183 | 2.738956 | 1.081372 |
rhs_graph = self.__substitute_names_in_graph(rhs_graph)
self.g = self.__merge_graphs(self.g, rhs_graph)
return self | def add_graph(self, rhs_graph) | Adds a graph to self.g
:param rhs_graph: the graph to add
:return: itself | 4.127818 | 4.817598 | 0.856821 |
if self.update:
self.vertices_substitution_dict, self.edges_substitution_dict, self.match_info\
= self.match.get_variables_substitution_dictionaries(self.g, self.matching_graph)
try:
self.matching_graph = self.__apply_code_to_graph(code, self.matching_gra... | 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 | 4.629021 | 4.246416 | 1.090101 |
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.select(name_in=variables)) | def delete_list(self, variables) | Deletes a list of vertices/edges from self.g
:param variables: the names of the variables to delete
:return: | 3.693414 | 3.861473 | 0.956478 |
variables = self.__substitute_names_in_list(variable_placeholders)
attributes = {}
for i, variable in enumerate(variables):
placeholder_name = variable_placeholders[i]
try:
vertices = self.g.vs.select(name=variable)
attributes[plac... | 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 | 2.392302 | 2.295915 | 1.041982 |
pidfile = open(lockfile, "a+")
# here we do some meta-locking by getting an exclusive lock on the
# pidfile before reading it, to prevent two daemons from seeing a
# stale lock at the same time, and both trying to run
try:
fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
... | 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 another unrel... | 4.531033 | 4.542099 | 0.997564 |
pidfile = open(lockfile, "r")
pidfile_pid = pidfile.readline().strip()
pidfile.close()
if int(pidfile_pid) != os.getpid():
raise RuntimeError, ("pidfile %s contains pid %s; expected pid %s!" %
(lockfile, os.getpid(), pidfile_pid))
return True | def confirm_lock(lockfile) | Confirm that the given lockfile contains our pid.
Should be entirely unecessary, but paranoia always served me well. | 3.062516 | 2.717602 | 1.126919 |
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.keys( ) )
myvalues = list( map( _totuple, list( mydict.values( ) ) ) )
maxlength = max( list... | def _argsdicts( args, mydict ) | A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1. | 2.640992 | 2.515743 | 1.049786 |
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 _totuple( x ) | Utility stuff to convert string, int, long, float, None or anything to a usable tuple. | 3.048012 | 2.399562 | 1.270237 |
if isinstance( text, basestring ):
if '&' in text:
text = text.replace( '&', '&' )
if '>' in text:
text = text.replace( '>', '>' )
if '<' in text:
text = text.replace( '<', '<' )
if '\"' in text:
text = text.replace( '\"... | def escape( text, newline=False ) | Escape special html characters. | 1.669033 | 1.601891 | 1.041914 |
if isinstance( text, basestring ):
if '&' in text:
text = text.replace( '&', '&' )
if '>' in text:
text = text.replace( '>', '>' )
if '<' in text:
text = text.replace( '<', '<' )
if '"' in text:
text =... | def unescape( text ) | Inverse of escape. | 1.670952 | 1.603517 | 1.042054 |
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_equ... | def render( self, tag, single, between, kwargs ) | Append the actual tags to content. | 3.806444 | 3.615125 | 1.052922 |
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 DeprecationErr... | def close( self ) | Append a closing tag unless element has only opening tag. | 6.090851 | 4.677103 | 1.30227 |
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 open( self, **kwargs ) | Append an opening tag. | 9.671753 | 7.919759 | 1.221218 |
self._full = True
if self.mode == 'strict_html' or self.mode == 'loose_html':
if doctype is None:
doctype = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"
self.header.append( doctype )
self.html( lang=lang )
se... | 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 method.
lang -- language, usually a two character string, will appear
as <html lang='en'> in html mode (ignored in xml mode)
... | 2.022035 | 1.953339 | 1.035169 |
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='stylesheet', type='text/css', media='all' ) | def css( self, filelist ) | This convenience function is only useful for html.
It adds css stylesheet(s) to the document via the <link> element. | 2.420427 | 1.991295 | 1.215504 |
if isinstance( mydict, dict ):
for name, content in list( mydict.items( ) ):
self.meta( name=name, content=content )
else:
raise TypeError( "Metainfo should be called with a dictionary argument of name:content pairs." ) | 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' }. | 5.016935 | 3.654862 | 1.372674 |
if isinstance( mydict, dict ):
for src, type in list( mydict.items( ) ):
self.script( '', src=src, type='text/%s' % type )
else:
try:
for src in mydict:
self.script( '', src=src, type='text/javascript' )
ex... | 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> | 4.691998 | 3.105642 | 1.510798 |
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 in
# pylal, that has been optimized for the current order and
# would need to be reoptimized if this function were to be... | 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, 10), (1, 10), (2, 1... | 8.347928 | 8.525401 | 0.979183 |
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 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 sequence is alwa... | 2.261926 | 2.790288 | 0.810643 |
temp_dict = {}
for e in iterable:
if e not in temp_dict:
yield temp_dict.setdefault(e, e) | 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] | 3.60101 | 4.183176 | 0.860832 |
temp_dict = {}
for e in iterable:
if e in temp_dict:
yield e
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] | 3.762793 | 4.831503 | 0.778804 |
if levels == 0:
for x in sequence:
yield x
else:
for x in sequence:
for y in flatten(x, levels - 1):
yield y | def flatten(sequence, levels = 1) | Example:
>>> nested = [[1,2], [[3]]]
>>> list(flatten(nested))
[1, 2, [3]] | 1.80087 | 1.925604 | 0.935224 |
target = 0
for source in xrange(len(sequence)):
if func(sequence[source]):
sequence[target] = sequence[source]
target += 1
del sequence[target:] | 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 part of the sequence is lef... | 2.743729 | 3.344241 | 0.820434 |
reverse = kwargs.pop("reverse", False)
keyfunc = kwargs.pop("key", lambda x: x) # 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(nextva... | 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=lambda x: x * x))
[0, 1, 1.... | 2.827003 | 2.90559 | 0.972953 |
if not 0 <= lo < hi:
raise ValueError("require 0 <= lo < hi: lo = %d, hi = %d" % (lo, hi))
if n <= 0.:
raise ValueError("n <= 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
... | 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 integers are drawn goes
as [inte... | 4.249363 | 3.925895 | 1.082394 |
return tuple.__new__(self.__class__, (self[0] + x, self[1] + x)) | def shift(self, x) | Return a new segment whose bounds are given by adding x to
the segment's upper and lower bounds. | 4.219558 | 4.53246 | 0.930964 |
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, max) | 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. | 3.048728 | 2.702245 | 1.12822 |
for i, seg in enumerate(self):
if item in seg:
return i
raise ValueError(item) | 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. | 4.057838 | 3.001951 | 1.351734 |
i = _bisect_left(self, other)
return ((i != 0) and (other[0] < self[i-1][1])) or ((i != len(self)) and (other[1] > self[i][0])) | 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. | 2.928783 | 3.202167 | 0.914625 |
# if either has zero length, the answer is False
if not (self and other):
return False
# walk through both lists in order, searching for a match
i = j = 0
seg = self[0]
otherseg = other[0]
while True:
if seg[1] <= otherseg[0]:
i += 1
if i >= len(self):
return False
seg = self[i]
... | 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. | 2.384734 | 2.187659 | 1.090085 |
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[j][1])
j += 1
if lo != hi:
self[i] = segment(lo, hi)
i += 1
del self[i : ]
return self | 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). | 2.643492 | 2.259124 | 1.17014 |
for i in xrange(len(self)):
self[i] = self[i].protract(x)
return self.coalesce() | def protract(self, x) | Execute the .protract() method on each segment in the list
and coalesce the result. Segmentlist is modified in place. | 3.863627 | 3.277376 | 1.178878 |
for i in xrange(len(self)):
self[i] = self[i].contract(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. | 4.152675 | 3.359069 | 1.236258 |
for i in xrange(len(self)):
self[i] = self[i].shift(x)
return self | 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. | 3.324263 | 3.036561 | 1.094746 |
for key, value in d.iteritems():
if key in self:
self[key] = value | 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 segmentlist... | 2.895565 | 3.750884 | 0.771969 |
if keys is None:
keys = self
new = self.__class__()
for key in keys:
new[key] = _shallowcopy(self[key])
dict.__setitem__(new.offsets, key, self.offsets[key])
return new | 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 will
not affect the ori... | 3.503284 | 3.412126 | 1.026716 |
return dict((key, func(value)) for key, value in self.iteritems()) | 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} | 4.438911 | 6.611312 | 0.671412 |
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 extent_all(self) | Return the result of running .extent() on the union of all
lists in the dictionary. | 3.93097 | 3.529579 | 1.113722 |
return [key for key, segs in self.items() if x 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'] | 6.412792 | 8.941489 | 0.717195 |
return any(value.intersects_segment(seg) for value in self.itervalues()) | def intersects_segment(self, seg) | Returns True if any segmentlist in self intersects the
segment, otherwise returns False. | 6.861898 | 6.586544 | 1.041806 |
return any(key in self and self[key].intersects(value) for key, value in other.iteritems()) | 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() | 5.401641 | 6.246776 | 0.864709 |
return all(key in self and self[key].intersects(value) for key, value in other.iteritems()) and bool(other) | 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() | 5.965204 | 6.025661 | 0.989967 |
return set(self) == set(other) and all(other[key].intersects(value) for key, value in self.iteritems()) and bool(self) | 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() | 4.960796 | 5.853099 | 0.84755 |
for key, value in other.iteritems():
if key not in self:
self[key] = _shallowcopy(value)
else:
self[key].extend(value) | def extend(self, other) | Appends the segmentlists from other to the corresponding
segmentlists in self, adding new segmentslists to self as
needed. | 2.838572 | 2.816092 | 1.007983 |
for value in self.itervalues():
value.contract(x)
return self | def contract(self, x) | Run .contract(x) on all segmentlists. | 5.823669 | 4.450357 | 1.308585 |
for value in self.itervalues():
value.protract(x)
return self | def protract(self, x) | Run .protract(x) on all segmentlists. | 5.355379 | 4.418022 | 1.212167 |
keys = set(keys)
new = self.__class__()
intersection = self.intersection(keys)
for key in keys:
dict.__setitem__(new, key, _shallowcopy(intersection))
dict.__setitem__(new.offsets, key, self.offsets[key])
return new | 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. | 4.252055 | 3.488425 | 1.218904 |
if keys is not None:
keys = set(keys)
self = tuple(self[key] for key in set(self) & keys)
other = tuple(other[key] for key in set(other) & keys)
else:
self = tuple(self.values())
other = tuple(other.values())
# make sure inner loop is smallest
if len(self) < len(other):
self, other = other,... | 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, keys not present in
both segment list... | 2.34954 | 2.368624 | 0.991943 |
keys = set(keys)
if not keys:
return segmentlist()
seglist = _shallowcopy(self[keys.pop()])
for key in keys:
seglist &= self[key]
return seglist | def intersection(self, keys) | Return the intersection of the segmentlists associated with
the keys in keys. | 4.61096 | 3.24901 | 1.419189 |
# 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 is deferred until after
# the rows are inserted, nothing will get updated. ... | def update_ids(connection, xmldoc, verbose = False) | For internal use only. | 7.920905 | 7.829398 | 1.011688 |
#
# 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 ... | 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 collisions with IDs already in the
database. If preserve_ids is True then IDs are not modifi... | 5.656361 | 5.304234 | 1.066386 |
#
# enable/disable ID remapping
#
orig_DBTable_append = dbtables.DBTable.append
if not preserve_ids:
try:
dbtables.idmap_create(connection)
except sqlite3.OperationalError:
# assume table already exists
pass
dbtables.idmap_sync(connection)
dbtables.DBTable.append = dbtables.DBTable._remapping_... | 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 database. If preserve_ids is True then IDs
are not modified; this will result in database ... | 4.321947 | 4.281242 | 1.009508 |
verbose = kwargs.get("verbose", False)
#
# load documents
#
for n, url in enumerate(urls, 1):
if verbose:
print >>sys.stderr, "%d/%d:" % (n, len(urls)),
insert_from_url(url, contenthandler = contenthandler, **kwargs)
#
# done. build indexes
#
dbtables.build_indexes(contenthandler.connection, verb... | 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. | 4.016701 | 3.815312 | 1.052784 |
xmldoc = ligolw.Document()
xmldoc.appendChild(dbtables.get_xml(connection, table_names))
ligolw_utils.write_filename(xmldoc, filename, gz = (filename or "stdout").endswith(".gz"), verbose = verbose, xsl_file = xsl_file)
# delete cursors
xmldoc.unlink() | 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 tables in that sequence will be
converted. If verbose is True then progress messages will b... | 7.604815 | 6.994441 | 1.087266 |
row = lsctables.SearchSummary()
row.process_id = process.process_id
row.shared_object = shared_object
row.lalwrapper_cvs_tag = lalwrapper_cvs_tag
row.lal_cvs_tag = lal_cvs_tag
row.comment = comment or process.comment
row.instruments = ifos if ifos is not None else process.instruments
row.in_segment = inseg
r... | 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 the newly-created
search_summary table row. | 2.268897 | 2.158652 | 1.051071 |
stbl = lsctables.SearchSummaryTable.get_table(xmldoc)
ptbl = lsctables.ProcessTable.get_table(xmldoc)
return stbl.get_in_segmentlistdict(program and ptbl.get_ids_by_program(program)) | 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 object from
the in segments in those rows.
Note: the segmentlist... | 5.863241 | 5.288644 | 1.108647 |
stbl = lsctables.SearchSummaryTable.get_table(xmldoc)
ptbl = lsctables.ProcessTable.get_table(xmldoc)
return stbl.get_out_segmentlistdict(program and ptbl.get_ids_by_program(program)) | 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 object from
the out segments in those rows.
Note: the segmentlis... | 5.94762 | 5.247691 | 1.133379 |
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)
func = click.option(
... | def common_options(func) | Commonly used command options. | 4.65802 | 4.595713 | 1.013558 |
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.secho('Server public: %s' % session.public_b64) | def get_private_and_public(username, password_verifier, private, preset) | Print out server public and private. | 4.461482 | 4.453253 | 1.001848 |
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.secho('Server session key: %s' % session.key_b64)
click.secho('Server session key proof... | def get_session_data( username, password_verifier, salt, client_public, private, preset) | Print out server session data. | 3.912138 | 3.883018 | 1.007499 |
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' % session.public_b64) | def get_private_and_public(ctx, username, password, private, preset) | Print out server public and private. | 4.15567 | 4.263957 | 0.974604 |
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: %s' % session.key_b64)
click.secho('Client session key proof: %s' % session.key_pro... | def get_session_data(ctx, username, password, salt, server_public, private, preset) | Print out client session data. | 3.658528 | 3.505142 | 1.04376 |
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' % password_verifier)
click.secho('Salt: %s' % salt) | def get_user_data_triplet(username, password) | Print out user data triplet: username, password verifier, salt. | 3.360888 | 2.587609 | 1.298839 |
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... | def cwd_decorator(func) | decorator to change cwd to directory containing rst for this function | 2.955584 | 2.507833 | 1.178541 |
fout = Sio()
etree = et.ElementTree(node)
etree.write(fout)
xml = fout.getvalue()
if pretty:
xml = pretty_xml(xml, True)
return xml | def to_xml(node, pretty=False) | convert an etree node to xml | 4.370075 | 4.352674 | 1.003998 |
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].childNodes[0].toprettyxml("... | def pretty_xml(string_input, add_ns=False) | pretty indent string_input | 3.167274 | 3.191937 | 0.992273 |
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_margin
avail_height -= padding * (height - 1)
column_height = avail_height / height
c... | def add_cell(preso, pos, width, height, padding=1, top_margin=4, left_margin=2) | Add a text frame to current slide | 2.567346 | 2.556344 | 1.004304 |
marker_end_ratio = .459 / 3 # .459cm/3pt
marker_start_ratio = .359 / 3 # .359cm/3pt
stroke_ratio = .106 / 3 # .106cm/3pt
w = float(width[0:width.index("pt")])
sw = w * stroke_ratio
mew = w * marker_end_ratio
msw = w * marker_start_ratio
attribs = {
"svg:stroke-width": "{... | 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="none"
draw:textarea-vertica... | 3.228129 | 2.325601 | 1.388084 |
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_data = self.override_styles(xml_data)
z... | def add_otp_style(self, zip_odp, style_file) | takes the slide content and merges in the style_file | 4.856472 | 4.913542 | 0.988385 |
out = zipwrap.Zippier(filename, "w")
out.write("mimetype", self.mime_type)
for p in self._pictures:
out.write("Pictures/%s" % p.internal_name, p.get_data())
out.write("content.xml", self.to_xml())
if write_style:
out.write("styles.xml", self.style... | 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'] | 3.288184 | 3.175253 | 1.035566 |
par = el("anim:par", attrib={"smil:begin": "next"})
par2 = sub_el(par, "anim:par", attrib={"smil:begin": "0s"})
par3 = sub_el(
par2,
"anim:par",
attrib={
"smil:begin": "0s",
"smil:fill": "hold",
"present... | 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="id1" anim:... | 2.837137 | 1.447593 | 1.959899 |
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_frame_attributes(self, attrib) | For positioning update the frame | 4.019892 | 4.054909 | 0.991364 |
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",
... | def update_style(self, mapping) | Use to update fill-color | 5.237612 | 5.15572 | 1.015884 |
if self.cur_element is None:
self.add_text_frame()
self.cur_element.pending_nodes.append((name, attr)) | 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. | 5.904434 | 5.198679 | 1.135756 |
# pictures should be added the the draw:frame element
self.pic_frame = PictureFrame(self, p)
self.pic_frame.add_node(
"draw:image",
attrib={
"xlink:href": "Pictures/" + p.internal_name,
"xlink:type": "simple",
"xlin... | 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" xlink:show="embed" xlink:a... | 5.092354 | 3.939281 | 1.292711 |
ins = copy.copy(self)
ins._fire_page_number(self.page_number + 1)
return ins | def _copy(self) | needs to update page numbers | 10.91603 | 7.530287 | 1.449617 |
# 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={"pre... | def get_node(self) | return etree Element representing this slide | 5.983422 | 5.462117 | 1.09544 |
# 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._preso._styles_added:
self._preso... | def add_list(self, bl) | note that this pushes the cur_element, but doesn't pop it.
You'll need to do that | 8.034943 | 7.236461 | 1.110341 |
self.push_element()
self._page.append(t.node)
self.cur_element = t | def add_table(self, t) | remember to call pop_element after done with table | 13.953127 | 7.864201 | 1.774259 |
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
... | def update_text(self, mapping) | Iterate over nodes, replace text with mapping | 2.562848 | 2.324714 | 1.102436 |
if not self._in_tag(name):
return
node = self.cur_node
while node.tag != name:
node = node.getparent()
self.cur_node = node.getparent() | def parent_of(self, name) | go to parent of node with name, and set as cur_node. Useful
for creating new paragraphs | 4.457761 | 3.580877 | 1.24488 |
children = self.cur_node.getchildren()
if children:
result = self._is_node(tagname, attributes, node=children[-1])
return result
return False | def _is_last_child(self, tagname, attributes=None) | Check if last child of cur_node is tagname with attributes | 4.860613 | 3.674001 | 1.322976 |
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 = node.... | def _in_tag(self, tagname, attributes=None) | Determine if we are already in a certain tag.
If we give attributes, make sure they match. | 3.207062 | 2.899078 | 1.106235 |
if name == ns("text", "a"):
if parent.tag == ns("draw", "text-box"):
return False
return True | def _check_add_node(self, parent, name) | Returns False if bad to make name a child of parent | 13.780691 | 13.238856 | 1.040928 |
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):
t_styles.update(s.styles)
p... | def _add_styles(self, add_paragraph=True, add_text=True) | Adds paragraph and span wrappers if necessary based on style | 3.391244 | 3.270215 | 1.03701 |
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"))
... | def line_break(self) | insert as many line breaks as the insert_line_break variable says | 5.425764 | 5.05302 | 1.073767 |
self._add_styles(add_p_style, add_t_style)
self._add_pending_nodes()
spaces = []
for i, letter in enumerate(text):
if letter == " ":
spaces.append(letter)
continue
elif len(spaces) == 1:
self._write(" ")
... | 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 the extra spaces | 2.703133 | 2.71966 | 0.993923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.