code
stringlengths
1
18.2k
def get_token(self): """ Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy contents of rel...
get Token. Status: ' + str(response.status_code)) return response
def get_model_info(self, model_id, token=None, url=API_GET_MODEL_INFO): """ Gets information about a specific previously trained model, ie: stats and accuracy :param model_id: string, model_id previously supplied by the API returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization'...
def get_datasets_info(self, token=None, url=API_GET_DATASETS_INFO): """ Gets information on all datasets for this account returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.get(the_url, headers=h) return r
def get_url_image_prediction(self, model_id, picture_url, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied picture url based on a previously trained model. :param model_id: string, once you train a model you'll be given a model id to use. :param picture_url: string, in the form of a ...
def get_fileb64_image_prediction(self, model_id, filename, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image on your machine, by encoding the image data as b64 and posting to the API. :param model_id: string, once you train a model you'll be given a model id to use. :param filen...
def get_b64_image_prediction(self, model_id, b64_encoded_string, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image enconded as a b64 string, useful when uploading images to a server backed by this library. :param model_id: string, once you train a model you'll be given a model i...
def create_dataset_synchronous(self, file_url, dataset_type='image', token=None, url=API_CREATE_DATASET): """ Creates a dataset so you can train models from it :param file_url: string, url to an accessible zip file containing the necessary image files and folder structure indicating the labels to train. See docs online...
def train_model(self, dataset_id, model_name, token=None, url=API_TRAIN_MODEL): """ Train a model given a specifi dataset previously created :param dataset_id: string, the id of a previously created dataset :param model_name: string, what you will call this model attention: This may take a while and a response will be ...
def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL): """ Gets status on the training process once you create a model :param model_id: string, id of the model to check returns: requests object """ auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} ...
def get_models_info_for_dataset(self, dataset_id, token=None, url=API_GET_MODELS): """ Gets metadata on all models available for given dataset id :param dataset_id: string, previously obtained dataset id warning: if providing your own url here, also include the dataset_id in the right place as this method will not incl...
def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET): """ Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox, AWS S3, Google Drive. warning: G...
def train_language_model_from_dataset(self, dataset_id, name, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Trains a model given a dataset and its ID. :param dataset_id: string, the ID for a dataset you created previously. :param name: string, name for your model. returns: a request object """ auth = 'Bearer ' + self....
def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object """ auth = 'Bearer ' + self.check_for_token(token) h = {'...
def get_language_prediction_from_model(self, model_id, document, token=None, url=API_GET_LANGUAGE_PREDICTION): """ Gets a prediction based on a body of text you send to a trained model you created previously. :param model_id: string, the ID for a model you created previously. :param document: string, a body of text to ...
def parse_rectlabel_app_output(self): """ Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the column headers. Could b...
boxes. if len(j['objects']) > max_boxes: max_boxes = len(j['objects']) # Each json file will end up being a row # set labels row = [] for o in j['objects']: labels = {} labels['label'] = o['label'] labels['x'] = o['x_y_w_h'][0] labels['y'] = o['x_y_w_h'][1] labels['width'] = o['x_y_w_h'][2] labels['height'] = o['x_y_w_...
def save_parsed_data_to_csv(self, output_filename='output.csv'): """ Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your conve...
def XML_save_parsed_data_to_csv(self, output_filename='output.csv'): """ Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your c...
def tokens(istr): """ Same as tokenize, but returns only tokens (and at all parantheses levels). """ # make a list of all alphanumeric tokens toks = re.findall(r'[^\*\\\+\-\^\(\)]+\(?', istr) # remove the functions return [t for t in toks if not t.endswith('(')]
def istr_type(istr): """ Given an "ion" specification, determine its "type", e.g. 1D, Events, etc. """ data = set(i.rstrip('0123456789') for i in tokens(istr)) has_events = not data.isdisjoint(istr_type_evts) has_2d = not data.isdisjoint(istr_type_2d) has_1d = data.difference(istr_type_evts).difference(istr_type_2d) !=...
def is_parans_exp(istr): """ Determines if an expression is a valid function "call" """ fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1 elif c == ')': plevel -= 1 if plevel == 0: return False...
def parse_ion_string(istr, analyses, twin=None): """ Recursive string parser that handles "ion" strings. """ if istr.strip() == '': return Trace() # remove (unnessary?) pluses from the front # TODO: plus should be abs? istr = istr.lstrip('+') # invert it if preceded by a minus sign if istr[0] == '-': return -parse_ion_...
some shortcuts to pull out common ions return parse_ion_string(SHORTCUTS[istr], analyses, twin) elif istr[0] == '!' and all(i in '0123456789.' for i in istr[1:]): # TODO: should this handle negative numbers? return float(istr[1:]) elif istr == '!pi': return np.pi elif istr == '!e': return np.e else: return trace_resolv...
point it shouldn\'t have!')
def set_pedalboard(self, pedalboard, notify=True, force=False): """ Set the current :class:`.Pedalboard` for the pedalboard only if the ``pedalboard != current_pedalboard or force`` Is also possible unload the current pedalboard data with replacing it for ``None``:: >>> current_controller.set_pedalboard(None) .. warnin...
def to_before_pedalboard(self): """ Change the current :class:`.Pedalboard` for the previous pedalboard. If the current pedalboard is the first in the current :class:`Bank`, the current pedalboard is will be the **last of the current Bank**. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.Curren...
def to_next_pedalboard(self): """ Change the current :class:`.Pedalboard` for the next pedalboard. If the current pedalboard is the last in the current :class:`.Bank`, the current pedalboard is will be the **first of the current Bank** .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedal...
def to_before_bank(self): """ Change the current :class:`Bank` for the before bank. If the current bank is the first, the current bank is will be the last bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the curre...
def to_next_bank(self): """ Change the current :class:`Bank` for the next bank. If the current bank is the last, the current bank is will be the first bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :...
def set_bank(self, bank, try_preserve_index=False): """ Set the current :class:`Bank` for the bank only if the ``bank != current_bank`` The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is...
raise CurrentPedalboardError('Bank {} has not added in banks manager'.format(bank)) if self.bank == bank: return if bank.pedalboards: pedalboard = self._equivalent_pedalboard(bank) if try_preserve_index else bank.pedalboards[0] self.set_pedalboard(pedalboard) else: self.set_pedalboard(None)
def _validate_and_get_value(options, options_name, key, _type): """ Check that `options` has a value for `key` with type `_type`. Return that value. `options_name` is a string representing a human-readable name for `options` to be used when printing errors. """ if isinstance(options, dict): has = lambda k: k in options...
def validate_event_and_assign_id(event): """ Ensure that the event has a valid time. Assign a random UUID based on the event time. """ event_time = event.get(TIMESTAMP_FIELD) if event_time is None: event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time()) elif type(event_time) not in (int, long): rai...
def validate_stream(stream): """ Check that the stream name is well-formed. """ if not STREAM_REGEX.match(stream) or len(stream) > MAX_STREAM_LENGTH: raise InvalidStreamName(stream)
def validate_storage_settings(storage_class, settings): """ Given a `storage_class` and a dictionary of `settings` to initialize it, this method verifies that all the settings are valid. """ if not isinstance(settings, dict): raise ImproperlyConfigured( '{}: storage class settings must be a dict'.format(storage_class))...
def validate_settings(settings): """ `settings` is either a dictionary or an object containing Kronos settings (e.g., the contents of conf/settings.py). This function checks that all required settings are present and valid. """ # Validate `storage` storage = _validate_and_get_value(settings, 'settings', 'storage', dict...
prefix), 'backends', dict) for backend in backends.keys(): if backend not in storage: raise ImproperlyConfigured( "`{}` backend for `namespace_to_streams_configuration['{}']" "['{}']` is not configured in `storage`" .format(backend, namespace, prefix)) read_backend = _validate_and_get_value( options, "namespace_to_stre...
def from_api(cls, **kwargs): """Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API re...
def to_api(self): """Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API. """ vals = {} for attribute, attribute_type in self._props.items(): prop = getattr(self, attribute) vals[self._to_camel_case(attribute)] = self._to_api_value( attribute_type, prop, )...
def _to_api_value(self, attribute_type, value): """Return a parsed value for the API.""" if not value: return None if isinstance(attribute_type, properties.Instance): return value.to_api() if isinstance(attribute_type, properties.List): return self._parse_api_value_list(value) return attribute_type.serialize(value)
def _parse_api_value_list(self, values): """Return a list field compatible with the API.""" try: return [v.to_api() for v in values] # Not models except AttributeError: return list(values)
def _parse_property(cls, name, value): """Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. Returns: mixed: A value compatibl...
def _parse_property_list(prop, value): """Parse a list property and return a list of the results.""" attributes = [] for v in value: try: attributes.append( prop.prop.instance_class.from_api(**v), ) except AttributeError: attributes.append(v) return attributes
def _to_snake_case(string): """Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string. """ sub_string = r'\1_\2' string = REGEX_CAMEL_FIRST.sub(sub_string, string) return REGEX_CAMEL_SECOND.sub(sub_string, string).lower()
def _to_camel_case(string): """Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string. """ components = string.split('_') return '%s%s' % ( components[0], ''.join(c.title() for c in components[1:]), )
def save(self, output=None): """ Save the database to a file. If ``output`` is not given, the ``dbfile`` given in the constructor is used. """ if output is None: if self.dbfile is None: return output = self.dbfile with open(output, 'w') as f: f.write(self._dump())
def feed(self, text=None, source=None): """ Feed some text to the database, either from a string (``text``) or a file (``source``). >>> db = TrigramsDB() >>> db.feed("This is my text") >>> db.feed(source="some/file.txt") """ if text is not None: words = re.split(r'\s+', text) wlen = len(words) for i in range(wlen - 2):...
def generate(self, **kwargs): """ Generate some text from the database. By default only 70 words are generated, but you can change this using keyword arguments. Keyword arguments: - ``wlen``: maximum length (words) - ``words``: a list of words to use to begin the text with """ words = list(map(self._sanitize, kwargs.ge...
def _load(self): """ Load the database from its ``dbfile`` if it has one """ if self.dbfile is not None: with open(self.dbfile, 'r') as f: self._db = json.loads(f.read()) else: self._db = {}
def _get(self, word1, word2): """ Return a possible next word after ``word1`` and ``word2``, or ``None`` if there's no possibility. """ key = self._WSEP.join([self._sanitize(word1), self._sanitize(word2)]) key = key.lower() if key not in self._db: return return sample(self._db[key], 1)[0]
def _insert(self, trigram): """ Insert a trigram in the DB """ words = list(map(self._sanitize, trigram)) key = self._WSEP.join(words[:2]).lower() next_word = words[2] self._db.setdefault(key, []) # we could use a set here, but sets are not serializables in JSON. This # is the same reason we use dicts instead of defaul...
def cohort_queryplan(plan): """ Input: { 'source': 'kronos', # Name of data source from settings 'cohort': {'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from. 'transform': lambda x: x, # Transformations on the kstream. 'start': date.now(), # The day of the first cohort. 'unit': DateUnit.XX, # Use...
event should we tie # to a key in the action stream? } Output: A metis-compatible query plan to return a cohort analysis. """ cohort = plan['cohort'] action = plan['action'] source = plan['source'] # Calculate the start and end dates, in Kronos time, of the # beginning and end of the cohort and action streams that will...
Property('action.%s' % action['grouping_key'])) & Condition(Condition.Op.GTE, Property('action.%s' % TIMESTAMP_FIELD), Property('cohort.%s' % TIMESTAMP_FIELD)) & Condition(Condition.Op.LT, Property('action.%s' % TIMESTAMP_FIELD), Add([Property('cohort.%s' % TIMESTAMP_FIELD), Constant(additional_action_time)])))) user_a...
def planetMassType(mass): """ Returns the planet masstype given the mass and using planetAssumptions['massType'] """ if mass is np.nan: return None for massLimit, massType in planetAssumptions['massType']: if mass < massLimit: return massType
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
def planetType(temperature, mass, radius): """ Returns the planet type as 'temperatureType massType' """ if mass is not np.nan: sizeType = planetMassType(mass) elif radius is not np.nan: sizeType = planetRadiusType(radius) else: return None return '{0} {1}'.format(planetTempType(temperature), sizeType)
def split_array_like(df, columns=None): #TODO rename TODO if it's not a big performance hit, just make them arraylike? We already indicated the column explicitly (sort of) so... ''' Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.D...
a b 0 1 1 1 1 1 2 1 2 1 1 3 3 1 1 4 4 1 1 5 5 1 2 3 6 1 2 4 7 1 2 5 8 2 1 1 9 2 1 2 ''' # TODO could add option to keep_index by using reset_index and eventually # set_index. index names trickery: MultiIndex.names, Index.name. Both can be # None. If Index.name can be None in which case it translates to 'index' or # if ...
df = pd.DataFrame(expanded, columns=df.columns) # keep types unchanged for i, dtype in enumerate(dtypes): df.iloc[:,i] = df.iloc[:,i].astype(dtype) return df
def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Get whether 2 data frames are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- df1 : ~pandas.DataFrame Data frame to compare. df2 : ~pandas.DataFrame Data frame to compare. ignore_or...
or None]`` is returned. The former is whether they're equal, the latter is `None` if equal or a short explanation of why the data frames aren't equal, otherwise. Notes ----- All values (including those of indices) must be copyable and ``__eq__`` must be such that a copy must equal its original. A value must equal itsel...
name='columns1') ... ) >>> df columns1 c1 c2 c3 index1 i1 1 2 3 i2 4 5 6 i3 7 8 9 >>> df2 = df.reindex(('i3', 'i1', 'i2'), columns=('c2', 'c1', 'c3')) >>> df2 columns1 c2 c1 c3 index1 i3 8 7 9 i1 2 1 3 i2 5 4 6 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_order=(0,1)) True >>> df2 = df.copy() >>> df2.in...
order! False >>> df_.equals(df, df2, ignore_order={0}) True >>> df2 = df.copy() >>> df2.index.name = 'other' >>> df_.equals(df, df2) # df.index.name must match as well, same goes for df.columns.name False ''' result = _equals(df1, df2, ignore_order, ignore_indices, all_close) if _return_reason: return result else: retu...
def _try_mask_first_row(row, values, all_close, ignore_order): ''' mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore_order : bool Ignore column order Return whether masked a row. If False, masked nothing. ''' for row2 in values: mask = ma.getmaskarray(row2) ...
def _try_mask_row(row1, row2, all_close, ignore_order): ''' if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instead of == Return whether masked the row ''' if ignore_order...
def _try_mask_first_value(value, row, all_close): ''' mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value ''' # Compare value to row for i, value2 in enumerate(row): if _value_equals(value, value2, all_close): row[i] = m...
def _value_equals(value1, value2, all_close): ''' Get whether 2 values are equal value1, value2 : ~typing.Any all_close : bool compare with np.isclose instead of == ''' if value1 is None: value1 = np.nan if value2 is None: value2 = np.nan are_floats = np.can_cast(type(value1), float) and np.can_cast(type(value2), float...
def assert_equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Assert 2 data frames are equal A more verbose form of ``assert equals(df1, df2, ...)``. See `equals` for an explanation of the parameters. Parameters ---------- df1 : ~pandas.DataFrame Actual data frame. df...
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
def find_dimension_by_name(self, dim_name): """the method searching dimension with a given name""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.name, dim_name): return dim return None
def find_dimension_by_id(self, dim_id): """the method searching dimension with a given id""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.id, dim_id): return dim return None
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'Dataset': self.dataset, 'Header' : self._get_item_array(self.header), 'Filter' : self._get_item_array(self.filter), 'Stub' : self._get_item_array(self.stub), 'Frequencies': self.frequencies } return json.dumps(requestvalues)
def save_to_json(self): """The method saves DatasetUpload to json from object""" requestvalues = { 'DatasetId': self.dataset, 'Name': self.name, 'Description': self.description, 'Source': self.source, 'PubDate': self.publication_date, 'AccessedOn': self.accessed_on, 'Url': self.dataset_ref, 'UploadFormatType': self.upl...
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'id': self.dataset, 'publicationDate': self.publication_date.strftime('%Y-%m-%d'), 'source': self.source, 'refUrl': self.refernce_url, } return json.dumps(requestvalues)
def keyspace(self, keyspace): """ Convenient, consistent access to a sub-set of all keys. """ if FORMAT_SPEC.search(keyspace): return KeyspacedProxy(self, keyspace) else: return KeyspacedProxy(self, self._keyspaces[keyspace])
def is_same(dir1, dir2): """ Compare two directory trees content. Return False if they differ, True is they are the same. :param dir2: :param dir1: """ compared = dircmp(dir1, dir2, IGNORED_FILES) # ignore the OS X file if compared.left_only or compared.right_only or compared.diff_files or compared.funny_files: return ...
def phase3(self): """ Find out differences between common files. Ensure we are using content comparison with shallow=False. """ fcomp = filecmp.cmpfiles(self.left, self.right, self.common_files, shallow=False) self.same_files, self.diff_files, self.funny_files = fcomp
def _insert(self, namespace, stream, events, configuration): """ `namespace` acts as db for different streams `stream` is the name of a stream and `events` is a list of events to insert. """ index = self.index_manager.get_index(namespace) start_dts_to_add = set() def actions(): for _id, event in events: dt = kronos_tim...
def _delete(self, namespace, stream, start_id, end_time, configuration): """ Delete events with id > `start_id` and end_time <= `end_time`. """ start_time = uuid_to_kronos_time(start_id) body_query = { 'query': { 'filtered': { 'query': {'match_all': {}}, 'filter': { 'bool': { 'should': [ { 'range': {TIMESTAMP_FIELD: {'...
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration): """ Yield events from stream starting after the event with id `start_id` until and including events with timestamp `end_time`. """ indices = self.index_manager.get_aliases(namespace, uuid_to_kronos_time(start_id), end_time) if not ...
ignore=[400, 404], allow_no_indices=True, ignore_unavailable=True) else: res = self.es.scroll(scroll_id, scroll='1m') if '_scroll_id' not in res: break scroll_id = res['_scroll_id'] hits = res.get('hits', {}).get('hits') if not hits: break for hit in hits: _id = TimeUUID(hit['_id'], descending=descending) if _id <= las...
def create_tables(self): """ create tables in database (if they don't already exist) """ cdir = os.path.dirname( os.path.realpath(__file__) ) # table schemas ------------------------------------- schema = os.path.join(cdir,"data","partsmaster.sql") if self.debug: print(self.hdr,"parts master schema is ",schema) self.po...
def parse_c_serialized(f): """ Reads in a binary file created by a C++ serializer (prob. MFC?) and returns tuples of (header name, data following the header). These are used by Thermo for *.CF and *.DXF files and by Agilent for new-style *.REG files. """ # TODO: rewrite to use re library f.seek(0) try: p_rec_type = Non...
rec_type except EOFError: rec_len = f.tell() - 6 - len(rec_type) - rec_off f.seek(rec_off) yield p_rec_type, f.read(rec_len)
def scan(self, t, dt=None, aggfunc=None): """ Returns the spectrum from a specific time or range of times. """ return self.data.scan(t, dt, aggfunc)
def _generate_storage_broker_lookup(): """Return dictionary of available storage brokers.""" storage_broker_lookup = dict() for entrypoint in iter_entry_points("dtool.storage_brokers"): StorageBroker = entrypoint.load() storage_broker_lookup[StorageBroker.key] = StorageBroker return storage_broker_lookup
def _get_storage_broker(uri, config_path): """Helper function to enable use lookup of appropriate storage brokers.""" uri = dtoolcore.utils.sanitise_uri(uri) storage_broker_lookup = _generate_storage_broker_lookup() parsed_uri = dtoolcore.utils.generous_parse_uri(uri) StorageBroker = storage_broker_lookup[parsed_uri.sc...
def _admin_metadata_from_uri(uri, config_path): """Helper function for getting admin metadata.""" uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) admin_metadata = storage_broker.get_admin_metadata() return admin_metadata
def _is_dataset(uri, config_path): """Helper function for determining if a URI is a dataset.""" uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) return storage_broker.has_admin_metadata()
def generate_admin_metadata(name, creator_username=None): """Return admin metadata as a dictionary.""" if not dtoolcore.utils.name_is_valid(name): raise(DtoolCoreInvalidNameError()) if creator_username is None: creator_username = dtoolcore.utils.getuser() datetime_obj = datetime.datetime.utcnow() admin_metadata = { "uu...
def _generate_uri(admin_metadata, base_uri): """Return dataset URI. :param admin_metadata: dataset administrative metadata :param base_uri: base URI from which to derive dataset URI :returns: dataset URI """ name = admin_metadata["name"] uuid = admin_metadata["uuid"] # storage_broker_lookup = _generate_storage_broker_l...
def generate_proto_dataset(admin_metadata, base_uri, config_path=None): """Return :class:`dtoolcore.ProtoDataSet` instance. :param admin_metadata: dataset administrative metadata :param base_uri: base URI for proto dataset :param config_path: path to dtool configuration file """ uri = _generate_uri(admin_metadata, base...
def copy(src_uri, dest_base_uri, config_path=None, progressbar=None): """Copy a dataset to another location. :param src_uri: URI of dataset to be copied :param dest_base_uri: base of URI for copy target :param config_path: path to dtool configuration file :returns: URI of new dataset """ dataset = DataSet.from_uri(src_...
def copy_resume(src_uri, dest_base_uri, config_path=None, progressbar=None): """Resume coping a dataset to another location. Items that have been copied to the destination and have the same size as in the source dataset are skipped. All other items are copied across and the dataset is frozen. :param src_uri: URI of dat...
def update_name(self, new_name): """Update the name of the proto dataset. :param new_name: the new name of the proto dataset """ if not dtoolcore.utils.name_is_valid(new_name): raise(DtoolCoreInvalidNameError()) self._admin_metadata['name'] = new_name if self._storage_broker.has_admin_metadata(): self._storage_broker.p...
def _put_overlay(self, overlay_name, overlay): """Store overlay so that it is accessible by the given name. :param overlay_name: name of the overlay :param overlay: overlay must be a dictionary where the keys are identifiers in the dataset :raises: TypeError if the overlay is not a dictionary, ValueError if identifiers...
def generate_manifest(self, progressbar=None): """Return manifest generated from knowledge about contents.""" items = dict() if progressbar: progressbar.label = "Generating manifest" for handle in self._storage_broker.iter_item_handles(): key = dtoolcore.utils.generate_identifier(handle) value = self._storage_broker.it...
def _manifest(self): """Return manifest content.""" if self._manifest_cache is None: self._manifest_cache = self._storage_broker.get_manifest() return self._manifest_cache