code stringlengths 1 18.2k |
|---|
def Fold(seglist1, seglist2): """ An iterator that generates the results of taking the intersection of seglist1 with each segment in seglist2 in turn. In each result, the segment start and stop values are adjusted to be with respect to the start of the corresponding segment in seglist2. See also the segmentlist_range()... |
seg in seglist2: yield (seglist1 & segments.segmentlist([seg])).shift(-seg[0]) |
def vote(seglists, n): """ Given a sequence of segmentlists, returns the intervals during which at least n of them intersect. The input segmentlists must be coalesced, the output is coalesced. Example: >>> from pycbc_glue.segments import * >>> w = segmentlist([segment(0, 15)]) >>> x = segmentlist([segment(5, 20)]) >>> ... |
segmentlists into an ordered sequence of off-on and # on-off transitions with the vote count for each transition # FIXME: this generator is declared locally for now, is it useful # as a stand-alone generator? def pop_min(l): # remove and return the smallest value from a list val = min(l) for i in xrange(len(l) - 1, -1,... |
this_bound, delta, segiter = pop_min(queue) if this_bound == bound: votes += delta else: yield bound, votes bound = this_bound votes = delta if segiter is not None: try: seg = segiter.next() except StopIteration: continue queue.append((seg[1], -1, segiter)) queue.append((seg[0], +1, None)) yield bound, votes # compute ... |
detect failed cumulative sum return result |
def validate_proxy(path): """Validate the users X509 proxy certificate Tests that the proxy certificate is RFC 3820 compliant and that it is valid for at least the next 15 minutes. @returns: L{True} if the certificate validates @raises RuntimeError: if the certificate cannot be validated """ # load the proxy from path ... |
= proxy.get_not_after().__str__() expireGMT = time.strptime(expireASN1, "%b %d %H:%M:%S %Y %Z") expireUTC = calendar.timegm(expireGMT) now = int(time.time()) secondsLeft = expireUTC - now except Exception, e: # problem getting or parsing time so just let the client # continue and pass the issue along to the server seco... |
def find_credential(): """Locate the users X509 certificate and key files This method uses the C{X509_USER_CERT} and C{X509_USER_KEY} to locate valid proxy information. If those are not found, the standard location in /tmp/ is searched. @raises RuntimeError: if the proxy found via either method cannot be validated @rai... |
"/tmp/x509up_u%d" % uid if os.access(path, os.R_OK): if validate_proxy(path): return path, path else: raise RuntimeError(rfc_proxy_msg) # if we get here could not find a credential raise RuntimeError(rfc_proxy_msg) |
def find_server(): """Find the default server host from the environment This method uses the C{LIGO_DATAFIND_SERVER} variable to construct a C{(host, port)} tuple. @returns: C{(host, port)}: the L{str} host name and L{int} port number @raises RuntimeError: if the C{LIGO_DATAFIND_SERVER} environment variable is not set ... |
def _requestresponse(self, method, url, body=None, headers={}): """Internal method to perform request and verify reponse. @param method: name of the method to use (e.g. 'GET') @param url : remote URL to query @type method: L{str} @type url : L{str} @returns: L{str} response from server query @raises RuntimeError: if qu... |
def find_observatories(self, match=None): """Query the LDR host for observatories. Use match to restrict returned observatories to those matching the regular expression. Example: >>> connection.find_observatories() ['AGHLT', 'G', 'GHLTV', 'GHLV', 'GHT', 'H', 'HL', 'HLT', 'L', 'T', 'V', 'Z'] >>> connection.find_observat... |
def find_types(self, site=None, match=None): """Query the LDR host for frame types. Use site to restrict query to given observatory prefix, and use match to restrict returned types to those matching the regular expression. Example: >>> connection.find_types("L", "RDS") ['L1_RDS_C01_LX', 'L1_RDS_C02_LX', 'L1_RDS_C03_L2'... |
def find_times(self, site, frametype, gpsstart=None, gpsend=None): """Query the LDR for times for which frames are avaliable Use gpsstart and gpsend to restrict the returned times to this semiopen interval. @returns: L{segmentlist<pycbc_glue.segments.segmentlist>} @param site: single-character name of site to match @pa... |
def find_frame(self, framefile, urltype=None, on_missing="warn"): """Query the LDR host for a single framefile @returns: L{Cache<pycbc_glue.lal.Cache>} @param frametype: name of frametype to match @param urltype: file scheme to search for (e.g. 'file') @param on_missing: what to do when the requested frame isn't found,... |
= self._requestresponse("GET", url) urllist = decode(response.read()) if len(urllist) == 0: if on_missing == "warn": sys.stderr.write("No files found!\n") elif on_missing == "error": raise RuntimeError("No files found!") # verify urltype is what we want cache = lal.Cache(e for e in [lal.CacheEntry.from_T050017(x, colty... |
def find_frame_urls(self, site, frametype, gpsstart, gpsend, match=None, urltype=None, on_gaps="warn"): """Find the framefiles for the given type in the [start, end) interval frame @param site: single-character name of site to match @param frametype: name of frametype to match @param gpsstart: integer GPS start time of... |
C{on_gaps='error'} """ if on_gaps not in ("warn", "error", "ignore"): raise ValueError("on_gaps must be 'warn', 'error', or 'ignore'.") url = ("%s/gwf/%s/%s/%s,%s" % (_url_prefix, site, frametype, gpsstart, gpsend)) # if a URL type is specified append it to the path if urltype: url += "/%s" % urltype # request JSON out... |
else: raise RuntimeError(msg) |
def WalkChildren(elem): """ Walk the XML tree of children below elem, returning each in order. """ for child in elem.childNodes: yield child for elem in WalkChildren(child): yield elem |
def make_parser(handler): """ Convenience function to construct a document parser with namespaces enabled and validation disabled. Document validation is a nice feature, but enabling validation can require the LIGO LW DTD to be downloaded from the LDAS document server if the DTD is not included inline in the XML. This ... |
def appendChild(self, child): """ Add a child to this element. The child's parentNode attribute is updated, too. """ self.childNodes.append(child) child.parentNode = self self._verifyChildren(len(self.childNodes) - 1) return child |
def insertBefore(self, newchild, refchild): """ Insert a new child node before an existing child. It must be the case that refchild is a child of this node; if not, ValueError is raised. newchild is returned. """ for i, childNode in enumerate(self.childNodes): if childNode is refchild: self.childNodes.insert(i, newchil... |
def removeChild(self, child): """ Remove a child from this element. The child element is returned, and it's parentNode element is reset. If the child will not be used any more, you should call its unlink() method to promote garbage collection. """ for i, childNode in enumerate(self.childNodes): if childNode is child: d... |
def unlink(self): """ Break internal references within the document tree rooted on this element to promote garbage collection. """ self.parentNode = None for child in self.childNodes: child.unlink() del self.childNodes[:] |
def replaceChild(self, newchild, oldchild): """ Replace an existing node with a new node. It must be the case that oldchild is a child of this node; if not, ValueError is raised. newchild is returned. """ # .index() would use compare-by-value, we want # compare-by-id because we want to find the exact object, # not some... |
def getElements(self, filter): """ Return a list of elements below and including this element for which filter(element) returns True. """ l = reduce(lambda l, e: l + e.getElements(filter), self.childNodes, []) if filter(self): l.append(self) return l |
def appendData(self, content): """ Add characters to the element's pcdata. """ if self.pcdata is not None: self.pcdata += content else: self.pcdata = content |
def write(self, fileobj = sys.stdout, indent = u""): """ Recursively write an element and it's children to a file. """ fileobj.write(self.start_tag(indent)) fileobj.write(u"\n") for c in self.childNodes: if c.tagName not in self.validchildren: raise ElementError("invalid child %s for %s" % (c.tagName, self.tagName)) c.... |
def start_tag(self, indent): """ Generate the string for the element's start tag. """ return u"%s<%s%s/>" % (indent, self.tagName, u"".join(u" %s=\"%s\"" % keyvalue for keyvalue in self.attributes.items())) |
def write(self, fileobj = sys.stdout, indent = u""): """ Recursively write an element and it's children to a file. """ fileobj.write(self.start_tag(indent)) fileobj.write(u"\n") |
def now(cls, Name = None): """ Instantiate a Time element initialized to the current UTC time in the default format (ISO-8601). The Name attribute will be set to the value of the Name parameter if given. """ self = cls() if Name is not None: self.Name = Name self.pcdata = datetime.datetime.utcnow() return self |
def from_gps(cls, gps, Name = None): """ Instantiate a Time element initialized to the value of the given GPS time. The Name attribute will be set to the value of the Name parameter if given. Note: the new Time element holds a reference to the GPS time, not a copy of it. Subsequent modification of the GPS time object w... |
def write(self, fileobj = sys.stdout, xsl_file = None): """ Write the document. """ fileobj.write(Header) fileobj.write(u"\n") if xsl_file is not None: fileobj.write(u'<?xml-stylesheet type="text/xsl" href="%s" ?>\n' % xsl_file) for c in self.childNodes: if c.tagName not in self.validchildren: raise ElementError("inval... |
def start_element(self, name, attrs): """ Callback for start of an XML element. Checks to see if we are about to start a table that matches the ignore pattern. @param name: the name of the tag being opened @type name: string @param attrs: a dictionary of the attributes for the tag being opened @type attrs: dictionary "... |
def parse_line(self, line): """ For each line we are passed, call the XML parser. Returns the line if we are outside one of the ignored tables, otherwise returns the empty string. @param line: the line of the LIGO_LW XML file to be parsed @type line: string @return: the line of XML passed in or the null string @rtype: ... |
def ping(self): """ Ping the LDBD Server and return any message received back as a string. @return: message received (may be empty) from LDBD Server as a string """ msg = "PING\0" self.sfile.write(msg) ret, output = self.__response__() reply = str(output[0]) if ret: msg = "Error pinging server %d:%s" % (ret, reply) rai... |
def query(self,sql): """ Execute an SQL query on the server and fetch the resulting XML file back. @return: message received (may be empty) from LDBD Server as a string """ msg = "QUERY\0" + sql + "\0" self.sfile.write(msg) ret, output = self.__response__() reply = str(output[0]) if ret: msg = "Error executing query on... |
def insert(self,xmltext): """ Insert the LIGO_LW metadata in the xmltext string into the database. @return: message received (may be empty) from LDBD Server as a string """ msg = "INSERT\0" + xmltext + "\0" self.sfile.write(msg) ret, output = self.__response__() reply = str(output[0]) if ret: msg = "Error executing ins... |
def insertmap(self,xmltext,lfnpfn_dict): """ Insert the LIGO_LW metadata in the xmltext string into the database. @return: message received (may be empty) from LDBD Server as a string """ pmsg = cPickle.dumps(lfnpfn_dict) msg = "INSERTMAP\0" + xmltext + "\0" + pmsg + "\0" self.sfile.write(msg) ret, output = self.__resp... |
def dayOfWeek(year, month, day): "returns day of week: 0=Sun, 1=Mon, .., 6=Sat" hr = 12 #make sure you fall into right day, middle is save t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1)) pyDow = time.localtime(t)[6] gpsDow = (pyDow + 1) % 7 return gpsDow |
def gpsWeek(year, month, day): "returns (full) gpsWeek for given date (in UTC)" hr = 12 #make sure you fall into right day, middle is save return gpsFromUTC(year, month, day, hr, 0, 0.0)[0] |
def julianDay(year, month, day): "returns julian day=day since Jan 1 of year" hr = 12 #make sure you fall into right day, middle is save t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1)) julDay = time.localtime(t)[7] return julDay |
def mkUTC(year, month, day, hour, min, sec): "similar to python's mktime but for utc" spec = [year, month, day, hour, min, sec] + [0, 0, 0] utc = time.mktime(spec) - time.timezone return utc |
def wtFromUTCpy(pyUTC, leapSecs=14): """convenience function: allows to use python UTC times and returns only week and tow""" ymdhms = ymdhmsFromPyUTC(pyUTC) wSowDSoD = apply(gpsFromUTC, ymdhms + (leapSecs,)) return wSowDSoD[0:2] |
def gpsFromUTC(year, month, day, hour, min, sec, leapSecs=14): """converts UTC to: gpsWeek, secsOfWeek, gpsDay, secsOfDay a good reference is: http://www.oc.nps.navy.mil/~jclynch/timsys.html This is based on the following facts (see reference above): GPS time is basically measured in (atomic) seconds since January 6, 1... |
integer seconds, fractions are lost!!! """ secFract = sec % 1 epochTuple = gpsEpoch + (-1, -1, 0) t0 = time.mktime(epochTuple) t = time.mktime((year, month, day, hour, min, sec, -1, -1, 0)) # Note: time.mktime strictly works in localtime and to yield UTC, it should be # corrected with time.timezone # However, since we ... |
def UTCFromGps(gpsWeek, SOW, leapSecs=14): """converts gps week and seconds to UTC see comments of inverse function! SOW = seconds of week gpsWeek is the full number (not modulo 1024) """ secFract = SOW % 1 epochTuple = gpsEpoch + (-1, -1, 0) t0 = time.mktime(epochTuple) - time.timezone #mktime is localtime, correct fo... |
def GpsSecondsFromPyUTC( pyUTC, leapSecs=14 ): """converts the python epoch to gps seconds pyEpoch = the python epoch from time.time() """ t = t=gpsFromUTC(*ymdhmsFromPyUTC( pyUTC )) return int(t[0] * 60 * 60 * 24 * 7 + t[1]) |
def genMeme(template_id, text0, text1): ''' This function returns the url of the meme with the given template, upper text, and lower text using the ImgFlip meme generation API. Thanks! Returns None if it is unable to generate the meme. ''' username = 'blag' password = 'blag' api_url = 'https://api.imgflip.com/caption_i... |
def findMeme(inptStr): ''' inptStr may be a string of the following forms: * 'text0 | text1' * 'text0' Returns None if it can't find find a meme from the list given above ''' global meme_id_dict testStr = inptStr testStr.lower() template_id = 0 ''' meme_id_dict[i] is of form: [meme_tagline, meme_name, template_id] ''' ... |
def processMeme(imgParams): ''' Wrapper function for genMeme() and findMeme() imgParams may be a string of the following forms: * 'text0 | text1' * 'text0' * ' | text1' Fails gracefully when it can't find or generate a meme by returning an appropriate image url with the failure message on it. ''' template_id = findMeme... |
else: # Success! # print(imgURL) return imgURL elif len(imgParams) > 2: print("Too many lines of captions! Cannot create meme.") return too_many_lines elif len(imgParams) < 1: # No top text text0 exists print("Too few lines of captions! Cannot create meme.") return too_few_lines |
def string_format_func(s): """ Function used internally to format string data for output to XML. Escapes back-slashes and quotes, and wraps the resulting string in quotes. """ return u"\"%s\"" % unicode(s).replace(u"\\", u"\\\\").replace(u"\"", u"\\\"") |
def mk_complex_format_func(fmt): """ Function used internally to generate functions to format complex valued data. """ fmt = fmt + u"+i" + fmt def complex_format_func(z): return fmt % (z.real, z.imag) return complex_format_func |
def fields(iterable, fields=None): """ Add a set of fields to each item in ``iterable``. The set of fields have a key=value format. '@' are added to the front of each key. """ if not fields: for item in iterable: yield item prepared_fields = _prepare_fields(fields) for item in iterable: yield _process_fields(item, prep... |
def tag(iterable, tags=None, key='@tags'): """ Add tags to each dict or dict-like object in ``iterable``. Tags are added to each dict with a key set by ``key``. If a key already exists under the key given by ``key``, this function will attempt to ``.extend()``` it, but will fall back to replacing it in the event of err... |
def _request(self, uri, params=None, postParams=None, verb='GET'): """Execute a request on the plugit api""" return getattr(requests, verb.lower())(self.url + uri, params=params, data=postParams, stream=True) |
def get_user(self, userPk): """Returns the user specified with the user's Pk or UUID""" r = self._request('user/' + str(userPk)) if r: # Set base properties and copy data inside the user u = User() u.pk = u.id = userPk u.__dict__.update(r.json()) return u return None |
def get_subscription_labels(self, userPk): """Returns a list with all the labels the user is subscribed to""" r = self._request('subscriptions/' + str(userPk)) if r: s = r.json() return s return [] |
def get_orgas(self): """Return the list of pk for all orgas""" r = self._request('orgas/') if not r: return None retour = [] for data in r.json()['data']: o = Orga() o.__dict__.update(data) o.pk = o.id retour.append(o) return retour |
def get_orga(self, orgaPk): """Return an organization speficied with orgaPk""" r = self._request('orga/' + str(orgaPk)) if r: # Set base properties and copy data inside the orga o = Orga() o.pk = o.id = orgaPk o.__dict__.update(r.json()) return o return None |
def get_project_members(self): """Return the list of members in the project""" r = self._request('members/') if not r: return None retour = [] for data in r.json()['members']: # Base properties u = User() u.__dict__.update(data) retour.append(u) return retour |
def send_mail(self, sender, subject, recipients, message, response_id=None, html_message=False): """Send an email using EBUio features. If response_id is set, replies will be send back to the PlugIt server.""" params = { 'sender': sender, 'subject': subject, 'dests': recipients, 'message': message, 'html_message': html... |
def forum_create_topic(self, subject, author, message, tags=""): """Create a topic using EBUio features.""" params = {'subject': subject, 'author': author, 'message': message, 'tags': tags} return self._request('ebuio/forum/', postParams=params, verb='POST') |
def forum_topic_get_by_tag_for_user(self, tag=None, author=None): """Get all forum topics with a specific tag""" if not tag: return None if author: r = self._request('ebuio/forum/search/bytag/' + tag + '?u=' + author) else: r = self._request('ebuio/forum/search/bytag/' + tag) if not r: return None retour = [] for data ... |
def get_for_directory( dp, hash_mode="md5", filter_dots=False, filter_func=lambda fp:False ): r""" Returns a hash string for the files below a given directory path. :param dp: Path to a directory. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resu... |
_filter_dot_fns, root_dps_fns ) fps_lists = itertools.imap( _gen_fps, root_dps_fns ) fps = itertools.chain( *fps_lists ) fps = itertools.ifilterfalse( filter_func, fps ) file_handles = itertools.imap( _get_file_handle, fps ) file_hash_digests = itertools.imap( _get_file_hash_digest, file_handles, itertools.repeat(hash_... |
def get_for_file( fp, hash_mode="md5" ): r""" Returns a hash string for the given file path. :param fp: Path to the file. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. """ with _get_file_handle(fp) as f: fi... |
def get_for_handle( f, hash_mode="md5" ): r""" Returns a hash string for the given file-like object. :param f: The file object. :param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'. Defines the algorithm used to generate the resulting hash string. Default is 'md5'. """ hash_func = _HASH_MODE_DICT.... |
def getArraysByName(elem, name): """ Return a list of arrays with name name under elem. """ name = StripArrayName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Array.tagName) and (e.Name == name)) |
def from_array(name, array, dim_names = None): """ Construct a LIGO Light Weight XML Array document subtree from a numpy array object. Example: >>> import numpy, sys >>> a = numpy.arange(12, dtype = "double") >>> a.shape = (4, 3) >>> from_array(u"test", a).write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE <Array Type=... |
doc |
def get_array(xmldoc, name): """ Scan xmldoc for an array named name. Raises ValueError if not exactly 1 such array is found. """ arrays = getArraysByName(xmldoc, name) if len(arrays) != 1: raise ValueError("document must contain exactly one %s array" % StripArrayName(name)) return arrays[0] |
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Array and ArrayStream classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler):... |
def get_shape(self): """ Return a tuple of this array's dimensions. This is done by querying the Dim children. Note that once it has been created, it is also possible to examine an Array object's .array attribute directly, and doing that is much faster. """ return tuple(int(c.pcdata) for c in self.getElementsByTagName(... |
def get_conversejs_settings(): """This helper function returns all the configuration needed by Converse.js frontend (javascript). Configurations specific to django-conversejs should be added above. """ converse_settings = { 'CONVERSEJS_AUTO_LIST_ROOMS': False, 'CONVERSEJS_AUTO_SUBSCRIBE': False, 'CONVERSEJS_BOSH_SERVIC... |
def get_all_files_in_range(dirname, starttime, endtime, pad=64): """Returns all files in dirname and all its subdirectories whose names indicate that they contain segments in the range starttime to endtime""" ret = [] # Maybe the user just wants one file... if os.path.isfile(dirname): if re.match('.*-[0-9]*-[0-9]*\.xml... |
# ifos, each of which has directories with times ret += get_all_files_in_range(os.path.join(dirname,filename), starttime, endtime, pad=pad) return ret |
def setup_database(database_location): """ 1. Determine protocol""" try: # When no protocol is given: if database_location.find('://') == -1: msg = "Error: Please specify protocol in your --segment-url argument in the format PROTOCOL://HOST" msg +="\nFor example: --segment-url https://segdb.ligo.caltech.edu" msg += "\n... |
0: # if no port number given, set default port respectively: host = host_and_port if protocol == 'http': port = 80 elif protocol == 'https': port = 443 elif protocol == 'ldbd': port = 30015 elif protocol == 'ldbdi': port = 30016 else: host, portString = host_and_port.split(':') port = int(portString) if port == 30020: ... |
+= host from pycbc_glue import gsiserverutils else: identity = None try: from pycbc_glue import LDBDClient client = LDBDClient.LDBDClient(host,port,identity) except Exception, e: print >>sys.stderr, "Unable to connect to LDBD Server at %s://%s:%d" % (protocol,host, port) + str(e) try: if gsiserverutils.checkCredentials... |
def ensure_segment_table(connection): """Ensures that the DB represented by connection posses a segment table. If not, creates one and prints a warning to stderr""" count = connection.cursor().execute("SELECT count(*) FROM sqlite_master WHERE name='segment'").fetchone()[0] if count == 0: print >>sys.stderr, "WARNING: N... |
def build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Optains a list of segments for the given ifo, name and version between the specified times. If a version is given the request is straightforward and is passed on to build_segment_list_one. Oth... |
end_pad) |
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0): """Builds a list of segments satisfying the given criteria """ seg_result = segmentlist([]) sum_result = segmentlist([]) # Is there any way to get segment and segement summary in one query? #... |
OR segment_summary.start_time > %s)" % (gps_start_time, gps_end_time) rows = engine.query(sql) for sum_start_time, sum_end_time in rows: sum_start_time = (sum_start_time < gps_start_time) and gps_start_time or sum_start_time sum_end_time = (sum_end_time > gps_end_time) and gps_end_time or sum_end_time sum_result |= seg... |
(gps_start_time, gps_end_time) rows = engine.query(sql) for seg_start_time, seg_end_time in rows: seg_start_time = (seg_start_time < gps_start_time) and gps_start_time or seg_start_time seg_end_time = (seg_end_time > gps_end_time) and gps_end_time or seg_end_time seg_result |= segmentlist([segment(seg_start_time, seg_e... |
def run_query_segments(doc, proc_id, engine, gps_start_time, gps_end_time, included_segments_string, excluded_segments_string = None, write_segments = True, start_pad = 0, end_pad = 0): """Runs a segment query. This was originally part of ligolw_query_segments, but now is also used by ligolw_segments_from_cats. The wri... |
segmentlist([]) for ifo, segment_name, version in split_segment_ids(excluded_segments_string.split(',')): sum_segments, seg_segments = build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version) excluded_segments |= seg_segments result = result - excluded_segments result.coalesce() # Add the se... |
def split_segment_ids(segment_ids): """Given an array of strings of the form ifo:name and ifo:name:version, returns an array of tuples of the form (ifo, name, version) where version may be None""" def split_segment_id(segment_id): temp = segment_id.split(':') if len(temp) == 2: temp.append(None) elif temp[2] == '*': te... |
def url2path(url): """ If url identifies a file on the local host, return the path to the file otherwise raise ValueError. """ scheme, host, path, nul, nul, nul = urlparse(url) if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"): return path raise ValueError(url) |
def remove_input(urls, preserves, verbose = False): """ Attempt to delete all files identified by the URLs in urls except any that are the same as the files in the preserves list. """ for path in map(url2path, urls): if any(os.path.samefile(path, preserve) for preserve in preserves): continue if verbose: print >>sys.st... |
def reassign_ids(doc, verbose = False): """ Assign new IDs to all rows in all LSC tables in doc so that there are no collisions when the LIGO_LW elements are merged. """ # Can't simply run reassign_ids() on doc because we need to # construct a fresh old --> new mapping within each LIGO_LW block. for n, elem in enumerat... |
def merge_ligolws(elem): """ Merge all LIGO_LW elements that are immediate children of elem by appending their children to the first. """ ligolws = [child for child in elem.childNodes if child.tagName == ligolw.LIGO_LW.tagName] if ligolws: dest = ligolws.pop(0) for src in ligolws: # copy children; LIGO_LW elements have... |
def compare_table_cols(a, b): """ Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise. """ return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in b.get... |
def merge_compatible_tables(elem): """ Below the given element, find all Tables whose structure is described in lsctables, and merge compatible ones of like type. That is, merge all SnglBurstTables that have the same columns into a single table, etc.. """ for name in lsctables.TableByName.keys(): tables = table.getTabl... |
def ligolw_add(xmldoc, urls, non_lsc_tables_ok = False, verbose = False, contenthandler = DefaultContentHandler): """ An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added. """ # Input for n, url in enumerate(urls): i... |
def run(self): """Loops and executes commands in interactive mode.""" if self._skip_delims: delims = readline.get_completer_delims() for delim in self._skip_delims: delims = delims.replace(delim, '') readline.set_completer_delims(delims) readline.parse_and_bind("tab: complete") readline.set_completer(self._completer.co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.