code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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("invalid child %s for %s" % (c.tagName, self.tagName))
c.write(fil... | def write(self, fileobj = sys.stdout, xsl_file = None) | Write the document. | 2.692873 | 2.641384 | 1.019493 |
if name.lower() == "table":
for attr in attrs.keys():
if attr.lower() == "name":
if self.__ignore_pat.search(attrs[attr]):
self.__in_table = 1 | 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 | 4.699185 | 3.901474 | 1.204464 |
self.__p.Parse(line)
if self.__in_table:
self.__silent = 1
if not self.__silent:
ret = line
else:
ret = ""
if not self.__in_table:
self.__silent = 0
return ret | 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: string | 5.225093 | 4.826907 | 1.082493 |
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)
raise LDBDClientException, msg
return reply | 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 | 12.719472 | 9.486834 | 1.34075 |
msg = "QUERY\0" + sql + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing query on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | 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 | 12.496443 | 8.820792 | 1.416703 |
msg = "INSERT\0" + xmltext + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing insert on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | 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 | 11.894838 | 9.690726 | 1.227445 |
pmsg = cPickle.dumps(lfnpfn_dict)
msg = "INSERTMAP\0" + xmltext + "\0" + pmsg + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing insert on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
retur... | 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 | 9.738653 | 7.955741 | 1.224104 |
"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 dayOfWeek(year, month, day) | returns day of week: 0=Sun, 1=Mon, .., 6=Sat | 6.802365 | 5.966706 | 1.140054 |
"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 gpsWeek(year, month, day) | returns (full) gpsWeek for given date (in UTC) | 22.617569 | 15.876464 | 1.424597 |
"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 julianDay(year, month, day) | returns julian day=day since Jan 1 of year | 8.405865 | 6.60864 | 1.271951 |
"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 mkUTC(year, month, day, hour, min, sec) | similar to python's mktime but for utc | 4.703095 | 3.329119 | 1.412715 |
ymdhms = ymdhmsFromPyUTC(pyUTC)
wSowDSoD = apply(gpsFromUTC, ymdhms + (leapSecs,))
return wSowDSoD[0:2] | def wtFromUTCpy(pyUTC, leapSecs=14) | convenience function:
allows to use python UTC times and
returns only week and tow | 9.238487 | 9.433817 | 0.979295 |
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 ... | 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, 1980, 00:00:00.0 (the GPS Epoch)
The... | 5.795379 | 5.643885 | 1.026842 |
secFract = SOW % 1
epochTuple = gpsEpoch + (-1, -1, 0)
t0 = time.mktime(epochTuple) - time.timezone #mktime is localtime, correct for UTC
tdiff = (gpsWeek * secsInWeek) + SOW - leapSecs
t = t0 + tdiff
(year, month, day, hh, mm, ss, dayOfWeek, julianDay, daylightsaving) = time.gmtime(t)
... | 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) | 6.334352 | 6.936097 | 0.913244 |
t = t=gpsFromUTC(*ymdhmsFromPyUTC( pyUTC ))
return int(t[0] * 60 * 60 * 24 * 7 + t[1]) | def GpsSecondsFromPyUTC( pyUTC, leapSecs=14 ) | converts the python epoch to gps seconds
pyEpoch = the python epoch from time.time() | 7.89757 | 8.326293 | 0.94851 |
'''
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_im... | 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. | 2.992999 | 2.058571 | 1.453921 |
'''
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_tag... | 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 | 4.152357 | 2.897101 | 1.43328 |
'''
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.
'''
temp... | 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. | 4.098848 | 2.615329 | 1.56724 |
return u"\"%s\"" % unicode(s).replace(u"\\", u"\\\\").replace(u"\"", u"\\\"") | 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. | 3.452075 | 3.956297 | 0.872552 |
fmt = fmt + u"+i" + fmt
def complex_format_func(z):
return fmt % (z.real, z.imag)
return complex_format_func | def mk_complex_format_func(fmt) | Function used internally to generate functions to format complex
valued data. | 3.983335 | 4.314788 | 0.923182 |
if not fields:
for item in iterable:
yield item
prepared_fields = _prepare_fields(fields)
for item in iterable:
yield _process_fields(item, prepared_fields) | 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. | 3.851654 | 4.128846 | 0.932864 |
if not tags:
for item in iterable:
yield item
else:
for item in iterable:
yield _tag(item, tags, key) | 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 error. | 3.335042 | 4.085703 | 0.816271 |
return getattr(requests, verb.lower())(self.url + uri, params=params, data=postParams, stream=True) | def _request(self, uri, params=None, postParams=None, verb='GET') | Execute a request on the plugit api | 3.658727 | 3.544685 | 1.032173 |
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_user(self, userPk) | Returns the user specified with the user's Pk or UUID | 5.864426 | 5.66049 | 1.036028 |
r = self._request('subscriptions/' + str(userPk))
if r:
s = r.json()
return s
return [] | def get_subscription_labels(self, userPk) | Returns a list with all the labels the user is subscribed to | 5.644562 | 5.374493 | 1.05025 |
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_orgas(self) | Return the list of pk for all orgas | 4.37181 | 3.980145 | 1.098405 |
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_orga(self, orgaPk) | Return an organization speficied with orgaPk | 5.520819 | 5.335368 | 1.034759 |
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 get_project_members(self) | Return the list of members in the project | 6.079929 | 5.389023 | 1.128206 |
params = {
'sender': sender,
'subject': subject,
'dests': recipients,
'message': message,
'html_message': html_message,
}
if response_id:
params['response_id'] = response_id
return self._request('mail/', ... | 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. | 2.854919 | 2.901136 | 0.984069 |
params = {'subject': subject, 'author': author, 'message': message, 'tags': tags}
return self._request('ebuio/forum/', postParams=params, verb='POST') | def forum_create_topic(self, subject, author, message, tags="") | Create a topic using EBUio features. | 5.851725 | 4.054463 | 1.44328 |
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 in r... | def forum_topic_get_by_tag_for_user(self, tag=None, author=None) | Get all forum topics with a specific tag | 3.53505 | 3.7036 | 0.95449 |
r
hash_func = _HASH_MODE_DICT.get(hash_mode)
root_dps_fns = os.walk( dp, topdown=True )
root_dps_fns = itertools.imap( list, root_dps_fns )
if filter_dots:
root_dps_fns = itertools.ifilterfalse( _is_dot_root, root_dps_fns )
root_dps_fns... | 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 resulting hash
... | 3.296344 | 3.448902 | 0.955766 |
r
with _get_file_handle(fp) as f:
file_hash_digest = get_for_handle(f, hash_mode)
return file_hash_digest | 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. Defau... | 6.897602 | 7.766012 | 0.888178 |
r
hash_func = _HASH_MODE_DICT.get(hash_mode)
file_hash_digest = _get_file_hash_digest( f, hash_func )
file_hash_digest = _get_utf8_encoded( file_hash_digest )
return file_hash_digest | 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.... | 4.288759 | 4.761996 | 0.900622 |
name = StripArrayName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Array.tagName) and (e.Name == name)) | def getArraysByName(elem, name) | Return a list of arrays with name name under elem. | 13.512795 | 11.531264 | 1.17184 |
# Type must be set for .__init__(); easier to set Name afterwards
# to take advantage of encoding handled by attribute proxy
doc = Array(Attributes({u"Type": ligolwtypes.FromNumPyType[str(array.dtype)]}))
doc.Name = name
for n, dim in enumerate(reversed(array.shape)):
child = ligolw.Dim()
if dim_names is no... | 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="real_8" Name="test:array">
<Dim>3</Dim>... | 8.488576 | 7.689615 | 1.103901 |
arrays = getArraysByName(xmldoc, name)
if len(arrays) != 1:
raise ValueError("document must contain exactly one %s array" % StripArrayName(name))
return arrays[0] | def get_array(xmldoc, name) | Scan xmldoc for an array named name. Raises ValueError if not
exactly 1 such array is found. | 4.823625 | 4.174425 | 1.155518 |
def startStream(self, parent, attrs, __orig_startStream = ContentHandler.startStream):
if parent.tagName == ligolw.Array.tagName:
return ArrayStream(attrs).config(parent)
return __orig_startStream(self, parent, attrs)
def startArray(self, parent, attrs):
return Array(attrs)
ContentHandler.startStream = ... | 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):
... pass
...
>>> use... | 5.428678 | 4.812166 | 1.128115 |
return tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1] | 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. | 43.145058 | 22.451286 | 1.921719 |
converse_settings = {
'CONVERSEJS_AUTO_LIST_ROOMS': False,
'CONVERSEJS_AUTO_SUBSCRIBE': False,
'CONVERSEJS_BOSH_SERVICE_URL': 'https://bind.opkode.im',
'CONVERSEJS_HIDE_MUC_SERVER': False,
'CONVERSEJS_PREBIND': True,
'CONVERSEJS_SHOW_CONTROLBOX_BY_DEFAULT': False... | 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. | 3.84649 | 3.921929 | 0.980765 |
ret = []
# Maybe the user just wants one file...
if os.path.isfile(dirname):
if re.match('.*-[0-9]*-[0-9]*\.xml$', dirname):
return [dirname]
else:
return ret
first_four_start = starttime / 100000
first_four_end = endtime / 100000
for file... | 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 | 2.320539 | 2.331498 | 0.9953 |
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 += "\nSupported protocols include: h... | def setup_database(database_location) | 1. Determine protocol | 3.576425 | 3.508872 | 1.019252 |
count = connection.cursor().execute("SELECT count(*) FROM sqlite_master WHERE name='segment'").fetchone()[0]
if count == 0:
print >>sys.stderr, "WARNING: None of the loaded files contain a segment table"
theClass = lsctables.TableByName['segment']
statement = "CREATE TABLE IF NOT... | 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 | 6.21756 | 5.894198 | 1.054861 |
if version is not None:
return build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version, start_pad, end_pad)
# This needs more sophisticated logic, for the moment just return the latest
# available version
sql = "SELECT max(version) FROM segment_definer "
... | 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. Otherwise more complex processing is
performed (not yet implemented) | 2.619986 | 2.467511 | 1.061793 |
seg_result = segmentlist([])
sum_result = segmentlist([])
# Is there any way to get segment and segement summary in one query?
# Maybe some sort of outer join where we keep track of which segment
# summaries we've already seen.
sql = "SELECT segment_summary.start_time, segment_summary.end_... | 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 | 2.200102 | 2.214732 | 0.993394 |
if write_segments:
all_ifos = {}
for ifo, segment_name, version in split_segment_ids(included_segments_string.split(',')):
all_ifos[ifo] = True
new_seg_def_id = add_to_segment_definer(doc, proc_id, ''.join(all_ifos.keys()), 'result', 0)
add_to_segment_summary... | 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 write_segments option is provided so callers can coalesce segments obtained over
sever invocations (as segments_from_cats does). | 2.803492 | 2.844208 | 0.985685 |
def split_segment_id(segment_id):
temp = segment_id.split(':')
if len(temp) == 2:
temp.append(None)
elif temp[2] == '*':
temp[2] = None
else:
temp[2] = int(temp[2])
return temp
return map(split_segment_id, segmen... | 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 | 2.763977 | 2.596285 | 1.064589 |
scheme, host, path, nul, nul, nul = urlparse(url)
if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"):
return path
raise ValueError(url) | def url2path(url) | If url identifies a file on the local host, return the path to the
file otherwise raise ValueError. | 4.291274 | 3.82678 | 1.12138 |
for path in map(url2path, urls):
if any(os.path.samefile(path, preserve) for preserve in preserves):
continue
if verbose:
print >>sys.stderr, "removing \"%s\" ..." % path
try:
os.remove(path)
except:
pass | 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. | 2.835907 | 2.812613 | 1.008282 |
# 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 enumerate(doc.childNodes):
if verbose:
print >>sys.stderr, "reassigning row IDs: %.1f%%\r" % (100.0 * (n + 1) / len(doc.childNodes)),
if elem.tagName == ligolw.LIGO_L... | 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. | 5.324658 | 4.288622 | 1.241578 |
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 no attributes
map(dest.appendChild, src.childNodes)
# unlink from parent
if src.parentNode is not None:
src.pare... | def merge_ligolws(elem) | Merge all LIGO_LW elements that are immediate children of elem by
appending their children to the first. | 4.2699 | 3.788119 | 1.127182 |
return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in b.getElementsByTagName(ligolw.Column.tagName))) | 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. | 6.36162 | 4.941844 | 1.287297 |
for name in lsctables.TableByName.keys():
tables = table.getTablesByName(elem, name)
if tables:
dest = tables.pop(0)
for src in tables:
if src.Name != dest.Name:
# src and dest have different names
continue
# src and dest have the same names
if compare_table_cols(dest, src):
# bu... | 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.. | 4.65022 | 4.212608 | 1.103881 |
# Input
for n, url in enumerate(urls):
if verbose:
print >>sys.stderr, "%d/%d:" % (n + 1, len(urls)),
utils.load_url(url, verbose = verbose, xmldoc = xmldoc, contenthandler = contenthandler)
# ID reassignment
if not non_lsc_tables_ok and lsctables.HasNonLSCTables(xmldoc):
raise ValueError("non-LSC table... | 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. | 3.92842 | 3.844496 | 1.02183 |
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(se... | def run(self) | Loops and executes commands in interactive mode. | 2.119818 | 2.056442 | 1.030819 |
command, kwargs = self.parse(*args)
return self._commands.execute(command, **kwargs) | def execute(self, *args) | Executes single command and returns result. | 7.203805 | 6.430911 | 1.120184 |
if not address:
# get token for any world
# this is only useful for testing,
# because that is exactly what m.agar.io does
url = 'http://at.gcommer.com/status'
text = urllib.request.urlopen(url).read().decode()
j = json.loads(text)
for address, num in j['... | def gcommer_claim(address=None) | Try to get a token for this server address.
`address` has to be ip:port, e.g. `'1.2.3.4:1234'`
Returns tuple(address, token) | 5.143685 | 4.313904 | 1.19235 |
token = urllib.request.quote(token)
url = 'http://at.gcommer.com/donate?server=%s&token=%s' % (address, token)
response = urllib.request.urlopen(url).read().decode()
return json.loads(response)['msg'] | def gcommer_donate(address, token, *_) | Donate a token for this server address.
`address` and `token` should be the return values from find_server(). | 3.498975 | 3.052832 | 1.14614 |
def donate_thread():
while 1:
gcommer_donate(*find_server(region, mode))
time.sleep(interval)
Thread(target=donate_thread, daemon=True).start() | def gcommer_donate_threaded(interval=5, region='EU-London', mode=None) | Run a daemon thread that requests and
donates a token every `interval` seconds. | 3.920817 | 4.221382 | 0.928799 |
if path_to_zip_file:
code = self.set_artefact_path(path_to_zip_file)
elif not self.config["deploy"].get("deploy_file", False):
code = self.build_artefact(src_project)
else:
code = self.set_artefact_path(self.config["deploy"].get("deploy_file"))
... | def run(self, src_project=None, path_to_zip_file=None) | Run deploy the lambdas defined in our project.
Steps:
* Build Artefact
* Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"]
* Reload conf with deploy changes
* check lambda if exist
* Create Lambda
* Update Lambda
... | 4.810397 | 3.861542 | 1.245719 |
self.config["deploy"]["deploy_file"] = path_to_zip_file
return {'ZipFile': self.build.read(self.config["deploy"]["deploy_file"])} | def set_artefact_path(self, path_to_zip_file) | Set the route to the local file to deploy
:param path_to_zip_file:
:return: | 7.591762 | 8.01311 | 0.947418 |
path_to_zip_file = self.build.run(src_project or self.config.get_projectdir())
self.set_artefact_path(path_to_zip_file)
deploy_method = self.config["deploy"]["deploy_method"]
if deploy_method == "S3":
deploy_bucket = self.config["deploy"]["deploy_bucket"]
... | def build_artefact(self, src_project=None) | Run deploy the lambdas defined in our project.
Steps:
* Build Artefact
* Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"]
:param src_project: str. Name of the folder or path of the project where our code lives
:return: bool | 2.864254 | 2.728119 | 1.049901 |
lambdas_deployed = []
for lambda_funcion in self.config.get_lambdas():
start_deploy = not len(self.lambdas_to_deploy) or \
lambda_funcion["FunctionNameOrigin"] in self.lambdas_to_deploy
if start_deploy:
lambdas_deployed.append(... | def deploy(self) | Upload code to AWS Lambda. To use this method, first, must set the zip file with code with
`self.set_artefact(code=code)`. Check all lambdas in our config file or the functions passed in command line
and exist in our config file. If the function is upload correctly, update/create versions, alias and
... | 3.049577 | 2.920629 | 1.044151 |
return re.compile("|".join(map(re.escape, self.keys()))) | def _make_regex(self) | Build a re object based on keys in the current dictionary | 6.95763 | 3.106597 | 2.23963 |
try:
return self.uqids[istring]
except KeyError:
curs = self.curs
curs.execute('VALUES BLOB(GENERATE_UNIQUE())')
self.uqids[istring] = curs.fetchone()[0]
return self.uqids[istring] | def lookup(self,istring) | istring = the ilwd:char string corresponding to a unique id | 5.277369 | 4.946885 | 1.066806 |
lstr = self.llsrx.sub('',lstr.encode('ascii'))
lstr = self.rlsrx.sub('',lstr)
lstr = self.xmltostr.xlat(lstr)
lstr = self.dlmrx.sub(',',lstr)
return lstr | def __lstring(self,lstr) | Returns a parsed lstring by stripping out and instances of
the escaped delimiter. Sometimes the raw lstring has whitespace
and a double quote at the beginning or end. If present, these
are removed. | 6.512106 | 6.62125 | 0.983516 |
istr_orig = istr
istr = self.licrx.sub('',istr.encode('ascii'))
istr = self.ricrx.sub('',istr)
if self.octrx.match(istr):
exec "istr = '"+istr+"'"
# if the DB2 module is loaded, the string should be converted
# to an instance of the DB2.Binary class. If not, leave it as
# a... | def __ilwdchar(self,istr) | If the ilwd:char field contains octal data, it is translated
to a binary string and returned. Otherwise a lookup is done
in the unique id dictionary and a binary string containing the
correct unique id is returned. | 6.691378 | 5.789516 | 1.155775 |
# first extract all the table and columns from the tuple from the
# children of the ligo lightweight parent tuple
table = {}
tupleidx = 0
for tag in xmltuple[2]:
if tag[0] == 'Table' or tag[0] == 'table':
tab = tag[1]['Name'].encode('ascii').lower()
try:
tab = se... | def parsetuple(self,xmltuple) | Parse an XML tuple returned by pyRXP into a dictionary
of LIGO metadata elements. The dictionary contains one
entry for each table found in the XML tuple. | 3.785713 | 3.747125 | 1.010298 |
if not self.xmlparser:
raise LIGOLwParseError, "pyRXP parser not initialized"
if not self.lwtparser:
raise LIGOLwParseError, "LIGO_LW tuple parser not initialized"
xml = "".join([x.strip() for x in xml.split('\n')])
ligolwtup = self.xmlparser(xml)
if self.curs:
self.lwtparser.... | def parse(self,xml) | Parses an XML document into a form read for insertion into the database
xml = the xml document to be parsed | 7.532507 | 7.252399 | 1.038623 |
if len(self.table['process']['stream']) > 1:
msg = "cannot add lfn to table with more than one process"
raise LIGOLwParseError, msg
# get the process_id from the process table
pid_col = self.table['process']['orderedcol'].index('process_id')
pid = self.table['process']['stream'][0][pid_... | def add_lfn(self,lfn) | Add an LFN table to a parsed LIGO_LW XML document.
lfn = lfn to be added | 5.33989 | 4.628447 | 1.153711 |
try:
domain_col = self.table['process']['orderedcol'].index('domain')
for row_idx in range(len(self.table['process']['stream'])):
row_list = list(self.table['process']['stream'][row_idx])
row_list[domain_col] = dn
self.table['process']['stream'][row_idx] = tuple(row_list)
... | def set_dn(self,dn) | Use the domain column in the process table to store the DN
dn = dn to be added | 2.4113 | 2.131429 | 1.131307 |
if not self.curs:
raise LIGOLwDBError, "Database connection not initalized"
if len(self.table) == 0:
raise LIGOLwDBError, 'attempt to insert empty table'
for tab in self.table.keys():
# find and add any missing unique ids
generate = []
missingcols = [k for k in self.ldb.un... | def insert(self) | Insert the object into the database | 3.863503 | 3.849206 | 1.003714 |
if not self.curs:
raise LIGOLwDBError, "Database connection not initalized"
if len(self.table) != 0:
raise LIGOLwDBError, 'attempt to fill non-empty table from database'
ligolw = ''
self.table = {}
sqltypes = {
-2 : 'ilwd:char_u',
1 : 'lstring',
3 : 'real_8',
... | def select(self,sql) | Execute an SQL select statement and stuff the results into a
dictionary.
sql = the (case sensitve) SQL statment to execute | 4.535518 | 4.543235 | 0.998302 |
if len(self.table) == 0:
raise LIGOLwDBError, 'attempt to convert empty table to xml'
ligolw =
for tab in self.table.keys():
try:
ligolw += ' <Comment>'+self.strtoxml.xlat(self.table[tab]['query'])+'</Comment>\n'
except KeyError:
pass
ligolw += ' <Table Nam... | def xml(self, ilwdchar_to_hex = True) | Convert a table dictionary to LIGO lightweight XML | 4.101895 | 4.012436 | 1.022295 |
config = {}
url = urlparse.urlparse(url)
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
if url.scheme in SCHEMES:
config["ENGINE"] = SCHEMES[url.scheme]
if url.scheme in USES_URL:
config["URL"] = urlparse.urlunparse(("http",) + url[1:])
... | def parse(url) | Parses a search URL. | 2.505803 | 2.506152 | 0.999861 |
def aux(self, *args, **kwargs):
out = func(self, *args, **kwargs)
path = (hasattr(self, 'path') and self.path
or os.path.join(os.getcwd(), '.td'))
gpath = (hasattr(self, 'gpath') and self.gpath
or os.path.expanduser('~/.tdrc'))
if os.path.exists(... | def save(func) | @decorator: Saves data after executing :func:.
Also performs modifications set as permanent options. | 2.995524 | 3.073326 | 0.974685 |
item = [name, priority, comment, False, []]
data = self.data
for c in self._split(parent):
data = data[int(c) - 1][4]
data.append(item) | def add(self, name, priority=3, comment="", parent="") | Adds new item to the model.
Name argument may contain (ref:) syntax, which will be
stripped down as needed.
:parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1").
:name: Name (with refs).
:priority: Item's priority.
:comment: Comment.
:parent: It... | 5.328699 | 7.232915 | 0.736729 |
if parent == -1:
parent = ''
parent = self._split(parent)
index = self._split(index)
item = self.data
for j, c in enumerate(index):
item = item[int(c) - 1]
if j + 1 != len(index):
item = item[4]
if name is not N... | def edit(
self, index, name=None, priority=None,
comment=None, done=None, parent=None
) | Modifies :index: to specified data.
Every argument, which is not None, will get changed.
If parent is not None, the item will get reparented.
Use parent=-1 or parent='' for reparenting to top-level.
:index: Index of the item to edit.
:name: New name.
:priority: New pri... | 2.18316 | 2.332004 | 0.936174 |
data = self.data
index = self._split(index)
for j, c in enumerate(index):
i = int(c) - 1
if j + 1 == len(index):
try:
del data[i]
except IndexError:
raise NoItemError('.'.join(index))
... | def remove(self, index) | Removes specified item from the model.
:index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1").
:index: Item's index. | 5.221822 | 4.454859 | 1.172163 |
data = self.data
try:
for c in self._split(index):
i = int(c) - 1
data = data[i][4]
except Exception:
return False
return True | def exists(self, index) | Checks whether :index: exists in the Model.
:index: Index to look for.
:returns: True if :index: exists in the Model, False otherwise. | 5.461799 | 6.379142 | 0.856197 |
data = self.data
index2 = self._split(index)
for c in index2[:-1]:
i = int(c) - 1
data = data[i][4]
return [index[:-2] or ""] + data[int(index[-1]) - 1] | def get(self, index) | Gets data values for specified :index:.
:index: Index for which to get data.
:returns: A list in form
[parent, name, priority, comment, done, children]. | 6.877711 | 6.736702 | 1.020932 |
sortAll, sortLevels = sort is not None and sort or ([], {})
doneAll, doneLevels = done is not None and done or ([], {})
def _mark(v, i):
if done is None:
return v[:4]
def _mark_(index, regexp, du):
if du is None:
... | def _modifyInternal(self, *, sort=None, purge=False, done=None) | Creates a whole new database from existing one, based on given
modifiers.
:sort: pattern should look like this:
([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}),
where True|False indicate whether to reverse or not,
<index> are one of Model.indexes and <level_i... | 3.414772 | 3.413666 | 1.000324 |
return self._modifyInternal(sort=sort, purge=purge, done=done) | def modify(self, *, sort=None, purge=False, done=None) | Calls Model._modifyInternal after loading the database. | 4.989676 | 2.481821 | 2.01049 |
self.data = self.modify(sort=sort, purge=purge, done=done) | def modifyInPlace(self, *, sort=None, purge=False, done=None) | Like Model.modify, but changes existing database instead of
returning a new one. | 4.430028 | 3.661309 | 1.209958 |
if glob:
self.globalOptions.update(kwargs)
else:
self.options.update(kwargs) | def setOptions(self, glob=False, **kwargs) | Set option(s).
:glob: If True, stores specified options globally.
:kwargs: Dictionary of options and values to set. | 2.972439 | 3.963164 | 0.750017 |
self.code_strings.append(string)
code = ''
if len(self.code_strings) == 1:
code = '(setv result ' + self.code_strings[0] + ')'
if len(self.code_strings) > 1:
code = '(setv result (and ' + ' '.join(self.code_strings) + '))'
self._compiled_ast_and_e... | def add_line(self, string) | Adds a line to the LISP code to execute
:param string: The line to add
:return: None | 4.112204 | 4.162698 | 0.98787 |
for node in graph.vs:
attributes = node.attributes()
self.namespace[node['name']] = attributes
for node in graph.es:
attributes = node.attributes()
self.namespace[node['name']] = attributes | def add_graph_to_namespace(self, graph) | Adds the variables name to the namespace of the local LISP code
:param graph: the graph to add to the namespace
:return: None | 2.942512 | 3.238076 | 0.908722 |
if not self.code_strings:
return True
if vertices_substitution_dict:
namespace = self.__substitute_names_in_namespace(self.namespace, vertices_substitution_dict)
else:
namespace = self.namespace
try:
self.__execute_code(self._com... | def execute(self, vertices_substitution_dict={}) | Executes the code
:param vertices_substitution_dict: aliases of the variables in the code
:return: True/False, depending on the result of the code (default is True) | 5.868808 | 5.172219 | 1.134679 |
for key, value in self.namespace.items():
try:
nodes = graph.vs.select(name=key)
for node in nodes:
for k, v in value.items():
node[k] = v
except:
pass
try:
no... | def substitute_namespace_into_graph(self, graph) | Creates a graph from the local namespace of the code (to be used after the execution of the code)
:param graph: The graph to use as a recipient of the namespace
:return: the updated graph | 1.895479 | 1.996462 | 0.949419 |
json = self.request('/droplets/', method='GET')
status = json.get('status')
if status == 'OK':
droplet_json = json.get('droplets', [])
droplets = [Droplet.from_json(droplet) for droplet in droplet_json]
return droplets
else:
messag... | def droplets(self) | This method returns the list of droplets | 3.087663 | 3.004377 | 1.027722 |
if not droplet_id:
raise DOPException('droplet_id is required to reboot a droplet!')
json = self.request('/droplets/%s/reboot' % droplet_id, method='GET')
status = json.get('status')
if status == 'OK':
return json.get('event_id')
else:
... | def reboot_droplet(self, droplet_id) | This method allows you to reboot a droplet. This is the preferred method
to use if a server is not responding. | 3.284386 | 3.307071 | 0.993141 |
if not droplet_id:
msg = 'droplet_id is required to power cycle a droplet!'
raise DOPException(msg)
json = self.request('/droplets/%s/power_cycle' % droplet_id, method='GET')
status = json.get('status')
if status == 'OK':
return json.get('even... | def power_cycle_droplet(self, droplet_id) | This method allows you to power cycle a droplet. This will turn off the
droplet and then turn it back on. | 3.302233 | 3.342771 | 0.987873 |
if not droplet_id:
raise DOPException('droplet_id is required to resize a droplet!')
params = {}
size_id = size.get('size_id')
if size_id:
params.update({'size_id': size_id})
else:
size_slug = size.get('size_slug')
if size_... | def resize_droplet(self, droplet_id, size) | This method allows you to resize a specific droplet to a different size.
This will affect the number of processors and memory allocated to the droplet.
Required parameters:
droplet_id:
Integer, this is the id of your droplet that you want to resize
size, one of... | 2.403351 | 2.443946 | 0.983389 |
if not droplet_id:
raise DOPException('droplet_id is required to restore a droplet!')
if not image_id:
raise DOPException('image_id is required to rebuild a droplet!')
params = {'image_id': image_id}
json = self.request('/droplets/%s/restore' % droplet_id... | def restore_droplet(self, droplet_id, image_id) | This method allows you to restore a droplet with a previous image or snapshot.
This will be a mirror copy of the image or snapshot to your droplet.
Be sure you have backed up any necessary information prior to restore.
Required parameters:
droplet_id:
Numeric, this ... | 2.730568 | 3.024658 | 0.902769 |
if not droplet_id:
raise DOPException('droplet_id is required to rebuild a droplet!')
if not name:
raise DOPException('name is required to rebuild a droplet!')
params = {'name': name}
json = self.request('/droplets/%s/rename' % droplet_id, method='GET',
... | def rename_droplet(self, droplet_id, name) | This method allows you to reinstall a droplet with a default image.
This is useful if you want to start again but retain the same IP address
for your droplet.
Required parameters:
droplet_id:
Numeric, this is the id of your droplet that you want to snapshot
... | 2.924268 | 3.140414 | 0.931173 |
params = {}
if scrub_data:
params['scrub_data'] = True
json = self.request('/droplets/%s/destroy' % droplet_id, method='GET',
params=params)
status = json.get('status')
if status == 'OK':
return json.get('event_id')
... | def destroy_droplet(self, droplet_id, scrub_data=False) | This method destroys one of your droplets - this is irreversible.
Required parameters:
droplet_id:
Numeric, this is the id of your droplet that you want to destroy
Optional parameters
scrub_data:
Boolean, this will strictly write 0s to your pri... | 3.229602 | 3.931978 | 0.821368 |
json = self.request('/regions', method='GET')
status = json.get('status')
if status == 'OK':
regions_json = json.get('regions', [])
regions = [Region.from_json(region) for region in regions_json]
return regions
else:
message = json... | def regions(self) | This method will return all the available regions within the
DigitalOcean cloud. | 3.260597 | 2.956758 | 1.102761 |
if filter and filter not in ('my_images', 'global'):
raise DOPException('"filter" must be either "my_images" or "global"')
params = {}
if filter:
params['filter'] = filter
json = self.request('/images', method='GET', params=params)
status = json.g... | def images(self, filter='global') | This method returns all the available images that can be accessed by
your client ID. You will have access to all public images by default,
and any snapshots or backups that you have created in your own account.
Optional parameters
filter:
String, either "my_images" ... | 2.729323 | 2.706862 | 1.008298 |
if not image_id_or_slug:
msg = 'image_id_or_slug is required to destroy an image!'
raise DOPException(msg)
json = self.request('/images/%s' % image_id_or_slug, method='GET')
image_json = json.get('image')
status = json.get('status')
if status == ... | def show_image(self, image_id_or_slug) | This method displays the attributes of an image.
Required parameters
image_id:
Numeric, this is the id of the image you would like to use to
rebuild your droplet with | 3.21636 | 3.393095 | 0.947913 |
if not image_id_or_slug:
msg = 'image_id_or_slug is required to destroy an image!'
raise DOPException(msg)
json = self.request('/images/%s/destroy' % image_id_or_slug, method='GET')
status = json.get('status')
return status | def destroy_image(self, image_id_or_slug) | This method allows you to destroy an image. There is no way to restore
a deleted image so be careful and ensure your data is properly backed up.
Required parameters
image_id:
Numeric, this is the id of the image you would like to destroy | 3.912998 | 4.398062 | 0.88971 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.