code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
query = self.Analysis.query.filter_by(
family=family,
started_at=started_at,
status=status,
)
return query.first() | def find_analysis(self, family, started_at, status) | Find a single analysis. | 2.557369 | 2.799318 | 0.913568 |
analysis_query = self.Analysis.query
if family:
analysis_query = analysis_query.filter_by(family=family)
elif query:
analysis_query = analysis_query.filter(sqa.or_(
self.Analysis.family.like(f"%{query}%"),
self.Analysis.status.like... | def analyses(self, *, family: str=None, query: str=None, status: str=None, deleted: bool=None,
temp: bool=False, before: dt.datetime=None, is_visible: bool=None) | Fetch analyses form the database. | 1.662181 | 1.633475 | 1.017573 |
return self.Analysis.query.get(analysis_id) | def analysis(self, analysis_id: int) -> models.Analysis | Get a single analysis. | 8.745668 | 7.014085 | 1.246872 |
metadata = self.info()
metadata.updated_at = dt.datetime.now()
self.commit() | def track_update(self) | Update the lastest updated date in the database. | 11.75757 | 9.218927 | 1.275373 |
latest_analysis = self.analyses(family=family).first()
return latest_analysis and latest_analysis.status in TEMP_STATUSES | def is_running(self, family: str) -> bool | Check if an analysis is currently running/pending for a family. | 11.313913 | 6.702811 | 1.687936 |
started_at = dt.datetime.now()
new_log = self.Analysis(family=family, status='pending', started_at=started_at)
new_log.user = self.user(email) if email else None
self.add_commit(new_log)
return new_log | def add_pending(self, family: str, email: str=None) -> models.Analysis | Add pending entry for an analysis. | 4.331394 | 4.124865 | 1.050069 |
new_user = self.User(name=name, email=email)
self.add_commit(new_user)
return new_user | def add_user(self, name: str, email: str) -> models.User | Add a new user to the database. | 3.898522 | 3.200702 | 1.218021 |
return self.User.query.filter_by(email=email).first() | def user(self, email: str) -> models.User | Fetch a user from the database. | 4.682575 | 3.717184 | 1.25971 |
categories = self.session.query(
self.Job.name.label('name'),
sqa.func.count(self.Job.id).label('count')
).filter(self.Job.status != 'cancelled').group_by(self.Job.name).all()
data = [{'name': category.name, 'count': category.count} for category in categories]
... | def aggregate_failed(self) -> List | Count the number of failed jobs per category (name). | 3.325673 | 2.772974 | 1.199316 |
self.log.debug('starting the ``ingest`` method')
if not self.radiusArcsec:
self.log.error(
'please give a radius in arcsec with which to preform the initial NED conesearch' % locals())
sys.exit(0)
# VARIABLES
# SIZE OF NUMBER OF ROWS TO ... | def ingest(self) | *Perform conesearches of the online NED database and import the results into a the sherlock-database*
The code:
1. uses the list of transient coordinates and queries NED for the results within the given search radius
2. Creates the `tcs_cat_ned_stream` table if it doesn't exist
... | 9.84892 | 7.380455 | 1.33446 |
self.log.debug(
'starting the ``_create_dictionary_of_ned`` method')
# GET THE NAMES (UNIQUE IDS) OF THE SOURCES WITHIN THE CONESEARCH FROM
# NED
names, searchParams = conesearch(
log=self.log,
radiusArcsec=self.radiusArcsec,
near... | def _create_dictionary_of_ned(
self) | *Create a list of dictionaries containing all the object ids (NED names) in the ned stream*
**Return:**
- ``dictList`` - a list of dictionaries containing all the object ids (NED names) in the ned stream
**Usage:**
.. code-block:: python
dictList = stream._cre... | 7.043092 | 6.778746 | 1.038996 |
self.log.debug('starting the ``_update_ned_query_history`` method')
myPid = self.myPid
# ASTROCALC UNIT CONVERTER OBJECT
converter = unit_conversion(
log=self.log
)
# UPDATE THE DATABASE HELPER TABLE TO GIVE DETAILS OF THE NED CONE
# SEARCH... | def _update_ned_query_history(
self) | *Update the database helper table to give details of the ned cone searches performed*
*Usage:*
.. code-block:: python
stream._update_ned_query_history() | 4.925751 | 4.383676 | 1.123658 |
self.log.debug('starting the ``_download_ned_source_metadata`` method')
self.dbTableName = "tcs_cat_ned_stream"
total, batches = self._count_ned_sources_in_database_requiring_metadata()
self.log.info(
"%(total)s galaxies require metadata. Need to send %(batches)s ... | def _download_ned_source_metadata(
self) | *Query NED using the names of the NED sources in our local database to retrieve extra metadata*
*Usage:*
.. code-block:: python
stream._download_ned_source_metadata() | 6.523405 | 6.310859 | 1.033679 |
self.log.debug(
'starting the ``_get_ned_sources_needing_metadata`` method')
tableName = self.dbTableName
# SELECT THE DATA FROM NED TABLE
sqlQuery = u % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=... | def _get_ned_sources_needing_metadata(
self) | *Get the names of 50000 or less NED sources that still require metabase in the database*
**Return:**
- ``len(self.theseIds)`` -- the number of NED IDs returned
*Usage:*
.. code-block:: python
numberSources = stream._get_ned_sources_needing_metadata() | 5.251544 | 4.774792 | 1.099848 |
self.log.debug(
'starting the ``_do_ned_namesearch_queries_and_add_resulting_metadata_to_database`` method')
# ASTROCALC UNIT CONVERTER OBJECT
converter = unit_conversion(
log=self.log
)
tableName = self.dbTableName
# QUERY NED WITH BATC... | def _do_ned_namesearch_queries_and_add_resulting_metadata_to_database(
self,
batchCount) | *Query NED via name searcha and add result metadata to database*
**Key Arguments:**
- ``batchCount`` - the index number of the batch sent to NED (only needed for printing to STDOUT to give user idea of progress)
*Usage:*
.. code-block:: python
numberSources = ... | 3.937387 | 3.931683 | 1.001451 |
self.log.debug(
'starting the ``_count_ned_sources_in_database_requiring_metadata`` method')
tableName = self.dbTableName
sqlQuery = u % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
... | def _count_ned_sources_in_database_requiring_metadata(
self) | *Count the sources in the NED table requiring metadata*
**Return:**
- ``self.total``, ``self.batches`` -- total number of galaxies needing metadata & the number of batches required to be sent to NED
*Usage:*
.. code-block:: python
totalRemaining, numberOfBatch... | 3.957364 | 3.596027 | 1.100482 |
if not self._is_running:
self._do_run = True
self._thread.start()
return self | def start(self) | Start the receiver. | 5.610894 | 4.752411 | 1.180642 |
addrs = []
with self._address_lock:
for metadata in self._addresses.values():
if (name == "" or
(name and name in metadata["service"])):
mda = copy.copy(metadata)
mda["receive_time"] = mda["receive_time... | def get(self, name="") | Get the address(es). | 5.02036 | 4.412512 | 1.137756 |
now = datetime.utcnow()
if (now - self._last_age_check) <= min_interval:
return
LOGGER.debug("%s - checking addresses", str(datetime.utcnow()))
self._last_age_check = now
to_del = []
with self._address_lock:
for addr, metadata in self._ad... | def _check_age(self, pub, min_interval=timedelta(seconds=0)) | Check the age of the receiver. | 4.675804 | 4.491796 | 1.040965 |
port = broadcast_port
nameservers = []
if self._multicast_enabled:
recv = MulticastReceiver(port).settimeout(2.)
while True:
try:
recv = MulticastReceiver(port).settimeout(2.)
LOGGER.info("Receiver initializ... | def _run(self) | Run the receiver. | 5.307042 | 5.210399 | 1.018548 |
with self._address_lock:
metadata["receive_time"] = datetime.utcnow()
self._addresses[adr] = metadata | def _add(self, adr, metadata) | Add an address. | 7.643098 | 5.929288 | 1.289041 |
self.log.debug('starting the ``get`` method')
self.primaryIdColumnName = "primaryId"
self.raColName = "raDeg"
self.declColName = "decDeg"
self.dbTableName = "tcs_cat_ifs_stream"
self.databaseInsertbatchSize = 500
dictList = self._create_dictionary_of_IF... | def ingest(self) | *Import the IFS catalogue into the sherlock-catalogues database*
The method first generates a list of python dictionaries from the IFS datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table.
**Usage:**
See class docstring for usage | 8.812218 | 7.481215 | 1.177913 |
self.log.debug(
'starting the ``_create_dictionary_of_IFS`` method')
# GRAB THE CONTENT OF THE IFS CSV
try:
response = requests.get(
url=self.settings["ifs galaxies url"],
)
thisData = response.content
thisData... | def _create_dictionary_of_IFS(
self) | *Generate the list of dictionaries containing all the rows in the IFS stream*
**Return:**
- ``dictList`` - a list of dictionaries containing all the rows in the IFS stream
**Usage:**
.. code-block:: python
from sherlock.imports import IFS
stre... | 3.063841 | 2.905446 | 1.054517 |
'''
Humansize.py from Dive into Python3
Mark Pilgrim - http://www.diveintopython3.net/
Copyright (c) 2009, Mark Pilgrim, All rights reserved.
Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use mult... | def approximate_size(size, a_kilobyte_is_1024_bytes=True) | Humansize.py from Dive into Python3
Mark Pilgrim - http://www.diveintopython3.net/
Copyright (c) 2009, Mark Pilgrim, All rights reserved.
Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 102... | 3.349141 | 1.608189 | 2.082554 |
if os.name == 'nt':
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# get console handle
from ctypes import windll, Structure, byref
try:
from ctypes.wintypes import SHORT, WORD, DWORD
except ImportError:
# ... | def get_console_width() | Return width of available window area. Autodetection works for
Windows and POSIX platforms. Returns 80 for others
Code from http://bitbucket.org/techtonik/python-pager | 1.660843 | 1.636571 | 1.014831 |
fname = os.path.basename(urlparse.urlparse(url).path)
if len(fname.strip(" \n\t.")) == 0:
return None
return fname | def filename_from_url(url) | :return: detected filename or None | 3.345592 | 3.101605 | 1.078665 |
if type(headers) == str:
headers = headers.splitlines()
if type(headers) == list:
headers = dict([x.split(':', 1) for x in headers])
cdisp = headers.get("Content-Disposition")
if not cdisp:
return None
cdtype = cdisp.split(';')
if len(cdtype) == 1:
return Non... | def filename_from_headers(headers) | Detect filename from Content-Disposition headers if present.
http://greenbytes.de/tech/tc2231/
:param: headers as dict, list or string
:return: filename from content-disposition header or None | 2.613843 | 2.513943 | 1.039738 |
name, ext = filename.rsplit('.', 1)
names = [x for x in os.listdir(dirname) if x.startswith(name)]
names = [x.rsplit('.', 1)[0] for x in names]
suffixes = [x.replace(name, '') for x in names]
# filter suffixes that match ' (x)' pattern
suffixes = [x[2:-1] for x in suffixes
i... | def filename_fix_existing(filename, dirname) | Expands name portion of filename with numeric ' (x)' suffix to
return filename that doesn't exist already. | 2.722761 | 2.489918 | 1.093514 |
'''
This callback for the download function is used to print the download bar
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(9)
total = approximate_size(total_size).center(9)
shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
... | def report_bar(bytes_so_far, total_size, speed, eta) | This callback for the download function is used to print the download bar | 3.595673 | 3.176601 | 1.131924 |
'''
This callback for the download function is used
when the total size is unknown
'''
sys.stdout.write(
"Downloading: {0} / Unknown - {1}/s ".format(approximate_size(bytes_so_far),
approximate_size(speed)))
sys.stdout.write... | def report_unknown(bytes_so_far, total_size, speed, eta) | This callback for the download function is used
when the total size is unknown | 6.223858 | 4.28265 | 1.453273 |
'''
This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(10)
total = approximate_size(total_size).center(10)
sys.s... | def report_onlysize(bytes_so_far, total_size, speed, eta) | This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes | 5.137363 | 3.16927 | 1.620993 |
'''
This is the Main function, which downloads a given link
and saves on outdir (default = current directory)
'''
url = None
fh = None
eta = 'unknown '
bytes_so_far = 0
filename = filename_from_url(link) or "."
cj = cjar.CookieJar()
# get filename for temp file in current di... | def download(link, outdir='.', chunk_size=4096) | This is the Main function, which downloads a given link
and saves on outdir (default = current directory) | 3.734165 | 3.533981 | 1.056646 |
runs = context.obj['store'].analyses(
status=status,
deleted=False,
before=parse_date(before) if before else None,
).limit(30)
for run_obj in runs:
if run_obj.status == 'pending':
message = f"{run_obj.id} | {run_obj.family} [{run_obj.status.upper()}]"
... | def ls_cmd(context, before, status) | Display recent logs for analyses. | 2.713924 | 2.599054 | 1.044197 |
if not account:
try:
account = settings.GOOGLE_ANALYTICS_ACCOUNT
except:
raise template.TemplateSyntaxError(
"Analytics account could not found either "
"in tag parameters or settings")
return {'account': account, 'params':kwa... | def analytics(account=None, *args, **kwargs) | Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Analytics account id to be used. | 8.596673 | 7.968207 | 1.078872 |
per_page = int(request.args.get('per_page', 50))
page = int(request.args.get('page', 1))
query = store.analyses(status=request.args.get('status'),
query=request.args.get('query'),
is_visible=request.args.get('is_visible') == 'true' or None)
que... | def analyses() | Display analyses. | 2.179512 | 2.153444 | 1.012105 |
analysis_obj = store.analysis(analysis_id)
if analysis_obj is None:
return abort(404)
if request.method == 'PUT':
analysis_obj.update(request.json)
store.commit()
data = analysis_obj.to_dict()
data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_... | def analysis(analysis_id) | Display a single analysis. | 2.334155 | 2.377319 | 0.981843 |
if defaults.ACCOUNTS_GRAVATAR_SECURE:
base_url = 'https://secure.gravatar.com/avatar/'
else: base_url = 'http://www.gravatar.com/avatar/'
gravatar_url = '%(base_url)s%(gravatar_id)s?' % \
{'base_url': base_url,
'gravatar_id': hashlib.md5(email.lower().encode('utf-8')).... | def get_gravatar(email, size=80, default='identicon') | Get's a Gravatar for a email address.
:param size:
The size in pixels of one side of the Gravatar's square image.
Optional, if not supplied will default to ``80``.
:param default:
Defines what should be displayed if no image is found for this user.
Optional argument which defau... | 2.13119 | 2.523685 | 0.844475 |
if redirect: return redirect
elif user is not None:
return defaults.ACCOUNTS_LOGIN_REDIRECT_URL % \
{'username': user.username}
else: return settings.LOGIN_REDIRECT_URL | def login_redirect(redirect=None, user=None) | Redirect user after successful sign in.
First looks for a ``requested_redirect``. If not supplied will fall-back
to the user specific account page. If all fails, will fall-back to the
standard Django ``LOGIN_REDIRECT_URL`` setting. Returns a string defining
the URI to go next.
:param redirect:
... | 4.704767 | 4.94215 | 0.951968 |
if not salt:
salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
hash = hashlib.sha1((salt+str(string)).encode('utf-8')).hexdigest()
return (salt, hash) | def generate_sha1(string, salt=None) | Generates a sha1 hash for supplied string. Doesn't need to be very secure
because it's not used for password checking. We got Django for that.
:param string:
The string that needs to be encrypted.
:param salt:
Optionally define your own salt. If none is supplied, will use a
random... | 2.314143 | 2.378636 | 0.972886 |
try:
from django.utils import timezone
return timezone.now()
except ImportError:
return datetime.datetime.now() | def get_datetime_now() | Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is True or False respectively.
In older versions of Django it uses dat... | 3.234876 | 2.761194 | 1.17155 |
print("Demonstrating complex handle_errors example")
def _handler_function(err, final_message, trace):
print("Handling exception")
print("==================")
print("Final Message")
print("-------------")
print(final_message)
print("Traceback")
... | def complex_handle_errors() | This function demonstrates a more complex usage of the handle_errors
ctx_mgr. The following features are demonstrated::
* Handling a specific exception type with ``exception_class``
* Absorbing exceptions by setting ``re_raise`` to ``False``
* Branching with ``do_except``, ``do_else``, and ``do_f... | 6.353663 | 5.980772 | 1.062348 |
if obj:
try:
tmp = json.dumps(obj, default=datetime_encoder)
del tmp
except (TypeError, UnicodeDecodeError):
return False
return True | def is_valid_data(obj) | Check if data is JSON serializable. | 4.793142 | 4.328284 | 1.1074 |
if isinstance(dct, list):
pairs = enumerate(dct)
elif isinstance(dct, dict):
pairs = dct.items()
result = []
for key, val in pairs:
if isinstance(val, six.string_types):
try:
val = strp_isoformat(val)
except ValueError:
... | def datetime_decoder(dct) | Decode datetimes to python objects. | 1.999457 | 1.956926 | 1.021734 |
# Check for the magick word.
try:
rawstr = rawstr.decode('utf-8')
except (AttributeError, UnicodeEncodeError):
pass
except (UnicodeDecodeError):
try:
rawstr = rawstr.decode('iso-8859-1')
except (UnicodeDecodeError):
rawstr = rawstr.decode('utf... | def _decode(rawstr) | Convert a raw string to a Message. | 3.05205 | 2.976835 | 1.025267 |
rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format(
msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version)
if not head and msg.data:
if not binary and isinstance(msg.data, six.string_types):
return (rawstr + ' ' +
'text/ascii' + '... | def _encode(msg, head=False, binary=False) | Convert a Message to a raw string. | 3.648286 | 3.529582 | 1.033631 |
import os
import pwd
import socket
host = socket.gethostname()
user = pwd.getpwuid(os.getuid())[0]
return "%s@%s" % (user, host) | def _getsender() | Return local sender.
Don't use the getpass module, it looks at various environment variables
and is unreliable. | 2.549765 | 2.256315 | 1.130057 |
if not is_valid_subject(self.subject):
raise MessageError("Invalid subject: '%s'" % self.subject)
if not is_valid_type(self.type):
raise MessageError("Invalid type: '%s'" % self.type)
if not is_valid_sender(self.sender):
raise MessageError("Invalid se... | def _validate(self) | Validate a messages attributes. | 2.47854 | 2.260057 | 1.096671 |
key = self.__KeyPair.generate()
key_serialized = self.__PublicKeyEncoder.encodePublicKey(
key.pub,
self.__curve
)
signature = self.__XEdDSA(mont_priv = self.__ik.priv).sign(key_serialized)
self.__spk = {
"key": key,
"si... | def __generateSPK(self) | Generate a new PK and sign its public key using the IK, add the timestamp aswell
to allow for periodic rotations. | 8.642951 | 6.857684 | 1.260331 |
if num_otpks == None:
num_otpks = self.__max_num_otpks
otpks = []
for _ in range(num_otpks):
otpks.append(self.__KeyPair.generate())
try:
self.__otpks.extend(otpks)
except AttributeError:
self.__otpks = otpks | def __generateOTPKs(self, num_otpks = None) | Generate the given amount of OTPKs.
:param num_otpks: Either an integer or None.
If the value of num_otpks is None, set it to the max_num_otpks value of the
configuration. | 2.364294 | 2.476942 | 0.954521 |
salt = b"\x00" * self.__hash_function().digest_size
if self.__curve == "25519":
input_key_material = b"\xFF" * 32
if self.__curve == "448":
input_key_material = b"\xFF" * 57
input_key_material += secret_key_material
hkdf = HKDF(
al... | def __kdf(self, secret_key_material) | :param secret_key_material: A bytes-like object encoding the secret key material.
:returns: A bytes-like object encoding the shared secret key. | 2.846952 | 2.921167 | 0.974594 |
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | def __checkSPKTimestamp(self) | Check whether the SPK is too old and generate a new one in that case. | 6.927251 | 3.822297 | 1.812327 |
remainingOTPKs = len(self.__otpks)
if remainingOTPKs < self.__min_num_otpks:
self.__generateOTPKs(self.__max_num_otpks - remainingOTPKs) | def __refillOTPKs(self) | If the amount of available OTPKs fell under the minimum, refills the OTPKs up to
the maximum limit again. | 3.43036 | 2.934837 | 1.168842 |
self.__checkSPKTimestamp()
for otpk in self.__otpks:
if otpk.pub == otpk_pub:
self.__otpks.remove(otpk)
self.__hidden_otpks.append(otpk)
self.__refillOTPKs() | def hideFromPublicBundle(self, otpk_pub) | Hide a one-time pre key from the public bundle.
:param otpk_pub: The public key of the one-time pre key to hide, encoded as a
bytes-like object. | 4.358269 | 4.858389 | 0.89706 |
self.__checkSPKTimestamp()
for otpk in self.__otpks:
if otpk.pub == otpk_pub:
self.__otpks.remove(otpk)
for otpk in self.__hidden_otpks:
if otpk.pub == otpk_pub:
self.__hidden_otpks.remove(otpk)
self.__refillOTPKs() | def deleteOTPK(self, otpk_pub) | Delete a one-time pre key, either publicly visible or hidden.
:param otpk_pub: The public key of the one-time pre key to delete, encoded as a
bytes-like object. | 2.730616 | 2.788074 | 0.979392 |
self.__checkSPKTimestamp()
ik_pub = self.__ik.pub
spk_pub = self.__spk["key"].pub
spk_sig = self.__spk["signature"]
otpk_pubs = [ otpk.pub for otpk in self.__otpks ]
return PublicBundle(ik_pub, spk_pub, spk_sig, otpk_pubs) | def getPublicBundle(self) | Fill a PublicBundle object with the public bundle data of this State.
:returns: An instance of PublicBundle, filled with the public data of this State. | 4.77261 | 4.99381 | 0.955705 |
self.__checkSPKTimestamp()
changed = self._changed
self._changed = False
return changed | def changed(self) | Read, whether this State has changed since it was loaded/since this flag was last
cleared.
:returns: A boolean indicating, whether the public bundle data has changed since
last reading this flag.
Clears the flag when reading. | 25.579664 | 25.63147 | 0.997979 |
self.__checkSPKTimestamp()
other_ik = self.__KeyPair(pub = other_public_bundle.ik)
other_spk = {
"key": self.__KeyPair(pub = other_public_bundle.spk),
"signature": other_public_bundle.spk_signature
}
other_otpks = [
self.__KeyPair(... | def getSharedSecretActive(
self,
other_public_bundle,
allow_zero_otpks = False
) | Do the key exchange, as the active party. This involves selecting keys from the
passive parties' public bundle.
:param other_public_bundle: An instance of PublicBundle, filled with the public
data of the passive party.
:param allow_zero_otpks: A flag indicating whether bundles with ... | 2.730043 | 2.470139 | 1.105218 |
self.__checkSPKTimestamp()
other_ik = self.__KeyPair(pub = passive_exchange_data["ik"])
other_ek = self.__KeyPair(pub = passive_exchange_data["ek"])
if self.__spk["key"].pub != passive_exchange_data["spk"]:
raise KeyExchangeException(
"The SPK used... | def getSharedSecretPassive(
self,
passive_exchange_data,
allow_no_otpk = False,
keep_otpk = False
) | Do the key exchange, as the passive party. This involves retrieving data about the
key exchange from the active party.
:param passive_exchange_data: A structure generated by the active party, which
contains data requried to complete the key exchange. See the "to_other" part
of t... | 2.572176 | 2.445541 | 1.051782 |
if self._parent is not None:
self._parent.save(mode=mode)
else:
config_dir = os.path.dirname(os.path.abspath(self.config_files[-1]))
try:
os.makedirs(config_dir)
except OSError as e:
if not (e.errno == errno.EEXIST ... | def save(self, mode=0o600) | Serialize the config data to the user home directory.
:param mode: The octal Unix mode (permissions) for the config file. | 2.104171 | 2.170645 | 0.969376 |
if 'filename' in kwargs:
return self.modelFromFile(kwargs['filename'])
if 'params' in kwargs:
params = kwargs.pop('params')
kwargs['model'] = 'default' if 'model' not in kwargs else kwargs['model']
kwargs['original_params'] = {} if 'original_params' not... | def model(self, *args, **kwargs) | Piority of Arguments: Arguments passed in `kwargs` has the most piority, 'param' key in `kwargs` has less
piority than `kwargs` and dictionary arguments in `args` have the least piority. Other arguments are ignored.
Argument List:
model - set model type, default value 'default';
... | 2.630607 | 2.492243 | 1.055518 |
if isinstance(solution, Solution):
solution = solution.getSolution()
self.mu = self.solver.chemicalPotential(solution)
return self.mu | def getChemicalPotential(self, solution) | Call solver in order to calculate chemical potential. | 5.01977 | 4.332406 | 1.158656 |
date = date if date else datetime.now()
date = date.replace(microsecond=0).isoformat()
filename = filename if filename else date + '.mat'
matfile = {
'model': str(type(self)),
'date': date,
'dim': len(self.init_sol.shape),
'dimles... | def store(self, filename=None, label=None, desc=None, date=None) | Store object to mat-file. TODO: determine format specification | 3.538679 | 3.387437 | 1.044648 |
matfile = loadmat(filename)
matfile['originals'] = matfile['originals'][0, 0]
if matfile['dim'] == 1:
matfile['init_solution'] = matfile['init_solution'][0, :]
matfile['pumping'] = matfile['pumping'][0, :]
self.coeffs = matfile['dimlesses'][0, :]
... | def restore(self, filename) | Restore object from mat-file. TODO: determine format specification | 3.077252 | 2.979433 | 1.032832 |
reservoir = self.getReservoir()
density = self.getDensity()
length = self.model.getSpatialStep()
if self.solution.ndim == 1:
nodes = self.model.getNumberOfNodes()
radius = linspace(0, nodes * self.model.getSpatialStep(), nodes)
integral = 2 *... | def getDampingIntegral(self) | Calculate integral of damping terms of hamiltonian using rectangular method. | 4.220679 | 4.138274 | 1.019913 |
date = datetime.now() if date is None else date
filename = filename if filename else date.replace(microsecond=0).isoformat() + '.mat'
def storeWithFileLikeObject(file_like):
content = {
'elapsed_time': self.elapsed_time,
'solution': self.solu... | def store(self, filename=None, label=None, desc=None, date=None) | Store object to mat-file. TODO: determine format specification | 3.251016 | 3.058804 | 1.062839 |
matfile = loadmat(filename)
if matfile['dim'] == 1:
matfile['solution'] = matfile['solution'][0, :]
self.elapsed_time = matfile['elapsed_time'][0, 0]
self.solution = matfile['solution']
return self | def restore(self, filename) | Restore object from mat-file. TODO: determine format specification | 4.011045 | 3.579755 | 1.12048 |
val = repr(val)
max = 50
if shorten:
if len(val) > max:
close = val[-1]
val = val[0:max-4] + "..."
if close in (">", "'", '"', ']', '}', ')'):
val = val + close
return val | def fmt_val(val, shorten=True) | Format a value for inclusion in an
informative text string. | 4.138542 | 4.283768 | 0.966099 |
items = dict_vals.items()
if not items:
return [fmt_val(None, shorten=shorten)]
return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items] | def fmt_dict_vals(dict_vals, shorten=True) | Returns list of key=val pairs formatted
for inclusion in an informative text string. | 2.734482 | 2.968804 | 0.921072 |
command = ['perl', self.script, CLI_OPTIONS['config']['option'], config]
for key, value in kwargs.items():
# enable passing in flags as "False" - shouldn't add command
if value:
command.append(CLI_OPTIONS[key]['option'])
if value is True:
... | def build_command(self, config, **kwargs) | Builds the command to execute MIP. | 6.17943 | 6.262372 | 0.986756 |
process = subprocess.Popen(
command,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)
)
return process | def execute(self, command) | Start a new MIP run. | 2.909675 | 2.884962 | 1.008566 |
self.log.debug('starting the ``update`` method')
if "sherlock wiki root" not in self.settings:
print "Sherlock wiki settings not found in settings file"
return
staticTableInfo = self._get_table_infos()
viewInfo = self._get_view_infos()
streamedT... | def update(self) | Update wiki pages
See class docstring for usage | 6.62836 | 6.022532 | 1.100594 |
self.log.debug('starting the ``_get_table_infos`` method')
sqlQuery = u % locals()
tableInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = [... | def _get_table_infos(
self,
trimmed=False) | query the sherlock-catalogues database table metadata | 4.515837 | 3.915503 | 1.153322 |
self.log.debug('starting the ``_get_view_infos`` method')
sqlQuery = u % locals()
viewInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
... | def _get_view_infos(
self,
trimmed=False) | query the sherlock-catalogues database view metadata | 4.84454 | 4.13999 | 1.170181 |
self.log.debug('starting the ``_get_stream_view_infos`` method')
sqlQuery = u % locals()
streamInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTa... | def _get_stream_view_infos(
self,
trimmed=False) | query the sherlock-catalogues database streamed data tables' metadata | 4.803359 | 4.081863 | 1.176757 |
self.log.debug('starting the ``_write_wiki_pages`` method')
pathToWriteFile = self.settings[
"sherlock wiki root"] + "/Crossmatch-Catalogue Tables.md"
writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
now = datetime.now()
now = now.strftim... | def _write_wiki_pages(
self) | write the markdown formated content of the database tables' metadata to local wiki pages | 2.374917 | 2.253364 | 1.053943 |
self.log.debug('starting the ``_update_github`` method')
from subprocess import Popen, PIPE, STDOUT
gdir = self.settings["sherlock wiki root"]
cmd = % locals()
p = Popen(cmd, stdout=PIPE, stdin=PIPE, shell=True)
output = p.communicate()[0]
print output
... | def _update_github(
self) | commit the changes and push them to github | 5.247916 | 4.92977 | 1.064536 |
receiver = self.email
if settings.EMAIL_OVERRIDE_ADDRESS:
receiver = settings.EMAIL_OVERRIDE_ADDRESS
send_mail(subject, message, from_email, [receiver], **kwargs) | def email_user(
self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs
) | Sends an email to this User.
If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address. | 3.074656 | 2.125523 | 1.446541 |
number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago)
analyses = context.obj['store'].analyses(
status='completed',
before=number_of_days_ago,
deleted=False,
)
for analysis_obj in analyses:
LOG.debug(f"checking analysis: {analysis_obj.family} ({analysi... | def clean(context, days_ago, yes) | Clean up files from "old" analyses runs. | 3.230463 | 3.121192 | 1.035009 |
log.debug('starting the ``get_crossmatch_catalogues_column_map`` function')
# GRAB THE NAMES OF THE IMPORTANT COLUMNS FROM DATABASE
sqlQuery = u % locals()
rows = readquery(
log=log,
sqlQuery=sqlQuery,
dbConn=dbConn,
quiet=False
)
colMaps = {}
for row in... | def get_crossmatch_catalogues_column_map(
dbConn,
log) | *Query the sherlock-catalogues helper tables to generate a map of the important columns of each catalogue*
Within your sherlock-catalogues database you need to manually map the inhomogeneous column-names from the sherlock-catalogues to an internal homogeneous name-set which includes *ra*, *dec*, *redshift*, *objec... | 4.594755 | 3.836245 | 1.197722 |
id_rows = [line for line in log_stream if 'scancel' in line]
jobs = [id_row.strip()[-7:-1] for id_row in id_rows]
return jobs | def job_ids(log_stream) | Grep out all lines with scancel example. | 4.886025 | 3.384858 | 1.443495 |
if os.path.isfile(path):
with open(path) as fh:
_LOG.debug("loading config from %s", os.path.abspath(path))
config._inflate(toml.load(fh))
else:
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass
with open(path, "w") ... | def get_or_create_config(path, config) | Using TOML format, load config from given path, or write out example based on defaults | 2.475849 | 2.406514 | 1.028811 |
data = {k: v for k, v in vars(cls).items() if not k.startswith("_")}
return {Constants.CONFIG_KEY: data} | def _deflate(cls) | Prepare for serialisation - returns a dictionary | 5.829595 | 4.730656 | 1.232302 |
for k, v in data[Constants.CONFIG_KEY].items():
setattr(cls, k, v)
return cls._deflate() | def _inflate(cls, data) | Update config by deserialising input dictionary | 7.683679 | 5.525971 | 1.390467 |
def patcher(method):
@wraps(method)
def method_call(*m_args, **m_kw):
patched_obj = patch_object(obj, attr_name, patched_value)
try:
return method(*m_args, **m_kw)
finally:
patched_obj.restore()
return method_call
r... | def with_patched_object(obj, attr_name, patched_value) | Decorator that patches an object before the decorated method
is called and restores it afterwards.
This is a wrapper around :func:`fudge.patcher.patch_object`
Example::
>>> from fudge import with_patched_object
>>> class Session:
... state = 'clean'
...
>>> @wi... | 2.478471 | 2.94399 | 0.841875 |
if isinstance(obj, (str, unicode)):
obj_path = adjusted_path = obj
done = False
exc = None
at_top_level = False
while not done:
try:
obj = __import__(adjusted_path)
done = True
except ImportError:
# ... | def patch_object(obj, attr_name, patched_value) | Patches an object and returns an instance of :class:`fudge.patcher.PatchHandler` for later restoration.
Note that if *obj* is not an object but a path to a module then it will be imported.
You may want to use a more convenient wrapper :func:`with_patched_object` or :func:`patched_context`
Example::
... | 4.620855 | 4.854006 | 0.951967 |
try:
if self.getter:
setattr(self.getter_class, self.attr_name, patched_value)
else:
setattr(self.orig_object, self.attr_name, patched_value)
except TypeError:
# Workaround for patching builtin objects:
proxy_name =... | def patch(self, patched_value) | Set a new value for the attribute of the object. | 3.013771 | 3.059623 | 0.985014 |
if self.proxy_object is None:
if self.getter:
setattr(self.getter_class, self.attr_name, self.getter)
elif self.is_local:
setattr(self.orig_object, self.attr_name, self.orig_value)
else:
# Was not a local, safe to delet... | def restore(self) | Restore the saved value for the attribute of the object. | 3.37645 | 3.321558 | 1.016526 |
return {
'email': data.get('email'),
'family': data['family_id'],
'samples': [{
'id': sample_id,
'type': analysis_type,
} for sample_id, analysis_type in data['analysis_type'].items()],
'config_path': data['config_file_analysis'],
'is_dryr... | def parse_config(data: dict) -> dict | Parse MIP config file.
Args:
data (dict): raw YAML input from MIP analysis config file
Returns:
dict: parsed data | 4.593914 | 4.735703 | 0.970059 |
genome_build = data['human_genome_build']
genome_build_str = f"{genome_build['source']}{genome_build['version']}"
if 'svdb' in data['program']:
svdb_outpath = (f"{data['program']['svdb']['path']}")
else:
svdb_outpath = ''
outdata = {
'date': data['analysis_date'],
... | def parse_sampleinfo(data: dict) -> dict | Parse MIP sample info file.
Args:
data (dict): raw YAML input from MIP qc sample info file
Returns:
dict: parsed data | 3.043384 | 3.024128 | 1.006367 |
data = {
'versions': {
'freebayes': metrics['program']['freebayes']['version'],
'gatk': metrics['program']['gatk']['version'],
'manta': metrics['program'].get('manta', {}).get('version'),
'bcftools': metrics['program']['bcftools']['version'],
... | def parse_qcmetrics(metrics: dict) -> dict | Parse MIP qc metrics file.
Args:
metrics (dict): raw YAML input from MIP qc metrics file
Returns:
dict: parsed data | 2.96873 | 2.971784 | 0.998973 |
data = {}
samples = csv.DictReader(handle)
for sample in samples:
data[sample['sample_id']] = {
'predicted_sex': sample['predicted_sex'],
'het_ratio': float(sample['het_ratio']),
'error': True if sample['error'] == 'True' else False,
}
return data | def parse_peddy_sexcheck(handle: TextIO) | Parse Peddy sexcheck output. | 3.367079 | 3.070642 | 1.096539 |
samples = csv.DictReader(handle, delimiter='\t')
for sample in samples:
return {
'predicted_sex': sample['sex'],
'x_coverage': float(sample['#X_coverage']),
'y_coverage': float(sample['Y_coverage']),
} | def parse_chanjo_sexcheck(handle: TextIO) | Parse Chanjo sex-check output. | 5.118119 | 4.462072 | 1.147027 |
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
user = request.user
grant = False
model = Model
mod_edit = False
if 'pk' in kwargs:
pk = int(kwargs['pk'])
if model:
mod... | def owner_required(Model=None) | Usage:
@owner_required(Entry)
def manage_entry(request, pk=None, object=None):
@owner_required()
def entry_delete(*args, **kwargs):
kwargs["post_delete_redirect"] = reverse('manage_blogs')
return delete_object(*args, **kwargs) | 2.547377 | 2.553478 | 0.997611 |
'''
Lazily imports a utils (class,
function,or variable) from a module) from
a string.
@param imp:
'''
mod_name, obj_name = imp.rsplit('.', 1)
mod = importlib.import_module(mod_name)
return getattr(mod, obj_name) | def import_util(imp) | Lazily imports a utils (class,
function,or variable) from a module) from
a string.
@param imp: | 6.600196 | 2.383131 | 2.769548 |
parser = argparse.ArgumentParser(
prog="auto_version",
description="auto version v%s: a tool to control version numbers" % __version__,
)
parser.add_argument(
"--target",
action="append",
default=[],
help="Files containing version info. "
"Assumes... | def get_cli() | Load cli options | 4.557728 | 4.505831 | 1.011518 |
r
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
new_stdout = StringIO()
new_stderr = StringIO()
new_stdin = TeeStdin(new_stdout, in_str)
sys.stdin = new_stdin
sys.stdout = new_stdout
sys.stderr = new_stderr
yield new_stdin, new_stdout, new_stderr
... | def stdio_mgr(in_str="") | r"""Subsitute temporary text buffers for `stdio` in a managed context.
Context manager.
Substitutes empty :cls:`~io.StringIO`\ s for
:cls:`sys.stdout` and :cls:`sys.stderr`,
and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context.
Upon exiting the context, the original stream object... | 1.858892 | 2.094843 | 0.887366 |
for segment in segments:
x, y, w, h = segment
cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width) | def draw_segments(image, segments, color=(255, 0, 0), line_width=1) | draws segments on image | 1.637545 | 1.570563 | 1.042648 |
for y in ys:
cv2.line(image, (0, y), (image.shape[1], y), color, line_width) | def draw_lines(image, ys, color=(255, 0, 0), line_width=1) | draws horizontal lines | 1.647726 | 1.602675 | 1.02811 |
total_sec = 0
if '-' in time_str:
# parse out days
days, time_str = time_str.split('-')
total_sec += (int(days) * 24 * 60 * 60)
# parse out the hours and mins (skip seconds)
hours_min_raw = time_str.split(':')[:-1]
time_parts = [int(round(float(val))) for val in hours_m... | def time_to_sec(time_str: str) -> int | Convert time in string format to seconds.
Skipping seconds since sometimes the last column is truncated
for entries where >10 days. | 2.744027 | 2.678104 | 1.024616 |
state = row[-2]
start_time_raw = row[-4]
end_time_raw = row[-3]
if state not in ('PENDING', 'CANCELLED'):
start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S')
if state != 'RUNNING':
end_time = datetime.strptime(end_time_raw, '%Y-%m-%dT%H:%M:%S')
el... | def convert_job(row: list) -> dict | Convert sacct row to dict. | 2.678341 | 2.553509 | 1.048886 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.