code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
existing_user = context.obj['store'].user(email) if existing_user: click.echo(existing_user.to_dict()) elif name: new_user = context.obj['store'].add_user(name, email) click.echo(click.style(f"New user added: {email} ({new_user.id})", fg='green')) else: click.echo(cl...
def user(context, name, email)
Add a new or display information about an existing user.
2.639524
2.545845
1.036797
analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: click.echo('analysis not found') context.abort() elif analysis_obj.status != 'running': click.echo(f"analysis not running: {analysis_obj.status}") context.abort() config_path = Path(a...
def cancel(context, jobs, analysis_id)
Cancel all jobs in a run.
2.639567
2.645575
0.997729
addrs = [] if names is None: names = ["", ] for name in names: then = datetime.now() + timedelta(seconds=timeout) while datetime.now() < then: addrs += get_pub_address(name, nameserver=nameserver) if addrs: break time.sleep(.5)...
def get_pub_addresses(names=None, timeout=10, nameserver="localhost")
Get the address of the publisher for a given list of publisher *names* from the nameserver on *nameserver* (localhost by default).
2.857862
2.900068
0.985447
# Socket to talk to server socket = get_context().socket(REQ) try: socket.setsockopt(LINGER, timeout * 1000) socket.connect("tcp://" + nameserver + ":" + str(PORT)) logger.debug('Connecting to %s', "tcp://" + nameserver + ":" + str(PORT)) poller = P...
def get_pub_address(name, timeout=10, nameserver="localhost")
Get the address of the publisher for a given publisher *name* from the nameserver on *nameserver* (localhost by default).
4.059864
4.1402
0.980596
addrs = arec.get(name) if addrs: return Message("/oper/ns", "info", addrs) else: return Message("/oper/ns", "info", "")
def get_active_address(name, arec)
Get the addresses of the active modules for a given publisher *name*.
7.286484
7.162848
1.017261
del args arec = AddressReceiver(max_age=self._max_age, multicast_enabled=self._multicast_enabled) arec.start() port = PORT try: with nslock: self.listener = get_context().socket(REP) self.listen...
def run(self, *args)
Run the listener and answer to requests.
4.588203
4.565584
1.004954
self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
def stop(self)
Stop the name server.
15.626893
10.869408
1.437695
ignore = (ignore or []) not_satisfied = [] working_set = pkg_resources.working_set installed_packages = dict((p.project_name, p) for p in working_set) # pylint: disable=E1133 if isinstance(requirements, str): with open(requirements, 'r') as file_h: requirements = file_h.readlines() elif hasattr(requireme...
def check_requirements(requirements, ignore=None)
Parse requirements for package information to determine if all requirements are met. The *requirements* argument can be a string to a requirements file, a file like object to be read, or a list of strings representing the package requirements. :param requirements: The file to parse. :type requirements: file obj, ...
1.905631
1.936401
0.98411
segments = segments if SEGMENTS_DIRECTION == 0 else segments.tranpose() segments = [map(int, s) for s in segments] return segments
def segments_from_numpy(segments)
reverses segments_to_numpy
7.999382
8.247513
0.969914
segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments) return segments
def segments_to_numpy(segments)
given a list of 4-element tuples, transforms it into a numpy array
7.539948
6.736687
1.119237
x, y, w, h = segment return image[y:y + h, x:x + w]
def region_from_segment(image, segment)
given a segment (rectangle) and an image, returns it's corresponding subimage
2.796717
2.117749
1.320608
self.log.debug('starting the ``get`` method') # A YAML DICTIONARY OF sherlock-catalogues TABLE NAME AND THE SELECT # QUERY TO LIFT THE DATA FROM THE MARSHALL yamlFilePath = '/'.join(string.split(__file__, '/') [:-1]) + "/resources/pessto_marshall...
def ingest(self)
*Ingest the ePESSTO Marshall transient stream into the catalogues database* The method first creates the tables for the various marshall feeder surveys in the sherlock-catalogues database (if they do not yet exist). Then the marshall database is queried for each transient survey and the results imported into t...
7.991424
6.545128
1.220973
self.log.debug( 'starting the ``_create_dictionary_of_marshall`` method') dictList = [] tableName = self.dbTableName rows = readquery( log=self.log, sqlQuery=marshallQuery, dbConn=self.pmDbConn, quiet=False ) ...
def _create_dictionary_of_marshall( self, marshallQuery, marshallTable)
create a list of dictionaries containing all the rows in the marshall stream **Key Arguments:** - ``marshallQuery`` -- the query used to lift the required data from the marshall database. - ``marshallTable`` -- the name of the marshall table we are lifting the data from. **Retu...
4.249694
3.960188
1.073104
self.log.debug('starting the ``get`` method') dictList = self._create_dictionary_of_ned_d() self.primaryIdColumnName = "primaryId" self.raColName = "raDeg" self.declColName = "decDeg" tableName = self.dbTableName createStatement = u % locals() ...
def ingest(self)
Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d 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.892471
7.298666
1.218369
self.log.debug( 'starting the ``_create_dictionary_of_ned_d`` method') count = 0 with open(self.pathToDataFile, 'rb') as csvFile: csvReader = csv.reader( csvFile, dialect='excel', delimiter=',', quotechar='"') totalRows = sum(1 for ro...
def _create_dictionary_of_ned_d( self)
create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments values and definitions with defaults - update return va...
3.060564
2.98945
1.023788
self.log.debug('starting the ``_clean_up_columns`` method') tableName = self.dbTableName print "cleaning up %(tableName)s columns" % locals() sqlQuery = u % locals() writequery( log=self.log, sqlQuery=sqlQuery, dbConn=self.catalogue...
def _clean_up_columns( self)
clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip...
3.988456
3.896894
1.023496
self.log.debug('starting the ``_get_metadata_for_galaxies`` method') total, batches = self._count_galaxies_requiring_metadata() print "%(total)s galaxies require metadata. Need to send %(batches)s batch requests to NED." % locals() totalBatches = self.batches thisCount...
def _get_metadata_for_galaxies( self)
get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any use...
5.622629
5.513632
1.019769
self.log.debug( 'starting the ``_get_3000_galaxies_needing_metadata`` method') tableName = self.dbTableName # SELECT THE DATA FROM NED TABLE self.theseIds = {} sqlQuery = u % locals() rows = readquery( log=self.log, sqlQuery=...
def _get_3000_galaxies_needing_metadata( self)
get 3000 galaxies needing metadata **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text ...
5.225248
4.334513
1.205498
self.log.debug( 'starting the ``_query_ned_and_add_results_to_database`` method') tableName = self.dbTableName # ASTROCALC UNIT CONVERTER OBJECT converter = unit_conversion( log=self.log ) # QUERY NED WITH BATCH totalCount = len(...
def _query_ned_and_add_results_to_database( self, batchCount)
query ned and add results to database **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples a...
3.616986
3.566415
1.01418
self.log.debug('starting the ``_update_sdss_coverage`` method') tableName = self.dbTableName # SELECT THE LOCATIONS NEEDING TO BE CHECKED sqlQuery = u % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.catalogu...
def _update_sdss_coverage( self)
update sdss coverage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful t...
3.442655
3.469232
0.992339
return RemoteTask(self.hostname, command, identity_file=self._identity_file, **kwargs)
def run(self, command, **kwargs)
Run a command on the remote host. This is just a wrapper around ``RemoteTask(self.hostname, ...)``
12.143474
6.143317
1.976696
cmd = ['rsync'] if self._identity_file: cmd += ['-e', 'ssh -i ' + os.path.expanduser(self._identity_file)] return cmd
def _rsync_cmd(self)
Helper method to generate base rsync command.
3.602532
3.225479
1.116898
if not remote_destination: remote_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', file_name, '%s:%s' % (self.hostname, remote_destination)], **kwargs)
def send_file(self, file_name, remote_destination=None, **kwargs)
Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as *...
5.057257
4.218437
1.198846
if not local_destination: local_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', '%s:%s' % (self.hostname, file_name), local_destination], **kwargs)
def get_file(self, file_name, local_destination=None, **kwargs)
Get a file from a remote host with rsync. Args: file_name (str): The relative location of the file on the remote host. local_destination (str): The destination for the file on the local host. If `None`, will be assumed to be the same as *...
5.413677
4.115633
1.315394
self.validate_config(data) config_data = self.prepare_config(data) return config_data
def make_config(self, data: dict)
Make a MIP config.
5.598792
4.050138
1.382371
errors = ConfigSchema().validate(data) if errors: for field, messages in errors.items(): if isinstance(messages, dict): for level, sample_errors in messages.items(): sample_id = data['samples'][level]['sample_id'] ...
def validate_config(data: dict) -> dict
Convert to MIP config format.
3.469052
3.239699
1.070794
data_copy = deepcopy(data) # handle single sample cases with 'unknown' phenotype if len(data_copy['samples']) == 1: if data_copy['samples'][0]['phenotype'] == 'unknown': LOG.info("setting 'unknown' phenotype to 'unaffected'") data_copy['sample...
def prepare_config(data: dict) -> dict
Prepare the config data.
3.100451
2.965194
1.045615
out_dir = Path(self.families_dir) / data['family'] out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / 'pedigree.yaml' dump = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2) out_path.write_text(dump) return out_path
def save_config(self, data: dict) -> Path
Save a config to the expected location.
2.855263
2.72243
1.048792
value = getattr(src_processor, src_atr_name) value = transform_function(value) for d in dest_processors: setattr(d, dest_atr_name, value)
def _broadcast(src_processor, src_atr_name, dest_processors, dest_atr_name, transform_function)
To be used exclusively by create_broadcast. A broadcast function gets an attribute on the src_processor and sets it (possibly under a different name) on dest_processors
2.213278
2.292713
0.965353
from functools import partial if dest_atr_name == None: dest_atr_name = src_atr_name if not hasattr(dest_processors, "__iter__"): # a single processor was given instead dest_processors = [dest_processors] return partial(_broadcast, src_atr_name=src_atr_name, dest_processors=dest_pr...
def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x)
This method creates a function, intended to be called as a Processor posthook, that copies some of the processor's attributes to other processors
2.143085
2.295159
0.933741
parameter_names = self.PARAMETERS.keys() # TODO: Unresolved reference for processor parameter_values = [getattr(processor, n) for n in parameter_names] return dict(zip(parameter_names, parameter_values))
def get_parameters(self)
returns a dictionary with the processor's stored parameters
6.160524
5.171726
1.191193
for k, v in self.PARAMETERS.items(): new_value = args.get(k) if new_value != None: if not _same_type(new_value, v): raise Exception( "On processor {0}, argument {1} takes something like {2}, but {3} was given".format(se...
def set_parameters(self, **args)
sets the processor stored parameters
3.3994
3.213302
1.057915
d = {} for p in self.processors: parameter_names = list(p.PARAMETERS.keys()) parameter_values = [getattr(p, n) for n in parameter_names] d.update(dict(zip(parameter_names, parameter_values))) return d
def get_parameters(self)
gets from all wrapped processors
3.14011
2.442469
1.285629
not_used = set() not_given = set() for p in self.processors: nu, ng = p.set_parameters(**args) not_used = not_used.union(nu) not_given = not_given.union(ng) return not_used, not_given
def set_parameters(self, **args)
sets to all wrapped processors
3.56709
2.879968
1.238587
self.elapsed_time = -time() dpi = 100 fig = figure(figsize=(16, 9), dpi=dpi) with self.writer.saving(fig, filename, dpi): for frame_id in xrange(self.frames + 1): self.renderFrame(frame_id) self.writer.grab_frame() self.elapsed...
def render(self, filename)
Perform initialization of render, set quality and size video attributes and then call template method that is defined in child class.
3.625838
3.59019
1.009929
message = 'Elapsed in {0} seconds with {1} frames and {2} step.' print(message.format(self.elapsed_time, self.frames, self.step))
def report(self)
Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of frames and step size that is used in functional animation.
7.039311
4.554377
1.545615
with self._lock: if address in self.addresses: return False topics = self._magickfy_topics(topics) or self._topics LOGGER.info("Subscriber adding address %s with topics %s", str(address), str(topics)) subscriber = ...
def add(self, address, topics=None)
Add *address* to the subscribing list for *topics*. It topics is None we will subscibe to already specified topics.
4.296649
4.301
0.998988
with self._lock: try: subscriber = self.addr_sub[address] except KeyError: return False LOGGER.info("Subscriber removing address %s", str(address)) if self.poller: self.poller.unregister(subscriber) ...
def remove(self, address)
Remove *address* from the subscribing list for *topics*.
3.45836
3.489985
0.990938
if isinstance(addresses, six.string_types): addresses = [addresses, ] s0_, s1_ = set(self.addresses), set(addresses) sr_, sa_ = s0_.difference(s1_), s1_.difference(s0_) for a__ in sr_: self.remove(a__) for a__ in sa_: self.add(a__) ...
def update(self, addresses)
Updating with a set of addresses.
3.224669
3.087273
1.044504
LOGGER.info("Subscriber adding SUB hook %s for topics %s", str(address), str(topics)) socket = get_context().socket(SUB) for t__ in self._magickfy_topics(topics): socket.setsockopt_string(SUBSCRIBE, six.text_type(t__)) socket.connect(address) ...
def add_hook_sub(self, address, topics, callback)
Specify a *callback* in the same stream (thread) as the main receive loop. The callback will be called with the received messages from the specified subscription. Good for operations, which is required to be done in the same thread as the main recieve loop (e.q operations on the underly...
7.390009
7.662282
0.964466
LOGGER.info("Subscriber adding PULL hook %s", str(address)) socket = get_context().socket(PULL) socket.connect(address) self._add_hook(socket, callback)
def add_hook_pull(self, address, callback)
Same as above, but with a PULL socket. (e.g good for pushed 'inproc' messages from another thread).
7.507486
5.660728
1.32624
self._hooks.append(socket) self._hooks_cb[socket] = callback if self.poller: self.poller.register(socket, POLLIN)
def _add_hook(self, socket, callback)
Generic hook. The passed socket has to be "receive only".
3.504064
3.239679
1.081608
if timeout: timeout *= 1000. for sub in list(self.subscribers) + self._hooks: self.poller.register(sub, POLLIN) self._loop = True try: while self._loop: sleep(0) try: socks = dict(self.polle...
def recv(self, timeout=None)
Receive, optionally with *timeout* in seconds.
3.532283
3.484725
1.013647
self.stop() for sub in list(self.subscribers) + self._hooks: try: sub.setsockopt(LINGER, 1) sub.close() except ZMQError: pass
def close(self)
Close the subscriber: stop it and close the local subscribers.
7.486107
5.530704
1.353554
# If topic does not start with messages._MAGICK (pytroll:/), it will be # prepended. if topics is None: return None if isinstance(topics, six.string_types): topics = [topics, ] ts_ = [] for t__ in topics: if not t__.startswith(...
def _magickfy_topics(topics)
Add the magick to the topics if missing.
5.136315
4.423453
1.161155
def _get_addr_loop(service, timeout): then = datetime.now() + timedelta(seconds=timeout) while datetime.now() < then: addrs = get_pub_address(service, nameserver=self._nameserver) if addrs: return [addr["URI"] for ...
def start(self)
Start the subscriber.
4.068625
3.906489
1.041504
addr_ = msg.data["URI"] status = msg.data.get('status', True) if status: service = msg.data.get('service') for service in self.services: if not service or service in service: LOGGER.debug("Adding address %s %s", str(addr_), ...
def handle_msg(self, msg)
handle the message *msg*.
4.453574
4.428813
1.005591
self.log.debug( 'starting the ``_get_transient_metadata_from_database_list`` method') sqlQuery = self.settings["database settings"][ "transients"]["transient query"] + " limit " + str(self.largeBatchSize) thisInt = randint(0, 100) if "where" in sqlQuery...
def _get_transient_metadata_from_database_list( self)
use the transient query in the settings file to generate a list of transients to corssmatch and classify **Return:** - ``transientsMetadataList`` .. todo :: - update key arguments values and definitions with defaults - update return values and definitions ...
4.164885
3.759794
1.107743
self.log.debug('starting the ``_update_ned_stream`` method') coordinateList = [] for i in transientsMetadataList: # thisList = str(i["ra"]) + " " + str(i["dec"]) thisList = (i["ra"], i["dec"]) coordinateList.append(thisList) coordinateList =...
def _update_ned_stream( self, transientsMetadataList )
update the NED stream within the catalogues database at the locations of the transients **Key Arguments:** - ``transientsMetadataList`` -- the list of transient metadata lifted from the database. .. todo :: - update key arguments values and definitions with defaults ...
4.332289
4.10846
1.05448
self.log.debug('starting the ``_remove_previous_ned_queries`` method') # 1 DEGREE QUERY RADIUS radius = 60. * 60. updatedCoordinateList = [] keepers = [] # CALCULATE THE OLDEST RESULTS LIMIT now = datetime.now() td = timedelta( days=...
def _remove_previous_ned_queries( self, coordinateList)
iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **Return:** - ``updatedCoordinateList`` -- coordinate list with previous queries r...
4.996804
5.044963
0.990454
global theseBatches self.log.debug( 'starting the ``_crossmatch_transients_against_catalogues`` method') # SETUP ALL DATABASE CONNECTIONS transientsMetadataList = theseBatches[transientsMetadataListIndex] dbConn = database( log=self.log, ...
def _crossmatch_transients_against_catalogues( self, transientsMetadataListIndex, colMaps)
run the transients through the crossmatch algorithm in the settings file **Key Arguments:** - ``transientsMetadataListIndex`` -- the list of transient metadata lifted from the database. - ``colMaps`` -- dictionary of dictionaries with the name of the database-view (e.g. `tcs_view_agn_m...
4.671331
4.536125
1.029807
self.log.debug('starting the ``_update_transient_database`` method') import time start_time = time.time() print "UPDATING TRANSIENTS DATABASE WITH RESULTS" print "DELETING OLD RESULTS" now = datetime.now() now = now.strftime("%Y-%m-%d_%H-%M-%S-%f") ...
def _update_transient_database( self, crossmatches, classifications, transientsMetadataList, colMaps)
update transient database with classifications and crossmatch results **Key Arguments:** - ``crossmatches`` -- the crossmatches and associations resulting from the catlaogue crossmatches - ``classifications`` -- the classifications assigned to the transients post-crossmatches (dictionar...
2.753581
2.679039
1.027824
self.log.debug('starting the ``_consolidate_coordinateList`` method') raList = [] raList[:] = np.array([c[0] for c in coordinateList]) decList = [] decList[:] = np.array([c[1] for c in coordinateList]) nedStreamRadius = self.settings[ "ned stream se...
def _consolidate_coordinateList( self, coordinateList)
*match the coordinate list against itself with the parameters of the NED search queries to minimise duplicated NED queries* **Key Arguments:** - ``coordinateList`` -- the original coordinateList. **Return:** - ``updatedCoordinateList`` -- the coordinate list with duplicated sea...
4.936309
4.6407
1.063699
self.log.debug('starting the ``classification_annotations`` method') from fundamentals.mysql import readquery sqlQuery = u % locals() topXMs = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.transientsDbConn ) for xm ...
def classification_annotations( self)
*add a detialed classification annotation to each classification in the sherlock_classifications table* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage ...
7.816816
8.036891
0.972617
self.log.debug('starting the ``update_peak_magnitudes`` method') sqlQuery = self.settings["database settings"][ "transients"]["transient peak magnitude query"] sqlQuery = % locals() writequery( log=self.log, sqlQuery=sqlQuery, ...
def update_peak_magnitudes( self)
*update peak magnitudes* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - write a command-line tool for this method - upd...
7.262677
7.128064
1.018885
self.log.debug('starting the ``_create_tables_if_not_exist`` method') transientTable = self.settings["database settings"][ "transients"]["transient table"] transientTableClassCol = self.settings["database settings"][ "transients"]["transient classification colum...
def _create_tables_if_not_exist( self)
*create the sherlock helper tables if they don't yet exist* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - write a command-line tool fo...
3.836941
3.753763
1.022158
analysis_obj = context.obj['store'].analyses(family=family).first() if analysis_obj is None: LOG.error('no analysis found') context.abort() config_path = Path(analysis_obj.config_path) if not config_path.exists(): LOG.error(f"analysis config not found: {config_path}") ...
def check(context: click.Context, family: str)
Delete an analysis log from the database.
2.266731
2.230232
1.016366
flowcell = f"{flowcell}-undetermined" if undetermined else flowcell date_str = date.strftime('%y%m%d') if date else '171015' index = index if index else 'XXXXXX' return f"{lane}_{date_str}_{flowcell}_{sample}_{index}_{read}.fastq.gz"
def name_file(lane: int, flowcell: str, sample: str, read: int, undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str
Name a FASTQ file following MIP conventions.
3.585934
3.1398
1.14209
root_dir = Path(self.families_dir) / family / analysis_type / sample / 'fastq' root_dir.mkdir(parents=True, exist_ok=True) for fastq_data in files: fastq_path = Path(fastq_data['path']) fastq_name = self.name_file( lane=fastq_data['lane'], ...
def link(self, family: str, sample: str, analysis_type: str, files: List[str])
Link FASTQ files for a sample.
2.503737
2.41106
1.038438
moduleDirectory = os.path.dirname(__file__) packagePath = os.path.dirname(__file__) + "/../" return packagePath
def getpackagepath()
*Get the root path for this python package - used in unit testing code*
3.930292
4.191263
0.937735
sock = socket(AF_INET, SOCK_DGRAM) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) if _is_broadcast_group(mcgroup): group = '<broadcast>' sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) elif((int(mcgroup.split(".")[0]) > 239) or (int(mcgroup.split(".")[0]) < 224)): raise ...
def mcast_sender(mcgroup=MC_GROUP)
Non-object interface for sending multicast messages.
3.022635
3.0153
1.002433
if _is_broadcast_group(mcgroup): group = None else: group = mcgroup # Create a socket sock = socket(AF_INET, SOCK_DGRAM) # Allow multiple copies of this program on one machine # (not strictly needed) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) if group: s...
def mcast_receiver(port, mcgroup=MC_GROUP)
Open a UDP socket, bind it to a port and select a multicast group.
3.561778
3.530658
1.008814
self.socket.setsockopt(SOL_SOCKET, SO_LINGER, struct.pack('ii', 1, 1)) self.socket.close()
def close(self)
Close the receiver.
3.398124
3.001727
1.132056
def wrapper(*args): code = args[0] ErrorMapping.mapping[http_code] = code return code return wrapper
def api_exception(http_code)
Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses. :param http_code: (int) HTTP status code. :return: wrapper function.
9.288619
10.003291
0.928556
for temp_log in self.store.analyses(family=family_name, temp=True): log.debug(f"delete temporary log: {temp_log.id} - {temp_log.status}") temp_log.delete()
def _delete_temp_logs(self, family_name: str)
Delete temporary logs for the current family.
5.371841
4.489653
1.196494
analysis_types = [sample['type'] for sample in config_data['samples']] run_data = { 'user': config_data['email'], 'family': config_data['family'], 'priority': config_data['priority'], 'started_at': sampleinfo_data['date'], 'version': s...
def parse(cls, config_data: dict, sampleinfo_data: dict, sacct_jobs: List[dict], jobs: int) -> dict
Parse information about a run.
3.13529
2.987698
1.0494
failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True) completed_jobs = [job for job in sacct_jobs if job['is_completed']] last_job_end = completed_jobs[-1]['end'] if len(completed_jobs) > 0 else None data = { 'jobs': jobs_count, 'completed_jobs': l...
def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None)
Parse out info from Sacct log.
2.942284
2.821255
1.042899
types_set = set(analysis_types) return types_set.pop() if len(types_set) == 1 else 'wgs'
def _get_analysis_type(analysis_types: List[str]) -> str
Determine the overall analysis type.
4.982936
3.70579
1.344635
existing_run = self.store.find_analysis(family=run_data['family'], started_at=run_data['started_at'], status=run_data['status']) if existing_run: return None run_data['user'] = s...
def build(self, run_data: dict) -> models.Analysis
Build a new Analysis object.
2.978506
2.863018
1.040338
default = self.default_value if isinstance(default, collections.Callable): default = default() return default
def get_default_value(self)
return default value
4.210778
3.643946
1.155554
self = cls.__new__(cls) self.root_connection = connection self._dbapi_connection = dbapi_connection self.dialect = connection.dialect self.compiled = compiled # this should be caught in the engine before # we get here assert compiled.can_execut...
def _init_compiled(cls, dialect, connection, dbapi_connection, compiled, parameters)
Initialize execution context for a Compiled construct.
3.272454
3.24238
1.009275
sentence_delimiters = re.compile(u'[.!?,;:\t\\\\"\\(\\)\\\'\u2019\u2013]|\\s\\-\\s') sentences = sentence_delimiters.split(text) return sentences
def split_sentences(text)
Utility function to return a list of sentences. @param text The text that must be split in to sentences.
3.459138
3.877771
0.892043
@wraps(func) def decorated_function(self, request, queryset): # func follows the prototype documented at: # https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions if not isinstance(queryset, QuerySet): try: # Django >=1....
def takes_instance_or_queryset(func)
Decorator that makes standard Django admin actions compatible.
2.662071
2.572383
1.034866
urls = super(BaseDjangoObjectActions, self).get_urls() return self._get_action_urls() + urls
def get_urls(self)
Prepend `get_urls` with our own patterns.
7.989094
5.992233
1.333242
actions = {} model_name = self.model._meta.model_name # e.g.: polls_poll base_url_name = '%s_%s' % (self.model._meta.app_label, model_name) # e.g.: polls_poll_actions model_actions_url_name = '%s_actions' % base_url_name self.tools_view_name = 'admin:' ...
def _get_action_urls(self)
Get the url patterns that route each action to a view.
3.106433
3.009629
1.032165
tool = getattr(self, tool_name) standard_attrs, custom_attrs = self._get_button_attrs(tool) return dict( name=tool_name, label=getattr(tool, 'label', tool_name), standard_attrs=standard_attrs, custom_attrs=custom_attrs, )
def _get_tool_dict(self, tool_name)
Represents the tool as a dict with extra meta.
3.138663
2.933438
1.069961
attrs = getattr(tool, 'attrs', {}) # href is not allowed to be set. should an exception be raised instead? if 'href' in attrs: attrs.pop('href') # title is not allowed to be set. should an exception be raised instead? # `short_description` should be set inste...
def _get_button_attrs(self, tool)
Get the HTML attributes associated with a tool. There are some standard attributes (class and title) that the template will always want. Any number of additional attributes can be specified and passed on. This is kinda awkward and due for a refactor for readability.
3.259675
3.175188
1.026609
obj.question = obj.question + '?' obj.save()
def question_mark(self, request, obj)
Add a question mark.
7.510513
5.504976
1.364314
return build_html_element(tag='a', text=text, href=href, cls=cls, icon_class=icon_class, **attrs)
def build_link(href, text, cls=None, icon_class=None, **attrs)
Builds an html link. :param href: link for the anchor element :param text: text for the anchor element :param attrs: other attribute kwargs >>> build_link('xyz.com', 'hello', 'big') u'<a href="xyz.com" class="big">hello</a>' >>> build_link('xyz.com', 'hello', 'big', 'fa fa-times') u'<a hre...
2.65618
3.713053
0.715363
if cls is not None: kwargs['class'] = cls tag_attrs = ' '.join(['{0}="{1}"'.format(k, v) for k, v in kwargs.items()]) tag_content = '{tag} {tag_attrs}'.format(tag=tag, tag_attrs=tag_attrs) if tag in ('img', 'input', 'hr', 'br'): return mark_safe('<{tag_content} />'.format(tag_con...
def build_html_element(tag, text=None, icon_class=None, cls=None, **kwargs)
Builds an html element. :param tag: the html tag to build ('a', 'div', 'img', etc) :param icon_class: the class to apply to an icon element. This only applies to elements that allow a closing tag. :param cls: the css class to apply to the tag. This can also be passed in as a kwarg as "cla...
2.05837
2.384112
0.86337
class BlockStyle(str): pass class SessionDumper(yaml.SafeDumper): pass def str_block_formatter(dumper, data): return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|') SessionDumper.add_representer(BlockStyle, str_block_formatter) raw = deepcopy(raw) for step in raw...
def dump_migration_session_state(raw)
Serialize a migration session state to yaml using nicer formatting Args: raw: object to serialize Returns: string (of yaml) Specifically, this forces the "output" member of state step dicts (e.g. state[0]['output']) to use block formatting. For example, rather than this: - migration: [app...
2.967096
2.731435
1.086277
if self.__closed: raise MigrationSessionError("Can't change applied session") self._to_apply.extend(migrations)
def add_migrations(self, migrations)
Add migrations to be applied. Args: migrations: a list of migrations to add of the form [(app, migration_name), ...] Raises: MigrationSessionError if called on a closed MigrationSession
18.336876
12.626303
1.452276
unapplied = [] graph = loader.graph plan = [] seen = set() # Generate the plan, in the order that migrations have been/should be applied. for target in graph.leaf_nodes(): for migration in graph.forwards_plan(target): if migration not...
def _get_unapplied_migrations(self, loader)
Output a list of unapplied migrations in the form [['migration1', migration2'], ...]. This implementation is mostly copied from the Django 'showmigrations' mgmt command. https://github.com/django/django/blob/stable/1.8.x/django/core/management/commands/showmigrations.py This should only be call...
4.431827
4.081614
1.085803
# Only care about applied migrations for the passed-in apps. apps = set(apps) relevant_applied = [migration for migration in loader.applied_migrations if migration[0] in apps] # Sort them by the most recent migration and convert to a dictionary, # leaving apps as keys an...
def _get_current_migration_state(self, loader, apps)
Extract the most recent migrations from the relevant apps. If no migrations have been performed, return 'zero' as the most recent migration for the app. This should only be called from list_migrations().
6.643569
5.859776
1.133758
connection = connections[self._database_name] loader = MigrationLoader(connection, ignore_no_migrations=True) unapplied = self._get_unapplied_migrations(loader) currents = self._get_current_migration_state(loader, [u[0] for u in unapplied]) return unapplied, currents
def list_migrations(self)
Returns a tuple of unapplied, current "Unapplied" is a list of unapplied migrations. "Current" is a list of the current migration states for apps with unapplied migrations. Both are tuples of the form (app, migration_name).
4.177581
3.492299
1.196227
failed = None succeeded = [] # Mark migrations: # - before exception migration as success # - exception migration as failed for line in output.split('\n'): line = _remove_escape_characters(line).strip() line_match = self.migration_regex.m...
def _parse_migrate_output(self, output)
Args: output: str, output of "manage.py migrate" Returns (succeeded: list(tuple), failed: tuple or None) Both tuples are of the form (app, migration)
4.099428
3.656017
1.121283
out = StringIO() trace = None migrate_kwargs = { 'interactive': False, 'stdout': out, 'database': self._database_name, } if migration is not None: migrate_kwargs.update({ 'app_label': migration[0], ...
def __apply(self, migration=None, run_all=False)
If a migration is supplied, runs that migration and appends to state. If run_all==True, runs all migrations. Raises a ValueError if neither "migration" nor "run_all" are provided.
3.48039
3.374168
1.031481
if self.__closed: raise MigrationSessionError("Can't apply applied session") try: while self._to_apply: self.__apply(migration=self._to_apply.pop(0)) except: raise finally: self.__closed = True
def apply(self)
Applies all migrations that have been added. Note that some migrations depend on others, so you might end up running more than one.
6.957167
5.973377
1.164696
if self.__closed: raise MigrationSessionError("Can't apply applied session") if self._to_apply: raise MigrationSessionError("Can't apply_all with migrations added to session") try: self.__apply(run_all=True) except: raise ...
def apply_all(self)
Applies all Django model migrations at once, recording the result.
7.871004
7.377365
1.066913
return send_emails_from_template( to_emails=[to_email], from_email=from_email, subject=subject, markdown_template=markdown_template, text_template=text_template, html_template=html_template, fail_silently=fail_silently, context=context, **...
def send_email_from_template(to_email, from_email, subject, markdown_template=None, text_template=None, html_template=None, fail_silently=False, context=None, **kwargs)
Send an email from a template. :param to_email: the email address to send the email to :param from_email: the email address the email will be from :param subject: the subject of the email :param markdown_template: the markdown syntax template to use for the email. If provided, this will generat...
1.524397
1.920578
0.793718
if not to_emails: return if context is None: context = {} if markdown_template: try: from markdown import markdown except ImportError: raise ImportError( 'The application is attempting to send an email by using the ' ...
def send_emails_from_template(to_emails, from_email, subject, markdown_template=None, text_template=None, html_template=None, fail_silently=False, context=None, attachments=None, **kwargs)
Send many emails from single template. Each email address listed in the ``to_emails`` will receive an separate email. :param to_emails: list of email address to send the email to :param from_email: the email address the email will be from :param subject: the subject of the email :param markdown_te...
2.122011
2.118457
1.001678
all_possible_interpretations = alphabet.powerset().symbols all_models = set() for i in all_possible_interpretations: # compute current Interpretation, considering False # all propositional symbols not present in current interpretation current_interpr...
def all_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]
Find all the possible interpretations given a set of symbols
5.350857
5.49373
0.973993
models = self.all_models(alphabet) minimal_models = set() for m in models: min_m = m for m1 in models: if min_m.true_propositions.issuperset(m1.true_propositions): min_m = m1 minimal_models.add(min_m) retu...
def minimal_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]
Find models of min size (i.e. the less number of proposition to True). Very trivial (and inefficient) algorithm: BRUTE FORCE on all the possible interpretations.
2.71649
2.48635
1.092561
self.save_prep(instance_or_instances=self) return super(AbstractTokenModel, self).save(*args, **kwargs)
def save(self, *args, **kwargs)
Make sure token is added.
8.761414
6.837132
1.281446
instances = make_obj_list(instance_or_instances) tokens = set(cls.objects.get_available_tokens( count=len(instances), token_length=cls.token_length )) for instance in instances: if not instance.token: instance.token = tokens....
def save_prep(cls, instance_or_instances)
Preprocess the object before the object is saved. This automatically gets called when the save method gets called.
3.730198
4.150142
0.898812
res = () for child in self.formulas: if type(child) == type(self): superchilds = child.formulas res += superchilds else: res += (child, ) return tuple(res)
def _popup(self)
recursively find commutative binary operator among child formulas and pop up them at the same level
5.985292
3.772899
1.586391
if (self.content_object and hasattr(self.content_object, 'get_absolute_url')): return self.content_object.get_absolute_url() return None
def get_content_object_url(self)
Gets the absolute url for the content object.
2.45159
2.101173
1.166772
r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = LDLfLexer.reserved.get(t.value, 'ATOM') # Check for reserved words return t
def t_ATOM(self, t)
r'[a-zA-Z_][a-zA-Z_0-9]*
4.369894
4.116147
1.061647
if len(p) == 2: if p[1] == Symbols.LOGICAL_TRUE.value: p[0] = LDLfLogicalTrue() elif p[1] == Symbols.LOGICAL_FALSE.value: p[0] = LDLfLogicalFalse() elif p[1] == Symbols.END.value: p[0] = LDLfEnd() elif p[1] ...
def p_temp_formula(self, p)
temp_formula : temp_formula EQUIVALENCE temp_formula | temp_formula IMPLIES temp_formula | temp_formula OR temp_formula | temp_formula AND temp_formula | BOXLSEPARATOR path BOXRSEPARATOR temp_formula ...
1.951464
1.807423
1.079694
if len(p)==2: p[0] = RegExpPropositional(p[1]) elif len(p)==3: if p[2]==Symbols.PATH_TEST.value: p[0] = RegExpTest(p[1]) elif p[2] == Symbols.PATH_STAR.value: p[0] = RegExpStar(p[1]) else: raise Val...
def p_path(self, p)
path : path UNION path | path SEQ path | path STAR | temp_formula TEST | propositional
2.290711
2.052013
1.116324