code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Find all data present in the repository (filtered by the passed IDs) return Tree.construct( self, *self.find_data(subject_ids=subject_ids, visit_ids=visit_ids), **kwargs)
def tree(self, subject_ids=None, visit_ids=None, **kwargs)
Return the tree of subject and sessions information within a project in the XNAT repository Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) Li...
8.532847
10.054407
0.848667
if subject_ids is not None: subject_ids = frozenset(subject_ids) if visit_ids is not None: visit_ids = frozenset(visit_ids) try: tree = self._cache[subject_ids][visit_ids] except KeyError: if fill: fill_subjects = s...
def cached_tree(self, subject_ids=None, visit_ids=None, fill=False)
Access the repository tree and caches it for subsequent accesses Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which ...
2.483137
2.554837
0.971936
try: names = self._resource_names[repo_type] except KeyError: names = [self.name, self.name.upper()] return names
def resource_names(self, repo_type)
Names of resources used to store the format on a given repository type. Defaults to the name of the name of the format
4.428026
4.383281
1.010208
return dict((n, primary_path[:-len(self.ext)] + ext) for n, ext in self.aux_files.items())
def default_aux_file_paths(self, primary_path)
Get the default paths for auxiliary files relative to the path of the primary file, i.e. the same name as the primary path with a different extension Parameters ---------- primary_path : str Path to the primary file in the fileset Returns ------- ...
6.688644
8.173367
0.818346
by_ext = defaultdict(list) for path in candidates: by_ext[split_extension(path)[1].lower()].append(path) try: primary_file = by_ext[self.ext] except KeyError: raise ArcanaFileFormatError( "No files match primary file extension ...
def assort_files(self, candidates)
Assorts candidate files into primary and auxiliary (and ignored) files corresponding to the format by their file extensions. Can be overridden in specialised subclasses to assort files based on other characteristics Parameters ---------- candidates : list[str] ...
2.593044
2.546061
1.018453
if fileset._resource_name is not None: return (fileset._resource_name in self.resource_names( fileset.repository.type)) elif self.directory: if op.isdir(fileset.path): if self.within_dir_exts is None: return True ...
def matches(self, fileset)
Checks to see whether the format matches the given fileset Parameters ---------- fileset : Fileset The fileset to check
4.160441
4.370824
0.951866
self._converters[file_format.name] = (file_format, converter)
def set_converter(self, file_format, converter)
Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be converted into this format
5.406748
4.940125
1.094456
scheme, dest = url.split('://') host = None ssl_context = None if scheme == 'elk': host, port = dest.split(':') if ':' in dest else (dest, 2101) elif scheme == 'elks': host, port = dest.split(':') if ':' in dest else (dest, 2601) ssl_context = ssl.SSLContext(ssl.PROTOCOL...
def parse_url(url)
Parse a Elk connection string
2.473083
2.333265
1.059924
words = value.split('_') pretty = words[0].capitalize() for word in words[1:]: pretty += ' ' + word.lower() return pretty
def pretty_const(value)
Make a constant pretty for printing in GUI
3.275681
2.912162
1.124828
if user_number >= 0 and user_number < elk.users.max_elements: return elk.users[user_number].name if user_number == 201: return "*Program*" if user_number == 202: return "*Elk RP*" if user_number == 203: return "*Quick arm*" return ""
def username(elk, user_number)
Return name of user.
4.431131
4.254488
1.041519
self.connection_lost_callbk = connection_lost_callbk url = self._config['url'] LOG.info("Connecting to ElkM1 at %s", url) scheme, dest, param, ssl_context = parse_url(url) conn = partial(Connection, self.loop, self._connected, self._disconnected, s...
async def _connect(self, connection_lost_callbk=None)
Asyncio connection to Elk.
3.009965
2.824311
1.065734
LOG.info("Connected to ElkM1") self._conn = conn self._transport = transport self._connection_retry_timer = 1 if url_scheme_is_secure(self._config['url']): self._conn.write_data(self._config['userid'], raw=True) self._conn.write_data(self._config[...
def _connected(self, transport, conn)
Login and sync the ElkM1 panel to memory.
5.469151
4.61992
1.183819
if desc_type not in self._descriptions_in_progress: LOG.debug("Text description response ignored for " + str(desc_type)) return (max_units, results, callback) = self._descriptions_in_progress[desc_type] if unit < 0 or unit >= max_units: callback(resu...
def _sd_handler(self, desc_type, unit, desc, show_on_keypad)
Text description
4.24687
4.21734
1.007002
if self._conn: self._conn.write_data(msg.message, msg.response_command)
def send(self, msg)
Send a message to Elk panel.
11.513941
12.445427
0.925154
self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.get_descriptions(TextDescriptions.ZONE.value)
def sync(self)
Retrieve zones from ElkM1
9.243057
6.485477
1.425193
try: model = self.instance.__class__.history.model except AttributeError: model = self.instance.__class__ field = [field for field in model._meta.fields if field.name == "history_id"] if field and not isinstance(field[0], UUIDField): raise Off...
def has_offline_historical_manager_or_raise(self)
Raises an exception if model uses a history manager and historical model history_id is not a UUIDField. Note: expected to use edc_model.HistoricalRecords instead of simple_history.HistoricalRecords.
4.103594
3.00034
1.36771
return [field for field in self.instance._meta.fields if field.primary_key][0]
def primary_key_field(self)
Return the primary key field. Is `id` in most cases. Is `history_id` for Historical models.
5.033092
4.700595
1.070735
OutgoingTransaction = django_apps.get_model( "django_collect_offline", "OutgoingTransaction" ) created = True if created is None else created action = INSERT if created else UPDATE timestamp_datetime = ( self.instance.created if created else self....
def to_outgoing_transaction(self, using, created=None, deleted=None)
Serialize the model instance to an AES encrypted json object and saves the json object to the OutgoingTransaction model.
4.308959
4.1057
1.049507
json = serialize(objects=[self.instance]) encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE) return encrypted_json
def encrypted_json(self)
Returns an encrypted json serialized from self.
13.914869
12.53554
1.110034
if isinstance(self._packages_map, dict): local_name = self._packages_map.get(requirement, requirement.name) else: local_name = self._packages_map(requirement) return local_name
def map_req(self, requirement)
Maps the name of an Requirement class to the name of the corresponding module in the environment Parameters ---------- requirement : Requirement The requirement to map to the name of a module on the system
3.571938
3.861128
0.925102
if isinstance(self._versions_map, dict): version = self._versions_map.get(requirement, {}).get( local_version, local_version) else: version = self._versions_map(requirement, local_version) return version
def map_version(self, requirement, local_version)
Maps a local version name to one recognised by the Requirement class Parameters ---------- requirement : str Name of the requirement version : str version string
2.75197
3.173496
0.867173
'''Register the TagProcessors that are bundled with doxytag2zealdb.''' register = self.register_tag_processor register('class', classTagProcessor(**self.opts)) register('file', fileTagProcessor(**self.opts)) register('namespace', namespaceTagProcessor(**self.opts)) regis...
def init_tag_processors(self)
Register the TagProcessors that are bundled with doxytag2zealdb.
3.201242
2.136247
1.498536
'''Run all tag processors.''' for tag_proc in self.tag_procs: before_count = self.entry_count self.run_tag_processor(tag_proc) after_count = self.entry_count if self.verbose: print('Inserted %d entries for "%s" tag processor' % ( ...
def process(self)
Run all tag processors.
3.509312
3.160466
1.110378
'''Run a tag processor. Args: tag_proc_name: A string key that maps to the TagProcessor to run. ''' tag_processor = self.tag_procs[tag_proc_name] for tag in tag_processor.find(self.soup): self.process_tag(tag_proc_name, tag)
def run_tag_processor(self, tag_proc_name)
Run a tag processor. Args: tag_proc_name: A string key that maps to the TagProcessor to run.
3.994171
3.129301
1.276378
'''Process a tag with a tag processor and insert a DB entry. Args: tag_proc_name: A string key that maps to the TagProcessor to use. tag: A BeautifulSoup Tag to process. ''' tag_processor = self.tag_procs[tag_proc_name] db_entry = (tag_processor.get_name...
def process_tag(self, tag_proc_name, tag)
Process a tag with a tag processor and insert a DB entry. Args: tag_proc_name: A string key that maps to the TagProcessor to use. tag: A BeautifulSoup Tag to process.
4.624613
2.669685
1.732269
if isinstance(key, (basestring, int)): key = itemgetter(key) elif isinstance(key, (tuple, list)): key = itemgetter(*key) for label, grp in igroupby(iterable, key): yield label, list(grp)
def groupby(iterable, key=0, filter=None)
wrapper to itertools.groupby that returns a list of each group, rather than a generator and accepts integers or strings as the key and automatically converts them to callables with itemgetter(key) Arguments: iterable: iterable key: string, int or callable that tells how to group Return...
3.393892
3.161969
1.073348
args = [iter(iterable)] * n for x in izip_longest(*args): yield [v for v in x if v is not None]
def groups_of(n, iterable)
>>> groups_of(2, range(5))
3.569088
4.299435
0.83013
if not iterators: return array dialated = np.copy(array) if self.study.SUBJECT_ID in iterators: # If we join over subjects we should include all subjects for every # visit we want to process dialated[:, dialated.any(axis=0)] = True ...
def _dialate_array(self, array, iterators)
'Dialates' a to_process/to_protect array to include all subject and/or visits if the pipeline contains any joins over the corresponding iterators. Parameters ---------- array : np.array[M, N] The array to potentially dialate iterators : set[str] T...
4.399922
3.409943
1.290321
args = super(ArcanaSlurmGraphPlugin, self)._get_args( node, keywords) # Substitute the template arg with the node-specific one new_args = [] for name, arg in zip(keywords, args): if name == 'template': new_args.append(self._processor.slurm...
def _get_args(self, node, keywords)
Intercept calls to get template and return our own node-specific template
4.835248
4.349154
1.111767
days = int(wall_time // 1440) hours = int((wall_time - days * 1440) // 60) minutes = int(math.floor(wall_time - days * 1440 - hours * 60)) seconds = int((wall_time - math.floor(wall_time)) * 60) return "{}-{:0>2}:{:0>2}:{:0>2}".format(days, hours, minutes, seconds)
def wall_time_str(self, wall_time)
Returns the wall time in the format required for the sbatch script
2.04093
1.929497
1.057752
self._elk.add_handler('VN', self._vn_handler) self._elk.add_handler('XK', self._xk_handler) self._elk.add_handler('RP', self._rp_handler) self._elk.add_handler('IE', self._elk.call_sync_handlers) self._elk.add_handler('SS', self._ss_handler) self._elk.send(vn_enc...
def sync(self)
Retrieve panel information from ElkM1
4.071554
3.59352
1.133027
self._elk.send(ts_encode(self.index, value, element_to_set))
def set(self, element_to_set, value)
(Helper) Set thermostat
17.986115
18.145805
0.9912
duplicate = copy(self) duplicate._name = name return duplicate
def renamed(self, name)
Duplicate the datum and rename it
9.453678
6.622126
1.42759
if self._req != other._req: raise ArcanaUsageError( "Can't compare versions of different requirements {} and {}" .format(self._req, other._req)) # Compare main sequence if self._seq < other._seq: return -1 elif self._seq > ...
def compare(self, other)
Compares the version with another Parameters ---------- other : Version The version to compare to
2.687024
2.642865
1.016709
# Check to see if version is not a string but rather another type # that can be interpreted as a version if isinstance(version, int): return (version,), None, None, None elif isinstance(version, (tuple, list)): return tuple(int(i) for i in version), None,...
def parse(self, version)
Splits a typical version string (e.g. <MAJOR>.<MINOR>.<MICRO>) into a tuple that can be sorted properly. Ignores all leading and trailing characters by using a regex search (instead of match) so as to pick the version string out of a block of text. Parameters ---------- ...
2.577642
2.299876
1.120774
if not isinstance(version, Version): version = type(self._min_ver)(self._req, version) return version >= self
def within(self, version)
A single version can also be interpreted as an open range (i.e. no maximum version)
8.937673
8.107121
1.102447
if not isinstance(version, Version): version = self.version_cls(self, version, **kwargs) # Return a version range instead of version if max_version is not None: if not isinstance(max_version, Version): max_version = self.version_cls(self, max_vers...
def v(self, version, max_version=None, **kwargs)
Returns either a single requirement version or a requirement version range depending on whether two arguments are supplied or one Parameters ---------- version : str | Version Either a version of the requirement, or the first version in a range of acceptable vers...
2.574313
2.779268
0.926256
'''Open a connection to the database. If a connection appears to be open already, transactions are committed and it is closed before proceeding. After establishing the connection, the searchIndex table is prepared (and dropped if it already exists). ''' if self.conn is n...
def open(self)
Open a connection to the database. If a connection appears to be open already, transactions are committed and it is closed before proceeding. After establishing the connection, the searchIndex table is prepared (and dropped if it already exists).
3.868528
2.272686
1.702183
'''Insert an entry into the Zeal database. Args: name: A string representing the name of the entry. entry_type: A string representing the entry type. filename: A string representing the filename of the documentation for the entry. Raises: ...
def insert(self, name, entry_type, filename)
Insert an entry into the Zeal database. Args: name: A string representing the name of the entry. entry_type: A string representing the entry type. filename: A string representing the filename of the documentation for the entry. Raises: Ru...
3.7681
2.455619
1.534481
return serializers.serialize( "json", objects, ensure_ascii=True, use_natural_foreign_keys=True, use_natural_primary_keys=False, )
def serialize(objects=None)
A simple wrapper of Django's serializer with defaults for JSON and natural keys. Note: use_natural_primary_keys is False as once a pk is set, it should not be changed throughout the distributed data.
2.830395
2.819215
1.003966
values = [values] spec = self.parameter_spec(name) if not isinstance(spec, SwitchSpec): raise ArcanaUsageError( "{} is standard parameter not a switch".format(spec)) switch = self._get_parameter(name) if spec.is_boolean: if values is no...
def branch(self, name, values=None): # @UnusedVariable @IgnorePep8 if isinstance(values, basestring)
Checks whether the given switch matches the value provided Parameters ---------- name : str The name of the parameter to retrieve value : str | None The value(s) of the switch to match if a non-boolean switch
3.719514
3.65438
1.017823
raise ArcanaDesignError( "'{}' value of '{}' switch in {} is not handled" .format(self._get_parameter(name), name, self._param_error_location))
def unhandled_branch(self, name)
Convenient method for raising exception if a pipeline doesn't handle a particular switch value Parameters ---------- name : str Name of the switch value : str Value of the switch which hasn't been handled
17.414906
15.373615
1.132779
pipeline = self.spec(spec_name).pipeline if full: workflow = pe.Workflow(name='{}_gen'.format(spec_name), base_dir=self.processor.work_dir) self.processor._connect_pipeline( pipeline, workflow, **kwargs) else: ...
def save_workflow_graph_for(self, spec_name, fname, full=False, style='flat', **kwargs)
Saves a graph of the workflow to generate the requested spec_name Parameters ---------- spec_name : str Name of the spec to generate the graph for fname : str The filename for the saved graph style : str The style of the graph, can be one of c...
3.576704
4.040015
0.885319
# If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, (BaseData, Parameter)): name = name.name # If name is a parameter than return the parameter spec if name in self._param_specs: retur...
def spec(self, name)
Returns either the input corresponding to a fileset or field field spec or a spec or parameter that has either been passed to the study as an input or can be derived. Parameters ---------- name : Str | BaseData | Parameter A parameter, fileset or field or name of one
5.683266
5.144352
1.104758
# If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, BaseData): name = name.name # Get the spec from the class spec = self.data_spec(name) try: bound = self._inputs[name] ...
def bound_spec(self, name)
Returns an input selector or derived spec bound to the study, i.e. where the repository tree is checked for existing outputs Parameters ---------- name : Str A name of a fileset or field
5.351116
5.247219
1.0198
# If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, BaseData): name = name.name try: return cls._data_specs[name] except KeyError: raise ArcanaNameError( na...
def data_spec(cls, name)
Return the fileset_spec, i.e. the template of the fileset expected to be supplied or generated corresponding to the fileset_spec name. Parameters ---------- name : Str Name of the fileset_spec to return
5.161663
5.353922
0.96409
workflow = pe.Workflow(name='cache_download', base_dir=self.processor.work_dir) subjects = pe.Node(IdentityInterface(['subject_id']), name='subjects', environment=self.environment) sessions = pe.Node(IdentityInterface(['subject_i...
def cache_inputs(self)
Runs the Study's repository source node for each of the inputs of the study, thereby caching any data required from remote repositorys. Useful when launching many parallel jobs that will all try to concurrently access the remote repository, and probably lead to timeout errors.
3.209349
2.990633
1.073134
try: spec = self.bound_spec(spec_name) except ArcanaMissingDataException: return False if isinstance(spec, BaseInputSpec): return spec.default is not None and default_okay else: return True
def provided(self, spec_name, default_okay=True)
Checks to see whether the corresponding data spec was provided an explicit input, as opposed to derivatives or missing optional inputs Parameters ---------- spec_name : str Name of a data spec
5.602368
6.373295
0.879038
return { set(it): f for f, it in cls.FREQUENCIES.items()}[set(iterators)]
def freq_from_iterators(cls, iterators)
Returns the frequency corresponding to the given iterators
8.674284
7.663854
1.131844
# Get list of repositories where inputs to the study are stored input_repos = list(set((i.repository for i in self.inputs))) inputs = {} for input in self.inputs: # @ReservedAssignment inputs[input.name] = { 'repository_index': input_repos.index(inpu...
def prov(self)
Extracts provenance information from the study for storage alongside generated derivatives. Typically for reference purposes only as only the pipeline workflow, inputs and outputs are checked by default when determining which sessions require reprocessing. Returns ------- ...
2.820452
2.794556
1.009267
self._elk.send(al_encode(level, self._index, code))
def arm(self, level, code)
(Helper) Arm system at specified level (away, vacation, etc)
28.642988
30.405571
0.942031
self._elk.send( dm_encode(self._index, clear, beep, timeout, line1, line2) )
def display_message(self, clear, beep, timeout, line1, line2)
Display a message on all of the keypads in this area.
9.888555
9.60963
1.029026
self.elk.send(as_encode()) self.get_descriptions(TextDescriptions.AREA.value)
def sync(self)
Retrieve areas from ElkM1
81.582962
32.614368
2.501442
if level <= 0: self._elk.send(pf_encode(self._index)) elif level >= 98: self._elk.send(pn_encode(self._index)) else: self._elk.send(pc_encode(self._index, 9, level, time))
def level(self, level, time=0)
(Helper) Set light to specified level
5.261388
5.115681
1.028483
for i in range(4): self.elk.send(ps_encode(i)) self.get_descriptions(TextDescriptions.LIGHT.value)
def sync(self)
Retrieve lights from ElkM1
31.769617
18.451349
1.721805
return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))
def dir_modtime(dpath)
Returns the latest modification time of all files/subdirectories in a directory
3.417902
4.336572
0.788158
for double_ext in double_exts: if path.endswith(double_ext): return path[:-len(double_ext)], double_ext dirname = os.path.dirname(path) filename = os.path.basename(path) parts = filename.split('.') if len(parts) == 1: base = filename ext = None else: ...
def split_extension(path)
A extension splitter that checks for compound extensions such as 'file.nii.gz' Parameters ---------- filename : str A filename to split into base and extension Returns ------- base : str The base part of the string, i.e. 'file' of 'file.nii.gz' ext : str The ext...
2.080563
2.280191
0.912451
if isinstance(value, basestring): try: if value.startswith('"') and value.endswith('"'): value = str(value[1:-1]) elif '.' in value: value = float(value) else: value = int(value) except ValueError: v...
def parse_single_value(value)
Tries to convert to int, float and then gives up and assumes the value is of type string. Useful when excepting values that may be string representations of numerical values
2.411113
2.460703
0.979847
return all(isinstance(i, Iterable) and not isinstance(i, basestring) for i in items)
def iscontainer(*items)
Checks whether all the provided items are containers (i.e of class list, dict, tuple, etc...)
3.705097
3.321052
1.11564
# Basic case where we are dealing with non-containers if not (isinstance(first, type(second)) or isinstance(second, type(first))): mismatch = (' types: self={} v other={}' .format(type(first).__name__, type(second).__name__)) elif not iscontainer(first, second):...
def find_mismatch(first, second, indent='')
Finds where two objects differ, iterating down into nested containers (i.e. dicts, lists and tuples) They can be nested containers any combination of primary dtypes, str, int, float, dict and lists Parameters ---------- first : dict | list | tuple | str | int | float The first object to com...
2.704446
2.616615
1.033567
return serializers.deserialize( "json", json_text, ensure_ascii=True, use_natural_foreign_keys=True, use_natural_primary_keys=False, )
def deserialize(json_text=None)
Returns a generator of deserialized objects. Wraps django deserialize with defaults for JSON and natural keys. See https://docs.djangoproject.com/en/2.1/topics/serialization/
3.221342
2.943121
1.094533
if not raw: if created: sender.objects.create(user=instance)
def create_auth_token(sender, instance, raw, created, **kwargs)
Create token when a user is created (from rest_framework).
4.789032
4.674203
1.024567
if action == "post_add": try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=True)
def serialize_m2m_on_save(sender, action, instance, using, **kwargs)
Part of the serialize transaction process that ensures m2m are serialized correctly. Skip those not registered.
7.897846
8.039942
0.982326
if not raw: if "historical" not in instance._meta.label_lower: try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(us...
def serialize_on_save(sender, instance, raw, created, using, **kwargs)
Serialize the model instance as an OutgoingTransaction. Skip those not registered.
8.157469
6.686455
1.219999
try: wrapped_instance = site_offline_models.get_wrapped_instance(history_instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=True)
def serialize_history_on_post_create(history_instance, using, **kwargs)
Serialize the history instance as an OutgoingTransaction. Skip those not registered.
8.985648
6.844609
1.312807
try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
def serialize_on_post_delete(sender, instance, using, **kwargs)
Creates a serialized OutgoingTransaction when a model instance is deleted. Skip those not registered.
9.763762
7.342387
1.32978
self._elk.send(cw_encode(self._index, value, self.value_format))
def set(self, value)
(Helper) Set custom value.
27.079645
26.675104
1.015165
self.elk.send(cp_encode()) self.get_descriptions(TextDescriptions.SETTING.value)
def sync(self)
Retrieve custom values from ElkM1
90.202965
43.995094
2.050296
if self.format is None: raise ArcanaFileFormatError( "Cannot get paths of fileset ({}) that hasn't had its format " "set".format(self)) if self.format.directory: return chain(*((op.join(root, f) for f in files) f...
def paths(self)
Iterates through all files in the set
5.806818
5.205598
1.115495
if self._format is not None: raise ArcanaFileFormatError( "Format has already been set for {}".format(self)) matches = [c for c in candidates if c.matches(self)] if not matches: raise ArcanaFileFormatError( "None of the candidate f...
def detect_format(self, candidates)
Detects the format of the fileset from a list of possible candidates. If multiple candidates match the potential files, e.g. NiFTI-X (see dcm2niix) and NiFTI, then the first matching candidate is selected. If a 'format_name' was specified when the fileset was created then that i...
3.043958
3.276047
0.929156
if hasattr(self.format, 'contents_equal'): equal = self.format.contents_equal(self, other, **kwargs) else: equal = (self.checksums == other.checksums) return equal
def contents_equal(self, other, **kwargs)
Test the equality of the fileset contents with another fileset. If the fileset's format implements a 'contents_equal' method than that is used to determine the equality, otherwise a straight comparison of the checksums is used. Parameters ---------- other : Fileset ...
3.543458
2.399328
1.476855
raise ArcanaError( "Attempted to bind '{}' to {} but only acquired specs with " "a default value should be bound to studies{})".format( self.name, study)) if self._study is not None: # This avoids rebinding specs to sub-studies that hav...
def bind(self, study, **kwargs): # @UnusedVariable if self.default is None
Returns a copy of the AcquiredSpec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__)
8.983862
7.036729
1.27671
# Avoid rebinding specs in sub-studies that have already # been bound to MultiStudy bound = self else: bound = copy(self) bound._study = study if not hasattr(study, self.pipeline_getter): raise ArcanaError( ...
def bind(self, study, **kwargs): # @UnusedVariable if self._study is not None
Returns a copy of the Spec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__)
8.672279
10.661035
0.813456
# Run the match against the tree if self.frequency == 'per_session': nodes = [] for subject in tree.subjects: for sess in subject.sessions: nodes.append(sess) elif self.frequency == 'per_subject': nodes = tree.subje...
def nodes(self, tree)
Returns the relevant nodes for the spec's frequency
3.198456
2.883341
1.109288
try: # Just need to iterate all study inputs and catch relevant # exceptions list(self.pipeline.study_inputs) except (ArcanaOutputNotProducedException, ArcanaMissingDataException): return False return True
def derivable(self)
Whether the spec (only valid for derived specs) can be derived given the inputs and switches provided to the study
21.34074
18.458937
1.15612
for role in self.Instances.keys(): for connection in self.Instances[role]: connection.reconnect()
def reconnect_all(self)
Re-establish connection to all instances
8.479334
6.769993
1.252488
if not role in self.Instances.keys(): self.Instances[role] = [] self.logger.debug('Adding ' + role + ' with private_hostname ' + instance['private_hostname'] + ', public_hostname ' + instance['public_hostname']) self.Instan...
def add_instance(self, role, instance, username='root', key_filename=None, output_shell=False)
Add instance to the setup @param role: instance's role @type role: str @param instance: host parameters we would like to establish connection to @type instance: dict @param username: user name for creating ssh connection @type username: str ...
3.237019
3.615617
0.895288
self.logger.debug('Loading config from ' + yamlfile) with open(yamlfile, 'r') as yamlfd: yamlconfig = yaml.load(yamlfd) for instance in yamlconfig['Instances']: self.add_instance(instance['role'].upper(), instance, ...
def setup_from_yamlfile(self, yamlfile, output_shell=False)
Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shell: bool
2.993542
2.963759
1.010049
try: for l in proc.stdout: yield l finally: if proc.poll() is None: # there was an exception return else: proc.wait() if proc.returncode not in (0, None, signal.SIGPIPE, signal.SIGPIPE + 128): sys.stderr.wri...
def process_iter(proc, cmd="")
helper function to iterate over a process stdout and report error messages when done
3.451103
3.484321
0.990466
fh = iter(nopen(fname)) h = tokens(next(fh), sep) h[0] = h[0].lstrip("#") return h
def header(fname, sep="\t")
just grab the header from a given file
7.093153
6.747304
1.051257
r if isinstance(fname, int_types): fname = sys.argv[fname] if not isinstance(fname, basestring) and \ isinstance(fname, types.GeneratorType): line_gen = fname elif sep is None: def _line_gen(f, sep): if sep is None: for line in nopen(f): ...
def reader(fname, header=True, sep="\t", skip_while=None, quotechar='"')
r""" for each row in the file `fname` generate dicts If `header` is True or lists if `header` is False. The dict keys are drawn from the first line. If `header` is a list of names, those will be used as the dict keys. If `header` is 'ordered', the function will yield ordered dicts. If `header` i...
3.011336
2.971966
1.013247
if isinstance(bfiles, basestring): bfiles = [bfiles] if not op.exists(a): return False if not all(op.exists(b) for b in bfiles): return False atime = os.stat(a).st_mtime # modification time for b in bfiles: # a has been modified since if atime > os.stat(b).st_mtime: ...
def is_newer_b(a, bfiles)
check that all b files have been modified more recently than a
2.909081
2.753865
1.056363
''' Expect a list of expressions @param connection: Connection to the host @type connection: L{Connection} @param regexp_list: regular expressions and associated return values @type regexp_list: list of (regexp, return value) @param timeout: timeout for perform...
def expect_list(connection, regexp_list, timeout=10)
Expect a list of expressions @param connection: Connection to the host @type connection: L{Connection} @param regexp_list: regular expressions and associated return values @type regexp_list: list of (regexp, return value) @param timeout: timeout for performing expect operation...
4.25583
2.815885
1.511365
''' Expect one expression @param connection: Connection to the host @type connection: L{Connection} @param strexp: string to convert to expression (.*string.*) @type strexp: str @param timeout: timeout for performing expect operation @type timeout: int ...
def expect(connection, strexp, timeout=10)
Expect one expression @param connection: Connection to the host @type connection: L{Connection} @param strexp: string to convert to expression (.*string.*) @type strexp: str @param timeout: timeout for performing expect operation @type timeout: int @return: Tr...
5.216512
2.434558
2.142693
''' Match against an expression @param connection: Connection to the host @type connection: L{Connection} @param regexp: compiled regular expression @type regexp: L{SRE_Pattern} @param grouplist: list of groups to return @type group: list of int ...
def match(connection, regexp, grouplist=[1], timeout=10)
Match against an expression @param connection: Connection to the host @type connection: L{Connection} @param regexp: compiled regular expression @type regexp: L{SRE_Pattern} @param grouplist: list of groups to return @type group: list of int @param timeout: ti...
3.193741
2.406255
1.327266
''' Enter a command and wait for something to happen (enter + expect combined) @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param strexp: string to convert to expression...
def ping_pong(connection, command, strexp, timeout=10)
Enter a command and wait for something to happen (enter + expect combined) @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param strexp: string to convert to expression (.*string.*) ...
5.669159
1.820171
3.11463
''' Run command and expect specified return valud @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param expected_status: expected return value @type expected_status: int ...
def expect_retval(connection, command, expected_status=0, timeout=10)
Run command and expect specified return valud @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param expected_status: expected return value @type expected_status: int @param timeou...
3.412242
2.536541
1.345234
self.elk.send(ka_encode()) self.get_descriptions(TextDescriptions.KEYPAD.value)
def sync(self)
Retrieve areas from ElkM1
80.508514
44.546349
1.807298
'''Yield tags matching the tag criterion from a soup. There is no need to override this if you are satisfied with finding tags that match match_criterion. Args: soup: A BeautifulSoup to search through. Yields: BeautifulSoup Tags that match the criterion...
def find(self, soup)
Yield tags matching the tag criterion from a soup. There is no need to override this if you are satisfied with finding tags that match match_criterion. Args: soup: A BeautifulSoup to search through. Yields: BeautifulSoup Tags that match the criterion.
7.309929
1.89825
3.850879
'''Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its parent scope included in...
def get_name(self, tag)
Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its parent scope included in the name b...
8.076869
1.842473
4.383711
'''Extract and return a documentation filename from a tag. Override as necessary, though this default implementation probably covers all the cases of interest. Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would b...
def get_filename(self, tag)
Extract and return a documentation filename from a tag. Override as necessary, though this default implementation probably covers all the cases of interest. Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropria...
8.066728
2.069457
3.897993
'''Override. Determine if a tag has the desired name and kind attribute value. Args: tag: A BeautifulSoup Tag. Returns: True if tag has the desired name and kind, otherwise False. ''' return tag.name == self.reference_tag_name and \ t...
def match_criterion(self, tag)
Override. Determine if a tag has the desired name and kind attribute value. Args: tag: A BeautifulSoup Tag. Returns: True if tag has the desired name and kind, otherwise False.
6.210873
2.345204
2.648329
'''Override. Extract a representative "name" from a function tag. get_name's output can be controlled through keyword arguments that are provided when initializing a functionTagProcessor. For instance, function arguments and return types can be included by passing include_functi...
def get_name(self, tag)
Override. Extract a representative "name" from a function tag. get_name's output can be controlled through keyword arguments that are provided when initializing a functionTagProcessor. For instance, function arguments and return types can be included by passing include_function_signatur...
5.831323
1.75824
3.316568
'''Override that returns u'Method' for class/struct methods. Override as necessary. Args: tag: A BeautifulSoup Tag for a function. Returns: If this is a class/struct method, returns u'Method', otherwise returns the value from the inherited implement...
def get_entry_type(self, tag)
Override that returns u'Method' for class/struct methods. Override as necessary. Args: tag: A BeautifulSoup Tag for a function. Returns: If this is a class/struct method, returns u'Method', otherwise returns the value from the inherited implementation of ...
7.487783
2.035196
3.679147
if dummy: from multiprocessing.dummy import Pool else: from multiprocessing import Pool if n is None: import multiprocessing n = multiprocessing.cpu_count() - 1 return Pool(n)
def pool(n=None, dummy=False)
create a multiprocessing pool that responds to interrupts.
3.03014
2.528322
1.198479
# make it easier to debug. if n == 1: for r in it.starmap(f, iterable): yield r raise StopIteration if p is None: po = pool(n, dummy) else: po = p assert hasattr(po, 'imap') f = _func_star(f) try: for r in po.imap(f, iterable): ...
def pmap(f, iterable, n=None, dummy=False, p=None)
parallel map of a function to an iterable if each item in iterable is itself an iterable, then automatically call f(*item) instead of f(item) Arguments: f: function iterable: any iterable where each item is sent to f n: number of cpus (default is number on machine) dummy: use dummy ...
4.592371
4.871751
0.942653
for callback in self._callbacks: callback(self, self._changeset) self._changeset = {}
def _call_callbacks(self)
Callbacks when attribute of element changes
5.465664
4.205262
1.29972
existing_value = getattr(self, attr, None) if existing_value != new_value: setattr(self, attr, new_value) self._changeset[attr] = new_value if close_the_changeset and self._changeset: self._call_callbacks()
def setattr(self, attr, new_value, close_the_changeset=True)
If attribute value has changed then set it and call the callbacks
2.324458
2.238912
1.038209
return self.__class__.__name__ + '{}{:03d}'.format( separator, self._index+1)
def default_name(self, separator='-')
Return a default name for based on class and index of element
7.0277
4.786472
1.468242
attrs = vars(self) return {key: attrs[key] for key in attrs if not key.startswith('_')}
def as_dict(self)
Package up the public attributes as a dict.
4.23629
2.721644
1.556519