code stringlengths 1 18.2k |
|---|
def isValidExp(self, exp): ''' Method to verify if a given expression is correct just in case the used regular expression needs additional processing to verify this fact.$ This method will be overwritten when necessary. :param exp: Expression to verify. :return: True | False ''' # order of the letters depending on whic... |
# verifying if it is a 7-length number number = int(exp[0:6]) except: # not a valid number pass if l == order[number%23]: return True else: return False |
def is_valid(self): """ Checks the feature list product spec against. Checks if all mandartory features are contained; Checks that all "never" features are not contained :return: boolean """ for spec in self.product_specs: for feature in spec.get('mandatory', []): if feature.replace('__', '.') not in self.feature_list:... |
def _read(self, spec_path, product_name): """ Reads the spec files and extracts the concrete product spec. :param spec_path: :param product_name: :return: """ matches = [] with codecs.open(spec_path, 'r') as f: for entry in json.loads(f.read()): if product_name in entry.get('products'): matches.append(entry) return mat... |
def connectivity_map(dset,prefix,x,y,z,radius=2): '''Will perform connectivity analysis on ``dset`` using seed point ``(x,y,z)`` (in RAI order) with a sphere of radius ``radius``. Does not perform any preprocessing of ``dset``. This should be already motion corrected, noise-regressed, residualized, etc.''' seed_series ... |
def extract_feature_base(dbpath, folder_path, set_object, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Generic function which extracts a feature and stores it in the database Parameters ---------- dbpath : string, path to SQLite database file folder_path : string, path to folder w... |
data is being extracted ever verbose steps (for example, verbose=500 will print 0, 500, 1000 etc.). default value: 0 add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, opt... |
else: i.features = {extractor_name: extractor(join(folder_path, i.path), add_args)} if verbose > 0: if a % verbose == 0: print a a += 1 elif (extractor_name not in tmp_object.features) or force_extraction is True: for i in session.query(set_object).order_by(set_object.id): if add_args is None: i.features[extractor_name... |
def return_features_base(dbpath, set_object, names): """ Generic function which returns a list of extracted features from the database Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database names : list of strings, a list of f... |
return_list.append(row_list[:]) else: for i in session.query(set_object).order_by(set_object.id): row_list = [] for feature in i.features: if feature in names: row_list.append(i.features[feature]) return_list.append(row_list[:]) return return_list |
def return_features_numpy_base(dbpath, set_object, points_amt, names): """ Generic function which returns a 2d numpy array of extracted features Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database points_amt : int, number o... |
= session.query(set_object).get(1) if names == 'all': columns_amt = 0 for feature in tmp_object.features: if type(tmp_object.features[feature]) is np.ndarray: columns_amt += tmp_object.features[feature].shape[0] else: columns_amt += 1 return_array = np.zeros([points_amt, columns_amt]) for i in enumerate(session.query(s... |
return_array[i[0], counter] = feature_val counter += 1 session.close() return return_array |
def return_real_id_base(dbpath, set_object): """ Generic function which returns a list of real_id's Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database Returns ------- return_list : list of real_id values for the dataset (a... |
def return_feature_list_base(dbpath, set_object): """ Generic function which returns a list of the names of all available features Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database Returns ------- return_list : list of st... |
def return_feature_list_numpy_base(dbpath, set_object): """ Generic function which returns a list of tuples containing, each containing the name of the feature and the length of the corresponding 1d numpy array of the feature (or length of the list) Parameters ---------- dbpath : string, path to SQLite database file se... |
def copy_features_base(dbpath_origin, dbpath_destination, set_object, force_copy=False): """ Generic function which copies features from one database to another (base object should be of the same type) Parameters ---------- dbpath_origin : string, path to SQLite database file from which the features will be copied dbpa... |
in i.features: if dest_obj.features is not None: dest_obj.features[feature] = i.features[feature] else: dest_obj.features = {feature: i.features[feature]} else: for i in session_origin.query(set_object).order_by(set_object.id): dest_obj = session_destination.query(set_object).get(i.id) for feature in i.features: if des... |
def return_single_real_id_base(dbpath, set_object, object_id): """ Generic function which returns a real_id string of an object specified by the object_id Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database object_id : int,... |
def return_single_path_base(dbpath, set_object, object_id): """ Generic function which returns a path (path is relative to the path_to_set stored in the database) of an object specified by the object_id Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) ... |
def return_single_features_base(dbpath, set_object, object_id): """ Generic function which returns the features of an object specified by the object_id Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database object_id : int, id... |
def return_single_convert_numpy_base(dbpath, folder_path, set_object, object_id, converter, add_args=None): """ Generic function which converts an object specified by the object_id into a numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- dbpath : string, path to... |
= create_engine('sqlite:////' + dbpath) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(set_object).get(object_id) session.close() if add_args is None: return converter(join(folder_path, tmp_object.path)) else: return converter(join(folder_path, tmp_object.path), add_args) |
def return_multiple_convert_numpy_base(dbpath, folder_path, set_object, start_id, end_id, converter, add_args=None): """ Generic function which converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters --... |
take only one input argument - the file path. default value: None Returns ------- result : 2-dimensional ndarray """ engine = create_engine('sqlite:////' + dbpath) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(set_object).get(start_id) if add_args is None: converted = converte... |
def dump_feature_base(dbpath, set_object, points_amt, feature_name, feature, force_extraction=True): """ Generic function which dumps a list of lists or ndarray of features into database (allows to copy features from a pre-existing .txt/.csv/.whatever file, for example) Parameters ---------- dbpath : string, path to SQ... |
raise errors.WrongSize(feature_name) else: if tmp_object.features is None: for i in session.query(set_object).order_by(set_object.id): i.features = {feature_name: feature_name[a, :]} a += 1 elif (feature_name not in tmp_object.features) or force_extraction is True: for i in session.query(set_object).order_by(set_object... |
def delete_feature_base(dbpath, set_object, name): """ Generic function which deletes a feature from a database Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database name : string, name of the feature to be deleted Returns --... |
def prepopulate(self): """ Creates a database file (if it doesn't exist, writes each data point's path, real_id into it) Parameters ---------- self Returns ------- None """ if self._prepopulated is False: engine = create_engine('sqlite:////' + self.dbpath) self._db_base.metadata.create_all(engine) self._prepopulated = ... |
def extract_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Extracts a feature and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point and *args as parameters and returns a feature force_extraction : boolean, if Tru... |
(it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return extract_feature_base(self.dbpath, self.path_to... |
def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Extracts a feature which may be dependent on other features and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point, a dictionary of all ... |
file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None """ if self._prepopulated is False: raise errors.Emp... |
def return_features(self, names='all'): """ Returns a list of extracted features from the database Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', the all features will be returned, default value: 'all' Returns ------- A list of list... |
def return_features_numpy(self, names='all'): """ Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default value: 'all' Returns ------- A numpy array of fea... |
def return_real_id(self): """ Returns a list of real_id's Parameters ---------- Returns ------- A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix) """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_real_id_base(self.dbpath, self.... |
def copy_features(self, dbpath_origin, force_copy=False): """ Copies features from one database to another (base object should be of the same type) Parameters ---------- dbpath_origin : string, path to SQLite database file from which the features will be copied force_copy : boolean, if True - will overwrite features wi... |
def return_single_convert_numpy(self, object_id, converter, add_args=None): """ Converts an object specified by the object_id into a numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- object_id : int, id of object in database converter : function, which takes the... |
def return_multiple_convert_numpy(self, start_id, end_id, converter, add_args=None): """ Converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- start_id : the id of the first object to be co... |
if end_id == -1: end_id = self.points_amt return return_multiple_convert_numpy_base(self.dbpath, self.path_to_set, self._set_object, start_id, end_id, converter, add_args) |
def dump_feature(self, feature_name, feature, force_extraction=True): """ Dumps a list of lists or ndarray of features into database (allows to copy features from a pre-existing .txt/.csv/.whatever file, for example) Parameters ---------- feature : list of lists or ndarray, contains the data to be written to the databa... |
def return_labels(self, original=False): """ Returns the labels of the dataset Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A list of lists, each 'inside list' corresponds to a single data... |
def return_labels_numpy(self, original=False): """ Returns a 2d numpy array of labels Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A numpy array of labels, each row corresponds to a single... |
def return_single_labels(self, object_id): """ Returns all labels for an object specified by the object_id Parameters ---------- object_id : int, id of object in database Returns ------- result : list of labels """ engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl ... |
def path_in_cache(self, filename, metahash): """Generates the path to a file in the mh cache. The generated path does not imply the file's existence! Args: filename: Filename relative to buildroot rule: A targets.SomeBuildRule object metahash: hash object """ cpath = self._genpath(filename, metahash) if os.path.exists(... |
def _genpath(self, filename, mhash): """Generate the path to a file in the cache. Does not check to see if the file exists. Just constructs the path where it should be. """ mhash = mhash.hexdigest() return os.path.join(self.mh_cachedir, mhash[0:2], mhash[2:4], mhash, filename) |
def putfile(self, filepath, buildroot, metahash): """Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object """ def gen_obj_path(filename): filehash = util.hash_file(filepath).hexdigest() return filehash, os.path.jo... |
the build environment compared to the ' 'previous build.') log.warn(' 2. This file has a timestamp or other build-time ' 'related data encoded into it, which will always ' 'cause the checksum to differ when built.') log.warn(' 3. Everything is terrible and nothing works.') os.unlink(incachepath) if not os.path.exists(i... |
def in_cache(self, objpath, metahash): """Returns true if object is cached. Args: objpath: Filename relative to buildroot. metahash: hash object """ try: self.path_in_cache(objpath, metahash) return True except CacheMiss: return False |
def get_obj(self, objpath, metahash, dst_path): """Get object from cache, write it to dst_path. Args: objpath: filename relative to buildroot (example: mini-boot/blahblah/somefile.bin) metahash: metahash. See targets/base.py dst_path: Absolute path where the file should be written. Raises: CacheMiss: if the item is not... |
def _get_link(self, peer): """ Returns a link to the given peer :return: A Link object :raise ValueError: Unknown peer """ assert isinstance(peer, beans.Peer) # Look for a link to the peer, using routers for router in self._routers: link = router.get_link(peer) if link: return link # Not found raise ValueError("No link... |
def send(self, peer_id, message): """ Synchronously sends a message :param peer_id: UUID of a peer :param message: Message to send to the peer :raise KeyError: Unknown peer :raise ValueError: No link to the peer """ assert isinstance(message, beans.RawMessage) # Get peer description (raises KeyError) peer = self._direc... |
def str_to_classes_in_namespaces_converter( template_for_namespace="%(name)s", list_splitter_fn=_default_list_splitter, class_extractor=_default_class_extractor, name_of_class_option='qualified_class_name', instantiate_classes=False, ): """ parameters: template_for_namespace - a template for the names of the namespaces... |
for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated.""" if isinstance(class_list_str, basestring): class_str_list = list_splitter_fn(class_list_str) else: raise TypeError('must be derivative of a basestring') # ==========================... |
class_list_str.replace('\n', '\\n') # for each class in the class list class_list = [] for namespace_index, class_list_element in enumerate( class_str_list ): a_class = class_converter( class_extractor(class_list_element) ) # figure out the Namespace name namespace_name_dict = { 'name': a_class.__name__, 'index': names... |
def web_services_from_str( list_splitter_fn=ujson.loads, ): """ parameters: list_splitter_fn - a function that will take the json compatible string rerpesenting a list of mappings. """ # ------------------------------------------------------------------------- def class_list_converter(collector_services_str): """This f... |
block of # code is actually adding class level attributes to this new class # 1st requirement for configman required_config = Namespace() # to help the programmer know what Namespaces we added subordinate_namespace_names = [] # for display original_input = collector_services_str.replace('\n', '\\n') # for each class in... |
turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option""" return "'%s'" % cls.original_input return InnerClassList # result of class_list_converter return class_list_converter |
def change_default( kls, key, new_default, new_converter=None, new_reference_value=None, ): """return a new configman Option object that is a copy of an existing one, giving the new one a different default value""" an_option = kls.get_required_config()[key].copy() an_option.default = new_default if new_converter: an_op... |
def get_target(self): """ Reads the android target based on project.properties file. Returns A string containing the project target (android-23 being the default if none is found) """ with open('%s/project.properties' % self.path) as f: for line in f.readlines(): matches = re.findall(r'^target=(.*)', line) if len(match... |
def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name='app'): """ Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param k... |
def prepare(self): """ Prepares the android project to the build process. Prepare the ant project to be built """ cmd = [ 'android', 'update', 'project', '-p', self.path, '-t', self.get_target() ] self.run_cmd(cmd, 'prepare') |
def lookup(self, name, host_override=None): """ Looks up a name from the DNSChain server. Throws exception if the data is not valid JSON or if the namecoin entry does not exist in the blockchain. @param name: The name to lookup, e.g. 'id/dionyziz', note this $NAMESPACE/$NAME format is not guaranteed. Additionally the c... |
data |
def cache_function(length): """ Caches a function, using the function itself as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put in a... |
func in cache: return value else: # This will set a temporary value while ``func`` is being # processed. When using threads, this is vital, as otherwise # the function can be called several times before it finishes # and is put into the cache. class MethodNotFinishedError(Exception): pass cache.set(func, MethodNotFinis... |
def _get_formatted_feature_dependencies(data): """ Takes the format of the feature_order.json in featuremodel pool. Creates a list of conditions in the following format: ] dict( name='django_productline.features.admin', subject='django_productline', ctype='after' ) ] :param data: :return: list """ conditions = list() f... |
def _get_condition_instances(data): """ Returns a list of OrderingCondition instances created from the passed data structure. The structure should be a list of dicts containing the necessary information: [ dict( name='featureA', subject='featureB', ctype='after' ), ] Example says: featureA needs to be after featureB. :... |
def angularFrontendAppDir(self) -> str: """ Angular Frontend Dir This directory will be linked into the angular app when it is compiled. :return: The absolute path of the Angular2 app directory. """ relDir = self._packageCfg.config.plugin.title(require_string) dir = os.path.join(self._pluginRoot, relDir) if not os.path... |
def join(self, path): """ Similar to :func:`os.path.join` but returns a storage object instead. :param str path: path to join on to this object's URI :returns: a storage object :rtype: BaseURI """ return self.parse_uri(urlparse(os.path.join(str(self), path)), storage_args=self.storage_args) |
def exists(self): """Uses ``HEAD`` requests for efficiency.""" try: self.s3_object.load() return True except botocore.exceptions.ClientError: return False |
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.s3_object.Bucket() prefix = self.s3_object.key if not prefix.endswith('/'): prefix += '/' for obj in bucket.objects.filter(Delimiter='/', Prefix=prefix): yield 's3://{}/{}'.format(o... |
def put_content(self, content): """ The default content type is set to ``application/octet-stream`` and content encoding set to ``None``. """ self.blob.content_encoding = self.content_encoding self.blob.metadata = self.metadata return self.blob.upload_from_string(content, content_type=self.content_type) |
def exists(self): """Uses ``HEAD`` requests for efficiency.""" try: self.blob.reload() return True except google.cloud.exceptions.NotFound: return False |
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.blob.bucket prefix = self.blob.name if not prefix.endswith('/'): prefix += '/' for blob in bucket.list_blobs(prefix=prefix, delimiter='/'): yield 'gs://{}/{}'.format(blob.bucket.nam... |
def put_content(self, content): """ Makes a ``PUT`` request with the content in the body. :raise: An :exc:`requests.RequestException` if it is not 2xx. """ r = requests.request(self.method if self.method else 'PUT', self.url, data=content, **self.storage_args) if self.raise_for_status: r.raise_for_status() |
def dir_exists(self): """ Makes a ``HEAD`` requests to the URI. :returns: ``True`` if status code is 2xx. """ r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args) try: r.raise_for_status() except Exception: return False return True |
def put_content(self, content): """ Publishes a message straight to SNS. :param bytes content: raw bytes content to publish, will decode to ``UTF-8`` if string is detected """ if not isinstance(content, str): content = content.decode('utf-8') self.topic.publish(Message=content, **self.storage_args) |
def _string2Duration(text): """ CONVERT SIMPLE <float><type> TO A DURATION OBJECT """ if text == "" or text == "zero": return ZERO amount, interval = re.match(r"([\d\.]*)(.*)", text).groups() amount = int(amount) if amount else 1 if MILLI_VALUES[interval] == None: from mo_logs import Log Log.error( "{{interval|quote}} ... |
def registerExitCall(): r"""Registers an exit call to start the core. The core would be started after the main module is loaded. Ec would be exited from the core. """ if state.isExitHooked: return state.isExitHooked = True from atexit import register register(core.start) |
def fisher(x,k): """Fisher distribution """ return k/(2*np.sinh(k)) * np.exp(k*np.cos(x))*np.sin(x) |
def sin_fisher(y,k): """pdf for y=sin(x) if x is fisher-distributed with parameter k. Support is [0,1). """ return 1/np.sqrt(1-y**2) * (k/(np.sinh(k)) * y * (np.cosh(k*np.sqrt(1-y**2)))) |
def cosi_pdf(z,k=1): """Equation (11) of Morton & Winn (2014) """ return 2*k/(np.pi*np.sinh(k)) * quad(cosi_integrand,z,1,args=(k,z))[0] |
def generate_veq(R=1.3, dR=0.1, Prot=6, dProt=0.1,nsamples=1e4,plot=False, R_samples=None,Prot_samples=None): """ Returns the mean and std equatorial velocity given R,dR,Prot,dProt Assumes all distributions are normal. This will be used mainly for testing purposes; I can use MC-generated v_eq distributions when we go f... |
def like_cosi(cosi,vsini_dist,veq_dist,vgrid=None): """likelihood of Data (vsini_dist, veq_dist) given cosi """ sini = np.sqrt(1-cosi**2) def integrand(v): #return vsini_dist(v)*veq_dist(v/sini) return vsini_dist(v*sini)*veq_dist(v) if vgrid is None: return quad(integrand,0,np.inf)[0] else: return np.trapz(integrand(vg... |
def cosi_posterior(vsini_dist,veq_dist,vgrid=None,npts=100,vgrid_pts=1000): """returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini) """ if vgrid is None: vgrid = np.linspace(min(veq_dist.ppf(0.001),vsini_dist.ppf(0.001)), max(veq_dist.ppf(0.999),vsini_dist.ppf(0.999)), vgrid_pts) logging... |
def sample_posterior(x,post,nsamples=1): """ Returns nsamples from a tabulated posterior (not necessarily normalized) """ cdf = post.cumsum() cdf /= cdf.max() u = rand.random(size=nsamples) inds = np.digitize(u,cdf) return x[inds] |
def v_posts_from_dataframe(df,N=1e4,alpha=0.23,l0=20,sigl=20): """ names: Prot, e_Prot, R, e_R, vsini, e_vsini """ vsini_posts = [] veq_posts = [] if 'ep_R' in df: for R,dR_p,dR_m,P,dP,v,dv in zip(df['R'],df['ep_R'],df['em_R'], df['Prot'],df['e_Prot'], df['vsini'],df['e_vsini']): vsini_posts.append(stats.norm(v,dv)) if... |
def post_process(self, paths, dry_run=False, **options): """ Overridden to work around https://code.djangoproject.com/ticket/19111 """ with post_process_error_counter(self): with patched_name_fn(self, 'hashed_name', 'hashed name'): with patched_name_fn(self, 'url', 'url'): for result in super(LaxPostProcessorMixin, sel... |
def post_process(self, paths, dry_run=False, **options): """ Overridden to allow some files to be excluded (using ``postprocess_exclusions``) """ if self.postprocess_exclusions: paths = dict((k, v) for k, v in paths.items() if not self.exclude_file(k)) return super(CachedFilesMixin, self).post_process(paths, dry_run, *... |
def get_paths(self): ''' get list of module paths ''' # guess site package dir of virtualenv (system dependent) venv_site_packages = '%s/lib/site-packages' % self.venv_dir if not os.path.isdir(venv_site_packages): venv_site_packages_glob = glob.glob('%s/lib/*/site-packages' % self.venv_dir) if len(venv_site_packages_gl... |
def create_virtualenv(venv_dir, use_venv_module=True): """ creates a new virtualenv in venv_dir By default, the built-in venv module is used. On older versions of python, you may set use_venv_module to False to use virtualenv """ if not use_venv_module: try: check_call(['virtualenv', venv_dir, '--no-site-packages']) ex... |
def data_dirpath(task=None, **kwargs): """Get the path of the corresponding data directory. Parameters ---------- task : str, optional The task for which datasets in the desired directory are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Ext... |
subdir_name) os.makedirs(path, exist_ok=True) return path |
def dataset_dirpath(dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-agnostic directory path is returned.... |
Returns ------- str The path to the desired dataset file. """ dataset_dir_path = data_dirpath(task=task, **kwargs) if dataset_name: dataset_dir_name = _snail_case(dataset_name) dataset_dir_path = os.path.join(dataset_dir_path, dataset_dir_name) os.makedirs(dataset_dir_path, exist_ok=True) return dataset_dir_path |
def dataset_filepath(filename, dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given... |
and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file. """ dataset_dir_path = dataset_dirpath( dataset_name=dataset_name, task=task, **kwargs) return os.path.join(dataset_dir_path, filename) |
def async_atomic(on_exception=None, raise_exception=True, **kwargs): ''' first argument will be a conn object :param func: :return: ''' if not raise_exception and not on_exception: async def default_on_exception(exc): resp_dict = {} resp_dict['status'] = type(exc) resp_dict['message'] = str(exc) return resp_dict on_exc... |
await on_exception(e) return wrapped return decorator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.