repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
fractalego/parvusdb
parvusdb/utils/graph_builder.py
GraphBuilder.set
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_dictionaries(self.g, self.matching_graph) try: self.matching_graph = self.__apply_code_to_graph(code, self.matching_graph) except: pass try: code = self.__substitute_names_in_code(code) self.g = self.__apply_code_to_graph(code, self.g) except: pass return True
python
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_dictionaries(self.g, self.matching_graph) try: self.matching_graph = self.__apply_code_to_graph(code, self.matching_graph) except: pass try: code = self.__substitute_names_in_code(code) self.g = self.__apply_code_to_graph(code, self.g) except: pass return True
[ "def", "set", "(", "self", ",", "code", ")", ":", "if", "self", ".", "update", ":", "self", ".", "vertices_substitution_dict", ",", "self", ".", "edges_substitution_dict", ",", "self", ".", "match_info", "=", "self", ".", "match", ".", "get_variables_substit...
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
[ "Executes", "the", "code", "and", "apply", "it", "to", "the", "self", ".", "g" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_builder.py#L32-L51
fractalego/parvusdb
parvusdb/utils/graph_builder.py
GraphBuilder.delete_list
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.select(name_in=variables))
python
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.select(name_in=variables))
[ "def", "delete_list", "(", "self", ",", "variables", ")", ":", "variables", "=", "set", "(", "self", ".", "__substitute_names_in_list", "(", "variables", ")", ")", "self", ".", "update", "=", "False", "self", ".", "g", ".", "delete_vertices", "(", "self", ...
Deletes a list of vertices/edges from self.g :param variables: the names of the variables to delete :return:
[ "Deletes", "a", "list", "of", "vertices", "/", "edges", "from", "self", ".", "g" ]
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_builder.py#L71-L81
fractalego/parvusdb
parvusdb/utils/graph_builder.py
GraphBuilder.build_variables
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) attributes = {} for i, variable in enumerate(variables): placeholder_name = variable_placeholders[i] try: vertices = self.g.vs.select(name=variable) attributes[placeholder_name] = vertices[0].attributes() except: pass for i, variable in enumerate(variables): placeholder_name = variable_placeholders[i] try: edges = self.g.es.select(name=variable) edge_attr = edges[0].attributes() attributes[placeholder_name] = edge_attr except: pass for i, variable in enumerate(variables): placeholder_name = variable_placeholders[i] try: attributes[placeholder_name] = self.match_info[placeholder_name] except: pass return attributes
python
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) attributes = {} for i, variable in enumerate(variables): placeholder_name = variable_placeholders[i] try: vertices = self.g.vs.select(name=variable) attributes[placeholder_name] = vertices[0].attributes() except: pass for i, variable in enumerate(variables): placeholder_name = variable_placeholders[i] try: edges = self.g.es.select(name=variable) edge_attr = edges[0].attributes() attributes[placeholder_name] = edge_attr except: pass for i, variable in enumerate(variables): placeholder_name = variable_placeholders[i] try: attributes[placeholder_name] = self.match_info[placeholder_name] except: pass return attributes
[ "def", "build_variables", "(", "self", ",", "variable_placeholders", ")", ":", "variables", "=", "self", ".", "__substitute_names_in_list", "(", "variable_placeholders", ")", "attributes", "=", "{", "}", "for", "i", ",", "variable", "in", "enumerate", "(", "vari...
: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
[ ":", "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", "JSO...
train
https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_builder.py#L98-L127
gwastro/pycbc-glue
pycbc_glue/pidfile.py
get_lock
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 unrelated process has been assigned the same pid by the OS. """ 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) except IOError,e: raise RuntimeError, "failed to lock %s: %s" % (lockfile, e) # we got the file lock, so 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 lock" % (lockfile, pidfile_pid)) # the pidfile didn't exist or was stale, so grab a new lock pidfile.truncate(0) pidfile.write("%d\n" % os.getpid()) pidfile.close() # should be entirely unecessary, but paranoia always served me well confirm_lock(lockfile) return True
python
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 unrelated process has been assigned the same pid by the OS. """ 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) except IOError,e: raise RuntimeError, "failed to lock %s: %s" % (lockfile, e) # we got the file lock, so 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 lock" % (lockfile, pidfile_pid)) # the pidfile didn't exist or was stale, so grab a new lock pidfile.truncate(0) pidfile.write("%d\n" % os.getpid()) pidfile.close() # should be entirely unecessary, but paranoia always served me well confirm_lock(lockfile) return True
[ "def", "get_lock", "(", "lockfile", ")", ":", "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 bo...
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 unrelated process has been assigned the same pid by the OS.
[ "Tries", "to", "write", "a", "lockfile", "containing", "the", "current", "pid", ".", "Excepts", "if", "the", "lockfile", "already", "contains", "the", "pid", "of", "a", "running", "process", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pidfile.py#L24-L64
gwastro/pycbc-glue
pycbc_glue/pidfile.py
confirm_lock
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 pid %s; expected pid %s!" % (lockfile, os.getpid(), pidfile_pid)) return True
python
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 pid %s; expected pid %s!" % (lockfile, os.getpid(), pidfile_pid)) return True
[ "def", "confirm_lock", "(", "lockfile", ")", ":", "pidfile", "=", "open", "(", "lockfile", ",", "\"r\"", ")", "pidfile_pid", "=", "pidfile", ".", "readline", "(", ")", ".", "strip", "(", ")", "pidfile", ".", "close", "(", ")", "if", "int", "(", "pidf...
Confirm that the given lockfile contains our pid. Should be entirely unecessary, but paranoia always served me well.
[ "Confirm", "that", "the", "given", "lockfile", "contains", "our", "pid", ".", "Should", "be", "entirely", "unecessary", "but", "paranoia", "always", "served", "me", "well", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pidfile.py#L67-L78
gwastro/pycbc-glue
pycbc_glue/markup.py
_argsdicts
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.keys( ) ) myvalues = list( map( _totuple, list( mydict.values( ) ) ) ) maxlength = max( list( map( len, [ args ] + myvalues ) ) ) for i in range( maxlength ): thisdict = { } for key, value in zip( mykeys, myvalues ): try: thisdict[ key ] = value[i] except IndexError: thisdict[ key ] = value[-1] try: thisarg = args[i] except IndexError: thisarg = args[-1] yield thisarg, thisdict
python
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.keys( ) ) myvalues = list( map( _totuple, list( mydict.values( ) ) ) ) maxlength = max( list( map( len, [ args ] + myvalues ) ) ) for i in range( maxlength ): thisdict = { } for key, value in zip( mykeys, myvalues ): try: thisdict[ key ] = value[i] except IndexError: thisdict[ key ] = value[-1] try: thisarg = args[i] except IndexError: thisarg = args[-1] yield thisarg, thisdict
[ "def", "_argsdicts", "(", "args", ",", "mydict", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "args", "=", "None", ",", "elif", "len", "(", "args", ")", "==", "1", ":", "args", "=", "_totuple", "(", "args", "[", "0", "]", ")", "el...
A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1.
[ "A", "utility", "generator", "that", "pads", "argument", "list", "and", "dictionary", "values", "will", "only", "be", "called", "with", "len", "(", "args", ")", "=", "0", "1", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L396-L423
gwastro/pycbc-glue
pycbc_glue/markup.py
_totuple
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
python
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", "_totuple", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "basestring", ")", ":", "out", "=", "x", ",", "elif", "isinstance", "(", "x", ",", "(", "int", ",", "long", ",", "float", ")", ")", ":", "out", "=", "str", "(", "x", ")...
Utility stuff to convert string, int, long, float, None or anything to a usable tuple.
[ "Utility", "stuff", "to", "convert", "string", "int", "long", "float", "None", "or", "anything", "to", "a", "usable", "tuple", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L425-L437
gwastro/pycbc-glue
pycbc_glue/markup.py
escape
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 '\'' in text: text = text.replace( '\'', '&quot;' ) if newline: if '\n' in text: text = text.replace( '\n', '<br>' ) return text
python
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 '\'' in text: text = text.replace( '\'', '&quot;' ) if newline: if '\n' in text: text = text.replace( '\n', '<br>' ) return text
[ "def", "escape", "(", "text", ",", "newline", "=", "False", ")", ":", "if", "isinstance", "(", "text", ",", "basestring", ")", ":", "if", "'&'", "in", "text", ":", "text", "=", "text", ".", "replace", "(", "'&'", ",", "'&amp;'", ")", "if", "'>'", ...
Escape special html characters.
[ "Escape", "special", "html", "characters", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L439-L457
gwastro/pycbc-glue
pycbc_glue/markup.py
unescape
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
python
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", "unescape", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "basestring", ")", ":", "if", "'&amp;'", "in", "text", ":", "text", "=", "text", ".", "replace", "(", "'&amp;'", ",", "'&'", ")", "if", "'&gt;'", "in", "text", ":", "te...
Inverse of escape.
[ "Inverse", "of", "escape", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L461-L474
gwastro/pycbc-glue
pycbc_glue/markup.py
element.render
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': # special cases, maybe change _ to - overall? key = 'http-equiv' elif key == 'accept_charset': key = 'accept-charset' out = "%s %s=\"%s\"" % ( out, key, escape( value ) ) else: out = "%s %s" % ( out, key ) if between is not None: out = "%s>%s</%s>" % ( out, between, tag ) else: if single: out = "%s />" % out else: out = "%s>" % out if self.parent is not None: self.parent.content.append( out ) else: return out
python
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': # special cases, maybe change _ to - overall? key = 'http-equiv' elif key == 'accept_charset': key = 'accept-charset' out = "%s %s=\"%s\"" % ( out, key, escape( value ) ) else: out = "%s %s" % ( out, key ) if between is not None: out = "%s>%s</%s>" % ( out, between, tag ) else: if single: out = "%s />" % out else: out = "%s>" % out if self.parent is not None: self.parent.content.append( out ) else: return out
[ "def", "render", "(", "self", ",", "tag", ",", "single", ",", "between", ",", "kwargs", ")", ":", "out", "=", "\"<%s\"", "%", "tag", "for", "key", ",", "value", "in", "list", "(", "kwargs", ".", "items", "(", ")", ")", ":", "if", "value", "is", ...
Append the actual tags to content.
[ "Append", "the", "actual", "tags", "to", "content", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L81-L105
gwastro/pycbc-glue
pycbc_glue/markup.py
element.close
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 DeprecationError( self.tag )
python
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 DeprecationError( self.tag )
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "tag", "in", "self", ".", "parent", ".", "twotags", ":", "self", ".", "parent", ".", "content", ".", "append", "(", "\"</%s>\"", "%", "self", ".", "tag", ")", "elif", "self", ".", "tag", "...
Append a closing tag unless element has only opening tag.
[ "Append", "a", "closing", "tag", "unless", "element", "has", "only", "opening", "tag", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L107-L115
gwastro/pycbc-glue
pycbc_glue/markup.py
element.open
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 )
python
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", "open", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "tag", "in", "self", ".", "parent", ".", "twotags", "or", "self", ".", "tag", "in", "self", ".", "parent", ".", "onetags", ":", "self", ".", "render", "(", "self", ...
Append an opening tag.
[ "Append", "an", "opening", "tag", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L117-L123
gwastro/pycbc-glue
pycbc_glue/markup.py
page.init
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) css -- Cascading Style Sheet filename as a string or a list of strings for multiple css files (ignored in xml mode) metainfo -- a dictionary in the form { 'name':'content' } to be inserted into meta element(s) as <meta name='name' content='content'> (ignored in xml mode) base -- set the <base href="..."> tag in <head> bodyattrs --a dictionary in the form { 'key':'value', ... } which will be added as attributes 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 element as <title>my title</title> (ignored in xml mode) header -- some text to be inserted right after the <body> element (ignored in xml mode) footer -- some text to be inserted right before the </body> element (ignored in xml mode) charset -- a string defining the character set, will be inserted into a <meta http-equiv='Content-Type' content='text/html; charset=myset'> element (ignored in xml mode) encoding -- a string defining the encoding, will be put into 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.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 ) self.head( ) if charset is not None: self.meta( http_equiv='Content-Type', content="text/html; charset=%s" % charset ) if metainfo is not None: self.metainfo( metainfo ) if css is not None: self.css( css ) if title is not None: self.title( title ) if script is not None: self.scripts( script ) if base is not None: self.base( href='%s' % base ) self.head.close() if 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 = "<?xml version='1.0' ?>" self.header.append( doctype )
python
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) css -- Cascading Style Sheet filename as a string or a list of strings for multiple css files (ignored in xml mode) metainfo -- a dictionary in the form { 'name':'content' } to be inserted into meta element(s) as <meta name='name' content='content'> (ignored in xml mode) base -- set the <base href="..."> tag in <head> bodyattrs --a dictionary in the form { 'key':'value', ... } which will be added as attributes 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 element as <title>my title</title> (ignored in xml mode) header -- some text to be inserted right after the <body> element (ignored in xml mode) footer -- some text to be inserted right before the </body> element (ignored in xml mode) charset -- a string defining the character set, will be inserted into a <meta http-equiv='Content-Type' content='text/html; charset=myset'> element (ignored in xml mode) encoding -- a string defining the encoding, will be put into 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.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 ) self.head( ) if charset is not None: self.meta( http_equiv='Content-Type', content="text/html; charset=%s" % charset ) if metainfo is not None: self.metainfo( metainfo ) if css is not None: self.css( css ) if title is not None: self.title( title ) if script is not None: self.scripts( script ) if base is not None: self.base( href='%s' % base ) self.head.close() if 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 = "<?xml version='1.0' ?>" self.header.append( doctype )
[ "def", "init", "(", "self", ",", "lang", "=", "'en'", ",", "css", "=", "None", ",", "metainfo", "=", "None", ",", "title", "=", "None", ",", "header", "=", "None", ",", "footer", "=", "None", ",", "charset", "=", "None", ",", "encoding", "=", "No...
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) css -- Cascading Style Sheet filename as a string or a list of strings for multiple css files (ignored in xml mode) metainfo -- a dictionary in the form { 'name':'content' } to be inserted into meta element(s) as <meta name='name' content='content'> (ignored in xml mode) base -- set the <base href="..."> tag in <head> bodyattrs --a dictionary in the form { 'key':'value', ... } which will be added as attributes 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 element as <title>my title</title> (ignored in xml mode) header -- some text to be inserted right after the <body> element (ignored in xml mode) footer -- some text to be inserted right before the </body> element (ignored in xml mode) charset -- a string defining the character set, will be inserted into a <meta http-equiv='Content-Type' content='text/html; charset=myset'> element (ignored in xml mode) encoding -- a string defining the encoding, will be put into 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)
[ "This", "method", "is", "used", "for", "complete", "documents", "with", "appropriate", "doctype", "encoding", "title", "etc", "information", ".", "For", "an", "HTML", "/", "XML", "snippet", "omit", "this", "method", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L250-L332
gwastro/pycbc-glue
pycbc_glue/markup.py
page.css
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='stylesheet', type='text/css', media='all' )
python
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='stylesheet', type='text/css', media='all' )
[ "def", "css", "(", "self", ",", "filelist", ")", ":", "if", "isinstance", "(", "filelist", ",", "basestring", ")", ":", "self", ".", "link", "(", "href", "=", "filelist", ",", "rel", "=", "'stylesheet'", ",", "type", "=", "'text/css'", ",", "media", ...
This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.
[ "This", "convenience", "function", "is", "only", "useful", "for", "html", ".", "It", "adds", "css", "stylesheet", "(", "s", ")", "to", "the", "document", "via", "the", "<link", ">", "element", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L334-L342
gwastro/pycbc-glue
pycbc_glue/markup.py
page.metainfo
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: raise TypeError( "Metainfo should be called with a dictionary argument of name:content pairs." )
python
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: raise TypeError( "Metainfo should be called with a dictionary argument of name:content pairs." )
[ "def", "metainfo", "(", "self", ",", "mydict", ")", ":", "if", "isinstance", "(", "mydict", ",", "dict", ")", ":", "for", "name", ",", "content", "in", "list", "(", "mydict", ".", "items", "(", ")", ")", ":", "self", ".", "meta", "(", "name", "="...
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' }.
[ "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", "}", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L344-L353
gwastro/pycbc-glue
pycbc_glue/markup.py
page.scripts
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.items( ) ): self.script( '', src=src, type='text/%s' % type ) else: try: for src in mydict: self.script( '', src=src, type='text/javascript' ) except: raise TypeError( "Script should be given a dictionary of src:type pairs or a list of javascript src's." )
python
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.items( ) ): self.script( '', src=src, type='text/%s' % type ) else: try: for src in mydict: self.script( '', src=src, type='text/javascript' ) except: raise TypeError( "Script should be given a dictionary of src:type pairs or a list of javascript src's." )
[ "def", "scripts", "(", "self", ",", "mydict", ")", ":", "if", "isinstance", "(", "mydict", ",", "dict", ")", ":", "for", "src", ",", "type", "in", "list", "(", "mydict", ".", "items", "(", ")", ")", ":", "self", ".", "script", "(", "''", ",", "...
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>
[ "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", ".", "W...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/markup.py#L355-L368
gwastro/pycbc-glue
pycbc_glue/iterutils.py
MultiIter
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, 10), (0, 11), (1, 11), (2, 11)] The elements in each output tuple are in the order of the input sequences, and the left-most input sequence is iterated over first. Internally, the input sequences themselves are each iterated over only once, so it is safe to pass generators as arguments. Also, this generator is significantly faster if the longest input sequence is given as the first argument. For example, this code >>> lengths = range(1, 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 in # pylal, that has been optimized for the current order and # would need to be reoptimized if this function were to be # reversed. head = tuple((x,) for x in sequences[0]) for t in MultiIter(*sequences[1:]): for h in head: yield h + t elif sequences: for t in sequences[0]: yield (t,)
python
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, 10), (0, 11), (1, 11), (2, 11)] The elements in each output tuple are in the order of the input sequences, and the left-most input sequence is iterated over first. Internally, the input sequences themselves are each iterated over only once, so it is safe to pass generators as arguments. Also, this generator is significantly faster if the longest input sequence is given as the first argument. For example, this code >>> lengths = range(1, 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 in # pylal, that has been optimized for the current order and # would need to be reoptimized if this function were to be # reversed. head = tuple((x,) for x in sequences[0]) for t in MultiIter(*sequences[1:]): for h in head: yield h + t elif sequences: for t in sequences[0]: yield (t,)
[ "def", "MultiIter", "(", "*", "sequences", ")", ":", "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", ...
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, 10), (0, 11), (1, 11), (2, 11)] The elements in each output tuple are in the order of the input sequences, and the left-most input sequence is iterated over first. Internally, the input sequences themselves are each iterated over only once, so it is safe to pass generators as arguments. Also, this generator is significantly faster if the longest input sequence is given as the first argument. For example, this code >>> lengths = range(1, 12) >>> for x in MultiIter(*map(range, lengths)): ... pass ... runs approximately 5 times faster if the lengths list is reversed.
[ "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", "c...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L54-L95
gwastro/pycbc-glue
pycbc_glue/iterutils.py
choices
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 always the same, so if choices() is called twice with two different sequences of the same length the first combination in each of the two output sequences will contain elements from the same positions in the two different input sequences, and so on for each subsequent pair of output combinations. Example: >>> x = choices(["a", "b", "c"], 2) >>> y = choices(["1", "2", "3"], 2) >>> zip(x, y) [(('a', 'b'), ('1', '2')), (('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 corresponding combination in the former. Example: >>> x = ["a", "b", "c", "d", "e"] >>> X = list(choices(x, 2)) >>> Y = list(choices(x, len(x) - 2)) >>> Y.reverse() >>> zip(X, Y) [(('a', 'b'), ('c', 'd', 'e')), (('a', 'c'), ('b', 'd', 'e')), (('a', 'd'), ('b', 'c', 'e')), (('a', 'e'), ('b', 'c', 'd')), (('b', 'c'), ('a', 'd', 'e')), (('b', 'd'), ('a', 'c', 'e')), (('b', 'e'), ('a', 'c', 'd')), (('c', 'd'), ('a', 'b', 'e')), (('c', 'e'), ('a', 'b', 'd')), (('d', 'e'), ('a', 'b', 'c'))] """ 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)
python
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 always the same, so if choices() is called twice with two different sequences of the same length the first combination in each of the two output sequences will contain elements from the same positions in the two different input sequences, and so on for each subsequent pair of output combinations. Example: >>> x = choices(["a", "b", "c"], 2) >>> y = choices(["1", "2", "3"], 2) >>> zip(x, y) [(('a', 'b'), ('1', '2')), (('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 corresponding combination in the former. Example: >>> x = ["a", "b", "c", "d", "e"] >>> X = list(choices(x, 2)) >>> Y = list(choices(x, len(x) - 2)) >>> Y.reverse() >>> zip(X, Y) [(('a', 'b'), ('c', 'd', 'e')), (('a', 'c'), ('b', 'd', 'e')), (('a', 'd'), ('b', 'c', 'e')), (('a', 'e'), ('b', 'c', 'd')), (('b', 'c'), ('a', 'd', 'e')), (('b', 'd'), ('a', 'c', 'e')), (('b', 'e'), ('a', 'c', 'd')), (('c', 'd'), ('a', 'b', 'e')), (('c', 'e'), ('a', 'b', 'd')), (('d', 'e'), ('a', 'b', 'c'))] """ 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", ")", ":", "if", "n", "==", "len", "(", "vals", ")", ":", "yield", "tuple", "(", "vals", ")", "elif", "n", ">", "1", ":", "n", "-=", "1", "for", "i", ",", "v", "in", "enumerate", "(", "vals", "[", ":"...
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 always the same, so if choices() is called twice with two different sequences of the same length the first combination in each of the two output sequences will contain elements from the same positions in the two different input sequences, and so on for each subsequent pair of output combinations. Example: >>> x = choices(["a", "b", "c"], 2) >>> y = choices(["1", "2", "3"], 2) >>> zip(x, y) [(('a', 'b'), ('1', '2')), (('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 corresponding combination in the former. Example: >>> x = ["a", "b", "c", "d", "e"] >>> X = list(choices(x, 2)) >>> Y = list(choices(x, len(x) - 2)) >>> Y.reverse() >>> zip(X, Y) [(('a', 'b'), ('c', 'd', 'e')), (('a', 'c'), ('b', 'd', 'e')), (('a', 'd'), ('b', 'c', 'e')), (('a', 'e'), ('b', 'c', 'd')), (('b', 'c'), ('a', 'd', 'e')), (('b', 'd'), ('a', 'c', 'e')), (('b', 'e'), ('a', 'c', 'd')), (('c', 'd'), ('a', 'b', 'e')), (('c', 'e'), ('a', 'b', 'd')), (('d', 'e'), ('a', 'b', 'c'))]
[ "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", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L98-L154
gwastro/pycbc-glue
pycbc_glue/iterutils.py
uniq
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)
python
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", "uniq", "(", "iterable", ")", ":", "temp_dict", "=", "{", "}", "for", "e", "in", "iterable", ":", "if", "e", "not", "in", "temp_dict", ":", "yield", "temp_dict", ".", "setdefault", "(", "e", ",", "e", ")" ]
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]
[ "Yield", "the", "unique", "items", "of", "an", "iterable", "preserving", "order", ".", "http", ":", "//", "mail", ".", "python", ".", "org", "/", "pipermail", "/", "tutor", "/", "2002", "-", "March", "/", "012930", ".", "html" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L157-L171
gwastro/pycbc-glue
pycbc_glue/iterutils.py
nonuniq
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: yield e temp_dict.setdefault(e, e)
python
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: yield e temp_dict.setdefault(e, e)
[ "def", "nonuniq", "(", "iterable", ")", ":", "temp_dict", "=", "{", "}", "for", "e", "in", "iterable", ":", "if", "e", "in", "temp_dict", ":", "yield", "e", "temp_dict", ".", "setdefault", "(", "e", ",", "e", ")" ]
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]
[ "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", "ou...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L174-L190
gwastro/pycbc-glue
pycbc_glue/iterutils.py
flatten
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
python
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
[ "def", "flatten", "(", "sequence", ",", "levels", "=", "1", ")", ":", "if", "levels", "==", "0", ":", "for", "x", "in", "sequence", ":", "yield", "x", "else", ":", "for", "x", "in", "sequence", ":", "for", "y", "in", "flatten", "(", "x", ",", "...
Example: >>> nested = [[1,2], [[3]]] >>> list(flatten(nested)) [1, 2, [3]]
[ "Example", ":", ">>>", "nested", "=", "[[", "1", "2", "]", "[[", "3", "]]]", ">>>", "list", "(", "flatten", "(", "nested", "))", "[", "1", "2", "[", "3", "]]" ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L193-L206
gwastro/pycbc-glue
pycbc_glue/iterutils.py
inplace_filter
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 left empty at the end, so sequences whose surviving members are predominantly at the bottom will be processed faster. """ target = 0 for source in xrange(len(sequence)): if func(sequence[source]): sequence[target] = sequence[source] target += 1 del sequence[target:]
python
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 left empty at the end, so sequences whose surviving members are predominantly at the bottom will be processed faster. """ 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", ")", ":", "target", "=", "0", "for", "source", "in", "xrange", "(", "len", "(", "sequence", ")", ")", ":", "if", "func", "(", "sequence", "[", "source", "]", ")", ":", "sequence", "[", "target", ...
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 left empty at the end, so sequences whose surviving members are predominantly at the bottom will be processed faster.
[ "Like", "Python", "s", "filter", "()", "builtin", "but", "modifies", "the", "sequence", "in", "place", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L218-L240
gwastro/pycbc-glue
pycbc_glue/iterutils.py
inorder
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.5, 1.75, 2, 2.25, 2.5, 3, 3.5, 3.75, 4.25, 4.5] >>> x.sort(key=lambda x: abs(x-3)) >>> y.sort(key=lambda x: abs(x-3)) >>> z.sort(key=lambda x: abs(x-3)) >>> list(inorder(x, y, z, key=lambda x: abs(x - 3))) [3, 2.5, 3.5, 2.25, 3.75, 2, 1.75, 4.25, 1.5, 4.5, 1, 0] >>> x = [3, 2, 1, 0] >>> y = [4.5, 3.5, 2.5, 1.5] >>> z = [4.25, 3.75, 2.25, 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 argument is False (the default) then the input sequences must yield elements in increasing order, likewise if the keyword argument is True then the input sequences must yield elements in decreasing order. Failure to adhere to this yields undefined results, and for performance reasons no check is performed to validate the element order in the input sequences. """ 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(nextval), nextval, next except StopIteration: pass if not nextvals: # all sequences are empty return if reverse: select = max else: select = min values = nextvals.itervalues if len(nextvals) > 1: while 1: _, val, next = select(values()) yield val try: nextval = next() nextvals[next] = keyfunc(nextval), nextval, next except StopIteration: del nextvals[next] if len(nextvals) < 2: break # exactly one sequence remains, short circuit and drain it (_, val, next), = values() yield val while 1: yield next()
python
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.5, 1.75, 2, 2.25, 2.5, 3, 3.5, 3.75, 4.25, 4.5] >>> x.sort(key=lambda x: abs(x-3)) >>> y.sort(key=lambda x: abs(x-3)) >>> z.sort(key=lambda x: abs(x-3)) >>> list(inorder(x, y, z, key=lambda x: abs(x - 3))) [3, 2.5, 3.5, 2.25, 3.75, 2, 1.75, 4.25, 1.5, 4.5, 1, 0] >>> x = [3, 2, 1, 0] >>> y = [4.5, 3.5, 2.5, 1.5] >>> z = [4.25, 3.75, 2.25, 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 argument is False (the default) then the input sequences must yield elements in increasing order, likewise if the keyword argument is True then the input sequences must yield elements in decreasing order. Failure to adhere to this yields undefined results, and for performance reasons no check is performed to validate the element order in the input sequences. """ 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(nextval), nextval, next except StopIteration: pass if not nextvals: # all sequences are empty return if reverse: select = max else: select = min values = nextvals.itervalues if len(nextvals) > 1: while 1: _, val, next = select(values()) yield val try: nextval = next() nextvals[next] = keyfunc(nextval), nextval, next except StopIteration: del nextvals[next] if len(nextvals) < 2: break # exactly one sequence remains, short circuit and drain it (_, val, next), = values() yield val while 1: yield next()
[ "def", "inorder", "(", "*", "iterables", ",", "*", "*", "kwargs", ")", ":", "reverse", "=", "kwargs", ".", "pop", "(", "\"reverse\"", ",", "False", ")", "keyfunc", "=", "kwargs", ".", "pop", "(", "\"key\"", ",", "lambda", "x", ":", "x", ")", "# def...
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.5, 1.75, 2, 2.25, 2.5, 3, 3.5, 3.75, 4.25, 4.5] >>> x.sort(key=lambda x: abs(x-3)) >>> y.sort(key=lambda x: abs(x-3)) >>> z.sort(key=lambda x: abs(x-3)) >>> list(inorder(x, y, z, key=lambda x: abs(x - 3))) [3, 2.5, 3.5, 2.25, 3.75, 2, 1.75, 4.25, 1.5, 4.5, 1, 0] >>> x = [3, 2, 1, 0] >>> y = [4.5, 3.5, 2.5, 1.5] >>> z = [4.25, 3.75, 2.25, 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 argument is False (the default) then the input sequences must yield elements in increasing order, likewise if the keyword argument is True then the input sequences must yield elements in decreasing order. Failure to adhere to this yields undefined results, and for performance reasons no check is performed to validate the element order in the input sequences.
[ "A", "generator", "that", "yields", "the", "values", "from", "several", "ordered", "iterables", "in", "order", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L252-L325
gwastro/pycbc-glue
pycbc_glue/iterutils.py
randindex
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 [integer]^{n}, where n > 0. Specifically, it's CDF(x) = (x^{n} - lo^{n}) / (hi^{n} - lo^{n}) n = 1 yields a uniform distribution; n > 1 favours larger integers, n < 1 favours smaller integers. """ 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 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 -= lnP[0] lnP /= lnP[-1] # differences give probabilities lnP = tuple(numpy.log(lnP[1:] - lnP[:-1])) if numpy.isinf(lnP).any(): raise ValueError("[lo, hi) domain error") beta = lo**n / (hi**n - lo**n) n = 1. / n alpha = hi / (1. + beta)**n flr = math.floor rnd = random.random while 1: index = int(flr(alpha * (rnd() + beta)**n)) # the tuple look-up provides the second part of the # range safety check on index assert index >= lo yield index, lnP[index - lo]
python
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 [integer]^{n}, where n > 0. Specifically, it's CDF(x) = (x^{n} - lo^{n}) / (hi^{n} - lo^{n}) n = 1 yields a uniform distribution; n > 1 favours larger integers, n < 1 favours smaller integers. """ 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 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 -= lnP[0] lnP /= lnP[-1] # differences give probabilities lnP = tuple(numpy.log(lnP[1:] - lnP[:-1])) if numpy.isinf(lnP).any(): raise ValueError("[lo, hi) domain error") beta = lo**n / (hi**n - lo**n) n = 1. / n alpha = hi / (1. + beta)**n flr = math.floor rnd = random.random while 1: index = int(flr(alpha * (rnd() + beta)**n)) # the tuple look-up provides the second part of the # range safety check on index assert index >= lo yield index, lnP[index - lo]
[ "def", "randindex", "(", "lo", ",", "hi", ",", "n", "=", "1.", ")", ":", "if", "not", "0", "<=", "lo", "<", "hi", ":", "raise", "ValueError", "(", "\"require 0 <= lo < hi: lo = %d, hi = %d\"", "%", "(", "lo", ",", "hi", ")", ")", "if", "n", "<=", "...
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 [integer]^{n}, where n > 0. Specifically, it's CDF(x) = (x^{n} - lo^{n}) / (hi^{n} - lo^{n}) n = 1 yields a uniform distribution; n > 1 favours larger integers, n < 1 favours smaller integers.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L337-L386
gwastro/pycbc-glue
pycbc_glue/segments.py
segment.shift
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))
python
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", "shift", "(", "self", ",", "x", ")", ":", "return", "tuple", ".", "__new__", "(", "self", ".", "__class__", ",", "(", "self", "[", "0", "]", "+", "x", ",", "self", "[", "1", "]", "+", "x", ")", ")" ]
Return a new segment whose bounds are given by adding x to the segment's upper and lower bounds.
[ "Return", "a", "new", "segment", "whose", "bounds", "are", "given", "by", "adding", "x", "to", "the", "segment", "s", "upper", "and", "lower", "bounds", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L434-L439
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.extent
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, max)
python
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, max)
[ "def", "extent", "(", "self", ")", ":", "if", "not", "len", "(", "self", ")", ":", "raise", "ValueError", "(", "\"empty list\"", ")", "min", ",", "max", "=", "self", "[", "0", "]", "for", "lo", ",", "hi", "in", "self", ":", "if", "min", ">", "l...
Return the segment whose end-points denote the maximum and minimum extent of the segmentlist. Does not require the segmentlist to be coalesced.
[ "Return", "the", "segment", "whose", "end", "-", "points", "denote", "the", "maximum", "and", "minimum", "extent", "of", "the", "segmentlist", ".", "Does", "not", "require", "the", "segmentlist", "to", "be", "coalesced", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L523-L537
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.find
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)
python
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", "find", "(", "self", ",", "item", ")", ":", "for", "i", ",", "seg", "in", "enumerate", "(", "self", ")", ":", "if", "item", "in", "seg", ":", "return", "i", "raise", "ValueError", "(", "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.
[ "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", "segmentli...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L539-L549
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.intersects_segment
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 (other[1] > self[i][0]))
python
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 (other[1] > self[i][0]))
[ "def", "intersects_segment", "(", "self", ",", "other", ")", ":", "i", "=", "_bisect_left", "(", "self", ",", "other", ")", "return", "(", "(", "i", "!=", "0", ")", "and", "(", "other", "[", "0", "]", "<", "self", "[", "i", "-", "1", "]", "[", ...
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.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L688-L695
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.intersects
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 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] elif otherseg[1] <= seg[0]: j += 1 if j >= len(other): return False otherseg = other[j] else: return True
python
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 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] elif otherseg[1] <= seg[0]: j += 1 if j >= len(other): return False otherseg = other[j] else: return True
[ "def", "intersects", "(", "self", ",", "other", ")", ":", "# 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", ...
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.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L697-L724
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.coalesce
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[j][1]) j += 1 if lo != hi: self[i] = segment(lo, hi) i += 1 del self[i : ] return self
python
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[j][1]) j += 1 if lo != hi: self[i] = segment(lo, hi) i += 1 del self[i : ] return self
[ "def", "coalesce", "(", "self", ")", ":", "self", ".", "sort", "(", ")", "i", "=", "j", "=", "0", "n", "=", "len", "(", "self", ")", "while", "j", "<", "n", ":", "lo", ",", "hi", "=", "self", "[", "j", "]", "j", "+=", "1", "while", "j", ...
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).
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L726-L745
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.protract
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()
python
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", "protract", "(", "self", ",", "x", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ")", ")", ":", "self", "[", "i", "]", "=", "self", "[", "i", "]", ".", "protract", "(", "x", ")", "return", "self", ".", "coalesce", "(",...
Execute the .protract() method on each segment in the list and coalesce the result. Segmentlist is modified in place.
[ "Execute", "the", ".", "protract", "()", "method", "on", "each", "segment", "in", "the", "list", "and", "coalesce", "the", "result", ".", "Segmentlist", "is", "modified", "in", "place", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L747-L754
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.contract
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()
python
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", "contract", "(", "self", ",", "x", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ")", ")", ":", "self", "[", "i", "]", "=", "self", "[", "i", "]", ".", "contract", "(", "x", ")", "return", "self", ".", "coalesce", "(",...
Execute the .contract() method on each segment in the list and coalesce the result. Segmentlist is modified in place.
[ "Execute", "the", ".", "contract", "()", "method", "on", "each", "segment", "in", "the", "list", "and", "coalesce", "the", "result", ".", "Segmentlist", "is", "modified", "in", "place", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L756-L763
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlist.shift
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
python
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", "shift", "(", "self", ",", "x", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ")", ")", ":", "self", "[", "i", "]", "=", "self", "[", "i", "]", ".", "shift", "(", "x", ")", "return", "self" ]
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.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L765-L774
gwastro/pycbc-glue
pycbc_glue/segments.py
_offsets.update
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 segmentlistdict objects from a common offset dictionary, when one or more of the segmentlistdicts contains only a subset of the keys. """ for key, value in d.iteritems(): if key in self: self[key] = value
python
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 segmentlistdict objects from a common offset dictionary, when one or more of the segmentlistdicts contains only a subset of the keys. """ for key, value in d.iteritems(): if key in self: self[key] = value
[ "def", "update", "(", "self", ",", "d", ")", ":", "for", "key", ",", "value", "in", "d", ".", "iteritems", "(", ")", ":", "if", "key", "in", "self", ":", "self", "[", "key", "]", "=", "value" ]
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 segmentlistdict objects from a common offset dictionary, when one or more of the segmentlistdicts contains only a subset of the keys.
[ "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", "...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L817-L830
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.copy
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 original, but without using much memory until such modifications are made. If the optional keys argument is not None, then should be an iterable of keys and only those segmentlists will be copied (KeyError is raised if any of those keys are not in the segmentlistdict). More details. There are two "built-in" ways to create a copy of a segmentlist object. The first is to initialize a new object from an 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 >>> new = old.copy() This creates a copy of the dictionary and of the segmentlists, but with references to the segment objects in the original segmentlists. Since segments are immutable, this effectively creates a completely independent working copy but without the memory cost of a full duplication of the data. """ 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
python
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 original, but without using much memory until such modifications are made. If the optional keys argument is not None, then should be an iterable of keys and only those segmentlists will be copied (KeyError is raised if any of those keys are not in the segmentlistdict). More details. There are two "built-in" ways to create a copy of a segmentlist object. The first is to initialize a new object from an 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 >>> new = old.copy() This creates a copy of the dictionary and of the segmentlists, but with references to the segment objects in the original segmentlists. Since segments are immutable, this effectively creates a completely independent working copy but without the memory cost of a full duplication of the data. """ 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", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "self", "new", "=", "self", ".", "__class__", "(", ")", "for", "key", "in", "keys", ":", "new", "[", "key", "]", "=", "_shallowcopy", ...
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 original, but without using much memory until such modifications are made. If the optional keys argument is not None, then should be an iterable of keys and only those segmentlists will be copied (KeyError is raised if any of those keys are not in the segmentlistdict). More details. There are two "built-in" ways to create a copy of a segmentlist object. The first is to initialize a new object from an 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 >>> new = old.copy() This creates a copy of the dictionary and of the segmentlists, but with references to the segment objects in the original segmentlists. Since segments are immutable, this effectively creates a completely independent working copy but without the memory cost of a full duplication of the data.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L905-L947
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.map
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, func(value)) for key, value in self.iteritems())
python
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, func(value)) for key, value in self.iteritems())
[ "def", "map", "(", "self", ",", "func", ")", ":", "return", "dict", "(", "(", "key", ",", "func", "(", "value", ")", ")", "for", "key", ",", "value", "in", "self", ".", "iteritems", "(", ")", ")" ]
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", "a", "dictionary", "of", "the", "results", "of", "func", "applied", "to", "each", "of", "the", "segmentlist", "objects", "in", "self", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L965-L978
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.extent_all
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))
python
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", "extent_all", "(", "self", ")", ":", "segs", "=", "tuple", "(", "seglist", ".", "extent", "(", ")", "for", "seglist", "in", "self", ".", "values", "(", ")", "if", "seglist", ")", "if", "not", "segs", ":", "raise", "ValueError", "(", "\"empty l...
Return the result of running .extent() on the union of all lists in the dictionary.
[ "Return", "the", "result", "of", "running", ".", "extent", "()", "on", "the", "union", "of", "all", "lists", "in", "the", "dictionary", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L994-L1002
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.keys_at
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]
python
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", "keys_at", "(", "self", ",", "x", ")", ":", "return", "[", "key", "for", "key", ",", "segs", "in", "self", ".", "items", "(", ")", "if", "x", "in", "segs", "]" ]
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", "a", "list", "of", "the", "keys", "for", "the", "segment", "lists", "that", "contain", "x", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1022-L1035
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.intersects_segment
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())
python
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_segment", "(", "self", ",", "seg", ")", ":", "return", "any", "(", "value", ".", "intersects_segment", "(", "seg", ")", "for", "value", "in", "self", ".", "itervalues", "(", ")", ")" ]
Returns True if any segmentlist in self intersects the segment, otherwise returns False.
[ "Returns", "True", "if", "any", "segmentlist", "in", "self", "intersects", "the", "segment", "otherwise", "returns", "False", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1098-L1103
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.intersects
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.iteritems())
python
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.iteritems())
[ "def", "intersects", "(", "self", ",", "other", ")", ":", "return", "any", "(", "key", "in", "self", "and", "self", "[", "key", "]", ".", "intersects", "(", "value", ")", "for", "key", ",", "value", "in", "other", ".", "iteritems", "(", ")", ")" ]
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()
[ "Returns", "True", "if", "there", "exists", "a", "segmentlist", "in", "self", "that", "intersects", "the", "corresponding", "segmentlist", "in", "other", ";", "returns", "False", "otherwise", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1105-L1115
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.intersects_all
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 key, value in other.iteritems()) and bool(other)
python
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 key, value in other.iteritems()) and bool(other)
[ "def", "intersects_all", "(", "self", ",", "other", ")", ":", "return", "all", "(", "key", "in", "self", "and", "self", "[", "key", "]", ".", "intersects", "(", "value", ")", "for", "key", ",", "value", "in", "other", ".", "iteritems", "(", ")", ")...
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()
[ "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", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1117-L1127
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.all_intersects_all
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(self) == set(other) and all(other[key].intersects(value) for key, value in self.iteritems()) and bool(self)
python
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(self) == set(other) and all(other[key].intersects(value) for key, value in self.iteritems()) and bool(self)
[ "def", "all_intersects_all", "(", "self", ",", "other", ")", ":", "return", "set", "(", "self", ")", "==", "set", "(", "other", ")", "and", "all", "(", "other", "[", "key", "]", ".", "intersects", "(", "value", ")", "for", "key", ",", "value", "in"...
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()
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1141-L1152
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.extend
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)
python
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", "extend", "(", "self", ",", "other", ")", ":", "for", "key", ",", "value", "in", "other", ".", "iteritems", "(", ")", ":", "if", "key", "not", "in", "self", ":", "self", "[", "key", "]", "=", "_shallowcopy", "(", "value", ")", "else", ":",...
Appends the segmentlists from other to the corresponding segmentlists in self, adding new segmentslists to self as needed.
[ "Appends", "the", "segmentlists", "from", "other", "to", "the", "corresponding", "segmentlists", "in", "self", "adding", "new", "segmentslists", "to", "self", "as", "needed", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1154-L1164
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.contract
def contract(self, x): """ Run .contract(x) on all segmentlists. """ for value in self.itervalues(): value.contract(x) return self
python
def contract(self, x): """ Run .contract(x) on all segmentlists. """ for value in self.itervalues(): value.contract(x) return self
[ "def", "contract", "(", "self", ",", "x", ")", ":", "for", "value", "in", "self", ".", "itervalues", "(", ")", ":", "value", ".", "contract", "(", "x", ")", "return", "self" ]
Run .contract(x) on all segmentlists.
[ "Run", ".", "contract", "(", "x", ")", "on", "all", "segmentlists", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1174-L1180
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.protract
def protract(self, x): """ Run .protract(x) on all segmentlists. """ for value in self.itervalues(): value.protract(x) return self
python
def protract(self, x): """ Run .protract(x) on all segmentlists. """ for value in self.itervalues(): value.protract(x) return self
[ "def", "protract", "(", "self", ",", "x", ")", ":", "for", "value", "in", "self", ".", "itervalues", "(", ")", ":", "value", ".", "protract", "(", "x", ")", "return", "self" ]
Run .protract(x) on all segmentlists.
[ "Run", ".", "protract", "(", "x", ")", "on", "all", "segmentlists", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1182-L1188
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.extract_common
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__(new, key, _shallowcopy(intersection)) dict.__setitem__(new.offsets, key, self.offsets[key]) return new
python
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__(new, key, _shallowcopy(intersection)) dict.__setitem__(new.offsets, key, self.offsets[key]) return new
[ "def", "extract_common", "(", "self", ",", "keys", ")", ":", "keys", "=", "set", "(", "keys", ")", "new", "=", "self", ".", "__class__", "(", ")", "intersection", "=", "self", ".", "intersection", "(", "keys", ")", "for", "key", "in", "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.
[ "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", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1190-L1203
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.is_coincident
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 dictionaries will be ignored). If keys is None (the default) then all segment lists are considered. This method is equivalent to the intersects() method, but without requiring the keys of the intersecting segment lists to match. """ 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, self return any(a.intersects(b) for a in self for b in other)
python
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 dictionaries will be ignored). If keys is None (the default) then all segment lists are considered. This method is equivalent to the intersects() method, but without requiring the keys of the intersecting segment lists to match. """ 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, self return any(a.intersects(b) for a in self for b in other)
[ "def", "is_coincident", "(", "self", ",", "other", ",", "keys", "=", "None", ")", ":", "if", "keys", "is", "not", "None", ":", "keys", "=", "set", "(", "keys", ")", "self", "=", "tuple", "(", "self", "[", "key", "]", "for", "key", "in", "set", ...
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 dictionaries will be ignored). If keys is None (the default) then all segment lists are considered. This method is equivalent to the intersects() method, but without requiring the keys of the intersecting segment lists to match.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1207-L1232
gwastro/pycbc-glue
pycbc_glue/segments.py
segmentlistdict.intersection
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
python
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", "intersection", "(", "self", ",", "keys", ")", ":", "keys", "=", "set", "(", "keys", ")", "if", "not", "keys", ":", "return", "segmentlist", "(", ")", "seglist", "=", "_shallowcopy", "(", "self", "[", "keys", ".", "pop", "(", ")", "]", ")", ...
Return the intersection of the segmentlists associated with the keys in keys.
[ "Return", "the", "intersection", "of", "the", "segmentlists", "associated", "with", "the", "keys", "in", "keys", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1234-L1245
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_sqlite.py
update_ids
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 is deferred until after # the rows are inserted, nothing will get updated. therefore, the # connection and xmldoc need to be passed separately to this # function, even though it seems this function could reconstruct # the xmldoc itself from the connection. table_elems = xmldoc.getElementsByTagName(ligolw.Table.tagName) for i, tbl in enumerate(table_elems): if verbose: print >>sys.stderr, "updating IDs: %d%%\r" % (100.0 * i / len(table_elems)), tbl.applyKeyMapping() if verbose: print >>sys.stderr, "updating IDs: 100%" # reset ID mapping for next document dbtables.idmap_reset(connection)
python
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 is deferred until after # the rows are inserted, nothing will get updated. therefore, the # connection and xmldoc need to be passed separately to this # function, even though it seems this function could reconstruct # the xmldoc itself from the connection. table_elems = xmldoc.getElementsByTagName(ligolw.Table.tagName) for i, tbl in enumerate(table_elems): if verbose: print >>sys.stderr, "updating IDs: %d%%\r" % (100.0 * i / len(table_elems)), tbl.applyKeyMapping() if verbose: print >>sys.stderr, "updating IDs: 100%" # reset ID mapping for next document dbtables.idmap_reset(connection)
[ "def", "update_ids", "(", "connection", ",", "xmldoc", ",", "verbose", "=", "False", ")", ":", "# 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 insid...
For internal use only.
[ "For", "internal", "use", "only", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_sqlite.py#L85-L106
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_sqlite.py
insert_from_url
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 modified; this will result in database consistency violations if any of the IDs of newly-inserted rows collide with row IDs already in the database, and is generally only sensible when inserting a document into an empty database. If verbose is True then progress reports will be printed to stderr. See pycbc_glue.ligolw.dbtables.use_in() for more information about constructing a suitable content handler class. """ # # 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_append else: dbtables.DBTable.append = dbtables.DBTable._append try: # # load document. this process inserts the document's contents into # the database. the XML tree constructed by this process contains # a table object for each table found in the newly-inserted # document and those table objects' last_max_rowid values have been # initialized prior to rows being inserted. therefore, this is the # XML tree that must be passed to update_ids in order to ensure (a) # that all newly-inserted tables are processed and (b) all # newly-inserted rows are processed. NOTE: it is assumed the # content handler is creating DBTable instances in the XML tree, # 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.append = orig_DBTable_append # # done. unlink the document to delete database cursor objects it # retains # contenthandler.connection.commit() xmldoc.unlink()
python
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 modified; this will result in database consistency violations if any of the IDs of newly-inserted rows collide with row IDs already in the database, and is generally only sensible when inserting a document into an empty database. If verbose is True then progress reports will be printed to stderr. See pycbc_glue.ligolw.dbtables.use_in() for more information about constructing a suitable content handler class. """ # # 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_append else: dbtables.DBTable.append = dbtables.DBTable._append try: # # load document. this process inserts the document's contents into # the database. the XML tree constructed by this process contains # a table object for each table found in the newly-inserted # document and those table objects' last_max_rowid values have been # initialized prior to rows being inserted. therefore, this is the # XML tree that must be passed to update_ids in order to ensure (a) # that all newly-inserted tables are processed and (b) all # newly-inserted rows are processed. NOTE: it is assumed the # content handler is creating DBTable instances in the XML tree, # 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.append = orig_DBTable_append # # done. unlink the document to delete database cursor objects it # retains # contenthandler.connection.commit() xmldoc.unlink()
[ "def", "insert_from_url", "(", "url", ",", "preserve_ids", "=", "False", ",", "verbose", "=", "False", ",", "contenthandler", "=", "None", ")", ":", "#", "# enable/disable ID remapping", "#", "orig_DBTable_append", "=", "dbtables", ".", "DBTable", ".", "append",...
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 modified; this will result in database consistency violations if any of the IDs of newly-inserted rows collide with row IDs already in the database, and is generally only sensible when inserting a document into an empty database. If verbose is True then progress reports will be printed to stderr. See pycbc_glue.ligolw.dbtables.use_in() for more information about constructing a suitable content handler class.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_sqlite.py#L109-L172
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_sqlite.py
insert_from_xmldoc
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 consistency violations if any of the IDs of newly-inserted rows collide with row IDs already in the database, and is generally only sensible when inserting a document into an empty database. If verbose is True then progress reports will be printed to stderr. """ # # 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_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 document need # ID ramapping, so xmldoc only contains representations of # the tables in the target document that are also in the # source document # xmldoc = ligolw.Document() xmldoc.appendChild(ligolw.LIGO_LW()) # # iterate over tables in the source XML tree, inserting # each into the target database # for tbl in source_xmldoc.getElementsByTagName(ligolw.Table.tagName): # # instantiate the correct table class, connected to the # target database, and save in XML tree # name = tbl.Name try: cls = dbtables.TableByName[name] except KeyError: cls = dbtables.DBTable dbtbl = xmldoc.childNodes[-1].appendChild(cls(tbl.attributes, connection = 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 references to row IDs and clean up ID remapping # if not preserve_ids: update_ids(connection, xmldoc, verbose = verbose) finally: dbtables.DBTable.append = orig_DBTable_append # # done. unlink the document to delete database cursor objects it # retains # connection.commit() xmldoc.unlink()
python
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 consistency violations if any of the IDs of newly-inserted rows collide with row IDs already in the database, and is generally only sensible when inserting a document into an empty database. If verbose is True then progress reports will be printed to stderr. """ # # 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_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 document need # ID ramapping, so xmldoc only contains representations of # the tables in the target document that are also in the # source document # xmldoc = ligolw.Document() xmldoc.appendChild(ligolw.LIGO_LW()) # # iterate over tables in the source XML tree, inserting # each into the target database # for tbl in source_xmldoc.getElementsByTagName(ligolw.Table.tagName): # # instantiate the correct table class, connected to the # target database, and save in XML tree # name = tbl.Name try: cls = dbtables.TableByName[name] except KeyError: cls = dbtables.DBTable dbtbl = xmldoc.childNodes[-1].appendChild(cls(tbl.attributes, connection = 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 references to row IDs and clean up ID remapping # if not preserve_ids: update_ids(connection, xmldoc, verbose = verbose) finally: dbtables.DBTable.append = orig_DBTable_append # # done. unlink the document to delete database cursor objects it # retains # connection.commit() xmldoc.unlink()
[ "def", "insert_from_xmldoc", "(", "connection", ",", "source_xmldoc", ",", "preserve_ids", "=", "False", ",", "verbose", "=", "False", ")", ":", "#", "# enable/disable ID remapping", "#", "orig_DBTable_append", "=", "dbtables", ".", "DBTable", ".", "append", "if",...
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 consistency violations if any of the IDs of newly-inserted rows collide with row IDs already in the database, and is generally only sensible when inserting a document into an empty database. If verbose is True then progress reports will be printed to stderr.
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_sqlite.py#L175-L268
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_sqlite.py
insert_from_urls
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 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, verbose)
python
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 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, verbose)
[ "def", "insert_from_urls", "(", "urls", ",", "contenthandler", ",", "*", "*", "kwargs", ")", ":", "verbose", "=", "kwargs", ".", "get", "(", "\"verbose\"", ",", "False", ")", "#", "# load documents", "#", "for", "n", ",", "url", "in", "enumerate", "(", ...
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.
[ "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", "descr...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_sqlite.py#L271-L293
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/ligolw_sqlite.py
extract
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 be printed to stderr. """ 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()
python
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 be printed to stderr. """ 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", ")", ":", "xmldoc", "=", "ligolw", ".", "Document", "(", ")", "xmldoc", ".", "appendChild", "(", "dbtables"...
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 be printed to stderr.
[ "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", "...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/ligolw_sqlite.py#L301-L315
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/search_summary.py
append_search_summary
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. """ 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 row.out_segment = outseg row.nevents = nevents row.nnodes = nnodes try: tbl = lsctables.SearchSummaryTable.get_table(xmldoc) except ValueError: tbl = xmldoc.childNodes[0].appendChild(lsctables.New(lsctables.SearchSummaryTable)) tbl.append(row) return row
python
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. """ 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 row.out_segment = outseg row.nevents = nevents row.nnodes = nnodes try: tbl = lsctables.SearchSummaryTable.get_table(xmldoc) except ValueError: tbl = xmldoc.childNodes[0].appendChild(lsctables.New(lsctables.SearchSummaryTable)) tbl.append(row) return row
[ "def", "append_search_summary", "(", "xmldoc", ",", "process", ",", "shared_object", "=", "\"standalone\"", ",", "lalwrapper_cvs_tag", "=", "\"\"", ",", "lal_cvs_tag", "=", "\"\"", ",", "comment", "=", "None", ",", "ifos", "=", "None", ",", "inseg", "=", "No...
Append search summary information associated with the given process to the search summary table in xmldoc. Returns the newly-created search_summary table row.
[ "Append", "search", "summary", "information", "associated", "with", "the", "given", "process", "to", "the", "search", "summary", "table", "in", "xmldoc", ".", "Returns", "the", "newly", "-", "created", "search_summary", "table", "row", "." ]
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/search_summary.py#L51-L75
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/search_summary.py
segmentlistdict_fromsearchsummary_in
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 segmentlists in the segmentlistdict are not necessarily coalesced, they contain the segments as they appear in the search_summary table. """ 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))
python
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 segmentlists in the segmentlistdict are not necessarily coalesced, they contain the segments as they appear in the search_summary table. """ 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", ")", ":", "stbl", "=", "lsctables", ".", "SearchSummaryTable", ".", "get_table", "(", "xmldoc", ")", "ptbl", "=", "lsctables", ".", "ProcessTable", ".", "get_table", "(", ...
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 segmentlists in the segmentlistdict are not necessarily coalesced, they contain the segments as they appear in the search_summary table.
[ "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...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/search_summary.py#L78-L92
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/search_summary.py
segmentlistdict_fromsearchsummary_out
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 segmentlists in the segmentlistdict are not necessarily coalesced, they contain the segments as they appear in the search_summary table. """ 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))
python
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 segmentlists in the segmentlistdict are not necessarily coalesced, they contain the segments as they appear in the search_summary table. """ 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", ")", ":", "stbl", "=", "lsctables", ".", "SearchSummaryTable", ".", "get_table", "(", "xmldoc", ")", "ptbl", "=", "lsctables", ".", "ProcessTable", ".", "get_table", "(",...
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 segmentlists in the segmentlistdict are not necessarily coalesced, they contain the segments as they appear in the search_summary table.
[ "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...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/search_summary.py#L95-L109
idlesign/srptools
srptools/cli.py
common_options
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) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func
python
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) func = click.option( '--preset', default=None, help='Preset ID defining prime and generator pair.', type=click.Choice(PRESETS.keys()), callback=parse_preset )(func) return func
[ "def", "common_options", "(", "func", ")", ":", "def", "parse_preset", "(", "ctx", ",", "param", ",", "value", ")", ":", "return", "PRESETS", ".", "get", "(", "value", ",", "(", "None", ",", "None", ")", ")", "def", "parse_private", "(", "ctx", ",", ...
Commonly used command options.
[ "Commonly", "used", "command", "options", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L41-L58
idlesign/srptools
srptools/cli.py
get_private_and_public
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.secho('Server public: %s' % session.public_b64)
python
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.secho('Server public: %s' % session.public_b64)
[ "def", "get_private_and_public", "(", "username", ",", "password_verifier", ",", "private", ",", "preset", ")", ":", "session", "=", "SRPServerSession", "(", "SRPContext", "(", "username", ",", "prime", "=", "preset", "[", "0", "]", ",", "generator", "=", "p...
Print out server public and private.
[ "Print", "out", "server", "public", "and", "private", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L75-L82
idlesign/srptools
srptools/cli.py
get_session_data
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.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64)
python
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.secho('Server session key: %s' % session.key_b64) click.secho('Server session key proof: %s' % session.key_proof_b64) click.secho('Server session key hash: %s' % session.key_proof_hash_b64)
[ "def", "get_session_data", "(", "username", ",", "password_verifier", ",", "salt", ",", "client_public", ",", "private", ",", "preset", ")", ":", "session", "=", "SRPServerSession", "(", "SRPContext", "(", "username", ",", "prime", "=", "preset", "[", "0", "...
Print out server session data.
[ "Print", "out", "server", "session", "data", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L91-L101
idlesign/srptools
srptools/cli.py
get_private_and_public
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' % session.public_b64)
python
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' % session.public_b64)
[ "def", "get_private_and_public", "(", "ctx", ",", "username", ",", "password", ",", "private", ",", "preset", ")", ":", "session", "=", "SRPClientSession", "(", "SRPContext", "(", "username", ",", "password", ",", "prime", "=", "preset", "[", "0", "]", ","...
Print out server public and private.
[ "Print", "out", "server", "public", "and", "private", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L108-L115
idlesign/srptools
srptools/cli.py
get_session_data
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: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64)
python
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: %s' % session.key_b64) click.secho('Client session key proof: %s' % session.key_proof_b64) click.secho('Client session key hash: %s' % session.key_proof_hash_b64)
[ "def", "get_session_data", "(", "ctx", ",", "username", ",", "password", ",", "salt", ",", "server_public", ",", "private", ",", "preset", ")", ":", "session", "=", "SRPClientSession", "(", "SRPContext", "(", "username", ",", "password", ",", "prime", "=", ...
Print out client session data.
[ "Print", "out", "client", "session", "data", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L124-L134
idlesign/srptools
srptools/cli.py
get_user_data_triplet
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' % password_verifier) click.secho('Salt: %s' % salt)
python
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' % password_verifier) click.secho('Salt: %s' % salt)
[ "def", "get_user_data_triplet", "(", "username", ",", "password", ")", ":", "context", "=", "SRPContext", "(", "username", ",", "password", ")", "username", ",", "password_verifier", ",", "salt", "=", "context", ".", "get_user_data_triplet", "(", "base64", "=", ...
Print out user data triplet: username, password verifier, salt.
[ "Print", "out", "user", "data", "triplet", ":", "username", "password", "verifier", "salt", "." ]
train
https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/cli.py#L140-L147
mattharrison/rst2odp
odplib/preso.py
cwd_decorator
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(*args, **kw) os.chdir(cur_dir) return data return wrapper
python
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(*args, **kw) os.chdir(cur_dir) return data return wrapper
[ "def", "cwd_decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "cur_dir", "=", "os", ".", "getcwd", "(", ")", "found", "=", "False", "for", "arg", "in", "sys", ".", "argv", ":", "if", "arg", "....
decorator to change cwd to directory containing rst for this function
[ "decorator", "to", "change", "cwd", "to", "directory", "containing", "rst", "for", "this", "function" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L92-L113
mattharrison/rst2odp
odplib/preso.py
to_xml
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
python
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", "to_xml", "(", "node", ",", "pretty", "=", "False", ")", ":", "fout", "=", "Sio", "(", ")", "etree", "=", "et", ".", "ElementTree", "(", "node", ")", "etree", ".", "write", "(", "fout", ")", "xml", "=", "fout", ".", "getvalue", "(", ")", ...
convert an etree node to xml
[ "convert", "an", "etree", "node", "to", "xml" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L178-L187
mattharrison/rst2odp
odplib/preso.py
pretty_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].childNodes[0].toprettyxml(" ") else: s1 = doc.toprettyxml(" ") return s1
python
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].childNodes[0].toprettyxml(" ") else: s1 = doc.toprettyxml(" ") return s1
[ "def", "pretty_xml", "(", "string_input", ",", "add_ns", "=", "False", ")", ":", "if", "add_ns", ":", "elem", "=", "\"<foo \"", "for", "key", ",", "value", "in", "DOC_CONTENT_ATTRIB", ".", "items", "(", ")", ":", "elem", "+=", "' %s=\"%s\"'", "%", "(", ...
pretty indent string_input
[ "pretty", "indent", "string_input" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L190-L202
mattharrison/rst2odp
odplib/preso.py
add_cell
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_margin avail_height -= padding * (height - 1) column_height = avail_height / height col_pos = int((pos - 1) % width) row_pos = int((pos - 1) / width) w = "{}cm".format(column_width) h = "{}cm".format(column_height) x = "{}cm".format(left_margin + (col_pos * column_width + (col_pos) * padding)) y = "{}cm".format(top_margin + (row_pos * column_height + (row_pos) * padding)) attr = { "presentation:class": "outline", "presentation:style-name": "Default-outline1", "svg:width": w, "svg:height": h, "svg:x": x, "svg:y": y, } preso.slides[-1].add_text_frame(attr) preso.slides[-1].grid_w_h_x_y = (w, h, x, y)
python
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_margin avail_height -= padding * (height - 1) column_height = avail_height / height col_pos = int((pos - 1) % width) row_pos = int((pos - 1) / width) w = "{}cm".format(column_width) h = "{}cm".format(column_height) x = "{}cm".format(left_margin + (col_pos * column_width + (col_pos) * padding)) y = "{}cm".format(top_margin + (row_pos * column_height + (row_pos) * padding)) attr = { "presentation:class": "outline", "presentation:style-name": "Default-outline1", "svg:width": w, "svg:height": h, "svg:x": x, "svg:y": y, } preso.slides[-1].add_text_frame(attr) preso.slides[-1].grid_w_h_x_y = (w, h, x, y)
[ "def", "add_cell", "(", "preso", ",", "pos", ",", "width", ",", "height", ",", "padding", "=", "1", ",", "top_margin", "=", "4", ",", "left_margin", "=", "2", ")", ":", "available_width", "=", "SLIDE_WIDTH", "available_width", "-=", "left_margin", "*", "...
Add a text frame to current slide
[ "Add", "a", "text", "frame", "to", "current", "slide" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L209-L236
mattharrison/rst2odp
odplib/preso.py
add_line
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-vertical-align="middle"/> </style:style> 3pt width color red <style:style style:name="gr2" style:family="graphic" style:parent-style-name="objectwithoutfill"> <style:graphic-properties svg:stroke-width="0.106cm" svg:stroke-color="#ed1c24" draw:marker-start-width="0.359cm" draw:marker-end="Arrow" draw:marker-end-width="0.459cm" draw:fill="none" draw:textarea-vertical-align="middle" fo:padding-top="0.178cm" fo:padding-bottom="0.178cm" fo:padding-left="0.303cm" fo:padding-right="0.303cm"/> </style:style> ... office:presentation/draw:page <draw:line draw:style-name="gr1" draw:text-style-name="P2" draw:layer="layout" svg:x1="6.35cm" svg:y1="10.16cm" svg:x2="10.668cm" svg:y2="5.842cm"><text:p/></draw:line> """ 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": "{}cm".format(sw), "svg:stroke-color": color, # "#ed1c24", "draw:marker-start-width": "{}cm".format(msw), "draw:marker-end": "Arrow", "draw:marker-end-width": "{}cm".format(mew), "draw:fill": "none", "draw:textarea-vertical-align": "middle", } style = LineStyle(**attribs) # node = style.style_node() preso.add_style(style) line_attrib = { "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)
python
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-vertical-align="middle"/> </style:style> 3pt width color red <style:style style:name="gr2" style:family="graphic" style:parent-style-name="objectwithoutfill"> <style:graphic-properties svg:stroke-width="0.106cm" svg:stroke-color="#ed1c24" draw:marker-start-width="0.359cm" draw:marker-end="Arrow" draw:marker-end-width="0.459cm" draw:fill="none" draw:textarea-vertical-align="middle" fo:padding-top="0.178cm" fo:padding-bottom="0.178cm" fo:padding-left="0.303cm" fo:padding-right="0.303cm"/> </style:style> ... office:presentation/draw:page <draw:line draw:style-name="gr1" draw:text-style-name="P2" draw:layer="layout" svg:x1="6.35cm" svg:y1="10.16cm" svg:x2="10.668cm" svg:y2="5.842cm"><text:p/></draw:line> """ 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": "{}cm".format(sw), "svg:stroke-color": color, # "#ed1c24", "draw:marker-start-width": "{}cm".format(msw), "draw:marker-end": "Arrow", "draw:marker-end-width": "{}cm".format(mew), "draw:fill": "none", "draw:textarea-vertical-align": "middle", } style = LineStyle(**attribs) # node = style.style_node() preso.add_style(style) line_attrib = { "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_line", "(", "preso", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "width", "=", "\"3pt\"", ",", "color", "=", "\"red\"", ")", ":", "marker_end_ratio", "=", ".459", "/", "3", "# .459cm/3pt", "marker_start_ratio", "=", ".359", "/", "3", ...
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-vertical-align="middle"/> </style:style> 3pt width color red <style:style style:name="gr2" style:family="graphic" style:parent-style-name="objectwithoutfill"> <style:graphic-properties svg:stroke-width="0.106cm" svg:stroke-color="#ed1c24" draw:marker-start-width="0.359cm" draw:marker-end="Arrow" draw:marker-end-width="0.459cm" draw:fill="none" draw:textarea-vertical-align="middle" fo:padding-top="0.178cm" fo:padding-bottom="0.178cm" fo:padding-left="0.303cm" fo:padding-right="0.303cm"/> </style:style> ... office:presentation/draw:page <draw:line draw:style-name="gr1" draw:text-style-name="P2" draw:layer="layout" svg:x1="6.35cm" svg:y1="10.16cm" svg:x2="10.668cm" svg:y2="5.842cm"><text:p/></draw:line>
[ "Arrow", "pointing", "up", "to", "right", ":" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L2139-L2208
mattharrison/rst2odp
odplib/preso.py
Preso.add_otp_style
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_data = self.override_styles(xml_data) zip_odp.write("styles.xml", xml_data)
python
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_data = self.override_styles(xml_data) zip_odp.write("styles.xml", xml_data)
[ "def", "add_otp_style", "(", "self", ",", "zip_odp", ",", "style_file", ")", ":", "style", "=", "zipwrap", ".", "Zippier", "(", "style_file", ")", "for", "picture_file", "in", "style", ".", "ls", "(", "\"Pictures\"", ")", ":", "zip_odp", ".", "write", "(...
takes the slide content and merges in the style_file
[ "takes", "the", "slide", "content", "and", "merges", "in", "the", "style_file" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L420-L430
mattharrison/rst2odp
odplib/preso.py
Preso.to_file
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._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.styles_xml()) out.write("meta.xml", self.meta_xml()) out.write("settings.xml", self.settings_xml()) out.write("META-INF/manifest.xml", self.manifest_xml(out)) return out
python
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._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.styles_xml()) out.write("meta.xml", self.meta_xml()) out.write("settings.xml", self.settings_xml()) out.write("META-INF/manifest.xml", self.manifest_xml(out)) return out
[ "def", "to_file", "(", "self", ",", "filename", "=", "None", ",", "write_style", "=", "True", ")", ":", "out", "=", "zipwrap", ".", "Zippier", "(", "filename", ",", "\"w\"", ")", "out", ".", "write", "(", "\"mimetype\"", ",", "self", ".", "mime_type", ...
>>> 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']
[ ">>>", "p", "=", "Preso", "()", ">>>", "z", "=", "p", ".", "to_file", "(", "/", "tmp", "/", "foo", ".", "odp", ")", ">>>", "sorted", "(", "z", ".", "ls", "(", "/", "))", "[", "META", "-", "INF", "/", "manifest", ".", "xml", "content", ".", ...
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L438-L455
mattharrison/rst2odp
odplib/preso.py
Animation.get_node
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:sub-item="text" smil:attributeName="visibility" smil:to="visible"/> </anim:par> </anim:par> </anim:par> """ 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", "presentation:node-type": "on-click", "presentation:preset-class": "entrance", "presentation:preset-id": "ooo-entrance-appear", }, ) if self.ids: for id in self.ids: sub_el( par3, "anim:set", attrib={ "smil:begin": "0s", "smil:dur": "0.001s", "smil:fill": "hold", "smil:targetElement": id, "anim:sub-item": "text", "smil:attributeName": "visibility", "smil:to": "visible", }, ) else: sub_el( par3, "anim:set", attrib={ "smil:begin": "0s", "smil:dur": "0.001s", "smil:fill": "hold", "smil:targetElement": self.id, "anim:sub-item": "text", "smil:attributeName": "visibility", "smil:to": "visible", }, ) return par
python
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:sub-item="text" smil:attributeName="visibility" smil:to="visible"/> </anim:par> </anim:par> </anim:par> """ 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", "presentation:node-type": "on-click", "presentation:preset-class": "entrance", "presentation:preset-id": "ooo-entrance-appear", }, ) if self.ids: for id in self.ids: sub_el( par3, "anim:set", attrib={ "smil:begin": "0s", "smil:dur": "0.001s", "smil:fill": "hold", "smil:targetElement": id, "anim:sub-item": "text", "smil:attributeName": "visibility", "smil:to": "visible", }, ) else: sub_el( par3, "anim:set", attrib={ "smil:begin": "0s", "smil:dur": "0.001s", "smil:fill": "hold", "smil:targetElement": self.id, "anim:sub-item": "text", "smil:attributeName": "visibility", "smil:to": "visible", }, ) return par
[ "def", "get_node", "(", "self", ")", ":", "par", "=", "el", "(", "\"anim:par\"", ",", "attrib", "=", "{", "\"smil:begin\"", ":", "\"next\"", "}", ")", "par2", "=", "sub_el", "(", "par", ",", "\"anim:par\"", ",", "attrib", "=", "{", "\"smil:begin\"", ":...
<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:sub-item="text" smil:attributeName="visibility" smil:to="visible"/> </anim:par> </anim:par> </anim:par>
[ "<anim", ":", "par", "smil", ":", "begin", "=", "next", ">", "<anim", ":", "par", "smil", ":", "begin", "=", "0s", ">", "<anim", ":", "par", "smil", ":", "begin", "=", "0s", "smil", ":", "fill", "=", "hold", "presentation", ":", "node", "-", "typ...
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L570-L624
mattharrison/rst2odp
odplib/preso.py
Picture.update_frame_attributes
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
python
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_frame_attributes", "(", "self", ",", "attrib", ")", ":", "if", "\"align\"", "in", "self", ".", "user_defined", ":", "align", "=", "self", ".", "user_defined", "[", "\"align\"", "]", "if", "\"top\"", "in", "align", ":", "attrib", "[", "\"styl...
For positioning update the frame
[ "For", "positioning", "update", "the", "frame" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L669-L678
mattharrison/rst2odp
odplib/preso.py
Slide.update_style
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": "true", "presentation:display-page-number": "false", "presentation:display-date-time": "true", } default.update(mapping) style = PageStyle(**default) node = style.style_node() # add style to automatic-style self.preso._auto_styles.append(node) # update page style-name # found in ._page self._page.set(ns("draw", "style-name"), node.attrib[ns("style", "name")])
python
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": "true", "presentation:display-page-number": "false", "presentation:display-date-time": "true", } default.update(mapping) style = PageStyle(**default) node = style.style_node() # add style to automatic-style self.preso._auto_styles.append(node) # update page style-name # found in ._page self._page.set(ns("draw", "style-name"), node.attrib[ns("style", "name")])
[ "def", "update_style", "(", "self", ",", "mapping", ")", ":", "default", "=", "{", "\"presentation:background-visible\"", ":", "\"true\"", ",", "\"presentation:background-objects-visible\"", ":", "\"true\"", ",", "\"draw:fill\"", ":", "\"solid\"", ",", "\"draw:fill-colo...
Use to update fill-color
[ "Use", "to", "update", "fill", "-", "color" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L880-L900
mattharrison/rst2odp
odplib/preso.py
Slide.push_pending_node
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.pending_nodes.append((name, attr))
python
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.pending_nodes.append((name, attr))
[ "def", "push_pending_node", "(", "self", ",", "name", ",", "attr", ")", ":", "if", "self", ".", "cur_element", "is", "None", ":", "self", ".", "add_text_frame", "(", ")", "self", ".", "cur_element", ".", "pending_nodes", ".", "append", "(", "(", "name", ...
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.
[ "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", "."...
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L930-L939
mattharrison/rst2odp
odplib/preso.py
Slide.add_picture
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:actuate="onLoad"> <text:p text:style-name="P1"/> </draw:image> </draw:frame> """ # 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", "xlink:show": "embed", "xlink:actuate": "onLoad", }, ) self._preso._pictures.append(p) node = self.pic_frame.get_node() self._page.append(node)
python
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:actuate="onLoad"> <text:p text:style-name="P1"/> </draw:image> </draw:frame> """ # 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", "xlink:show": "embed", "xlink:actuate": "onLoad", }, ) self._preso._pictures.append(p) node = self.pic_frame.get_node() self._page.append(node)
[ "def", "add_picture", "(", "self", ",", "p", ")", ":", "# pictures should be added the the draw:frame element", "self", ".", "pic_frame", "=", "PictureFrame", "(", "self", ",", "p", ")", "self", ".", "pic_frame", ".", "add_node", "(", "\"draw:image\"", ",", "att...
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:actuate="onLoad"> <text:p text:style-name="P1"/> </draw:image> </draw:frame>
[ "needs", "to", "look", "like", "this", "(", "under", "draw", ":", "page", ")" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L971-L994
mattharrison/rst2odp
odplib/preso.py
Slide._copy
def _copy(self): """ needs to update page numbers """ ins = copy.copy(self) ins._fire_page_number(self.page_number + 1) return ins
python
def _copy(self): """ needs to update page numbers """ ins = copy.copy(self) ins._fire_page_number(self.page_number + 1) return ins
[ "def", "_copy", "(", "self", ")", ":", "ins", "=", "copy", ".", "copy", "(", "self", ")", "ins", ".", "_fire_page_number", "(", "self", ".", "page_number", "+", "1", ")", "return", "ins" ]
needs to update page numbers
[ "needs", "to", "update", "page", "numbers" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1013-L1017
mattharrison/rst2odp
odplib/preso.py
Slide.get_node
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-type": "main-sequence"} ) for a in self.animations: a_node = a.get_node() anim_seq.append(a_node) # add notes now (so they are last) if self.notes_frame: notes = self.notes_frame.get_node() self._page.append(notes) if self.footer: self._page.attrib[ns("presentation", "use-footer-name")] = self.footer.name return self._page
python
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-type": "main-sequence"} ) for a in self.animations: a_node = a.get_node() anim_seq.append(a_node) # add notes now (so they are last) if self.notes_frame: notes = self.notes_frame.get_node() self._page.append(notes) if self.footer: self._page.attrib[ns("presentation", "use-footer-name")] = self.footer.name return self._page
[ "def", "get_node", "(", "self", ")", ":", "# already added title, text frames", "# add animation chunks", "if", "self", ".", "animations", ":", "anim_par", "=", "el", "(", "\"anim:par\"", ",", "attrib", "=", "{", "\"presentation:node-type\"", ":", "\"timing-root\"", ...
return etree Element representing this slide
[ "return", "etree", "Element", "representing", "this", "slide" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1043-L1063
mattharrison/rst2odp
odplib/preso.py
Slide.add_list
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._preso._styles_added: self._preso._styles_added[style] = 1 content = bl.default_styles_root()[0] self._preso._auto_styles.append(content) self.cur_element = bl
python
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._preso._styles_added: self._preso._styles_added[style] = 1 content = bl.default_styles_root()[0] self._preso._auto_styles.append(content) self.cur_element = bl
[ "def", "add_list", "(", "self", ",", "bl", ")", ":", "# 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_elem...
note that this pushes the cur_element, but doesn't pop it. You'll need to do that
[ "note", "that", "this", "pushes", "the", "cur_element", "but", "doesn", "t", "pop", "it", ".", "You", "ll", "need", "to", "do", "that" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1086-L1101
mattharrison/rst2odp
odplib/preso.py
Slide.add_table
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
python
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", "add_table", "(", "self", ",", "t", ")", ":", "self", ".", "push_element", "(", ")", "self", ".", "_page", ".", "append", "(", "t", ".", "node", ")", "self", ".", "cur_element", "=", "t" ]
remember to call pop_element after done with table
[ "remember", "to", "call", "pop_element", "after", "done", "with", "table" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1103-L1109
mattharrison/rst2odp
odplib/preso.py
XMLSlide.update_text
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.tail = node.tail.replace(old, new) found = True if not found: raise KeyError("Updating text failed with mapping:{}".format(mapping))
python
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.tail = node.tail.replace(old, new) found = True if not found: raise KeyError("Updating text failed with mapping:{}".format(mapping))
[ "def", "update_text", "(", "self", ",", "mapping", ")", ":", "found", "=", "False", "for", "node", "in", "self", ".", "_page", ".", "iter", "(", "\"*\"", ")", ":", "if", "node", ".", "text", "or", "node", ".", "tail", ":", "for", "old", ",", "new...
Iterate over nodes, replace text with mapping
[ "Iterate", "over", "nodes", "replace", "text", "with", "mapping" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1207-L1220
mattharrison/rst2odp
odplib/preso.py
MixedContent.parent_of
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()
python
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", "parent_of", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "_in_tag", "(", "name", ")", ":", "return", "node", "=", "self", ".", "cur_node", "while", "node", ".", "tag", "!=", "name", ":", "node", "=", "node", ".", "getparent...
go to parent of node with name, and set as cur_node. Useful for creating new paragraphs
[ "go", "to", "parent", "of", "node", "with", "name", "and", "set", "as", "cur_node", ".", "Useful", "for", "creating", "new", "paragraphs" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1282-L1293
mattharrison/rst2odp
odplib/preso.py
MixedContent._is_last_child
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
python
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", "_is_last_child", "(", "self", ",", "tagname", ",", "attributes", "=", "None", ")", ":", "children", "=", "self", ".", "cur_node", ".", "getchildren", "(", ")", "if", "children", ":", "result", "=", "self", ".", "_is_node", "(", "tagname", ",", ...
Check if last child of cur_node is tagname with attributes
[ "Check", "if", "last", "child", "of", "cur_node", "is", "tagname", "with", "attributes" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1302-L1311
mattharrison/rst2odp
odplib/preso.py
MixedContent._in_tag
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 = node.getparent() return False
python
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 = node.getparent() return False
[ "def", "_in_tag", "(", "self", ",", "tagname", ",", "attributes", "=", "None", ")", ":", "node", "=", "self", ".", "cur_node", "while", "not", "node", "is", "None", ":", "if", "node", ".", "tag", "==", "tagname", ":", "if", "attributes", "and", "node...
Determine if we are already in a certain tag. If we give attributes, make sure they match.
[ "Determine", "if", "we", "are", "already", "in", "a", "certain", "tag", ".", "If", "we", "give", "attributes", "make", "sure", "they", "match", "." ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1322-L1339
mattharrison/rst2odp
odplib/preso.py
MixedContent._check_add_node
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
python
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", "_check_add_node", "(", "self", ",", "parent", ",", "name", ")", ":", "if", "name", "==", "ns", "(", "\"text\"", ",", "\"a\"", ")", ":", "if", "parent", ".", "tag", "==", "ns", "(", "\"draw\"", ",", "\"text-box\"", ")", ":", "return", "False",...
Returns False if bad to make name a child of parent
[ "Returns", "False", "if", "bad", "to", "make", "name", "a", "child", "of", "parent" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1350-L1356
mattharrison/rst2odp
odplib/preso.py
MixedContent._add_styles
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): t_styles.update(s.styles) para = ParagraphStyle(**p_styles) if add_paragraph or self.slide.paragraph_attribs: p_attrib = {ns("text", "style-name"): para.name} p_attrib.update(self.slide.paragraph_attribs) if not self._in_tag(ns("text", "p"), p_attrib): self.parent_of(ns("text", "p")) # Create paragraph style first self.slide._preso.add_style(para) self.add_node("text:p", attrib=p_attrib) # span is only necessary if style changes if add_text and t_styles: text = TextStyle(**t_styles) children = self.cur_node.getchildren() if children: # if we already are using this text style, reuse the last one last = children[-1] if ( last.tag == ns("text", "span") and last.attrib[ns("text", "style-name")] == text.name and last.tail is None ): # if we have a tail, we can't reuse self.cur_node = children[-1] return if 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})
python
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): t_styles.update(s.styles) para = ParagraphStyle(**p_styles) if add_paragraph or self.slide.paragraph_attribs: p_attrib = {ns("text", "style-name"): para.name} p_attrib.update(self.slide.paragraph_attribs) if not self._in_tag(ns("text", "p"), p_attrib): self.parent_of(ns("text", "p")) # Create paragraph style first self.slide._preso.add_style(para) self.add_node("text:p", attrib=p_attrib) # span is only necessary if style changes if add_text and t_styles: text = TextStyle(**t_styles) children = self.cur_node.getchildren() if children: # if we already are using this text style, reuse the last one last = children[-1] if ( last.tag == ns("text", "span") and last.attrib[ns("text", "style-name")] == text.name and last.tail is None ): # if we have a tail, we can't reuse self.cur_node = children[-1] return if 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", "_add_styles", "(", "self", ",", "add_paragraph", "=", "True", ",", "add_text", "=", "True", ")", ":", "p_styles", "=", "self", ".", "get_para_styles", "(", ")", "t_styles", "=", "self", ".", "get_span_styles", "(", ")", "for", "s", "in", "self", ...
Adds paragraph and span wrappers if necessary based on style
[ "Adds", "paragraph", "and", "span", "wrappers", "if", "necessary", "based", "on", "style" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1388-L1431
mattharrison/rst2odp
odplib/preso.py
MixedContent.line_break
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.add_node(ns("text", "line-break")) self.pop_node() if self.cur_node.tag == ns("text", "p"): return if self.cur_node.getparent().tag != ns("text", "p"): self.pop_node() self.slide.insert_line_break = 0
python
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.add_node(ns("text", "line-break")) self.pop_node() if self.cur_node.tag == ns("text", "p"): return if self.cur_node.getparent().tag != ns("text", "p"): self.pop_node() self.slide.insert_line_break = 0
[ "def", "line_break", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "slide", ".", "insert_line_break", ")", ":", "# needs to be inside text:p", "if", "not", "self", ".", "_in_tag", "(", "ns", "(", "\"text\"", ",", "\"p\"", ")", ")", ...
insert as many line breaks as the insert_line_break variable says
[ "insert", "as", "many", "line", "breaks", "as", "the", "insert_line_break", "variable", "says" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1437-L1453
mattharrison/rst2odp
odplib/preso.py
MixedContent.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 """ 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(" ") self._write(letter) spaces = [] continue elif spaces: num_spaces = len(spaces) - 1 # write just a plain space at the start self._write(" ") if num_spaces > 1: # write the attrib only if more than one space self.add_node("text:s", {"text:c": str(num_spaces)}) else: self.add_node("text:s") self.pop_node() self._write(letter) spaces = [] continue self._write(letter) if spaces: num_spaces = len(spaces) if num_spaces > 1: self.add_node("text:s", {"text:c": str(num_spaces)}) else: self.add_node("text:s") self.pop_node()
python
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 """ 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(" ") self._write(letter) spaces = [] continue elif spaces: num_spaces = len(spaces) - 1 # write just a plain space at the start self._write(" ") if num_spaces > 1: # write the attrib only if more than one space self.add_node("text:s", {"text:c": str(num_spaces)}) else: self.add_node("text:s") self.pop_node() self._write(letter) spaces = [] continue self._write(letter) if spaces: num_spaces = len(spaces) if num_spaces > 1: self.add_node("text:s", {"text:c": str(num_spaces)}) else: self.add_node("text:s") self.pop_node()
[ "def", "write", "(", "self", ",", "text", ",", "add_p_style", "=", "True", ",", "add_t_style", "=", "True", ")", ":", "self", ".", "_add_styles", "(", "add_p_style", ",", "add_t_style", ")", "self", ".", "_add_pending_nodes", "(", ")", "spaces", "=", "["...
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
[ "see", "mixed", "content", "http", ":", "//", "effbot", ".", "org", "/", "zone", "/", "element", "-", "infoset", ".", "htm#mixed", "-", "content", "Writing", "is", "complicated", "by", "requirements", "of", "odp", "to", "ignore", "duplicate", "spaces", "to...
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1455-L1501
mattharrison/rst2odp
odplib/preso.py
TextStyle.style_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(additional_style_attrib) if self.PARENT_STYLE_DICT: style_attrib.update(self.PARENT_STYLE_DICT) node = el("style:style", attrib=style_attrib) props = sub_el(node, self.STYLE_PROP, attrib=self.styles) return node
python
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(additional_style_attrib) if self.PARENT_STYLE_DICT: style_attrib.update(self.PARENT_STYLE_DICT) node = el("style:style", attrib=style_attrib) props = sub_el(node, self.STYLE_PROP, attrib=self.styles) return node
[ "def", "style_node", "(", "self", ",", "additional_style_attrib", "=", "None", ")", ":", "style_attrib", "=", "{", "\"style:name\"", ":", "self", ".", "name", ",", "\"style:family\"", ":", "self", ".", "FAMILY", "}", "if", "additional_style_attrib", ":", "styl...
generate a style node (for automatic-styles) could specify additional attributes such as 'style:parent-style-name' or 'style:list-style-name'
[ "generate", "a", "style", "node", "(", "for", "automatic", "-", "styles", ")" ]
train
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1705-L1721
gwastro/pycbc-glue
pycbc_glue/segmentdb/logic.py
run_file_operation
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 DMT-FLAG1 operation ...) DMT-FLAG2 = (file 1's DMT-FLAG2 operation file 2's DMT-FLAG2 operation ...) etc """ proc_id = table.get_table(outdoc, lsctables.ProcessTable.tableName)[0].process_id # load up the files into individual documents xmldocs = [ligolw_add.ligolw_add(ligolw.Document(), [fname]) for fname in filenames] # Get the list of dinstinct segment_definers across all docs segment_definers = {} def register_definer(seg_def): key = (seg_def.ifos, seg_def.name, seg_def.version) segment_definers[key] = True return key for xmldoc in xmldocs: seg_def_table = table.get_table(xmldoc, lsctables.SegmentDefTable.tableName) map (register_definer, seg_def_table) # For each unique segment definer, find the 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: result &= find_segments(xmldoc, '%s:%s:%d' % (ifo, name, version), use_segment_table) elif operation == UNION: result = pycbc_glue.segments.segmentlist([]) for xmldoc in xmldocs: result |= find_segments(xmldoc, '%s:%s:%d' % (ifo, name, version), use_segment_table) elif operation == DIFF: result = find_segments(xmldocs[0], '%s:%s:%d' % (ifo, name, version), use_segment_table) for xmldoc in xmldocs[1:]: result -= find_segments(xmldoc, '%s:%s:%d' % (ifo, name, version), use_segment_table) else: raise NameError ("%s is not a known operation (intersect, union or diff)" % operation) # Add a segment definer for the result seg_def_id = add_to_segment_definer(outdoc, proc_id, ifo, name, version) # Add the segments if use_segment_table: add_to_segment(outdoc, proc_id, seg_def_id, result) else: 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_add.merge_compatible_tables(outdoc) return outdoc, abs(result)
python
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 DMT-FLAG1 operation ...) DMT-FLAG2 = (file 1's DMT-FLAG2 operation file 2's DMT-FLAG2 operation ...) etc """ proc_id = table.get_table(outdoc, lsctables.ProcessTable.tableName)[0].process_id # load up the files into individual documents xmldocs = [ligolw_add.ligolw_add(ligolw.Document(), [fname]) for fname in filenames] # Get the list of dinstinct segment_definers across all docs segment_definers = {} def register_definer(seg_def): key = (seg_def.ifos, seg_def.name, seg_def.version) segment_definers[key] = True return key for xmldoc in xmldocs: seg_def_table = table.get_table(xmldoc, lsctables.SegmentDefTable.tableName) map (register_definer, seg_def_table) # For each unique segment definer, find the 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: result &= find_segments(xmldoc, '%s:%s:%d' % (ifo, name, version), use_segment_table) elif operation == UNION: result = pycbc_glue.segments.segmentlist([]) for xmldoc in xmldocs: result |= find_segments(xmldoc, '%s:%s:%d' % (ifo, name, version), use_segment_table) elif operation == DIFF: result = find_segments(xmldocs[0], '%s:%s:%d' % (ifo, name, version), use_segment_table) for xmldoc in xmldocs[1:]: result -= find_segments(xmldoc, '%s:%s:%d' % (ifo, name, version), use_segment_table) else: raise NameError ("%s is not a known operation (intersect, union or diff)" % operation) # Add a segment definer for the result seg_def_id = add_to_segment_definer(outdoc, proc_id, ifo, name, version) # Add the segments if use_segment_table: add_to_segment(outdoc, proc_id, seg_def_id, result) else: 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_add.merge_compatible_tables(outdoc) return outdoc, abs(result)
[ "def", "run_file_operation", "(", "outdoc", ",", "filenames", ",", "use_segment_table", ",", "operation", ",", "preserve", "=", "True", ")", ":", "proc_id", "=", "table", ".", "get_table", "(", "outdoc", ",", "lsctables", ".", "ProcessTable", ".", "tableName",...
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 DMT-FLAG1 operation ...) DMT-FLAG2 = (file 1's DMT-FLAG2 operation file 2's DMT-FLAG2 operation ...) etc
[ "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", "th...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/logic.py#L62-L132
gwastro/pycbc-glue
pycbc_glue/segmentdb/logic.py
run_segment_operation
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-FLAG1 this returns RESULT = (table 1's DMT-FLAG1 union table 2's DMT-FLAG1 union ...) operation (table 1's DMT-FLAG2 union table 2's DMT-FLAG2 union ...) operation etc """ proc_id = table.get_table(outdoc, lsctables.ProcessTable.tableName)[0].process_id if preserve: indoc = ligolw_add.ligolw_add(outdoc, filenames) else: indoc = ligolw_add.ligolw_add(ligolw.Document(), filenames) # Start with a segment covering all of time, then # intersect with each of the fields of interest keys = segments.split(',') if operation == INTERSECT: sgmntlist = pycbc_glue.segments.segmentlist([pycbc_glue.segments.segment(-pycbc_glue.segments.infinity(), pycbc_glue.segments.infinity())]) for key in keys: sgmntlist &= find_segments(indoc, key, use_segment_table) elif operation == UNION: 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 a known operation (intersect, union or diff)" % operation) # Add a segment definer and segments seg_def_id = add_to_segment_definer(outdoc, proc_id, '', result_name, 1) if use_segment_table: add_to_segment(outdoc, proc_id, seg_def_id, sgmntlist) else: add_to_segment_summary(outdoc, proc_id, seg_def_id, sgmntlist) return outdoc, abs(sgmntlist)
python
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-FLAG1 this returns RESULT = (table 1's DMT-FLAG1 union table 2's DMT-FLAG1 union ...) operation (table 1's DMT-FLAG2 union table 2's DMT-FLAG2 union ...) operation etc """ proc_id = table.get_table(outdoc, lsctables.ProcessTable.tableName)[0].process_id if preserve: indoc = ligolw_add.ligolw_add(outdoc, filenames) else: indoc = ligolw_add.ligolw_add(ligolw.Document(), filenames) # Start with a segment covering all of time, then # intersect with each of the fields of interest keys = segments.split(',') if operation == INTERSECT: sgmntlist = pycbc_glue.segments.segmentlist([pycbc_glue.segments.segment(-pycbc_glue.segments.infinity(), pycbc_glue.segments.infinity())]) for key in keys: sgmntlist &= find_segments(indoc, key, use_segment_table) elif operation == UNION: 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 a known operation (intersect, union or diff)" % operation) # Add a segment definer and segments seg_def_id = add_to_segment_definer(outdoc, proc_id, '', result_name, 1) if use_segment_table: add_to_segment(outdoc, proc_id, seg_def_id, sgmntlist) else: add_to_segment_summary(outdoc, proc_id, seg_def_id, sgmntlist) return outdoc, abs(sgmntlist)
[ "def", "run_segment_operation", "(", "outdoc", ",", "filenames", ",", "segments", ",", "use_segment_table", ",", "operation", ",", "result_name", "=", "'RESULT'", ",", "preserve", "=", "True", ")", ":", "proc_id", "=", "table", ".", "get_table", "(", "outdoc",...
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-FLAG1 this returns RESULT = (table 1's DMT-FLAG1 union table 2's DMT-FLAG1 union ...) operation (table 1's DMT-FLAG2 union table 2's DMT-FLAG2 union ...) operation etc
[ "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", ...
train
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentdb/logic.py#L136-L188
urosjarc/decisionTable.py
decisionTable/core.py
Table.__setWildcardSymbol
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)
python
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", "__setWildcardSymbol", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "if", "not", "value", "is", "str", "and", "not", "value", ".", "split", "(", ")", ":", "errors", ".", "append", "(", "'wildcardSymbol_ERROR : Symbol : must be char or...
self.__wildcardSymbol variable setter
[ "self", ".", "__wildcardSymbol", "variable", "setter" ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L41-L51
urosjarc/decisionTable.py
decisionTable/core.py
Table.__setParentSymbol
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)
python
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", "__setParentSymbol", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "if", "not", "value", "is", "str", "and", "not", "value", ".", "split", "(", ")", ":", "errors", ".", "append", "(", "'parentSymbol_ERROR : Symbol : must be char or str...
self.__parentSymbol variable setter
[ "self", ".", "__parentSymbol", "variable", "setter" ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L53-L63
urosjarc/decisionTable.py
decisionTable/core.py
Table.__tableStringParser
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. ValueError: Missing parent data. Returns: Array of header and decisions:: print(return) [ ['headerVar1', ... ,'headerVarN'], [ ['decisionValue1', ... ,'decisionValueN'], [<row2 strings>], ... [<rowN strings>] ] ] """ error = [] header = [] decisions = [] if tableString.split() == []: error.append('Table variable is empty!') else: tableString = tableString.split('\n') newData = [] for element in tableString: if element.strip(): newData.append(element) for element in newData[0].split(): if not element in header: header.append(element) else: error.append('Header element: ' + element + ' is not unique!') for i, tableString in enumerate(newData[2:]): split = 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]
python
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. ValueError: Missing parent data. Returns: Array of header and decisions:: print(return) [ ['headerVar1', ... ,'headerVarN'], [ ['decisionValue1', ... ,'decisionValueN'], [<row2 strings>], ... [<rowN strings>] ] ] """ error = [] header = [] decisions = [] if tableString.split() == []: error.append('Table variable is empty!') else: tableString = tableString.split('\n') newData = [] for element in tableString: if element.strip(): newData.append(element) for element in newData[0].split(): if not element in header: header.append(element) else: error.append('Header element: ' + element + ' is not unique!') for i, tableString in enumerate(newData[2:]): split = 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", "__tableStringParser", "(", "self", ",", "tableString", ")", ":", "error", "=", "[", "]", "header", "=", "[", "]", "decisions", "=", "[", "]", "if", "tableString", ".", "split", "(", ")", "==", "[", "]", ":", "error", ".", "append", "(", "'T...
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. ValueError: Missing parent data. Returns: Array of header and decisions:: print(return) [ ['headerVar1', ... ,'headerVarN'], [ ['decisionValue1', ... ,'decisionValueN'], [<row2 strings>], ... [<rowN strings>] ] ]
[ "Will", "parse", "and", "check", "tableString", "parameter", "for", "any", "invalid", "strings", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L65-L124
urosjarc/decisionTable.py
decisionTable/core.py
Table.__replaceSpecialValues
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(decisions): if '.' in line: for i, element in enumerate(line): if row == 0: error.append( "Row: {}colume: {}==> don't have parent value".format(str(row).ljust(4), str(i).ljust(4))) if element == self.__parentSymbol: if decisions[row - 1][i] == '.': error.append("Row: {}Colume: {}==> don't have parent value".format(str(row).ljust(4), str(i).ljust(4))) decisions[row][i] = decisions[row - 1][i] if error: view.Tli.showErrors('ReplaceSpecialValuesError', error) else: return decisions
python
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(decisions): if '.' in line: for i, element in enumerate(line): if row == 0: error.append( "Row: {}colume: {}==> don't have parent value".format(str(row).ljust(4), str(i).ljust(4))) if element == self.__parentSymbol: if decisions[row - 1][i] == '.': error.append("Row: {}Colume: {}==> don't have parent value".format(str(row).ljust(4), str(i).ljust(4))) decisions[row][i] = decisions[row - 1][i] if error: view.Tli.showErrors('ReplaceSpecialValuesError', error) else: return decisions
[ "def", "__replaceSpecialValues", "(", "self", ",", "decisions", ")", ":", "error", "=", "[", "]", "for", "row", ",", "line", "in", "enumerate", "(", "decisions", ")", ":", "if", "'.'", "in", "line", ":", "for", "i", ",", "element", "in", "enumerate", ...
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.
[ "Will", "replace", "special", "values", "in", "decisions", "array", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L126-L155
urosjarc/decisionTable.py
decisionTable/core.py
Table.__toString
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
python
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", "__toString", "(", "self", ",", "values", ")", ":", "for", "key", "in", "values", ":", "if", "not", "values", "[", "key", "]", "is", "str", ":", "values", "[", "key", "]", "=", "str", "(", "values", "[", "key", "]", ")", "return", "values"...
Will replace dict values with string values Args: values (dict): Dictionary of values Returns: Updated values dict
[ "Will", "replace", "dict", "values", "with", "string", "values" ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L157-L170
urosjarc/decisionTable.py
decisionTable/core.py
Table.__valueKeyWithHeaderIndex
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 header array), ... } """ machingIndexes = {} for index, name in enumerate(self.header): if name in values: machingIndexes[index] = values[name] return machingIndexes
python
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 header array), ... } """ machingIndexes = {} for index, name in enumerate(self.header): if name in values: machingIndexes[index] = values[name] return machingIndexes
[ "def", "__valueKeyWithHeaderIndex", "(", "self", ",", "values", ")", ":", "machingIndexes", "=", "{", "}", "for", "index", ",", "name", "in", "enumerate", "(", "self", ".", "header", ")", ":", "if", "name", "in", "values", ":", "machingIndexes", "[", "in...
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 header array), ... }
[ "This", "is", "hellper", "function", "so", "that", "we", "can", "mach", "decision", "values", "with", "row", "index", "as", "represented", "in", "header", "index", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L172-L192
urosjarc/decisionTable.py
decisionTable/core.py
Table.__checkDecisionParameters
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. ValueError: Not find result key in header. ValueError: Result value is empty. Returns: Error array values """ error = [] if not result: error.append('Function parameter (result array) should contain one or more header string!') if not values: error.append('Function parameter (values variables) should contain one or more variable') for header in result: if not header in self.header: error.append('String (' + header + ') in result is not in header!') for header in values: if not header in self.header: error.append('Variable (' + header + ') in values is not in header!') elif not values[header].split(): error.append('Variable (' + header + ') in values is empty string') if error: return error
python
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. ValueError: Not find result key in header. ValueError: Result value is empty. Returns: Error array values """ error = [] if not result: error.append('Function parameter (result array) should contain one or more header string!') if not values: error.append('Function parameter (values variables) should contain one or more variable') for header in result: if not header in self.header: error.append('String (' + header + ') in result is not in header!') for header in values: if not header in self.header: error.append('Variable (' + header + ') in values is not in header!') elif not values[header].split(): error.append('Variable (' + header + ') in values is empty string') if error: return error
[ "def", "__checkDecisionParameters", "(", "self", ",", "result", ",", "*", "*", "values", ")", ":", "error", "=", "[", "]", "if", "not", "result", ":", "error", ".", "append", "(", "'Function parameter (result array) should contain one or more header string!'", ")", ...
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. ValueError: Not find result key in header. ValueError: Result value is empty. Returns: Error array values
[ "Checker", "of", "decision", "parameters", "it", "will", "raise", "ValueError", "if", "finds", "something", "wrong", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L194-L231
urosjarc/decisionTable.py
decisionTable/core.py
Table.__getDecision
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, (headerString : value). Returns: Maped result values with finded elements in row/row. """ values = self.__toString(values) __valueKeyWithHeaderIndex = self.__valueKeyWithHeaderIndex(values) errors = self.__checkDecisionParameters(result, **values) if errors: view.Tli.showErrors('ParametersError', errors) machingData = {} for line in self.decisions: match = True for index in __valueKeyWithHeaderIndex: if line[index] != __valueKeyWithHeaderIndex[index]: if line[index] != self.__wildcardSymbol: match = False break if match: if multiple: for header in result: if header not in machingData: machingData[header] = [line[self.header.index(header)]] else: machingData[header].append(line[self.header.index(header)]) else: for header in result: machingData[header] = line[self.header.index(header)] return machingData 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)
python
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, (headerString : value). Returns: Maped result values with finded elements in row/row. """ values = self.__toString(values) __valueKeyWithHeaderIndex = self.__valueKeyWithHeaderIndex(values) errors = self.__checkDecisionParameters(result, **values) if errors: view.Tli.showErrors('ParametersError', errors) machingData = {} for line in self.decisions: match = True for index in __valueKeyWithHeaderIndex: if line[index] != __valueKeyWithHeaderIndex[index]: if line[index] != self.__wildcardSymbol: match = False break if match: if multiple: for header in result: if header not in machingData: machingData[header] = [line[self.header.index(header)]] else: machingData[header].append(line[self.header.index(header)]) else: for header in result: machingData[header] = line[self.header.index(header)] return machingData 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", "__getDecision", "(", "self", ",", "result", ",", "multiple", "=", "False", ",", "*", "*", "values", ")", ":", "values", "=", "self", ".", "__toString", "(", "values", ")", "__valueKeyWithHeaderIndex", "=", "self", ".", "__valueKeyWithHeaderIndex", "(...
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, (headerString : value). Returns: Maped result values with finded elements in row/row.
[ "The", "main", "method", "for", "decision", "picking", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L233-L281
urosjarc/decisionTable.py
decisionTable/core.py
Table.decisionCall
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 string **values (dict): What should finder look for, (headerString : value). Example: >>> def call(header1,header2): >>> print(header1,header2) >>> >>> table = DecisionTable(''' >>> header1 header2 >>> =============== >>> value1 value2 >>> ''') >>> >>> header1, header2 = table.decision( >>> call, >>> ['header1','header2'], >>> header1='value1', >>> header2='value2' >>> ) (value1 value2) """ callback(**self.__getDecision(result, **values))
python
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 string **values (dict): What should finder look for, (headerString : value). Example: >>> def call(header1,header2): >>> print(header1,header2) >>> >>> table = DecisionTable(''' >>> header1 header2 >>> =============== >>> value1 value2 >>> ''') >>> >>> header1, header2 = table.decision( >>> call, >>> ['header1','header2'], >>> header1='value1', >>> header2='value2' >>> ) (value1 value2) """ callback(**self.__getDecision(result, **values))
[ "def", "decisionCall", "(", "self", ",", "callback", ",", "result", ",", "*", "*", "values", ")", ":", "callback", "(", "*", "*", "self", ".", "__getDecision", "(", "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 **values (dict): What should finder look for, (headerString : value). Example: >>> def call(header1,header2): >>> print(header1,header2) >>> >>> table = DecisionTable(''' >>> header1 header2 >>> =============== >>> value1 value2 >>> ''') >>> >>> header1, header2 = table.decision( >>> call, >>> ['header1','header2'], >>> header1='value1', >>> header2='value2' >>> ) (value1 value2)
[ "The", "decision", "method", "with", "callback", "option", ".", "This", "method", "will", "find", "matching", "row", "construct", "a", "dictionary", "and", "call", "callback", "with", "dictionary", ".", "Args", ":", "callback", "(", "function", ")", ":", "Ca...
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L283-L309
urosjarc/decisionTable.py
decisionTable/core.py
Table.decision
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 **values (dict): What should finder look for, (headerString : value). Returns: Arrays of finded values strings Example: >>> table = DecisionTable(''' >>> header1 header2 >>> =============== >>> value1 value2 >>> ''') >>> >>> header1, header2 = table.decision( >>> ['header1','header2'], >>> header1='value1', >>> header2='value2' >>> ) >>> print(header1,header2) (value1 value2) """ data = self.__getDecision(result, **values) data = [data[value] for value in result] if len(data) == 1: return data[0] else: return data
python
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 **values (dict): What should finder look for, (headerString : value). Returns: Arrays of finded values strings Example: >>> table = DecisionTable(''' >>> header1 header2 >>> =============== >>> value1 value2 >>> ''') >>> >>> header1, header2 = table.decision( >>> ['header1','header2'], >>> header1='value1', >>> header2='value2' >>> ) >>> print(header1,header2) (value1 value2) """ data = self.__getDecision(result, **values) data = [data[value] for value in result] if len(data) == 1: return data[0] else: return data
[ "def", "decision", "(", "self", ",", "result", ",", "*", "*", "values", ")", ":", "data", "=", "self", ".", "__getDecision", "(", "result", ",", "*", "*", "values", ")", "data", "=", "[", "data", "[", "value", "]", "for", "value", "in", "result", ...
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 **values (dict): What should finder look for, (headerString : value). Returns: Arrays of finded values strings Example: >>> table = DecisionTable(''' >>> header1 header2 >>> =============== >>> value1 value2 >>> ''') >>> >>> header1, header2 = table.decision( >>> ['header1','header2'], >>> header1='value1', >>> header2='value2' >>> ) >>> print(header1,header2) (value1 value2)
[ "The", "decision", "method", "with", "callback", "option", ".", "This", "method", "will", "find", "matching", "row", "construct", "a", "dictionary", "and", "call", "callback", "with", "dictionary", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L311-L343
urosjarc/decisionTable.py
decisionTable/core.py
Table.allDecisions
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: return data[0] else: return data
python
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: return data[0] else: return data
[ "def", "allDecisions", "(", "self", ",", "result", ",", "*", "*", "values", ")", ":", "data", "=", "self", ".", "__getDecision", "(", "result", ",", "multiple", "=", "True", ",", "*", "*", "values", ")", "data", "=", "[", "data", "[", "value", "]",...
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.
[ "Joust", "like", "self", ".", "decision", "but", "for", "multiple", "finded", "values", "." ]
train
https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L345-L357