code
stringlengths
1
18.2k
def remove_alt_text_language(self, language_type): """Removes the specified alt_text. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if self.get_alt_texts_metadata().is_read_only(): raise NoAccess() self.re...
def get_media_descriptions_metadata(self): """Gets the metadata for all media descriptions. return: (osid.Metadata) - metadata for the media descriptions *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._media_descriptions_metadata) metadata.update({'existing_string_values': [t['text...
def add_media_description(self, media_description): """Adds a media_description. arg: media_description (displayText): the new media_description raise: InvalidArgument - ``media_description`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``media_description`` is ``null`` *comp...
def remove_media_description_language(self, language_type): """Removes the specified media_description. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if self.get_media_descriptions_metadata().is_read_only(...
def add_vtt_file(self, vtt_file, language_type=None): """Adds a vtt file tagged as the given language. arg: vtt_file (displayText): the new vtt_file raise: InvalidArgument - ``vtt_file`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``media_description`` is ``null`` *complianc...
def add_transcript_file(self, transcript_file, language_type=None): """Adds a transcript file tagged as the given language. arg: transcript_file (displayText): the new transcript_file raise: InvalidArgument - ``transcript_file`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'birdland.mit.edu', 'namespace': 'unit system', 'identifier': name, 'domain': 'Unit System Types', 'display_name': JEFFS_UNIT_SYSTEM_TYPES[na...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'okapia.net', 'namespace': 'string match types', 'identifier': name, 'domain': 'String Match Types', 'display_name': STRING_MATCH_TYPES[name]...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedAgencyIds'] = [str(kwargs['agency_id'])]
def load_settings_sizes(): """ Load sizes from settings or fallback to the module constants """ page_size = AGNOCOMPLETE_DEFAULT_PAGESIZE settings_page_size = getattr( settings, 'AGNOCOMPLETE_DEFAULT_PAGESIZE', None) page_size = settings_page_size or page_size page_size_min = AGNOCOMPLETE_MIN_PAGESIZE settings_page_siz...
def is_valid_query(self, query): """ Return True if the search query is valid. e.g.: * not empty, * not too short, """ # No query, no item if not query: return False # Query is too short, no item if len(query) < self.get_query_size_min(): return False return True
def selected(self, ids): """ Return the selected options as a list of tuples """ result = copy(self.choices) result = filter(lambda x: x[0] in ids, result) # result = ((item, item) for item in result) return list(result)
def get_model(self): """ Return the class Model used by this Agnocomplete """ if hasattr(self, 'model') and self.model: return self.model # Give me a "none" queryset try: none = self.get_queryset().none() return none.model except Exception: raise ImproperlyConfigured( "Integrator: Unable to determine the model with thi...
def get_field_name(self): """ Return the model field name to be used as a value, or 'pk' if unset """ if hasattr(self, 'agnocomplete_field') and \ hasattr(self.agnocomplete_field, 'to_field_name'): return self.agnocomplete_field.to_field_name or 'pk' return 'pk'
def _construct_qs_filter(self, field_name): """ Using a field name optionnaly prefixed by `^`, `=`, `@`, return a case-insensitive filter condition name usable as a queryset `filter()` keyword argument. """ if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return ...
def get_queryset_filters(self, query): """ Return the filtered queryset """ conditions = Q() for field_name in self.fields: conditions |= Q(**{ self._construct_qs_filter(field_name): query }) return conditions
def item(self, current_item): """ Return the current item. @param current_item: Current item @type param: django.models @return: Value and label of the current item @rtype : dict """ return { 'value': text(getattr(current_item, self.get_field_name())), 'label': self.label(current_item) }
def build_filtered_queryset(self, query, **kwargs): """ Build and return the fully-filtered queryset """ # Take the basic queryset qs = self.get_queryset() # filter it via the query conditions qs = qs.filter(self.get_queryset_filters(query)) return self.build_extra_filtered_queryset(qs, **kwargs)
def items(self, query=None, **kwargs): """ Return the items to be sent to the client """ # Cut this, we don't need no empty query if not query: self.__final_queryset = self.get_model().objects.none() return self.serialize(self.__final_queryset) # Query is too short, no item if len(query) < self.get_query_size_min(): se...
def selected(self, ids): """ Return the selected options as a list of tuples """ # Cleanup the ID list if self.get_field_name() == 'pk': ids = filter(lambda x: "{}".format(x).isdigit(), copy(ids)) else: ids = filter(lambda x: len("{}".format(x)) > 0, copy(ids)) # Prepare the QS # TODO: not contextually filtered, check ...
def get_http_method_arg_name(self): """ Return the HTTP function to call and the params/data argument name """ if self.method == 'get': arg_name = 'params' else: arg_name = 'data' return getattr(requests, self.method), arg_name
def http_call(self, url=None, **kwargs): """ Call the target URL via HTTP and return the JSON result """ if not url: url = self.search_url http_func, arg_name = self.get_http_method_arg_name() # Build the argument dictionary to pass in the http function _kwargs = { arg_name: kwargs, } # The actual HTTP call response = ...
def validate(self, value): """ From a value available on the remote server, the method returns the complete item matching the value. If case the value is not available on the server side or filtered through :meth:`item`, the class:`agnocomplete.exceptions.ItemNotFound` is raised. """ url = self.get_item_url(value) try:...
def emit(self): """Get a mapping from a transcript :return: One random Transcript sequence :rtype: sequence """ i = self.options.rand.get_weighted_random_index(self._weights) return self._transcriptome.transcripts[i]
def set_weights_by_dict(self,weights): """input: an array of weights <<txname1> <weight1>> <<txname2> <weight2>>... if this does not get set then even weighting will be used :param weights: [[tx1,wght1],[tx2,wght2],...[txN,wightN]] :type weights: list """ self._weights = [] txnames = [x.name for x in self._transcriptom...
def emit(self,rlen=150): """Emit a read based on a source sequence""" source_tx = self._source.emit() source_read = self._cutter.cut(source_tx) if self._flip and self.options.rand.random() < 0.5: source_read = source_read.rc() srname = self.options.rand.uuid4() seqfull = FASTQ('@'+self.options.rand.uuid4()+"\tlong\n"+s...
def unwrapArray(a, recursive=True, readH5pyDataset=True): """ This function takes an object (like a dictionary) and recursively unwraps it solving issues like: * the fact that many objects are packaged as 0d array This funciton has also some specific hack for handling h5py limits: * handle the None python object * nump...
is a string # a.value returns a str(py3) or unicode(py2) if readH5pyDataset or a.shape == (): a = a.value#[...] # special None flag # not array needed for FutureWarning: elementwise comparison failed; ... if not isinstance(a,np.ndarray) and a == "NONE_PYTHON_OBJECT": a = None # clean up non-hdf5 specific if isinstance(...
not handle %s, error was: %s"%(a,str(e))) return a
def dictToH5Group(d, group, link_copy=True): """ helper function that transform (recursive) a dictionary into an hdf group by creating subgroups link_copy = True, tries to save space in the hdf file by creating an internal link. the current implementation uses memory though ... """ for key in d.keys(): value = d[key] l...
coverted to dict like only # by DataStorage (and not by dict) except: value = dictToH5Group(DataStorage(value),group[key],link_copy=link_copy) # take care of unicode (h5py can't handle numpy unicode arrays) elif isinstance(value,np.ndarray) and value.dtype.char == "U": value = np.asarray([vv.encode('ascii') for vv in v...
def dictToH5(h5, d, link_copy=False): """ Save a dictionary into an hdf5 file h5py is not capable of handling dictionaries natively""" global _array_cache _array_cache = dict() h5 = h5py.File(h5, mode="w") dictToH5Group(d, h5["/"], link_copy=link_copy) h5.close() _array_cache = dict();
def h5ToDict(h5, readH5pyDataset=True): """ Read a hdf5 file into a dictionary """ h = h5py.File(h5, "r") ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset) if readH5pyDataset: h.close() return ret
def _toDict(datastorage_obj,recursive=True): """ this is the recursive part of the toDict (otherwise it fails when converting to DataStorage """ if "items" not in dir(datastorage_obj): return datastorage_obj d = dict() for k, v in datastorage_obj.items(): try: d[k] = _toDict(v) except Exception as e: log.info("In toDic...
def toDict(datastorage_obj, recursive=True): """ convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too """ # if not a DataStorage, convert to it first if "items" not in dir(datastorage_obj): datastorage_obj = DataStorage(datastorage_obj) return _toDict(datastorage_obj)
def save(fname, d, link_copy=True,raiseError=False): """ link_copy is used by hdf5 saving only, it allows to creat link of identical arrays (saving space) """ # make sure the object is dict (recursively) this allows reading it # without the DataStorage module fname = pathlib.Path(fname) d = toDict(d, recursive=True) d[...
def save(self, fname=None, link_copy=False,raiseError=False): """ link_copy: only works in hfd5 format save space by creating link when identical arrays are found, it may slows down the saving (3 or 4 folds) but saves space when saving different dataset together (since it does not duplicate arrays) """ if fname is None...
def match_learning_objective_id(self, objective_id, match): """Sets the learning objective ``Id`` for this query. arg: objective_id (osid.id.Id): a learning objective ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for negative match raise: NullArgument - ``objective_id`` is ``null`` *compliance: ...
def match_start_time(self, start, end, match): """Matches assessments whose start time falls between the specified range inclusive. arg: start (osid.calendaring.DateTime): start of range arg: end (osid.calendaring.DateTime): end of range arg: match (boolean): ``true`` for a positive match, ``false`` for a negative matc...
def match_deadline(self, start, end, match): """Matches assessments whose end time falls between the specified range inclusive. arg: start (osid.calendaring.DateTime): start of range arg: end (osid.calendaring.DateTime): end of range arg: match (boolean): ``true`` for a positive match, ``false`` for a negative match ra...
def match_taking_agent_id(self, agent_id, match): """Sets the agent ``Id`` for this query. arg: agent_id (osid.id.Id): an agent ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for a negative match raise: NullArgument - ``agent_id`` is ``null`` *compliance: mandatory -- This method must be implemen...
def match_ancestor_bank_id(self, bank_id, match): """Sets the bank ``Id`` for to match banks in which the specified bank is an acestor. arg: bank_id (osid.id.Id): a bank ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for a negative match raise: NullArgument - ``bank_id`` is ``null`` *compliance: ...
def fill(cdb, defs, pparms): """ Take field values in parms and insert them into cdb based on the field definitions in defs. """ #print "defs =", defs parms = {n:v[2] for (n,v) in defs.items()} # Create parms for default field values. parms.update(pparms) # Insert real parameters. for (name, value) in parms.items(): if...
= value else: if value >= 1<<width: raise Exception("value too large for field: "+name) startbitnum = start[0]*8 + (7-start[1]) # Number bits l-to-r. bitnum = startbitnum + defs[name][1] - 1 # TODO Is value inserted backwards? while width > 0: if bitnum % 8 == 7 and width >= 8: bitlen= 8 cdb[bitnum//8] = value & 0xff; ...
def extract(data, defs, byteoffset=0): """ Extract fields from data into a structure based on field definitions in defs. byteoffset is added to each local byte offset to get the byte offset returned for each field. defs is a list of lists comprising start, width in bits, format, nickname, description. field start is ei...
<< 8) | ord(data[ix]) ix += 1 width -= 8 else: lastbit = bitnum+1 - width if lastbit < 0: lastbit = 0 thiswidth = bitnum+1 - lastbit val = (val << thiswidth) | ((ord(data[ix]) >> lastbit) & ((1<<thiswidth)-1)) bitnum = 7 ix += 1 width -= thiswidth retval.append(Cmd.Field(val, byteoffset+start[0], name, desc), name) eli...
def inq(pt, page=None, alloc=74): """ Create an Inquiry command, send it, and parse the results. Input: pt : ScsiPT object page : vital product page number or None alloc: size to allocate for result TODO: implement page """ cmd = Cmd("inq", {"evpd":0, "alloc":alloc}) cdb = CDB(cmd.cdb) cdb.set_data_in(alloc) pt.sendcdb...
def get_question_mdata(): """Return default mdata map for Question""" return { 'item': { 'element_label': { 'text': 'item', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.id.Id object', 'lang...
def get_answer_mdata(): """Return default mdata map for Answer""" return { 'item': { 'element_label': { 'text': 'item', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.id.Id object', 'language...
def get_item_mdata(): """Return default mdata map for Item""" return { 'learning_objectives': { 'element_label': { 'text': 'learning objectives', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osi...
def get_assessment_mdata(): """Return default mdata map for Assessment""" return { 'rubric': { 'element_label': { 'text': 'rubric', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.id.Id object...
def get_assessment_offered_mdata(): """Return default mdata map for AssessmentOffered""" return { 'level': { 'element_label': { 'text': 'level', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid...
'linked': False, 'array': False, 'default_id_values': [''], 'syntax': 'ID', 'id_set': [], }, 'items_shuffled': { 'element_label': { 'text': 'items shuffled', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'en...
'linked': False, 'array': False, 'default_date_time_values': [None], 'syntax': 'DATETIME', 'date_time_set': [], }, 'duration': { 'element_label': { 'text': 'duration', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { '...
False, 'linked': False, 'array': False, 'default_boolean_values': [None], 'syntax': 'BOOLEAN', }, }
def get_assessment_taken_mdata(): """Return default mdata map for AssessmentTaken""" return { 'assessment_offered': { 'element_label': { 'text': 'assessment offered', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 't...
def get_assessment_section_mdata(): """Return default mdata map for AssessmentSection""" return { 'assessment_taken': { 'element_label': { 'text': 'assessment taken', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 't...
def match_agent_id(self, agent_id, match): """Matches the agent identified by the given ``Id``. arg: agent_id (osid.id.Id): the Id of the ``Agent`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``agent_id`` is ``null`` *compliance: mandatory -- This method must...
def match_function_id(self, function_id, match): """Matches the function identified by the given ``Id``. arg: function_id (osid.id.Id): the Id of the ``Function`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``function_id`` is ``null`` *compliance: mandatory -...
def match_qualifier_id(self, qualifier_id, match): """Matches the qualifier identified by the given ``Id``. arg: qualifier_id (osid.id.Id): the Id of the ``Qualifier`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``qualifier_id`` is ``null`` *compliance: manda...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'okapia.net', 'namespace': 'heading', 'identifier': name, 'domain': 'Headings', 'display_name': HEADING_TYPES[name] + ' Heading Type', 'displ...
def make_temp(suffix="", prefix="tmp", dir=None): """ Creates a temporary file with a closed stream and deletes it when done. :return: A contextmanager retrieving the file path. """ temporary = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir) os.close(temporary[0]) try: yield temporary[1] finally: os.remove(temp...
def _make_request( self, api_resource, method='GET', params=None, **kwargs): """ Shortcut for a generic request to the Toshl API :param url: The URL resource part :param method: REST method :param parameters: Querystring parameters :return: requests.Response """ if kwargs.get('json'): headers = { 'Authorization': 'Bear...
def _list_response(self, response): """ This method check if the response is a dict and wrap it into a list. If the response is already a list, it returns the response directly. This workaround is necessary because the API doesn't return a list if only one item is found. """ if type(response) is list: return response i...
def main(args): """Main program""" (ribo_file, transcriptome_fasta, read_lengths, read_offsets, count_five, count_three, output_path, html_file) = \ (args.ribo_file, args.transcriptome_fasta, args.read_lengths, args.read_offsets, args.count_five, args.count_three, args.output_path, args.html_file) log.debug('Supplied a...
= '3' # create output directories if not os.path.exists(output_path): os.mkdir(output_path) # zip_dir contents will be written here and a zip archive will be created # from this directory zip_dir = os.path.join(output_path, 'ribocount_output') if not os.path.exists(zip_dir): os.mkdir(zip_dir) csv_dir = os.path.join(zip...
{} if count_five or count_three: # use default start and stop codons and find ORFs in all 3 # frames (+) orfs = ribocore.get_three_frame_orfs(sequence=transcript_sequence) if not len(orfs): log.debug('No ORFs for transcript {0}'.format(transcript)) continue longest_orf = ribocore.get_longest_orf(orfs=orfs) orf_start, o...
write_counts[pos][2], write_counts[pos][3])) else: cw.write('{0},{1},{2},{3},{4}\n'.format(pos, nucleotide, 0, 0, 0)) # HTML table table_body += '<tr><td>{0}</td><td>{1}</td>'.format(transcript, ribo_reads) if count_five: table_body += '<td>{0}</td>'.format(five_reads) elif count_three: table_body += '<td>{0}</td>'.for...
file') os.chdir(output_path) with zipfile.ZipFile('ribocount_output.zip', 'w', allowZip64=True) as zipf: for root, d, f in os.walk('ribocount_output'): for name in f: zipf.write(os.path.join(root, name)) shutil.rmtree('ribocount_output') os.chdir('../') log.debug('Writing HTML report') with open(os.path.join(CONFIG.PKG...
def match_ancestor_objective_id(self, objective_id=None, match=None): """Sets the objective ``Id`` for this query to match objectives that have the specified objective as an ancestor. arg: objective_id (osid.id.Id): an objective ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for a negative match ...
def match_descendant_objective_id(self, objective_id=None, match=None): """Sets the objective ``Id`` for this query to match objectives that have the specified objective as a descendant. arg: objective_id (osid.id.Id): an objective ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for a negative mat...
def skip(self, n): """Skips a specified number of ``bytes`` in the stream. arg: n (cardinal): the number of ``bytes`` to skip return: (cardinal) - the actual number of ``bytes`` skipped raise: IllegalState - this stream has been closed or ``at_end_of_stream()`` is ``true`` *compliance: mandatory -- This method must be ...
def read_to_buffer(self, buf, n): """Reads a specified number of ``bytes`` from this stream. arg: buf (byte[]): the buffer in which the data is read arg: n (cardinal): the number of ``bytes`` to read return: (integer) - the actual number of ``bytes`` read raise: IllegalState - this stream has been closed or ``at_end_of...
def read(self, buf=None, n=None): """Reads a specified number of ``bytes`` from this stream. arg: n (cardinal): the number of ``bytes`` to read return: (integer) - the ``bytes`` read raise: IllegalState - this stream has been closed or ``at_end_of_stream()`` is ``true`` raise: InvalidArgument - the size of ``buf`` is l...
def root(self): """ Property provides access to root object in CFB. """ sector = self.header.directory_sector_start position = (sector + 1) << self.header.sector_shift return RootEntry(self, position)
def next_fat(self, current): """ Helper gives you seekable position of next FAT sector. Should not be called from external code. """ sector_size = self.header.sector_size // 4 block = current // sector_size difat_position = 76 if block >= 109: block -= 109 sector = self.header.difat_sector_start while block >= sector_s...
def next_minifat(self, current): """ Helpers provides access to next mini-FAT sector and returns it's seekable position. Should not be called from external code. """ position = 0 sector_size = self.header.sector_size // 4 sector = self.header.minifat_sector_start while sector != ENDOFCHAIN and (position + 1) * sector_s...
def get_items_by_search(self, item_query, item_search): """Pass through to provider ItemSearchSession.get_items_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() return self._provider_session....
def get_assessments_by_search(self, assessment_query, assessment_search): """Pass through to provider AssessmentSearchSession.get_assessments_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() ...
def get_assessments_offered_by_search(self, assessment_offered_query, assessment_offered_search): """Pass through to provider AssessmentOfferedSearchSession.get_assessments_offered_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._c...
def get_assessments_taken_by_search(self, assessment_taken_query, assessment_taken_search): """Pass through to provider AssessmentTakenSearchSession.get_assessments_taken_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search...
def get_choices_files_map(self): """stub""" files_map = [] for choice in self.get_choices(): choice = dict(choice) choice['smallOrthoViewSet'] = base64.b64encode( self._get_asset_content(Id(choice['assetId']), OV_SET_SMALL_ASSET_CONTENT_TYPE ).get_data().read()) choice['largeOrthoViewSet'] = base64.b64encode( self._get...
def get_choices_file_urls_map(self): """stub""" file_urls_map = [] for choice in self.get_choices(): choice = dict(choice) small_asset_content = self._get_asset_content( Id(choice['assetId']), OV_SET_SMALL_ASSET_CONTENT_TYPE) choice['smallOrthoViewSet'] = small_asset_content.get_url() small_asset_content = self._get_as...
def get_files(self): """stub""" files_map = {} try: files_map['choices'] = self.get_choices_file_urls_map() try: files_map.update(self.get_file_urls_map()) except IllegalState: pass except Exception: files_map['choices'] = self.get_choices_files_map() try: files_map.update(self.get_files_map()) except IllegalState: pas...
def _init_map(self): """stub""" QuestionFilesFormRecord._init_map(self) FirstAngleProjectionFormRecord._init_map(self) super(MultiChoiceOrthoQuestionFormRecord, self)._init_map()
def _init_metadata(self): """stub""" QuestionFilesFormRecord._init_metadata(self) FirstAngleProjectionFormRecord._init_metadata(self) super(MultiChoiceOrthoQuestionFormRecord, self)._init_metadata()
def set_manip_id(self, o3d_asset_id): """stub""" if not isinstance(o3d_asset_id, ABCId): raise InvalidArgument('Argument must be a valid Id') self.add_asset(o3d_asset_id, label='manip', asset_content_type=MANIP_ASSET_CONTENT_TYPE)
def create_o3d_asset(self, manip=None, small_ov_set=None, large_ov_set=None, display_name='', description=''): """stub""" if manip and not isinstance(manip, ABCDataInputStream): raise InvalidArgument('Manipulatable object must be an ' + 'osid.transport.DataInputStream object') if small_ov_set and not isinstance(small_o...
def set_manip(self, manip, ovs_sm=None, ovs_lg=None, name='A manipulatable'): """stub""" o3d_manip_id = self.create_o3d_asset(manip, small_ov_set=ovs_sm, large_ov_set=ovs_lg, display_name=name) self.set_manip_id(o3d_manip_id)
def set_ortho_choice(self, small_asset_data, large_asset_data, name='Choice'): """stub""" o3d_asset_id = self.create_o3d_asset(manip=None, small_ov_set=small_asset_data, large_ov_set=large_asset_data, display_name=name) self.add_choice(o3d_asset_id, name=name)
def generate_dmu_over_dt(species, propensity, n_counter, stoichiometry_matrix): r""" Calculate :math:`\frac{d\mu_i}{dt}` in eq. 6 (see Ale et al. 2013). .. math:: \frac{d\mu_i}{dt} = S \begin{bmatrix} \sum_{l} \sum_{n_1=0}^{\infty} ... \sum_{n_d=0}^{\infty} \frac{1}{\mathbf{n!}} \frac{\partial^n \mathbf{n}a_l(\mathbf{x...
EACH REACTION and EACH entry in COUNTER # this does not depend of the reaction, so we just repeat the result for each reaction factorial_terms = [get_one_over_n_factorial(tuple(c.n_vector)) for c in n_counter] * len(propensity) # we make a matrix in which every element is the entry-wise multiplication of `derives` and ...
def get_authentication_mdata(): """Return default mdata map for Authentication""" return { 'agent': { 'element_label': { 'text': 'agent', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.id.Id ...
def register(username, password): """ Create a new user account. Creates a user account with the given credentials on the selected cloud server. """ check_for_cloud_server() server = Server(config["cloud_server"]["url"]) server.create_user(username, password)
def login(username, password): """ Log into your user account """ check_for_cloud_server() old_username = config["cloud_server"]["username"] if old_username and old_username != username: raise click.ClickException( "Already logged in as user \"{}\". Run `openag cloud user logout` " "before attempting to log in as a dif...
def logout(ctx): """ Log out of your user account """ check_for_cloud_server() check_for_cloud_user() if config["cloud_server"]["farm_name"]: ctx.invoke(deinit_farm) config["cloud_server"]["username"] = None config["cloud_server"]["password"] = None
def instruction(self, val): """Set the action and command from an instruction""" self._instruction = val if isinstance(val, tuple): if len(val) is 2: self._action, self.command = val else: self._action, self.command, self.extra = val else: split = val.split(" ", 1) if split[0] == "FROM": split = val.split(" ", 2) if le...
def as_string(self): """Return the command as a single string for the docker file""" if type(self.instruction) is str: return self.instruction if self.action == "FROM" and not isinstance(self.command, six.string_types): extra = "" if self.extra is NotSpecified else " {0}".format(self.extra) return "{0} {1}{2}".format(s...
def commands(self): """Memoize and return the flattened list of commands""" if not getattr(self, "_commands", None): self._commands = [] for command in self.orig_commands: if isinstance(command, Command): command = [command] for instruction in command: self._commands.append(instruction) return self._commands
def external_dependencies(self): """ Return all the external images this Dockerfile will depend on These are images from self.dependent_images that aren't defined in this configuration. """ found = [] for dep in self.dependent_images: if isinstance(dep, six.string_types): if dep not in found: yield dep found.append(dep...