content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def cenzura(text): """Replaces in text, for words s / e with vowels, the odd positions with *.""" words = r"(\W|^)([aeiou]\w+[aeiou])" #Finds out words s / e with vowels odds = r"(\w)(\w)|(\w)" # Finds groups of positions (impar, par) wwregex = re.compile(words, flags=re.IGNORECASE) oddr...
319a5ff9a9ae62a8ae236db34daf312030802aab
630,351
def is_dam_tol(stack, constraints): """ checks if a stacking sequence satisfies the damage tolerance guideline Args: stack (numpy array): stacking sequence constraints (instance of the class Constraints): set of design guidelines Returns: boolean: True if the stacki...
41ea148a58a468fde422f035311162629657e387
630,352
def create_compiled_task_c_ppm(self, name, node): """Creates the ppm task and binds it to the :py:class:`f_ti_arm_cgt.c_ppm` class. """ out = "%s.%d.ppm" % (node.name, self.idx) task = self.create_task(name, node, node.parent.find_or_declare(out)) return task
225913d60f2c1795de6e0a051e85de5ad9f4882e
630,353
def is_in(x, l): """Transforms into set and checks existence Given an element `x` and an array-like `l`, this function turns `l` into a set and checks the existence of `x` in `l`. Parameters -------- x : any l : array-like Returns -------- bool """ return x in set(l)
4e99e946177f85493f6404f170fadca4b5c1e8f2
630,354
import re def termlist_to_doubleamp_query(termlist_str, field=None): """ Take a comma separated term list and change to a (double ampersand) type query term (e.g., for solr) >>> a = "tuckett, dav" >>> termlist_to_doubleamp_query(a) 'tuckett && dav' >>> termlist_to_doubleamp_query(a, f...
2d841e0508c4c403f0aae9398fca33e398c6b4e5
630,355
import re def tokenize_datetime(text: str) -> str: """Tokenizes datetime to make it consistent with the seaweed tokens.""" # 5.10 => 5 . 10 # 4:00 => 4 : 00 # 5/7 => 5 / 7 # 5\7 => 5 \ 7 # 3-9 => 3 - 9 text = re.sub(r"(\d)([.:/\\-])(\d)", r"\1 \2 \3", text) # 4pm => 4 pm text = re...
f7a92b501ad44eef318a46c63c05b028a2d5658f
630,356
def up_zs_number(ka): """检查最新走势的连续向上中枢数量""" zs_num = 1 if len(ka.zs) > 1: k_zs = ka.zs[::-1] zs_cur = k_zs[0] for zs_next in k_zs[1:]: if zs_cur['zs'][0] >= zs_next['zs'][1]: zs_num += 1 zs_cur = zs_next else: br...
03f7fc64c5b22e3f8edb34465ff5d0e0171f397f
630,357
def count_neighbors(grid, i, j): """Count lit eight-connected neighbors. Calculate all neighbors and check if they're already on (i.e., in the grid) """ return sum(((x, y) in grid for x in (i - 1, i, i + 1) for y in (j - 1, j, j + 1) if (x, y) != (i, ...
aeae9f9fcd8a67d623ac485d709581f27e01c485
630,358
from typing import Callable def _update_annotations(discretized_pulse: Callable) -> Callable: """Update annotations of discretized continuous pulse function with duration. Args: discretized_pulse: Discretized decorated continuous pulse. """ undecorated_annotations = list(discretized_pulse.__a...
418be7e4424ddfa6920b491430b262196437850d
630,359
def ambitus(pitches: list) -> int: """The ambitus or range of a melody in semitones >>> ambitus([60, 62, 64, 65, 60]) 5 Parameters ---------- pitches : list List of MIDI pitches Returns ------- int The ambitus """ return max(pitches) - min(pitches)
6acc0ec73d7c8cb18cc10eaa0ea0d47d6f0f4ad7
630,360
def Clamp01(num): """ Returns ``num`` clamped between 0 and 1. Parameters ---------- num : float Input number """ if num < 0: return 0 if num > 1: return 1 return num
0c3eda62d9fbf077804329d0fe088d7871f20f2d
630,361
def extendBin(bnum, length): """ :param str bnum: binary number or integer :param int length: :return list-str: binary number with leading zeros """ if not isinstance(bnum, str): bnum = bin(bnum) result = list(bnum)[2:] while len(result) < length: result.insert(0, '0') return result
12f8f1b1b8833734665f44af266f97307486d45d
630,362
def array_product2(arr): """ :param arr: input array of integers :return: product array """ prod_arr = [1 for _ in range(0, len(arr))] for i in range(0, len(arr)): for j in range(0, len(arr)): if j == i: continue else: prod_arr[i]...
b06963d80e86472a9f26279b9c3e00ec5a25a671
630,363
def parseFile(filePath, separator): """Parses a .txt file with regular separators""" f = open(filePath, 'r'); #Opens file in read mode. f_content = f.read().split(separator) #f_content = cleanEncodingErrors(f_content) hlSet = set(f_content) f.close() return hlSet
3a97af0f0d95ea9d3f08c7675aff97b158ab0288
630,364
def get_dayseconds(dt): """Returns the number of seconds behind the most recent midnight. For example: ``get_dayseconds(datetime(2016, 9, 12, 1, 2, 3)) => 3723``. """ return dt.hour * 3600 + dt.minute * 60 + dt.second
3d538a9a5396017ae265599fe4de36fe8ec00065
630,365
def parse_snippy_files(folder_results): """ Parse Snippy output files Check details of results generated in :ref:`snippy-output-files` """ return ()
3ea4cc3d56775832a914f72e3bec5334fe1bc787
630,366
def extract_encoding_and_rate_from_wav_header(wav_header): """ Attempt to extract encoding, sample rate from possible WAV header. Args: wav_header (bytes): Possible WAV file header. Returns: Union[bool, str]: False or truthy value, which may be the encoding name...
b4fd300e9e3656f1b1d0d866255c749aabd5e7f7
630,367
def receive_from(connection): """ :param connection: established socket connection :return: buffer received from socket """ buffer = bytes() # This timeout gets repeated between each read/send so stay low or things will become very slow. # Removing this makes things break. ;) connectio...
3f7ee521306e46f0ed676501039fe8e3daa09b32
630,368
def get_learning_rate(epoch, total_batch, **kwargs): """ modularized for more fine tuning options """ decay_steps = 5000 lr = ( kwargs['starter_learning_rate'] * kwargs['decay_factor'] ** (epoch * total_batch / decay_steps) ) return lr
79908ab778dfa2c829bf45cc4ba2021fd25a7ab9
630,369
def parse_schema(d, md=[], depth=0, pre=""): """ Generate markdown headers from a passed python dictionary created by parsing a schema.yaml file. """ if "then" in d: d = d["then"] if "properties" in d: depth += 1 # Create markdown headers for each schema level fo...
4c06fe549bd97a840824308f12528ad6ec375215
630,371
def wrap_in(key): """Wraps value in dict ``{key: value}``""" return lambda val: {key: val}
a6024eeb8f5479dc8ab22aa1eee12fd46baaf9a0
630,372
def tartaglia(n): """ Funzione per generare un triangolo di tartaglia. Parametri --------- n: int Altezza del triangolo da generare Output ------ triangolo: list of lists [[],[],[],...] Lista di liste, corrispondenti alle righe del triangolo di tartaglia. Esempio -...
1dbb18879e565feef3405e533da492936d4a4b20
630,373
def close_powerplants(df, objective, capacity_factor, fuel, year): """ Simple algorithm to close power plants based on a given objetive value """ df = df.copy() power = objective * 1000 / (capacity_factor * 8.6) if fuel == "Coal" and year >= 2038: drop_index = df.loc[(df["geographical_la...
e9ca7e16d79b0333654e355958e347e1457022c0
630,374
import re def checkPassword(password): """ Validate the password """ if len(password) < 8: # Password to short print("Your password must be 8 characters long.") return False elif not re.findall(r'\d+', password): # Missing a number print("You need a number i...
4f543ecdbcc3eaef805f15c9993441e6cba6112e
630,375
def table_two_access(is_accredited, column, table, row_iter, data, one_cols, max_rows): """! Captures the information in the Assessment Methods table(s) of the document. @param is_accredited - Boolean value, True if the report is for an accredited degree program. @param column - A tuple that refers to...
d60e3f020f96443c1869e1561e5185ff117d394b
630,376
def solve_oxygen_or_co2_rating(lines, rating): """Return the oxygen generator rating or the CO2 scrubber rating.""" index = 0 while len(lines) > 1: ones = sum(line[index] == '1' for line in lines) if (ones >= len(lines) / 2 and rating == 'oxygen' or ones < len(lines) / 2 and ...
d259d5bbb90406b0a8ea657c3bafab4cb600128a
630,377
from datetime import datetime def format_datetime(dt: datetime): """Format a datetime for Magento.""" # "2021-07-02 13:19:18.300700" -> "2021-07-02 13:19:18" return dt.isoformat(sep=" ").split(".", 1)[0]
a155da72139ab17f0e19c93fe0cd68f1e3ff8dbc
630,378
def _normalize_path(path): """Internal helper that strips "./" on the left side of the path. """ if path.startswith("./"): return path[2:] return path
3db6add232715b51bfa8965eb4270808fe87df0a
630,379
def fasta_count(filepath): """Count the number of lines in a file""" lines = 0 buf_size = 1024 * 1024 with filepath.open("rb") as fh: read_f = fh.raw.read buf = read_f(buf_size) while buf: lines += buf.count(b">") buf = read_f(buf_size) return lines
1140ba15e48409b32f3da1eb08eaa9ca9daa73e1
630,380
def decode_stdout(resource): """Decode the information and return one line of the decoded information :param resource: it contains information produced by subprocess.Popen method """ line = resource.stdout.readline().decode('ascii') return line
7b5daa8aaf55ffe2e05e45bb619cda40cbe1f26f
630,381
from datetime import datetime import uuid def generate_new_results(): """ The default function for generating a new unique version string when saving a new bento or a new model """ date_string = datetime.now().strftime("%Y%m%d") random_hash = uuid.uuid4().hex[:6].upper() # Example output:...
b2475f98519d102d38dd5360699963926cb5994a
630,382
def add(a, b): """ Adds two numbers. >>> add(3, 2) 5 :param a: first number :param b: second number :return: sum """ return a + b
d6dba1312b240d6c7e36fe2a6d00a33cb316f611
630,383
import json def load_dataset(data_path): """Load existing json format dataset """ datafile = open(data_path) return json.load(datafile)
7d125a6308c89de15cf4fa6a6edb8cd7c656148c
630,384
def convert_ID(mobile_number): """ Covert valid mobile to ID phone code""" number_str = ''.join(filter(str.isdigit, str(mobile_number))) if number_str[:2]=='08': number_str = '62'+number_str[1:] elif number_str[:1] == '8' : number_str = '62'+number_str[0:] return number_str
c383a172d1b4d4e45c0127336d4b2f6d0d131f47
630,385
def get_sorted_node_parents(graph, node_with_parents): """ Get the parent nodes of a WIR node sorted by argument index. """ node_parents = list(graph.predecessors(node_with_parents)) node_parents_with_arg_index = [(node_parent, graph.get_edge_data(node_parent, node_with_parents)) ...
8bff6064b01f6eff8baf6de545fb925440f43523
630,386
from datetime import datetime def dt_obj_to_isodt_str(dt): """ Convert datetime object to ISO 8601 string. :param datetime dt: datetime object in UTC timezone :returns: ISO 8601 string """ assert isinstance(dt, datetime) # Using naive datetime object without timezone, assumed utc retu...
a5949c6eca118f8611ed7b3cf61735c376c6a578
630,387
import json def is_json_format(str): """json値判断 Args: str (str): json文字列 Returns: bool: True:json, False:not json """ try: # Exceptionで引っかかるときはすべてJson意外と判断 json.loads(str) except json.JSONDecodeError: return False except ValueError: return ...
38dd2df38dd9ec4be900284476a237cd33c946dd
630,388
def get_blocked_to(ruleId): """ Function obtains parameter 'blockedTo' from a rule with given id. Implementation of this function depends on how the rules are stored :param ruleId: ID of the rule :return: Returns value of the key 'ruleBlockedTo' from rule with given ID """ return "default"
ee3426caddffa4e46a264a670b2c6610054aa02c
630,389
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y): """ Find control points of the Bezier curve passing through (*c1x*, *c1y*), (*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1. """ cmx = .5 * (4 * mmx - (c1x + c2x)) cmy = .5 * (4 * mmy - (c1y + c2y)) return [(c1x, c...
219b053f98a14149305dbeda67acd5ba1163b04c
630,390
import re def md_header(data): """ ## {...} """ compile = re.compile(r"^(#{1,6})\s*(.*?)\s*$", re.M) def repl(match): tags = match.group(1) content = match.group(2) tag_start = '<h{}>'.format(len(tags)) tag_end = '</h{}>'.format(len(tags)) return tag_start + conten...
ab93e24792b7c1a6698287864196b69d52ae49a4
630,391
def sensitivity_calc(sign_residues_per_iter): """ | Inputs the output of ``bootstrapped_residue_analysis`` and calculates the sensitivity of each residue. | The returned sensitivity of each residue is calculated by calculating ``residue_appearances / iterations``. | A sensitivity of 1 is ideal meaning t...
f92772ea60d3ca660ee63aefa024047f8e3c5495
630,392
def numpy_dtype_to_numeric_type(element): """Return a valid numeric_type value based on the dtype of numpy array.""" lst = { "<u1": "uint8", "<u2": "uint16", "<u4": "uint32", "<u8": "uint64", "<i1": "int8", "<i2": "int16", "<i4": "int32", "<i8": "i...
acf1fb8e7016319bfc97314e751beae34aee8c06
630,393
def groupSubjects(segments): """Group subjects by parent page mongo id""" grouped = {} for s in segments: if s['parent_subject_id']['$oid'] in grouped: grouped[s['parent_subject_id']['$oid']].append(s) else: grouped[s['parent_subject_id']['$oid']] = [s] return gro...
05c3108074f2f5a6b901e21aa72578b5ca53e701
630,394
def value_check(inval): """ Check if a value is equal to None :param inval: the input value :param inval: float :return: 1 if the input value is None, 0 otherwise :return type: integer """ result = 0 if inval is None: result = 1 return result
fa2cfd39c8ec581eb486553cde82331fe21b50de
630,395
import numpy def _gmvs_to_haz_curve(gmvs, imls, invest_time, duration): """ Given a set of ground motion values (``gmvs``) and intensity measure levels (``imls``), compute hazard curve probabilities of exceedance. :param gmvs: A list of ground motion values, as floats. :param imls: ...
1ea4c82e10044f3e4e38935e548ba8995303eafc
630,396
def nvl(value, defval="Unknown"): """ Provide a default value for empty/NULL/None. Parameters ---------- value: obj The value to verify. defval: obj The value to return if the provide value is None or empty. Returns ------- defval if value is None or empty, othe...
2717b259464a75bca2305aa90f34ba8dafb2935b
630,397
def might_exit_to_port(descriptor, port): """Returns if will exit to port for *some* ip. Is conservative - never returns a false negative.""" for rule in descriptor.exit_policy: if (port >= rule.min_port) and\ (port <= rule.max_port): # assumes full range for wildcard port ...
2f439703802b43e5e6ec22817f5aadaebccf468b
630,399
def slope_tree_check(lines: list, dx: int, dy: int) -> int: """check how many trees would be encountered with a specific slope""" x_pos = 0 y_pos = 0 trees_encountered = 0 line_length = len(lines[0]) while y_pos < len(lines): if lines[y_pos][x_pos] == '#': trees_encountered +...
d4d518a121893df0d21720e2986887c85087f2e6
630,400
import torch def compute_loss(gold_seq, scores, index_to_token_maps, gold_tok_to_id, noise=0.00000001): """ Computes the loss of a gold sequence given scores. Inputs: gold_seq (list of str): A sequence of gold tokens. scores ...
30fe55a72a863911ce821dabde5d3839cb6269f7
630,401
def resourcequery_type(type): """ Property: ResourceQuery.Type """ valid_types = ["TAG_FILTERS_1_0", "CLOUDFORMATION_STACK_1_0"] if type not in valid_types: raise ValueError('Type must be one of: "%s"' % (", ".join(valid_types))) return type
1824c9448f32046efa6e17c93d7b5e9487355c4a
630,402
import math def log10_zero(x): """Return the log10 of x, map log10(0) -> 0.""" if x == 0: return 0 else: return math.log10(x)
c47498ff88c83785e98420a02cd2d3d6884864e6
630,404
def get_digit_at_pos(num, base, pos): """ Gets the integer at the given position of the number in a specific base @param num The number we wish to find the converted digit in @param base The base in which the digit is calculated @param pos The position of the digit to be found @re...
09026aad59d635f45c706d3d1c5bc61a6127c17b
630,405
def bit_last(x): """ Get the last digit where 1 stands (0-indexed) x.bit_length()と同じ。 ref: https://www.slideshare.net/KMC_JP/slide-www Args: x (int): bit Returns: int: last digit >>> bit_last(1) 0 >>> bit_last(4) 2 >>> bit_last(6) 1 >>> bit_last...
0c5d81af03a19ce7ae1b2c06323fa3ddf35c14cf
630,406
import os def DirExists(folder): """Returns true if the folder exists""" return os.path.isdir(folder)
c1f5b6cd397628e614b44c2eccea3705d0922520
630,407
import json def dictFormatter(dictionary): """Formats the provided dictionary and writes it to file. :param dictionary: The dictionary containing all the user code to write out. :type dictionary: dict :returns: True if successfully wrote the file, False otherwise. """ try: fileTmp = ...
3ea261874bd395bc6a9504a521b9d54cfe390952
630,408
import hashlib def get_file_hash(path, block_size=8192): """Calculates the content hash for the file at the given path.""" md5 = hashlib.md5() with open(path, 'rb') as f: while True: block = f.read(block_size) if not block: break md5.update(block...
429258dc30bb5a6ab10e5c5c5f98000a0c1f324d
630,409
def test_decorated_function_with_defaults(a, b=2, c='Hello'): """Test Decorated Function With Defaults Docstring.""" return [a, b, c]
65f4a409a44a34fdca7a1e17e8b20a763c370073
630,410
def create_message_subject(info, context): """ Create the message subject """ base = '%s request completed' % context['display_name'] if info['errors'] > 0: return '%s with ERRORS!' % base elif info['warnings'] > 0: return '%s with WARNINGS!' % base else: return base
3369b7d3637dd6540ff721b33346d428d4bcd1bb
630,411
def table_splitted(table1, table2): """ Combines two tables """ result = [table1[line] + ' ' * 2 + table2[line] for line in range(len(table1))] return '\n'.join(result)
3879f75e040852d87ab6ccaa0149a4b41edefb37
630,412
def newtons_method_1d(f, df_dx, x0, tol): """Return the root of `f` within `tol` by using Newton's method. Parameters ---------- f : callable[[float], float] The function of which the root should be found. df_dx : callable[[float], float] The derivative of `f`. x_0 : float ...
843ff00f5765efe6637bee4b35f555a393368a26
630,413
import string def is_pangram(s): """ Detect whether or not a given string input is a pangram. :param s: a string value. :return: true if string is a pangram, otherwise false. """ return set(string.ascii_lowercase) <= set(s.lower())
89acf3fa64f74091df74f095cf7a806c78457658
630,414
def _integer_list_to_string(integer_list): """For [0, 1, 2, 14, 91, 92, 15, 182, 183, 16] return '#$%1~!$2!~!!$3'.""" if (len(integer_list) > 0) and (min(integer_list) < 0): raise SystemExit('negative value in integer_list: {}'.format(integer_list)) mult_chr = 33 # 33='!' min_chr = 35 # 35='#'...
50e95803a80ca060355c7f861d489f66b34c177f
630,415
def format_input(x): """Transforms rows of numers written as strings into a list of lists of ints""" delimiter = '\t' if '\t' in x else ' ' # test_value doesn't use \t but input does return [[int(s) for s in r.split(delimiter) if s != ''] for r in x.split('\n')]
991503c0e0fc5fbc3a444a0849d7eb976a91a5fe
630,416
def is_cmake(file_path): """ :param file_path: the path of a file :return: true if file with suffix .cmake """ return file_path.split(".")[-1] == "cmake"
f7be7defda5e1fe9c5d5ce7e5590d321173abf28
630,417
def cond(x, singular=False, order=0): """ If It is singular, return 1 if x>0 else 0. If It is not singular, return x**order if x>0 else 0 """ if singular: return 1 if x>0 else 0 return x**order if x>0 else 0
f49aea4010c44613d8b8c98c25d86d0ed5627d34
630,419
def _left_or_eq_to(a, b, open_a, open_b): """ a <= b 当两个全是close a < b 其他情况 """ if open_a or open_b: return a < b else: return a <= b
ff5eb0a2ce27a335357920ac67f5f391afab7c97
630,420
def _get_pkgdocs(cfg): """Return a string in reST format that contains the metadata for the package. cfg: ConfigParser ConfigParser object used to read the setup.cfg file. """ lines = ['\n', '================\n', 'Package Metadata\n', '================...
969b9532e766436fc5e4b2ae9e59abb0a611c6c3
630,421
import os def split_file_ext(file_name): """ splits the extension from the file name. :param file_name: :return: """ return os.path.splitext(file_name)[1]
79cdb614752a5d46e82690bfd1bfaf574f97ec87
630,423
def valid_json_file_with_job_name(tmpdir_factory): """Create a valid JSON on disk. Args: tmpdir_factory (_pytest.tmpdir.TempdirFactory): Create a temp directory. Returns: str: Path to config file. """ config_path = tmpdir_factory.mktemp('data').join('valid.json').strpath with ...
2ab15935b03ab63f47b9bd90be82764ac491b7dd
630,424
import json def read_summary(filename): """Reads the summary dict from a JSON file.""" with open(filename) as f: return json.load(f)
da7d1798181e513dff2e8cae934081759ce5045d
630,425
from typing import List def ma(lst: List[float], x: int) -> List[float]: """return the moving average with range x Preconditions: - len(lst) > x """ res = [] for i in range(len(lst) - x): temp = lst[i:i + x] res.append(sum(temp) / x) starting = [0.0] * x starting.exten...
037e83f1a33422b735487dbcd4d5f8c4dd3605e8
630,426
def rho(parameters, theta_v, pi): """ Returns an expression for the dry density rho in kg / m^3 from the (virtual) potential temperature and Exner pressure. :arg parameters: a CompressibleParameters object. :arg theta_v: the virtual potential temperature in K. :arg pi: the Exner pressure. "...
8b7a38bdaa48994af7dbb77034b8c795f5f89cb5
630,427
def check_column(col, sep=":"): """Convert input column string to list of columns :param col: input string :param sep: default ":" :return: list of columns """ if isinstance(col, str): col = col.split(sep) elif not isinstance(col, list): raise TypeError(f'Columns "{col}" nee...
eb6fb0e645fd7eb59fbf46a13c01efecef4906d8
630,428
def is_palindrome(value): """Check if a string is a palindrome.""" return value == value[::-1]
524c2c67874f41854034ec319c10a05e7e267727
630,429
def _mult_diag_matrix(D, mtx, on_right=False): """ Multiply diagonal matrix D to mtx Args: D (N ndarray) - diagonal matrix mtx (ndarray) - matrix to multiply on_right (bool) - whether to return D * mtx (False) or mtx * D (True) """ if not on_right: return (D*mtx.T).T else: ...
f2d30e8cbb2ef7b842d3daa922185bc3758a5094
630,430
def get_reflectivity_name(radar): """ Test for several possible name for the ground radar reflectivity. Parameters: =========== radar: object Py-ART radar structure Returns: key: str Reflectivity field name. """ possible_name = ['reflectivity', 'corrected_reflectivi...
75bdf283334f2eaea853396fe500bc844bbadfb4
630,431
import tempfile def setup_workdir(): """ :return: Path of the created working dir """ return tempfile.mkdtemp(dir="/tmp", prefix="python-tests-")
1ac1a1454f0922d132108903bc69610d9cc53f14
630,432
import random import string def generate_id(length: int = 6) -> str: """Helper function for generating an id.""" return "".join(random.choices(string.ascii_uppercase, k=length))
d90f15c0332c5257846f6f719321d182111c6782
630,433
def combine_expression_columns(df, columns_to_combine, remove_combined=True): """ Combine expression columns, calculating the mean for 2 columns :param df: Pandas dataframe :param columns_to_combine: A list of tuples containing the column names to combine :return: """ df = df.copy() ...
8c9e4be3dbfb8660e659ae09d4d01024bf910906
630,434
import click def stack_options(func): """ stack_options is a decorator which adds the stack and environment arguments to the click function ``func``. :param func: The click function to add the arguments to. :type func: function :returns: function """ func = click.argument("stack")(fun...
2291bf119703dae45722dd721ccfd42c2d238bf6
630,435
def format_pdb_code_for_inputs(pdb_code: str, source_type: str): """Format given PDB code for prediction inputs.""" return pdb_code[1:3] if source_type.lower() == 'input' else pdb_code.upper()
430a97ec59e5c32175f40f2595db5dd90650275a
630,436
def is_palindrome(n): """Tests if a number is a palindrome Args: n (Integer): Integer to test palindromomity Returns: Boolean: True if n is a palindrome, false otherwise """ # Turn the integer into a list of characters chars = list(str(n)) length = len(chars) # ...
333b76f1b3de1f66489d3295e2d6e459e89b2727
630,437
def get_state_ranges(states): """From a list of characters, finds all regions with similar values. Returns regions with respective values as: {(start, end):value, (start, end):value} """ ranges = {} values = [] for i in range(len(states)): if i == 0: # Start position ...
ef89d98761147b8a276ece894d444519fb2b1ba9
630,438
from typing import Callable def create_callable(func: Callable, *args, **kwargs) -> Callable: """ Function creates a callable function where the called function gets passed as an argument along with its args and kwargs. Args: func (Callable): Function to be called *args (any): Args pa...
247fd8b29f93cbca2109d4c5d527ae44d21f8abc
630,439
def flatten_deps(deps): """Converts deps.lock dict into a list of go packages specified there.""" out = [] for p in deps['imports']: # Each 'p' here have a form similar to: # # - name: golang.org/x/net # version: 31df19d69da8728e9220def59b80ee577c3e48bf # repo: https://go.googlesource.com/...
1a1b5206ff0b592b1972f4f081594c7a8c7b867b
630,440
def transpose(a): """ transposes a matrix """ return list(zip(*a))
5d311c90c61977eb59d63e9ebc0c3bc23b73889e
630,441
def reduce_names(l): """Reduce the names in the list to acronyms, if possible. Args: l (list(str)): list of names to convert. Returns: (list(str)): list of converted names. """ for i, item in enumerate(l): if item == 'QuadraticDiscriminantAnalysis': l[i] = 'QDA'...
0d9c8a7d226297658054491d10067b6426cb1287
630,442
def cipher(text, shift, encrypt=True): """ This is a package to encrypt sth. Caesar cipher is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. Inputs ------ text: str. A set of string we want to en...
b5e05ddb81e83d2a49dc268bbc9b6b75330560c6
630,443
def vaporcode(s: str) -> str: """ This function converts any sentence into a V A P O R W A V E sentence """ return ' '.join(i.upper() for i in s if i != ' ')
35f824f42250489ea6e371b2cae3f3b698057431
630,444
def breit_wigner_fano_alt(x, height=1.0, center=0.0, sigma=1.0, q=-3.0): """ An alternate Breit-Wigner-Fano lineshape that uses height rather than amplitude. breit_wigner_fano(x, height, center, sigma, q) = height * (1 + (x - center) / (q * sigma))**2 / (1 + ((x - center) / sigma)**2) """ ...
bf52b96b56ed3fc89a8ed694488ac0b9a0e0b2bf
630,445
import json def load(file: str): """ load json file with default options :param file: file path to load :return: json data as python object """ with open(file, 'r', encoding='utf-8') as jsonfile: config = json.load(jsonfile, encoding='utf-8') return config
4b500378512d9e2373a92454d0a625107de6f17e
630,446
def update_and_return(dictionary: dict, **kwargs) -> dict: """ Utilises the standard dictionary update() function but instead of returning None it will return the updated dictionary. :param dictionary: The dictionary that should be updated :param kwargs: Kwargs of the update method :return: The...
69652f1a512eecfa323b7df5048f14c6e4900bde
630,447
def marital_replace(df): """ replaces values of the variable "MaritalStatus" from input dataset to the format used for analysis and visualisation Grouped in to 'married' and 'not married' Parameters ---------- df : main datatset Returns ------- df : main dataset af...
450d40a1fa47be3a44c4f1c7cbae16489f9f9a71
630,449
def optimizedNewArr(arr): """ Ref: https://www.geeksforgeeks.org/a-product-array-puzzle/ O(n) 1) Construct a temporary array left[] such that left[i] contains product of all elements on left of arr[i] excluding arr[i]. 2) Construct another temporary array right[] such that right[i] contains product of a...
4f88d153e60c70663e2af91261adf3bee39c2585
630,450
def mtx_zip_url(expression_accession): """Make the url to grab the zipped mtx experssion data from the ebi's accessionI_id""" url = "https://www.ebi.ac.uk/gxa/sc/experiment/%s/download/zip?fileType=quantification-filtered&accessKey=" \ % expression_accession return url
d853cb999958a58651a05e6a2c27d9bc528c4396
630,451
from datetime import datetime def read_timestamp(time_string): """Return a datetime object from the timestamp string""" return datetime.strptime(time_string, '%Y%m%d%H%M%S')
6b4e2d2521e738acb7166d4a1a1b716128fc14e8
630,452
def convert_input_parameters(alpha_range, t0_range, tau_range, body_band, surface_band, snr_threshold, cc_threshold, deltat_threshold): """ convert_input_parameters: convert the input form of some parameters to be used in the script """ alpha_ran...
3c09224937a92d3aa22d264e2ff18d9193c9727e
630,453
async def async_setup(hass, config): """Register the built-in help panel.""" hass.components.frontend.async_register_built_in_panel( "aishelp", require_admin=True, sidebar_title="Przydatne linki", sidebar_icon="mdi:qrcode", ) """Register the built-in doc panel.""" has...
3f0ce5efed289bfa0f20e6e3824a7c5a4b1b0499
630,455
def sliceRespSeq(r): """After the epitope has been identified, slice the response sequence to the appropriate size""" start, stop = int(r['EpStart'] - r['start']), int(r['EpStart'] - r['start'] + len(r['EpSeq'])) if 'align seq' in r: s = r['align seq'] else: s = r['seq'] if sta...
0c7ed8eb37fa7b5dbb6a2b245ea86f056adc5fc1
630,457
import sys def read_file(path, mode='r'): """ Read an import file and return its content """ # Read import file try: file = open(path, mode=mode) fileContent = file.read() file.close() return fileContent except Exception as e: print("The file `%s` ...
38d45eadb9e4cb946fd1763829276046b9247abf
630,458