code
stringlengths
1
18.2k
def bam_has_index(bam_file): """Check if bam file has an index. Returns True/False.""" has_index = None with pysam.AlignmentFile(bam_file, 'rb') as bam_fileobj: try: bam_fileobj.fetch(bam_fileobj.references[0]) except ValueError as err: if err.message == 'fetch called on bamfile without index': bam_fileobj.close() has_...
def is_fasta_valid(fasta_file): """Check if fasta file is valid. Raises a ValueError if pysam cannot read the file. #TODO: pysam does not differentiate between BAM and SAM """ try: f = pysam.FastaFile(fasta_file) except IOError: raise else: f.close() return True
def get_first_transcript_name(fasta_file): """Return the first FASTA sequence from the given FASTA file. Keyword arguments: fasta_file -- FASTA format file of the transcriptome """ with open_pysam_file(fname=fasta_file, ftype='fasta') as f: transcript_name = f.references[0] return transcript_name
def get_fasta_record(fasta_file, transcript_name): """Return a single transcript from a valid fasta file as a record. record[transcript_name] = sequence Keyword arguments: fasta_file -- FASTA format file of the transcriptome transcript_name -- Name of the transcript as in the FASTA header """ with open_pysam_file(fname...
def get_fasta_records(fasta, transcripts): """Return list of transcript records from the given fasta file. Each record will be of the form {'sequence_id': {'sequence': 'AAA', 'length': 3}} trascripts should be provided as a list of sequence id's. """ records = {} f = pysam.FastaFile(fasta) for transcript in transcripts...
def get_three_frame_orfs(sequence, starts=None, stops=None): """Find ORF's in frames 1, 2 and 3 for the given sequence. Positions returned are 1-based (not 0) Return format [{'start': start_position, 'stop': stop_position, 'sequence': sequence}, ] Keyword arguments: sequence -- sequence for the transcript starts -- Lis...
continue. This is an internal MET if start_codon is not None: orf += codon continue # New orf start start_codon = position orf = codon else: # if sequence starts with ATG, start_codon will be 0 if start_codon is None: # We haven't found a start codon yet continue orf += codon if codon in stops: # orfs[start_codon + 1] ...
def get_longest_orf(orfs): """Find longest ORF from the given list of ORFs.""" sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0] return sorted_orf
def filter_ribo_counts(counts, orf_start=None, orf_stop=None): """Filter read counts and return only upstream of orf_start or downstream of orf_stop. Keyword arguments: counts -- Ribo-Seq read counts obtained from get_ribo_counts. orf_start -- Start position of the longest ORF. orf_stop -- Stop position of the longest ...
if position <= orf_stop: filtered_counts.pop(position) # calculate total reads for this transcript total_reads = sum(sum(item.values()) for item in filtered_counts.values()) return filtered_counts, total_reads
def get_ribo_counts(ribo_fileobj, transcript_name, read_lengths, read_offsets): """For each mapped read of the given transcript in the BAM file (pysam AlignmentFile object), return the position (+1) and the corresponding frame (1, 2 or 3) to which it aligns. Keyword arguments: ribo_fileobj -- file object - BAM file ope...
continue total_reads += 1 try: read_counts[position] except KeyError: read_counts[position] = {1: 0, 2: 0, 3: 0} # calculate the frame of the read from position rem = position % 3 if rem == 0: read_counts[position][3] += 1 else: read_counts[position][rem] += 1 log.debug('Total read counts: {}'.format(total_reads)) log....
def check_required_arguments(ribo_file, transcriptome_fasta, transcript_name=None): """Check required arguments of both riboplot and ribocount.""" # Is this a valid BAM file? i.e., can pysam read it? try: is_bam_valid(ribo_file) except ValueError: log.error('The given RiboSeq BAM file is not valid') raise # Does the BA...
of "{}" from transcriptome FASTA file'.format(transcript_name)) raise else: # ribocount doesn't have a transcript option so we get the first # sequence name from the fasta file transcript_name = get_first_transcript_name(transcriptome_fasta) # check if transcript also exists in BAM with pysam.AlignmentFile(ribo_file, '...
def check_rna_file(rna_file): """Check if bedtools is available and if the given RNA-Seq bam file is valid. """ try: subprocess.check_output(['bedtools', '--version']) except OSError: log.error('Could not find bedtools in PATH. bedtools is required ' 'for generating RNA coverage plot.') raise # Is this a valid BAM file...
def check_read_lengths(ribo_file, read_lengths): """Check if read lengths are valid (positive). """ # check if there are any valid read lengths to check i.e., not equal to 0 valid_lengths = list(set(read_lengths)) # if read length is 0, all read lengths are requested so we skip further # checks. if len(valid_lengths) =...
def check_read_offsets(read_offsets): """Check if read offsets are valid (positive).""" for read_offset in read_offsets: if read_offset < 0: msg = 'Read offset must be 0 or greater' log.error(msg) raise ArgumentError(msg)
def is_header(line): """true if we are in a header""" if re.match('^@',line): f = line.rstrip().split("\t") if(len(f) > 9): return False return True return False
def sort_header(header_text): """sort the chromosomes in a header text""" lines = header_text.rstrip().split("\n") rlens = {} for ln in lines: m = re.match('@SQ\tSN:(\S+)\tLN:(\S+)',ln) if m: rlens[m.group(1)] = m.group(2) output = '' done_lens = False for ln in lines: if re.match('@SQ\tSN:',ln): if not done_lens: done...
def alignment_ranges(self): """Put the heavy alignment ranges calculation called on demand and then cached""" if not self.is_aligned(): raise ValueError("you can't get alignment ranges from something that didn't align") if self._alignment_ranges: return self._alignment_ranges self._alignment_ranges = self._get_alignmen...
def target_sequence_length(self): """ Get the length of the target sequence. length of the entire chromosome throws an error if there is no information available :return: length :rtype: int """ if not self.is_aligned(): raise ValueError("no length for reference when read is not not aligned") if self.entries.tlen: retur...
def query_sequence(self): """ Overrides align. corrects orientation with reverse complement if on negative strand .. warning:: this returns the full query sequence, not just the aligned portion, but i also does not include hard clipped portions (only soft clipped) """ if not self.entries.seq: return None if self.check_...
def query_quality(self): """ Overrides align .. warning:: this returns the full query quality, not just the aligned portion """ if not self.entries.qual: return None if self.entries.qual == '*': return None if self.check_flag(0x10): return self.entries.qual[::-1] return self.entries.qual
def query_sequence_length(self): """ does not include hard clipped""" if self.entries.seq: return len(self.entries.seq) if not self.entries.cigar: raise ValueError('Cannot give a query length if no cigar and no query sequence are present') return sum([x[0] for x in self.cigar_array if re.match('[MIS=X]',x[1])])
def original_query_sequence_length(self): """Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int """ if not self.is_aligned() or not self.entries.cigar: return self.qu...
def actual_original_query_range(self): """ This accounts for hard clipped bases and a query sequence that hasnt been reverse complemented :return: the range covered on the original query sequence :rtype: GenomicRange """ l = self.original_query_sequence_length a = self.alignment_ranges qname = a[0][1].chr qstart = a[0]...
def _get_alignment_ranges(self): """A key method to extract the alignment data from the line""" if not self.is_aligned(): return None alignment_ranges = [] cig = [x[:] for x in self.cigar_array] target_pos = self.entries.pos query_pos = 1 while len(cig) > 0: c = cig.pop(0) if re.match('[S]$',c[1]): # hard or soft clipp...
def target_range(self): """Get the range on the target strand :return: target range :rtype: GenomicRange """ if not self.is_aligned(): return None if self._target_range: return self._target_range # check cache global _sam_cigar_target_add tlen = sum([x[0] for x in self.cigar_array if _sam_cigar_target_add.match(x[1])])...
def cigar_array(self): """cache this one to speed things up a bit""" if self._cigar: return self._cigar self._cigar = [CIGARDatum(int(m[0]),m[1]) for m in re.findall('([0-9]+)([MIDNSHP=X]+)',self.entries.cigar)] return self._cigar
def tags(self): """Access the auxillary data here""" if self._tags: return self._tags tags = {} if not tags: return {} for m in [[y.group(1),y.group(2),y.group(3)] for y in [re.match('([^:]{2,2}):([^:]):(.+)$',x) for x in self.entries.optional_fields.split("\t")]]: if m[1] == 'i': m[2] = int(m[2]) elif m[1] == 'f': m[2...
def eq_central_moments(n_counter, k_counter, dmu_over_dt, species, propensities, stoichiometry_matrix, max_order): r""" Function used to calculate the terms required for use in equations giving the time dependence of central moments. The function returns the list Containing the sum of the following terms in in equation...
one column per each :math:`[n_1, ... n_d]` combination """ central_moments = [] # Loops through required combinations of moments (n1,...,nd) # (does not include 0th order central moment as this is 1, # or 1st order central moment as this is 0 # copy dmu_mat matrix as a list of rows vectors (1/species) dmu_mat = [sp.Mat...
make_k_chose_e(k_vec, n_vec) # (-1)^(n-k) term in equation 9 minus_one_pow_n_minus_k = product([sp.Integer(-1) ** (n - m) for (n,m) in zip(n_vec, k_vec)]) # Calculate alpha, dalpha_over_dt terms in equation 9 alpha = product([s ** (n - k) for s, n, k in zip(species, n_vec, k_vec)]) # eq 10 {(n - k) mu_i^(-1)} correspon...
in k_counter if k_iter >= k and k.order > 0] dbeta_over_dt = d_beta_over_dt_calculator.get(k_iter.n_vector, e_counter) # Calculate beta, dbeta_over_dt terms in equation 9 if len(e_counter) == 0: beta = 1 else: beta = k_iter.symbol taylor_exp_mat.append(n_choose_k * minus_one_pow_n_minus_k * (alpha * dbeta_over_dt + bet...
def authenticate(self): """Set BitMEX authentication information.""" if self.apiKey: return loginResponse = self._curl_bitmex( api="user/login", postdict={'email': self.login, 'password': self.password, 'token': self.otpToken}) self.token = loginResponse['id'] self.session.headers.update({'access-token': self.token})
def authentication_required(function): """Annotation for methods that require auth.""" def wrapped(self, *args, **kwargs): if not (self.token or self.apiKey): msg = "You must be authenticated to use this method" raise AuthenticationError(msg) else: return function(self, *args, **kwargs) return wrapped
def place_order(self, quantity, symbol, price): """Place an order.""" if price < 0: raise Exception("Price must be positive.") endpoint = "order" # Generate a unique clOrdID with our prefix so we can identify it. clOrdID = self.orderIDPrefix + base64.b64encode(uuid.uuid4().bytes).decode('ascii').rstrip('=\n') postdict ...
def open_orders(self, symbol=None): """Get open orders via HTTP. Used on close to ensure we catch them all.""" api = "order" query = {'ordStatus.isTerminated': False } if symbol != None: query['symbol'] =symbol orders = self._curl_bitmex( api=api, query={'filter': json.dumps(query)}, verb="GET" ) return orders
def cancel(self, orderID): """Cancel an existing order.""" api = "order" postdict = { 'orderID': orderID, } return self._curl_bitmex(api=api, postdict=postdict, verb="DELETE")
def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None): """Send a request to BitMEX Servers.""" # Handle URL url = self.base_url + api # Default to POST if data is attached, GET otherwise if not verb: verb = 'POST' if postdict else 'GET' # Auth: Use Access Token by default, API Key/Secret if provi...
self.logger.warning("Token expired, reauthenticating...") sleep(1) self.authenticate() return self._curl_bitmex(api, query, postdict, timeout, verb) # 404, can be thrown if order canceled does not exist. elif response.status_code == 404: if verb == 'DELETE': self.logger.error("Order not found: %s" % postdict['orderID']...
% (url, json.dumps(postdict))) sleep(1) return self._curl_bitmex(api, query, postdict, timeout, verb) # Unknown Error else: self.logger.error("Unhandled Error: %s: %s %s" % (e, response.text, json.dumps(response.json(), indent=4))) self.logger.error("Endpoint was: %s %s" % (verb, api)) except requests.exceptions.Timeou...
def allow_create(function): """ Decorate the `form_valid` method in a Create/Update class to create new values if necessary. .. warning:: Make sure that this decorator **only** decorates the ``form_valid()`` method and **only** this one. """ @wraps(function) def _wrapped_func(*args, **kwargs): form = args[0] # If this ...
def add_handler(self, event, handler): """Adds a handler function for an event. Note: Only one handler function is allowed per event on the module level (different modules can provide handlers for the same event). This is because ordering of handler functions is not guaranteed to be preserved at the module level. Also ...
def handle(event): """Decorator for indicating that a given method handles an event. Note: while multiple instances of this decorator may be applied to a single method, it is not recommended. """ def dec(func): if not hasattr(func, '_handle_events'): func._handle_events = set() func._handle_events.add(event) return fun...
def start(self, reloading=False): """Called when the module is loaded. If the load is due to a reload of the module, then the 'reloading' argument will be set to True. By default, this method calls the controller's listen() for each event in the self.event_handlers dict. """ for event in self.event_handlers: self.contr...
def handle_event(self, event, client, args): """Dispatch an event to its handler. Note: the handler does not receive the event which triggered its call. If you want to handle more than one event, it's recommended to put the shared handling in a separate function, and create wrapper handlers that call the shared functio...
def trigger_event(self, event, client, args, force_dispatch=False): """Trigger a new event that will be dispatched to all modules.""" self.controller.process_event(event, client, args, force_dispatch=force_dispatch)
def listen(self, event): """Request that the Controller listen for and dispatch an event. Note: Even if the module that requested the listening is later unloaded, the Controller will continue to dispatch the event, there just might not be anything that cares about it. That's okay. """ if event in self.registered: # Alr...
def start(self): """Begin listening for events from the Client and acting upon them. Note: If configuration has not already been loaded, it will be loaded immediately before starting to listen for events. Calling this method without having specified and/or loaded a configuration will result in completely default values...
def process_event(self, event, client, args, force_dispatch=False): """Process an incoming event. Offers it to each module according to self.module_ordering, continuing to the next unless the module inhibits propagation. Returns True if a module inhibited propagation, otherwise False. """ if not self.running: _log.debu...
"loaded (%r).", event, module_name, self.loaded_on_this_event) continue module = self.loaded_modules[module_name] if module.handle_event(event, client, args): return True finally: self.loaded_on_this_event = old_loaded
def load_config(self, config_path=None): """Load configuration from the specified path, or self.config_path""" if config_path is None: config_path = self.config_path else: self.config_path = config_path config = ConfigParser.SafeConfigParser(self.DEFAULT_SUBSTITUTIONS, allow_no_value=True) # Avoid the configparser auto...
def save_config(self, config_path=None): """Save configuration to the specified path, or self.config_path""" if config_path is None: config_path = self.config_path else: self.config_path = config_path with open(config_path, 'w') as f: self.config.write(f)
def reload_modules(self): """(Re)load all of the configured modules. 1. Calls stop(reloading=True) on each loaded module 2. Clears .loaded_modules and .module_ordering 3. Loads each module specified in the config 4. Calls start() on each loaded module, with reloading set depending on whether the module was previously l...
failed to load: %s", modules_failure) for module_name in self.module_ordering: module = self.loaded_modules[module_name] module.start(reloading=(module_name in old_modules)) self.process_event("STARTUP", self.client, (), force_dispatch=True) return not modules_failure
def reload_module(self, module_name): """Reloads the specified module without changing its ordering. 1. Calls stop(reloading=True) on the module 2. Reloads the Module object into .loaded_modules 3. Calls start(reloading=True) on the new object If called with a module name that is not currently loaded, it will load it. ...
def load_module(self, module_name): """Attempts to load the specified module. If successful, .loaded_modules[module_name] will be populated, and module_name will be added to the end of .module_ordering as well if it is not already present. Note that this function does NOT call start()/stop() on the module - in general,...
not found.", module_name) return False except SyntaxError: _log.exception("Unable to load module '%s' - syntax error(s).", module_name) return False if not hasattr(_temp, "module"): _log.error("Unable to load module '%s' - no 'module' member.", module_name) return False module = _temp.module if not issubclass(module, M...
def unload_module(self, module_name): """Unload the specified module, if it is loaded.""" module = self.loaded_modules.get(module_name) if not module: _log.warning("Ignoring request to unload non-existant module '%s'", module_name) return False module.stop(reloading=False) del self.loaded_modules[module_name] self.modu...
def _parse_url(url, fully_qualified=False): """Parse the given charm or bundle URL, provided as a string. Return a tuple containing the entity reference fragments: schema, user, series, name and revision. Each fragment is a string except revision (int). Raise a ValueError with a descriptive message if the given URL is ...
'' if part.startswith('~'): user = part[1:] if not valid_user(user): msg = 'URL has invalid user name: {}'.format(user) raise ValueError(msg.encode('utf-8')) if schema == 'local': msg = 'local entity URL with user name: {}'.format(url) raise ValueError(msg.encode('utf-8')) if not parts: msg = 'URL has invalid form: {}'...
= part, None if revision is not None: try: revision = int(revision) except ValueError: if fully_qualified: msg = 'URL has invalid revision: {}'.format(revision) raise ValueError(msg.encode('utf-8')) name, revision = name + '-' + revision, None if not valid_name(name): msg = 'URL has invalid name: {}'.format(name) raise...
def tasks_spec(self, available_actions, default_action="run"): """Tasks for a particular image""" return dictof( self.task_name_spec , create_spec(task_objs.Task, validators.deprecated_key("spec", "Use ``action`` and ``options`` instead (note that ``action`` defaults to run)") , action = defaulted(string_choice_spec(av...
def authentications_spec(self): """Spec for a group of authentication options""" return container_spec(authentication_objs.Authentication , dictof(string_spec(), set_options( reading = optional_spec(authentication_spec()) , writing = optional_spec(authentication_spec()) ) ) )
def wait_condition_spec(self): """Spec for a wait_condition block""" from harpoon.option_spec import image_objs formatted_string = formatted(string_spec(), formatter=MergedOptionStringFormatter) return create_spec(image_objs.WaitCondition , harpoon = formatted(overridden("{harpoon}"), formatter=MergedOptionStringFormat...
def context_spec(self): """Spec for specifying context options""" from harpoon.option_spec import image_objs return dict_from_bool_spec(lambda meta, val: {"enabled": val} , create_spec(image_objs.Context , validators.deprecated_key("use_git_timestamps", "Since docker 1.8, timestamps no longer invalidate the docker laye...
def image_spec(self): """Spec for each image""" from harpoon.option_spec import image_specs as specs from harpoon.option_spec import image_objs class persistence_shell_spec(Spec): """Make the persistence shell default to the shell on the image""" def normalise(self, meta, val): shell = defaulted(string_spec(), "/bin/ba...
image_index = formatted(defaulted(string_spec(), ""), formatter=MergedOptionStringFormatter) , container_name = optional_spec(string_spec()) , image_name_prefix = defaulted(string_spec(), "") , no_tty_option = defaulted(formatted(boolean(), formatter=MergedOptionStringFormatter), False) , user = defaulted(string_spec()...
, wait_condition = optional_spec(self.wait_condition_spec) ) ) , env = listof(specs.env_spec(), expect=image_objs.Environment) , ports = listof(specs.port_spec(), expect=image_objs.Port) , ulimits = defaulted(listof(dictionary_spec()), None) , log_config = defaulted(listof(dictionary_spec()), None) , security_opt = def...
defaulted(listof(string_spec()), None) , mem_limit = defaulted(integer_spec(), 0) , cpu_shares = defaulted(integer_spec(), None) , memswap_limit = defaulted(integer_spec(), 0) ) , devices = defaulted(listof(dictionary_spec()), None) , privileged = defaulted(boolean(), False) , restart_policy = defaulted(string_spec(), ...
def harpoon_spec(self): """Spec for harpoon options""" formatted_string = formatted(string_spec(), MergedOptionStringFormatter, expected_type=six.string_types) formatted_boolean = formatted(boolean(), MergedOptionStringFormatter, expected_type=bool) return create_spec(Harpoon , config = optional_spec(file_spec()) , tag...
tty_stdout = defaulted(any_spec(), lambda: sys.stdout) , tty_stderr = defaulted(any_spec(), lambda: sys.stderr) )
def namespace_uri(self): """ Finds and returns first applied URI of this node that has a namespace. :return str: uri """ try: return next( iter(filter(lambda uri: URI(uri).namespace, self._uri)) ) except StopIteration: return None
def _init_map(self): """stub""" super(EdXDragAndDropQuestionFormRecord, self)._init_map() QuestionTextFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) self.my_osid_object_form._my_map['text']['text'] = ''
def _init_metadata(self): """stub""" super(EdXDragAndDropQuestionFormRecord, self)._init_metadata() QuestionTextFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self)
def _init_map(self): """call these all manually because non-cooperative""" DecimalAnswerFormRecord._init_map(self) DecimalValuesFormRecord._init_map(self) TextAnswerFormRecord._init_map(self) TextsFormRecord._init_map(self) super(edXNumericResponseAnswerFormRecord, self)._init_map()
def _init_metadata(self): """stub""" DecimalAnswerFormRecord._init_metadata(self) DecimalValuesFormRecord._init_metadata(self) TextAnswerFormRecord._init_metadata(self) TextsFormRecord._init_metadata(self) super(edXNumericResponseAnswerFormRecord, self)._init_metadata()
def set_tolerance_value(self, tolerance): """stub""" # include index because could be multiple response / tolerance pairs if not isinstance(tolerance, float): raise InvalidArgument('tolerance value must be a decimal') self.add_decimal_value(tolerance, 'tolerance')
def pre_dispatch(self, request, path_args): """ Pre dispatch hook """ secret_key = self.get_secret_key(request, path_args) if not secret_key: raise PermissionDenied('Signature not valid.') try: signing.verify_url_path(request.path, request.GET, secret_key) except SigningError as ex: raise PermissionDenied(str(ex))
def get_catalogs(self): """Gets the catalog list resulting from the search. return: (osid.cataloging.CatalogList) - the catalogs list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: raise errors.IllegalState('List has already been ...
def get_authorization_session(self): """Gets an ``AuthorizationSession`` which is responsible for performing authorization checks. return: (osid.authorization.AuthorizationSession) - an authorization session for this service raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authoriza...
def get_authorization_session_for_vault(self, vault_id): """Gets an ``AuthorizationSession`` which is responsible for performing authorization checks for the given vault. arg: vault_id (osid.id.Id): the ``Id`` of the vault return: (osid.authorization.AuthorizationSession) - ``an _authorization_session`` raise: NotFound...
def get_authorization_lookup_session(self): """Gets the ``OsidSession`` associated with the authorization lookup service. return: (osid.authorization.AuthorizationLookupSession) - an ``AuthorizationLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_lookup...
def get_authorization_query_session(self): """Gets the ``OsidSession`` associated with the authorization query service. return: (osid.authorization.AuthorizationQuerySession) - an ``AuthorizationQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_query()`` ...
def get_authorization_query_session_for_vault(self, vault_id): """Gets the ``OsidSession`` associated with the authorization query service for the given vault. arg: vault_id (osid.id.Id): the ``Id`` of the vault return: (osid.authorization.AuthorizationQuerySession) - ``an _authorization_query_session`` raise: NotFound...
def get_authorization_admin_session(self): """Gets the ``OsidSession`` associated with the authorization administration service. return: (osid.authorization.AuthorizationAdminSession) - an ``AuthorizationAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_a...
def get_authorization_admin_session_for_vault(self, vault_id): """Gets the ``OsidSession`` associated with the authorization admin service for the given vault. arg: vault_id (osid.id.Id): the ``Id`` of the vault return: (osid.authorization.AuthorizationAdminSession) - ``an _authorization_admin_session`` raise: NotFound...
def get_authorization_vault_session(self): """Gets the session for retrieving authorization to vault mappings. return: (osid.authorization.AuthorizationVaultSession) - an ``AuthorizationVaultSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_vault()`` is ``fals...
def get_authorization_vault_assignment_session(self): """Gets the session for assigning authorizations to vault mappings. return: (osid.authorization.AuthorizationVaultAssignmentSession) - a ``AuthorizationVaultAssignmentSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_aut...
def get_vault_lookup_session(self): """Gets the OsidSession associated with the vault lookup service. return: (osid.authorization.VaultLookupSession) - a ``VaultLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_vault_lookup() is false`` *compliance: optional -- This m...
def get_vault_admin_session(self): """Gets the OsidSession associated with the vault administration service. return: (osid.authorization.VaultAdminSession) - a ``VaultAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_vault_admin() is false`` *compliance: optional -- Th...
def get_vault_hierarchy_session(self): """Gets the session traversing vault hierarchies. return: (osid.authorization.VaultHierarchySession) - a ``VaultHierarchySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_vault_hierarchy() is false`` *compliance: optional -- This metho...
def get_vault_hierarchy_design_session(self): """Gets the session designing vault hierarchies. return: (osid.authorization.VaultHierarchyDesignSession) - a ``VaultHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_vault_hierarchy_design() is false`` *complianc...
def get_authorization_lookup_session_for_vault(self, vault_id, proxy): """Gets the ``OsidSession`` associated with the authorization lookup service for the given vault. arg: vault_id (osid.id.Id): the ``Id`` of the vault arg: proxy (osid.proxy.Proxy): a proxy return: (osid.authorization.AuthorizationLookupSession) - ``...
def get_vault_query_session(self, proxy): """Gets the OsidSession associated with the vault query service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.authorization.VaultQuerySession) - a ``VaultQuerySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise...
def _qr_code(self, instance): """ return generate html code with "otpauth://..." link and QR-code """ request = self.request # FIXME try: user = instance.user except ObjectDoesNotExist: return _("Please save first!") current_site = get_current_site(request) username = user.username secret = six.text_type(base64.b32enco...
def qr_code(self, instance): """ Display picture of QR-code from used secret """ try: return self._qr_code(instance) except Exception as err: if settings.DEBUG: import traceback return "<pre>%s</pre>" % traceback.format_exc()
def tokens(self, instance): """ Just display current acceptable TOTP tokens """ if not instance.pk: # e.g.: Use will create a new TOTP entry return "-" totp = TOTP(instance.bin_key, instance.step, instance.t0, instance.digits) tokens = [] for offset in range(-instance.tolerance, instance.tolerance + 1): totp.drift = in...
def parse(text, showToc=True): """Returns HTML from MediaWiki markup""" p = Parser(show_toc=showToc) return p.parse(text)