code stringlengths 1 18.2k |
|---|
contig if currentlength >= genome_length_dict[file_name] * 0.5: l50_dict[file_name] = currentcontig break return l50_dict |
def find_l75(contig_lengths_dict, genome_length_dict): """ Calculate the L50 for each strain. L75 is defined as the number of contigs required to achieve the N75 :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :param genome_length_dict: dictionary of strain name: total g... |
def find_l90(contig_lengths_dict, genome_length_dict): """ Calculate the L90 for each strain. L90 is defined as the number of contigs required to achieve the N90 :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :param genome_length_dict: dictionary of strain name: total g... |
contig if currentlength >= genome_length_dict[file_name] * 0.9: l90_dict[file_name] = currentcontig break return l90_dict |
def predict_orfs(file_dict, num_threads=1): """ Use prodigal to predict the number of open reading frames (ORFs) in each strain :param file_dict: dictionary of strain name: /sequencepath/strain_name.extension :param num_threads: number of threads to use in the pool of prodigal processes :return: orf_file_dict: dictiona... |
# Setup the multiprocessing pool. pool = multiprocessing.Pool(processes=num_threads) pool.map(run_prodigal, prodigallist) pool.close() pool.join() return orf_file_dict |
def find_orf_distribution(orf_file_dict): """ Parse the prodigal outputs to determine the frequency of ORF size ranges for each strain :param orf_file_dict: dictionary of strain name: /sequencepath/prodigal results.sco :return: orf_dist_dict: dictionary of strain name: tuple of ORF size range distribution frequencies "... |
stop: 920, # direction: - contig, start, stop, direction = line.split('_') # The size of the ORF is the end position minus the start position e.g. 920 - 345 = 575 size = int(stop) - int(start) # Increment the total number of ORFs before binning based on ORF size total_orfs += 1 # Increment the appropriate integer based... |
def reporter(gc_dict, contig_dist_dict, longest_contig_dict, genome_length_dict, num_contigs_dict, n50_dict, n75_dict, n90_dict, l50_dict, l75_dict, l90_dict, orf_dist_dict, genus_dict, sequencepath): """ Create a report of all the extracted features :param gc_dict: dictionary of strain name: GC% :param contig_dist_dic... |
:param sequencepath: path of folder containing FASTA genomes """ # Initialise string with header information data = 'SampleName,TotalLength,NumContigs,LongestContig,Contigs>1000000,Contigs>500000,Contigs>100000,' \ 'Contigs>50000,Contigs>10000,Contigs>5000,Contigs<5000,TotalORFs,ORFs>3000,ORFs>1000,ORFs>500,' \ 'ORFs<5... |
def cli(sequencepath, report, refseq_database): """ Pass command line arguments to, and run the feature extraction functions """ main(sequencepath, report, refseq_database, num_threads=multiprocessing.cpu_count()) |
def grouplabelencode(data, mapping, nacode=None, nastate=False): """Encode data array with grouped labels Parameters: ----------- data : list array with labels mapping : dict, list of list the index of each element is used as encoding. Each element is a single label (str) or list of labels that are mapped to the encodi... |
dict): m = list(mapping.values()) e = list(mapping.keys()) else: raise Exception("'data' must be list-of-list or dict.") # Loop over 'data' array return grouplabelencode_loop(data, m, e, nacode=nacode) |
def get_csv_col_headers(rows, row_headers_count_value=0): """ Retrieve csv column headers """ count = 0 if rows: for row in rows: if exclude_empty_values(row[:row_headers_count_value]): break count += 1 if len(rows) == count: count = 1 # by default return [r[row_headers_count_value:] for r in rows[:count]] |
def populate_csv_headers(rows, partial_headers, column_headers_count=1): """ Populate csv rows headers when are empty, extending the superior or upper headers. """ result = [''] * (len(rows) - column_headers_count) for i_index in range(0, len(partial_headers)): for k_index in range(0, len(partial_headers[i_index])): # ... |
def get_row_headers(rows, row_headers_count_value=0, column_headers_count=1): """ Return row headers. Assume that by default it has one column header. Assume that there is only one father row header. """ # TODO: REFACTOR ALGORITHM NEEDED partial_headers = [] if row_headers_count_value: # Take partial data for k_index i... |
def retrieve_csv_data(rows, row_header=0, column_header=0, limit_column=0): """ Take the data from the rows. """ return [row[row_header:limit_column] for row in rows[column_header:]] |
def csv_tolist(path_to_file, **kwargs): """ Parse the csv file to a list of rows. """ result = [] encoding = kwargs.get('encoding', 'utf-8') delimiter = kwargs.get('delimiter', ',') dialect = kwargs.get('dialect', csv.excel) _, _ext = path_to_file.split('.', 1) try: file = codecs.open(path_to_file, 'r', encoding) items... |
def excel_todictlist(path_to_file, **kwargs): """ Parse excel file to a dict list of sheets, rows. """ result = collections.OrderedDict() encoding = kwargs.get('encoding', 'utf-8') formatting_info = '.xlsx' not in path_to_file count = 0 with xlrd.open_workbook( path_to_file, encoding_override=encoding, formatting_info=... |
def search_mergedcell_value(xl_sheet, merged_range): """ Search for a value in merged_range cells. """ for search_row_idx in range(merged_range[0], merged_range[1]): for search_col_idx in range(merged_range[2], merged_range[3]): if xl_sheet.cell(search_row_idx, search_col_idx).value: return xl_sheet.cell(search_row_idx... |
def is_merged(sheet, row, column): """ Check if a row, column cell is a merged cell """ for cell_range in sheet.merged_cells: row_low, row_high, column_low, column_high = cell_range if (row in range(row_low, row_high)) and \ (column in range(column_low, column_high)): # TODO: IS NECESARY THIS IF? if ((column_high - col... |
def populate_headers(headers): """ Concatenate headers with subheaders """ result = [''] * len(headers[0]) values = [''] * len(headers) for k_index in range(0, len(headers)): for i_index in range(0, len(headers[k_index])): if headers[k_index][i_index]: values[k_index] = normalizer( str(headers[k_index][i_index])) # pas... |
def row_csv_limiter(rows, limits=None): """ Limit row passing a value or detect limits making the best effort. """ limits = [None, None] if limits is None else limits if len(exclude_empty_values(limits)) == 2: upper_limit = limits[0] lower_limit = limits[1] elif len(exclude_empty_values(limits)) == 1: upper_limit = lim... |
def row_iter_limiter(rows, begin_row, way, c_value): """ Alghoritm to detect row limits when row have more that one column. Depending the init params find from the begin or behind. NOT SURE THAT IT WORKS WELL.. """ limit = None for index in range(begin_row, len(rows)): if not len(exclude_empty_values(rows[way * index])... |
def csv_row_cleaner(rows): """ Clean row checking: - Not empty row. - >=1 element different in a row. - row allready in cleaned row result. """ result = [] for row in rows: # check not empty row check_empty = len(exclude_empty_values(row)) > 1 # check more or eq than 1 unique element in row check_set = len(set(exclude_... |
def csv_column_cleaner(rows): """ clean csv columns parsed omitting empty/dirty rows. """ # check columns if there was empty columns result = [[] for x in range(0, len(rows))] for i_index in range(0, len(rows[0])): partial_values = [] for x_row in rows: partial_values.append( x_row[i_index] if len(x_row) > i_index else... |
def csv_dict_format(csv_data, c_headers=None, r_headers=None): """ Format csv rows parsed to Dict. """ # format dict if has row_headers if r_headers: result = {} for k_index in range(0, len(csv_data)): if r_headers[k_index]: result[r_headers[k_index]] = collections.OrderedDict( zip(c_headers, csv_data[k_index])) # form... |
def csv_array_clean_format(csv_data, c_headers=None, r_headers=None): """ Format csv rows parsed to Array clean format. """ result = [] real_num_header = len(force_list(r_headers[0])) if r_headers else 0 result.append([""] * real_num_header + c_headers) for k_index in range(0, len(csv_data)): if r_headers: result.appen... |
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs): """ Format csv rows parsed to Dict or Array """ result = None c_headers = [] if c_headers is None else c_headers r_headers = [] if r_headers is None else r_headers rows = [] if rows is None else rows result_format = kwargs.get('result_format... |
def csv_to_dict(csv_filepath, **kwargs): """ Turn csv into dict. Args: :csv_filepath: path to csv file to turn into dict. :limits: path to csv file to turn into dict """ callbacks = {'to_list': csv_tolist, 'row_csv_limiter': row_csv_limiter, 'csv_row_cleaner': csv_row_cleaner, 'row_headers_count': row_headers_count, 'g... |
format colum_headers c_headers_dirty = callbacks.get('populate_headers')( c_headers_raw) if len(c_headers_raw) > 1 else c_headers_raw[0] # Clean csv column headers of empty values. c_headers = callbacks.get('csv_column_header_cleaner')(c_headers_dirty) # take data csv_data = callbacks.get('retrieve_csv_data')( rows, co... |
def excel_to_dict(excel_filepath, encapsulate_filepath=False, **kwargs): """ Turn excel into dict. Args: :excel_filepath: path to excel file to turn into dict. :limits: path to csv file to turn into dict """ result = {} try: callbacks = {'to_dictlist': excel_todictlist} # Default callback callbacks.update(kwargs.get('a... |
def notify( self, force_notify=None, use_email=None, use_sms=None, email_body_template=None, **kwargs, ): """Notify / send an email and/or SMS. Main entry point. This notification class (me) knows from whom and to whom the notifications will be sent. See signals and kwargs are: * history_instance * instance * user """ ... |
def _notify_on_condition(self, test_message=None, **kwargs): """Returns the value of `notify_on_condition` or False. """ if test_message: return True else: return self.enabled and self.notify_on_condition(**kwargs) |
def enabled(self): """Returns True if this notification is enabled based on the value of Notification model instance. Note: Notification names/display_names are persisted in the "Notification" model where each mode instance can be flagged as enabled or not, and are selected/subscribed to by each user in their user prof... |
def notification_model(self): """Returns the Notification 'model' instance associated with this notification. """ NotificationModel = django_apps.get_model("edc_notification.notification") # trigger exception if this class is not registered. site_notifications.get(self.name) try: notification_model = NotificationModel.... |
def get_template_options(self, instance=None, test_message=None, **kwargs): """Returns a dictionary of message template options. Extend using `extra_template_options`. """ protocol_name = django_apps.get_app_config("edc_protocol").protocol_name test_message = test_message or self.test_message template_options = dict( n... |
def sms_recipients(self): """Returns a list of recipients subscribed to receive SMS's for this "notifications" class. See also: edc_auth.UserProfile. """ sms_recipients = [] UserProfile = django_apps.get_model("edc_auth.UserProfile") for user_profile in UserProfile.objects.filter( user__is_active=True, user__is_staff=T... |
def sign_filter_permissions(permissions): """ Return a compressed, signed dump of the json blob. This function expects a json blob that is a dictionary containing model dotted names as keys. Those keys each have a value that is a list of dictionaries, each of which contains the keys 'filters' and 'actions': The key 'fi... |
def unsign_filters_and_actions(sign, dotted_model_name): """Return the list of filters and actions for dotted_model_name.""" permissions = signing.loads(sign) return permissions.get(dotted_model_name, []) |
def equal(obj1, obj2): """Calculate equality between two (Comparable) objects.""" Comparable.log(obj1, obj2, '==') equality = obj1.equality(obj2) Comparable.log(obj1, obj2, '==', result=equality) return equality |
def similar(obj1, obj2): """Calculate similarity between two (Comparable) objects.""" Comparable.log(obj1, obj2, '%') similarity = obj1.similarity(obj2) Comparable.log(obj1, obj2, '%', result=similarity) return similarity |
def _repr(self, *args, **kwargs): """Return a __repr__ string from the arguments provided to __init__. @param args: list of arguments to __init__ @param kwargs: dictionary of keyword arguments to __init__ @return: __repr__ string """ # Remove unnecessary empty keywords arguments and sort the arguments kwargs = {k: v fo... |
def equality(self, other): """Compare two objects for equality. @param self: first object to compare @param other: second object to compare @return: boolean result of comparison """ # Compare specified attributes for equality cname = self.__class__.__name__ for aname in self.attributes: try: attr1 = getattr(self, aname... |
def similarity(self, other): """Compare two objects for similarity. @param self: first object to compare @param other: second object to compare @return: L{Similarity} result of comparison """ sim = self.Similarity() total = 0.0 # Calculate similarity ratio for each attribute cname = self.__class__.__name__ for aname, w... |
attr2, '%', cname=cname, aname=aname, result=attr_sim) # Add the similarity to the total sim += attr_sim * weight total += weight # Scale the similarity so the total is 1.0 if total: sim *= (1.0 / total) return sim |
def Similarity(self, value=None): # pylint: disable=C0103 """Constructor for new default Similarities.""" if value is None: value = 0.0 return Similarity(value, threshold=self.threshold) |
def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913 """Log the objects being compared and the result. When no result object is specified, subsequence calls will have an increased indentation level. The indentation level is decreased once a result object is provided. @param obj1: first... |
= fmt.format(o1=repr(obj1), o2=repr(obj2), c=cname, a=aname, sym=sym, r=result) logging.info(msg) |
def translate_path(self, dep_file, dep_rule): """Translate dep_file from dep_rule into this rule's output path.""" dst_base = dep_file.split(os.path.join(dep_rule.address.repo, dep_rule.address.path), 1)[-1] if self.params['strip_prefix']: dst_base = dep_file.split(self.params['strip_prefix'], 1)[-1] return os.path.joi... |
def output_files(self): """Returns the list of output files from this rule. Paths are generated from the outputs of this rule's dependencies, with their paths translated based on prefix and strip_prefix. Returned paths are relative to buildroot. """ for dep in self.subgraph.successors(self.address): dep_rule = self.sub... |
def new(ruletype, **kwargs): """Instantiate a new build rule based on kwargs. Appropriate args list varies with rule type. Minimum args required: [... fill this in ...] """ try: ruleclass = TYPE_MAP[ruletype] except KeyError: raise error.InvalidRule('Unrecognized rule type: %s' % ruletype) try: return ruleclass(**kwarg... |
def human_to_boolean(human): '''Convert a boolean string ('Yes' or 'No') to True or False. PARAMETERS ---------- human : list a list containing the "human" boolean string to be converted to a Python boolean object. If a non-list is passed, or if the list is empty, None will be returned. Only the first element of the li... |
def generate(self, data, *args, **kwargs): """ 根据传入的数据结构生成最终用于推送的文件字节字符串( :func:`bytes` ), MoEar会将其持久化并用于之后的推送任务 :param dict data: 待打包的数据结构 :return: 返回生成的书籍打包输出字节 :rtype: bytes """ with tempfile.TemporaryDirectory() as tmpdirname: self.options.setdefault('package_build_dir', tmpdirname) crawler = CrawlerScript(self.opt... |
def _countdown(seconds): """ Wait `seconds` counting down. """ for i in range(seconds, 0, -1): sys.stdout.write("%02d" % i) time.sleep(1) sys.stdout.write("\b\b") sys.stdout.flush() sys.stdout.flush() |
def export(self, location): """Export the Bazaar repository at the url to the destination location""" temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) if os.path.exists(location): # Remove the location to make sure Bazaar can export it correctly rmtree(location) try: call_subprocess([self.cmd, 'expo... |
def verify(self, email): """ Verify a single email address. :param str email: Email address to verify. :return: A VerifiedEmail object. """ resp = self._call(endpoint='single', data={'email': email}) return VerifiedEmail(email, resp['result']) |
def create_job(self, emails): """ Create a new bulk verification job for the list of emails. :param list emails: Email addresses to verify. :return: A Job object. """ resp = self._call(endpoint='bulk', data={'input_location': '1', 'input': '\n'.join(emails)}) return Job(resp['job_id']) |
def check_job(self, job_id): """ Check the status of a bulk verification job. :param int job_id: ID of a job to check the status of. :return: A JobStatus object. """ resp = self._call(endpoint='status', data={'job_id': job_id}) map = {'id': 'job_id', 'status': 'status_code', 'type': 'type_code'} job_status_args = {map.... |
def results(self, job_id): """ Yield the result of a completed bulk verification job. :param int job_id: ID of a job to retrieve the results for. :yields: The next VerifiedEmail objects. """ resp = self._call(endpoint='download', data={'job_id': job_id}) Row = namedtuple('Row', ['email', 'result_text_code']) for line i... |
def retrieve_job(self, job_id): """ Result of a completed bulk verification job. :param int job_id: ID of a job to retrieve the results for. :return: A list of VerifiedEmail objects. """ warnings.warn('Use results generator method instead of retrieve_job which returns a list', UserWarning) return list(self.results(job_... |
def account(self): """ Get the API account details like balance of credits. :return: An Account object. """ resp = self._call(endpoint='account') return Account(resp['credits'], resp['jobs_completed'], resp['jobs_processing']) |
def access_token(self): """ Retrieve and cache an access token to authenticate API calls. :return: An access token string. """ if self._cached_access_token is not None: return self._cached_access_token resp = self._request(endpoint='access_token', data={'grant_type': 'client_credentials', 'scope': 'basic user'}, auth=(... |
def _call(self, endpoint, data=None): """ Make an authorized API call to specified endpoint. :param str endpoint: API endpoint's relative URL, eg. `/account`. :param dict data: POST request data. :return: A dictionary or a string with response data. """ data = {} if data is None else data try: data['access_token'] = se... |
def _request(self, endpoint, data, auth=None): """ Make HTTP POST request to an API endpoint. :param str endpoint: API endpoint's relative URL, eg. `/account`. :param dict data: POST request data. :param tuple auth: HTTP basic auth credentials. :return: A dictionary or a string with response data. """ url = '{}/{}'.for... |
def _handle_response(response): """ Handle the response and possible failures. :param Response response: Response data. :return: A dictionary or a string with response data. :raises: NeverBounceAPIError if the API call fails. """ if not response.ok: raise NeverBounceAPIError(response) if response.headers.get('Content-T... |
def post_process(table, post_processors): """Applies the list of post processing methods if any""" table_result = table for processor in post_processors: table_result = processor(table_result) return table_result |
def describe(cls, full=False): """Prints a description of the table based on the provided documentation and post processors""" divider_double = "=" * 80 divider_single = "-" * 80 description = cls.__doc__ message = [] message.append(divider_double) message.append(cls.__name__ + ':') message.append(description) if full ... |
def describe_processors(cls): """List all postprocessors and their description""" # TODO: Add dependencies to this dictionary for processor in cls.post_processors(cls): yield {'name': processor.__name__, 'description': processor.__doc__, 'processor': processor} |
def dependencies(cls): """Returns a list of all dependent tables, in the order they are defined. Add new dependencies for source and every post proecssor like this:: source.dependencies = [PersonalData] some_post_processor.dependencies = [SomeOtherTable, AnotherTable] `some_post_processor.dependencies` needs to be plac... |
def get_settings_list(self): """The settings list used for building the cache id.""" return [ self.source, self.output, self.kwargs, self.post_processors, ] |
def get_hash(self): """Retruns a hash based on the the current table code and kwargs. Also changes based on dependent tables.""" depencency_hashes = [dep.get_hash() for dep in self.dep()] sl = inspect.getsourcelines hash_sources = [sl(self.__class__), self.args, self.kwargs, *depencency_hashes] hash_input = pickle.dump... |
def get_cached_filename(self, filename, extention, settings_list=None): """Creates a filename with md5 cache string based on settings list Args: filename (str): the filename without extention extention (str): the file extention without dot. (i.e. 'pkl') settings_list (dict|list): the settings list as list (optional) NB... |
def _process_table(self, cache=True): """Applies the post processors""" table = self.source() assert not isinstance(table, None.__class__), \ "{}.source needs to return something, not None".format(self.__class__.__name__) table = post_process(table, self.post_processors()) if cache: self.to_cache(table) return table |
def fetch(self, rebuild=False, cache=True): """Fetches the table and applies all post processors. Args: rebuild (bool): Rebuild the table and ignore cache. Default: False cache (bool): Cache the finished table for faster future loading. Default: True """ if rebuild: return self._process_table(cache) try: return self.re... |
def generate(self): """Runs generation process.""" for root, _, files in os.walk(self.source_dir): for fname in files: source_fpath = os.path.join(root, fname) self.generate_api_for_source(source_fpath) |
def generate_api_for_source(self, source_fpath: str): """Generate end json api file with directory structure for concrete source file.""" content = self.convert_content(source_fpath) if content is None: return dest_fpath = self.dest_fpath(source_fpath) self.create_fpath_dir(dest_fpath) with open(dest_fpath, 'w+') as de... |
def convert_content(self, fpath: str) -> typing.Optional[dict]: """Convert content of source file with loader, provided with `loader_cls` self attribute. Returns dict with converted content if loader class support source file extenstions, otherwise return nothing.""" try: loader = self.loader_cls(fpath) except Unsuppor... |
def dest_fpath(self, source_fpath: str) -> str: """Calculates full path for end json-api file from source file full path.""" relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:]) relative_dirpath = os.path.dirname(relative_fpath) source_fname = relative_fpath.split(os.sep)[-1] base_fname = source_fname.split('... |
def create_fpath_dir(self, fpath: str): """Creates directory for fpath.""" os.makedirs(os.path.dirname(fpath), exist_ok=True) |
def add_options(cls, parser): """Required by flake8 add the possible options, called first Args: parser (OptionsManager): """ kwargs = {'action': 'store', 'default': '', 'parse_from_config': True, 'comma_separated_list': True} for num in range(cls.min_check, cls.max_check): parser.add_option(None, "--filename_check{}".... |
def parse_options(cls, options): """Required by flake8 parse the options, called after add_options Args: options (dict): options to be parsed """ d = {} for filename_check, dictionary in cls.filename_checks.items(): # retrieve the marks from the passed options filename_data = getattr(options, filename_check) if len(fil... |
def run(self): """Required by flake8 Will be called after add_options and parse_options. Yields: tuple: (int, int, str, type) the tuple used by flake8 to construct a violation """ if len(self.filename_checks) == 0: message = "N401 no configuration found for {}, " \ "please provide filename configuration in a flake8 con... |
def get_my_ips(): """highly os specific - works only in modern linux kernels""" ips = list() if not os.path.exists("/sys/class/net"): # not linux return ['127.0.0.1'] for ifdev in os.listdir("/sys/class/net"): if ifdev == "lo": continue try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ips.append(socket.inet... |
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity: """ Get an Identity document :param current_block: Current block data :param uid: Unique IDentifier :param salt: Passphrase of the account :param password: Password of the account :rtype: Identity """ # get current block Blo... |
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # capture current block to get version and currency and blockstamp current_block = await... |
client.close() |
def make_hash_id(): """ Compute the `datetime.now` based SHA-1 hash of a string. :return: Returns the sha1 hash as a string. :rtype: str """ today = datetime.datetime.now().strftime(DATETIME_FORMAT) return hashlib.sha1(today.encode('utf-8')).hexdigest() |
def read_header(filename): ''' returns a dictionary of values in the header of the given file ''' header = {} in_header = False data = nl.universal_read(filename) lines = [x.strip() for x in data.split('\n')] for line in lines: if line=="*** Header Start ***": in_header=True continue if line=="*** Header End ***": retu... |
def parse_frames(filename): ''' quick and dirty eprime txt file parsing - doesn\'t account for nesting **Example usage**:: for frame in neural.eprime.parse_frames("experiment-1.txt"): trial_type = frame['TrialSlide.Tag'] trial_rt = float(frame['TrialSlide.RT']) print '%s: %fms' % (trial_type,trial_rt) ''' frames = [] f... |
def appointment(self): """Returns the appointment instance for this request or None. """ return django_apps.get_model(self.appointment_model).objects.get( pk=self.request.GET.get("appointment") ) |
def previous_visit(self): """Returns the previous visit for this request or None. Requires attr `visit_model_cls`. """ previous_visit = None if self.appointment: appointment = self.appointment while appointment.previous_by_timepoint: try: previous_visit = self.model.visit_model_cls().objects.get( appointment=appointmen... |
def previous_obj(self): """Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF. """ previous_obj = None if self.previous_visit: try: previous_obj = self.model.objects.get( **{f"{self.model.visit_model_attr()}": ... |
def read(fname): """ utility function to read and return file contents """ fpath = os.path.join(os.path.dirname(__file__), fname) with codecs.open(fpath, 'r', 'utf8') as fhandle: return fhandle.read().strip() |
def ensure_utf8(app_name_to_show_on_error: str): """ Python3 uses by default the system set, but it expects it to be ‘utf-8’ to work correctly. This can generate problems in reading and writing files and in ``.decode()`` method. An example how to 'fix' it: nano .bash_profile and add the following: export LC_CTYPE=en_US... |
def create_files(filedef, cleanup=True): """Contextmanager that creates a directory structure from a yaml descripttion. """ cwd = os.getcwd() tmpdir = tempfile.mkdtemp() try: Filemaker(tmpdir, filedef) if not cleanup: # pragma: nocover pass # print("TMPDIR =", tmpdir) os.chdir(tmpdir) yield tmpdir finally: os.chdir(cwd... |
def make_file(self, filename, content): """Create a new file with name ``filename`` and content ``content``. """ with open(filename, 'w') as fp: fp.write(content) |
def smart_insert(col, data, minimal_size=5): """An optimized Insert strategy. **中文文档** 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要 远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略: 1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。 2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。 3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。 直到成功为... |
def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5): """Insert ``pandas.DataFrame``. :param col: :class:`pymongo.collection.Collection` instance. :param df: :class:`pandas.DataFrame` instance. :param int_col: list of integer-type column. :param binary_col: list of binary-type column. """ data ... |
def create(message: str, pubkey: Optional[str] = None, signing_keys: Optional[List[SigningKey]] = None, message_comment: Optional[str] = None, signatures_comment: Optional[str] = None) -> str: """ Encrypt a message in ascii armor format, optionally signing it :param message: Utf-8 message :param pubkey: Public key of r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.