content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def returns_int(indata: int) -> int: """This function returns an int""" return indata
894ce7f0094b61f8fc93fbe793ce79d3a3ac9c35
542,927
def compose1(f, g): """"Return a function h, such that h(x) = f(g(x)).""" def h(x): return f(g(x)) return h
1613e41cf70446755586b4edf0093c1ed75c3915
623,442
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool: """Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s). Used primarily for checking against the registered command data from Discord. Will not work great if values inside the dictionary can be or are None. If both dictionaries lack the keyword(s), it can still return True. Parameters ---------- dict1: :class:`dict` First dictionary to compare. dict2: :class:`dict` Second dictionary to compare. keywords: :class:`str` Words to compare both dictionaries to. Returns ------- :class:`bool` True if keyword values in both dictionaries match, False otherwise. """ for keyword in keywords: if dict1.get(keyword, None) != dict2.get(keyword, None): return False return True
46b537ea1353c29c9ada561a0469b8f6658501c3
651,036
def sort_into_sections(events, categories): """Separates events into their distinct (already-defined) categories.""" categorized = {} for c in categories: categorized[c] = [] for e in events: categorized[e["category"]].append(e) return categorized
74cb24b59e3079310d08383d535f077d626ba865
538,101
def _FormatTime(t): """Formats a duration as a human-readable string. Args: t: A duration in seconds. Returns: A formatted duration string. """ if t < 1: return '%dms' % round(t * 1000) else: return '%.2fs' % t
738b8fb6e31b0fdf56d314a9c9e1155f82030003
354,779
def lookup_dashboard(stackdriver, display_name): """Find the dashboard definition with the given display_name.""" parent = 'projects/{0}'.format(stackdriver.project) dashboards = stackdriver.stub.projects().dashboards() request = dashboards.list(parent=parent) while request: response = request.execute() for elem in response.get('dashboards', []): if elem['displayName'] == display_name: return elem request = dashboards.list_next(request, response) return None
5633e6af36fbf927b881aa027ade1f84bd130164
505,356
def _extract_header_alignment(header, alignments, nt): """ With a provided complete header, extract the alignment and process to correct format for fill in zeros :param header: reference sequence header string :param alignments: alignments dictionary :return: sorted_fwd_alignment, sorted_rvs_alignment, aln_count list """ sorted_fwd_alignment = [] sorted_rvs_alignment = [] aln_count = 0.0 ref_len = 0 if header in alignments: extracted_alignments = alignments[header] for alignment in extracted_alignments: ref_len = alignment[0] if alignment[3] =="+": sorted_fwd_alignment.append((alignment[2], alignment[4], alignment[5])) elif alignment[3] =="-": sorted_rvs_alignment.append((alignment[2], -alignment[4], alignment[5])) aln_count += alignment[4] return [sorted_fwd_alignment, sorted_rvs_alignment, aln_count], ref_len
414ad2ddcf5f876052e737fe27acd7430056846e
214,069
def layer1(self) -> tuple: """ Solve first layer corners. Returns ------- tuple of (list of str, dict of {'FIRST LAYER': int}) Moves to solve first layer, statistics (move count in ETM). Notes ----- A corner on the top layer with a white sticker is rotated so that it is directly above the correct position at the front-right slot. Then repeatedly do `R U R' U'` until the corner is correctly inserted. If there are no more corners with a white sticker on the top layer and the first layer is still unsolved, an unsolved corner with a white sticker on the bottom layer is rotated to the front-right slot and moved to the top layer by doing `R U R' U'`. Repeat until the first layer is solved. """ cube = self.cube solve = [] corners = (0,0), (0,-1), (-1,0), (-1,-1) first_layer = ( ((0,-1,-1), (2,0,-1), (3,0,0)), ((0,-1,0), (1,0,-1), (2,0,0)), ((0,0,-1), (3,0,-1), (4,0,0)), ((0,0,0), (4,0,-1), (1,0,0)) ) while not(all(cube[5][y][x] == 'U' for y, x in corners) and all(len(set(side[-1])) == 1 for side in cube[1:5])): for corner in first_layer: if any(cube[x[0]][x[1]][x[2]] == 'U' for x in corner): break else: if cube[5][0][-1] != 'U' or cube[2][-1][-1] != cube[2][1][1]: pass elif cube[5][0][0] != 'U' or cube[1][-1][-1] != cube[1][1][1]: self.move("y'") solve.append("y'") elif cube[5][-1][-1] != 'U' or cube[3][-1][-1] != cube[3][1][1]: self.move('y') solve.append('y') else: self.move('y2') solve.append('y2') moves = 'R', 'U', "R'", "U'" self.move(moves) solve.extend(moves) continue piece = [] for x in corner: piece.append(cube[x[0]][x[1]][x[2]]) slot = piece[piece.index('U') - 1] for s, side in enumerate(cube[1:5], 1): if side[1][1] == slot: slot = s - 1 break piece = corner[1][0] - 1 turns = (piece - slot) % 4 if turns == 1: self.move('U') solve.append('U') elif turns == 2: self.move('U2') solve.append('U2') elif turns == 3: self.move("U'") solve.append("U'") if not slot: self.move("y'") solve.append("y'") elif slot == 2: self.move('y') solve.append('y') elif slot == 3: self.move('y2') solve.append('y2') while cube[5][0][-1] != 'U' or cube[2][-1][-1] != cube[2][-1][1]: moves = 'R', 'U', "R'", "U'" self.move(moves) solve.extend(moves) return solve, {'FIRST LAYER': len(solve)}
230e44363c57d4429691ca8853aea877a73aa322
497,880
from typing import Iterable def get_item(collection, item_path): """Retrieve an item from a component's collection, possibly going through multiple levels of nesting. :param collection: the collection where the item resides. :param item_path: a string with the name of the item, or an iterable of strings giving its location in a nested hierarchy. :returns: the value of the specified item in the collection. """ if isinstance(item_path, str): return collection[item_path] else: assert isinstance(item_path, Iterable) # iterate through the parts of the path until we reach the final level current = collection for item in item_path: current = current[item] return current
20564a36f384b1813b144bc2e98d6f9335233bf8
535,499
import json def response_success(data): """Return success response.""" body = { "error": None, "code": 200, } data.update(body) return { "statusCode": 200, "body": json.dumps(data) }
7a432e8a8a9c792cd1a9c9a71036a05994815b05
508,351
import json def load_stats(filename): """ Loads statistics. :param filename: File to be loaded. :return: users, user_stats, global_stats arrays """ with open(filename, 'r', encoding='utf-8') as jsonfile: data = json.load(jsonfile) return data["users"], data["user_stats"], data["global_stats"]
5799e900282ece3cd7ec87164d785b206d1504b6
217,326
def get_training_cost( model_path: str, dataset_path: str, train_batch_size: int, run_stats: dict, gpu_cost_per_hr: float = 0.35, # GCP cost for Tesla T4 ) -> float: """ Return total cost to train model using GCP compute resource """ total_time_s = int(run_stats["hyperopt_results"]["time_total_s"]) total_time_hr = total_time_s / 3600 return float(total_time_hr * gpu_cost_per_hr)
97ba0baa299bd7223fe60a262dbd4e3dc5cb4897
471,878
import io def make_csv_file(fieldnames, datarows): """Helper function to make CSV file-like object using *fieldnames* (a list of field names) and *datarows* (a list of lists containing the row values). """ init_string = [] init_string.append(','.join(fieldnames)) # Concat cells into row. for row in datarows: row = [str(cell) for cell in row] init_string.append(','.join(row)) # Concat cells into row. init_string = '\n'.join(init_string) # Concat rows into final string. return io.StringIO(init_string)
f8af4554d16bb5eb5e86abbeff54073128d8ef32
194,031
def zero_float(string): """Try to make a string into a floating point number and make it zero if it cannot be cast. This function is useful because python will throw an error if you try to cast a string to a float and it cannot be. """ try: return float(string) except: return 0
075a49b53a0daf0f92072a5ec33f4b8240cc6885
702,546
def GetEst(coeff): """Extracts the estimated coefficient from a coeff tuple.""" name, est, stderr = coeff return est
bda62c49252d4078879736046fa606d5d5c1ee33
260,136
from typing import Callable from typing import Iterable def zip_with(func: Callable, *iters) -> Iterable: """`zip` all the iters and apply function `func` to each of them """ return map(func, zip(*iters))
9e0c1635d9f11b133fa54c47310125fa480b91b6
633,578
import random def random_bytes(size): """Returns a byte array with the given size that contains randomly generated bytes.""" return bytes(random.randrange(0 ,256) for i in range(size))
050945884d4110c43c9ab6c0cf0da2f207d7d046
315,099
def _formulate_smt_constraints_final_layer( z3_optimizer, smt_output, delta, label_index): """Formulates smt constraints using the logits in the final layer. Generates constraints by setting the logit corresponding to label_index to be more than the rest of the logits by an amount delta for the forward pass of a masked image. Args: z3_optimizer: instance of z3.Optimizer, z3 optimizer. smt_output: list of z3.ExprRef with length num_output. delta: float, masked logit for the label is greater than the rest of the masked logits by delta. label_index: int, index of the label of the training image. Returns: z3 optimizer with added smt constraints. """ for i, output in enumerate(smt_output): if i != label_index: z3_optimizer.solver.add(smt_output[label_index] - output > delta) return z3_optimizer
1031db93f7821ad8cce1bdcec4a9f6687c582e4c
525,012
def taxdump_from_text(text): """Read taxdump from comma-delimited text. Parameters ---------- text : list of str multi-line, comma-delimited text columns: taxId, name, parent taxId, rank Returns ------- dict of dict taxonomy database """ res = {} for line in text: x = line.split(',') res[x[0]] = {'name': x[1], 'parent': x[2], 'rank': x[3]} return res
8213b1aa7f72ef4b1b99e7f8b3eba7f0d6db4721
511,773
import re def parse_cg_history(fh): """Parse CG history Keyword Arguments: fh -- file handle Returns: a list of tuples: [e_1, ..., e_N] where: e_i = (i, F, resX, resf|eta) """ # step 24 F: -26.34592024007 res: X,fn -6.84493e-04 -8.38853e-01 # step 218 F: -60.51049737235 res: X,eta -4.43797e-12, -3.10230e-1 out = [] rgx1 = '\s*step\s*([0-9]+)\s*F:\s*(.*)res:\s*X,(?:fn|eta)\s+([0-9e\+\-\.]+)\s+([0-9.+-e]+)' rgx2 = '\s*step\s*([0-9]+)\s*F:\s*(.*)res:\s*X,(?:fn|eta)\s+([0-9e\+\-\.]+),\s*([0-9.+-e]+)' for line in fh.readlines(): # .strip() to remove newlines at the end match1 = re.match(rgx1, line.strip()) match2 = re.match(rgx2, line.strip()) match = match1 or match2 if match: i = int(match.group(1)) F = float(match.group(2)) resX = float(match.group(3)) resf = float(match.group(4)) out.append((i, F, resX, resf)) return out
7de0778c5dc0efa2909d8dcc1e8169ec0723b879
268,450
import re def strip_path(path_to_strip="", uri=""): """Strip a particular path from a URI. Keyword Arguments: path_to_strip {str} -- Path to remove from the URI (default: {""}) uri {str} -- URI requested (default: {""}) Returns: {str} -- URI with path stripped out """ return re.sub(path_to_strip, "/", uri)
712bb96da31a8c7784b3c1f9de6c0bdb43e6c399
204,639
def nested_dict_traverse(path, d): """Uses path to traverse a nested dictionary and returns the value at the end of the path. Assumes path is valid, will return KeyError if it is not. Warning: if key is in multiple nest levels, this will only return one of those values.""" val = d for p in path: val = val[p] return val
1f7e4744585ae134ab1f2eface9284756526ed65
698,335
def _genprop(converter, *apipaths, **kwargs): """ This internal helper method returns a property (similar to the @property decorator). In additional to a simple Python property, this also adds a type validator (`converter`) and most importantly, specifies the path within a dictionary where the value should be stored. Any object using this property *must* have a dictionary called ``_json`` as a property :param converter: The converter to be used, e.g. `int` or `lambda x: x` for passthrough :param apipaths: Components of a path to store, e.g. `foo, bar, baz` for `foo['bar']['baz']` :return: A property object """ if not apipaths: raise TypeError('Must have at least one API path') def fget(self): d = self._json_ try: for x in apipaths: d = d[x] return d except KeyError: return None def fset(self, value): value = converter(value) d = self._json_ for x in apipaths[:-1]: d = d.setdefault(x, {}) d[apipaths[-1]] = value def fdel(self): d = self._json_ try: for x in apipaths[:-1]: d = d[x] del d[apipaths[-1]] except KeyError: pass doc = kwargs.pop( 'doc', 'Corresponds to the ``{0}`` field'.format('.'.join(apipaths))) return property(fget, fset, fdel, doc)
d4c916df257f5271fc35d7cb993488b1011df9ed
254,299
def split_usn(usn): """Split a USN into a UDN and a device or service type. USN is short for Unique Service Name, and UDN is short for Unique Device Name. If the USN only contains a UDN, the type is empty. Return a list of exactly two items. """ parts = usn.split('::') if len(parts) == 2: return parts else: return [parts[0], '']
29811dc8430cf3673a99a1acf8640b8f73c3b1ff
422,244
def has_special_character(password: str) -> bool: """ checks if password has at least one special character """ return any(char for char in password if not char.isalnum() and not char.isspace())
505ee2c9f9c139d587c91acf5dc456c017d06924
215,303
def format_toml(data): """Pretty-formats a given toml string.""" data = data.split('\n') for i, line in enumerate(data): if i > 0: if line.startswith('['): data[i] = '\n{0}'.format(line) return '\n'.join(data)
7f429cb40720f624ceb52cf837a6e523a8cdfb5c
362,420
def get_line_equation(p1, p2): """ Solve the system of equations: y1 = m*x1 + b y2 = m*x2 + b This translates to: m = (y2 - y1) / (x2 - x1) b = y1 - m*x1 Input: p1: first point [x1, y1] p2: second point [x2, y2] returns: slope, intercept """ m = (p2[1] - p1[1]) / (p2[0] - p1[0]) # Slope b = p1[1] - m * p1[0] # Intercept return m, b
064a56a62d4295b8ad3c8c0d62ebaefdf0d36678
435,612
def unscalar_lex(arg): """Lexically unwraps a string containing a string or numeric constant, such as are created by the PyTT parser. If the argument (presumed to be a string) starts with the string "scalar(" and ends with the string ")", evaluates and returns the portion of the argument between those strings; otherwise just returns the argument. """ if arg.startswith("scalar(") and arg.endswith(")"): return eval(arg[7:-1]) else: return arg
5dc13d91ac497269e374b5c2703a7b8debbaa2a1
192,523
import click def _prompt(*args, allow_empty=False, **kwargs): """ Print a breakline before prompting for input and normalize values to accept empty input when requested by caller. Args: args (any): arguments to click.prompt allow_empty (boolean): whether to allow prompt to accept empty as input kwargs (any): arguments to click.prompt Returns: str: input text """ # allow empty input: check if default value must be normalized if allow_empty: def_value = kwargs.get('default') # def_value is empty string or None: make sure it's set to empty string # so that click.prompt will accept empty input if not def_value: def_value = '' kwargs['default'] = def_value click.echo() ret = click.prompt(*args, **kwargs) # input was empty and flag is set: convert back to None if allow_empty and not ret: ret = None return ret
2e007ea744fd993bc69971208fc70b34e9ebf63e
567,755
def load_candidate_bond_changes_for_one_reaction(line): """Load candidate bond changes for a reaction Parameters ---------- line : str Candidate bond changes separated by ;. Each candidate bond change takes the form of atom1, atom2, change_type and change_score. Returns ------- list of 4-tuples Loaded candidate bond changes. """ reaction_candidate_bond_changes = [] elements = line.strip().split(';')[:-1] for candidate in elements: atom1, atom2, change_type, score = candidate.split(' ') atom1, atom2 = int(atom1) - 1, int(atom2) - 1 reaction_candidate_bond_changes.append(( min(atom1, atom2), max(atom1, atom2), float(change_type), float(score))) return reaction_candidate_bond_changes
1dfe4c5e7f53a86e5aaa9d8a7eb3a44c3b2599b7
347,335
def truncate(x, maxlen=1000): """ >>> truncate('1234567890', 8) '1234 ...' >>> truncate('1234567890', 10) '1234567890' """ if len(x) > maxlen: suffix = ' ...' return '%s%s' % (x[:maxlen - len(suffix)], suffix) else: return x
2923d853b0e3d53aba3bd180f0790d14f143b829
492,344
def find_tag_column_pairs(tags): """ Creates a dict, where k = the user-created tag names, like 'life', v = db column names, like 'tag1'} """ all_tag_columns = {} counter = 0 for tag in tags: counter += 1 all_tag_columns[str(tag)] = "tag" + str(counter) return all_tag_columns
80984628b3f2daf2fb761a5e958452d5e5521efd
595,337
def fetch_courses(job_config, data_bucket, data_dir ="morf-data/"): """ Fetch list of course names in data_bucket/data_dir. :param job_config: MorfJobConfig object. :param data_bucket: name of bucket containing data; s3 should have read/copy access to this bucket. :param data_dir: path to directory in data_bucket that contains course-level directories of raw data. :return: courses; list of course names as strings. """ s3 = job_config.initialize_s3() if not data_dir.endswith("/"): data_dir = "{0}/".format(data_dir) bucket_objects = s3.list_objects(Bucket=data_bucket, Prefix=data_dir, Delimiter="/") courses = [item.get("Prefix").split("/")[1] for item in bucket_objects.get("CommonPrefixes")] return courses
3fe3ed0670d3d22950d8be393404fc9665c4334d
67,916
def markdown_paragraph(text: str) -> str: """Return the text as Markdown paragraph.""" return f"\n{text}\n\n"
38f2a790f565e6417d73a2b2430cc0c5efabc27a
35,027
def height_to_imperial(height): """Converts height in cm to feet/inches.""" height_inches = height / 2.54 feet = int(height_inches) // 12 inches = height_inches % 12 return feet, inches
bdec165de4b1576e53f2c81e6d3fc9d60b82d8ee
19,707
def build_stop_names(shape_id): """ Create a pair of stop names based on the given shape ID. """ return ["Stop {!s} on shape {!s} ".format(i, shape_id) for i in range(2)]
fad14e29bfdd0471d048f9b731a63eba65ad4439
336,905
def rotl(x, count): """Rotates the 64-bit value `x` to the left by `count` bits.""" ret = 0 for i in range(64): bit = (x >> i) & 1 ret |= bit << ((i + count) % 64) return ret
6bba2bf109f9ddd0f9b4c202c3192e14a0cd625f
31,701
import shutil import logging def safe_move(src, dst): """ Attempt to move a directory or file using shutil.move() Returns true if it worked, false otherwise. """ try: shutil.move(src, dst) return True except Exception as e: logging.error(f"An error occured while trying to move {src} to {dst}: {e}") return False
1ef2688d99ab214c6882ead35218bca80d0c3555
561,612
def py2(h, kr, rho, cp, r): """ Calculate the pyrolysis number. Parameters ---------- h = heat transfer coefficient, W/m^2K kr = rate constant, 1/s rho = density, kg/m^3 cp = heat capacity, J/kgK r = radius, m Returns ------- py = pyrolysis number, - """ py = h / (kr * rho * cp * r) return py
5a9868feeeaa5a99cf06e2c47671beeab7d45156
654,542
from datetime import datetime def get_current_datetime() -> datetime: """ Generate datetime in UTC timezone. Returns: datetime: datetime. """ return datetime.utcnow()
f93af05b4660306545e2e505c50a7fd016ec2773
635,359
import typing def days(day: typing.Union[str, int]) -> str: """ Humanize the number of days. Parameters ---------- day: Union[int, str] The number of days passed. Returns ------- str A formatted string of the number of days passed. """ day = int(day) if day == 0: return '**today**' return f'{day} day ago' if day == 1 else f'{day} days ago'
f6ae38fa8d8a9a9679854af52716c38e57249061
349,108
def palindrome(word): """ Verify if a word is a palindrome. The palindrome are words or phrases that you can read equally in both sides. Whether is palindrome returns True else False >>> palindrome("radar") True >>> palindrome("taco cat") True >>> palindrome("holah") False >>> palindrome("Ana") True >>> palindrome("Atar a la rata") True """ if word.lower().replace(" ", "") == word[::-1].lower().replace(" ", ""): return True return False
5fa97cf41ddc750b1fb1c1c808b829984ed29bbe
94,783
from typing import NamedTuple def _to_dict(conf: NamedTuple): """Convert nested named tuple to dict.""" d = conf._asdict() for k in conf._fields: el = getattr(conf, k) if hasattr(el, '_asdict'): d[k] = _to_dict(el) return d
1ef32f61b3903ace12c80de78df934a50d6d14e1
657,284
def hide(ans): """ To hide the answer form the user. :param ans: str, the initiated random word :return riddle: str, has an identical length of ans but with each alphabet covered with '-' """ riddle = '' for i in range(len(ans)): riddle += '-' return riddle
651724593b59ee1d51404d5092a6d109ac3a04df
144,436
def _policy_profile_generator(total_profiles): """ Generate policy profile response and return a dictionary. :param total_profiles: integer representing total number of profiles to return """ profiles = {} for num in range(1, total_profiles + 1): name = "pp-%s" % num profile_id = "00000000-0000-0000-0000-00000000000%s" % num profiles[name] = {"properties": {"name": name, "id": profile_id}} return profiles
ad7c6eaf9cb9230d74eb0edef7f2051b3b2d181d
363,555
def valid_url(string): """Checks if the given url is valid Parameters ---------- string: str Url which needs to be validated Returns ------- bool """ if string and (string[:7] == "http://" or string[:8] == "https://"): return True return False
06ac6a0f62ffd6c0dcbfc07603d84f3e3151eb13
331,084
def well_row_name(x): """Return a well row name for the given zero-based index""" if x < 26: return chr(ord("A") + x) return chr(ord("A") + int(x / 26) - 1) + chr(ord("A") + x % 26)
76beaba56e67ff1a3b107ea0e47af6f120426d60
465,504
def crop(img, xmin, xmax, ymin, ymax): """Crops a given image.""" if len(img) < xmax: print('WARNING') patch = img[xmin: xmax] patch = [row[ymin: ymax] for row in patch] return patch
d0b3e628fadd5d5e5cb742a406ead69ed5fd0e3d
396,147
def get_col_names_and_indices(sqlite_description, ignore_gt_cols=False): """Return a list of column namanes and a list of the row indices. Optionally exclude gt_* columns. """ col_indices = [] col_names = [] for idx, col_tup in enumerate(sqlite_description): # e.g., each col in sqlite desc is a tuple like: # ('variant_id', None, None, None, None, None, None) col_name = col_tup[0] if ((not ignore_gt_cols) or (ignore_gt_cols and not col_name.startswith('gt'))): col_indices.append(idx) col_names.append(col_name) return col_names, col_indices
804d1b80e56ba043a68ff7fa899a8b111a6cd74f
517,634
def aoec_lung_concepts2labels(report_concepts): """ Convert the concepts extracted from lung reports to the set of pre-defined labels used for classification Params: report_concepts (dict(list)): the dict containing for each lung report the extracted concepts Returns: a dict containing for each lung report the set of pre-defined labels where 0 = absence and 1 = presence """ report_labels = dict() # loop over reports for rid, rconcepts in report_concepts.items(): # assign pre-defined set of labels to current report report_labels[rid] = { 'cancer_scc': 0, 'cancer_nscc_adeno': 0, 'cancer_nscc_squamous': 0, 'cancer_nscc_large': 0, 'no_cancer': 0} # make diagnosis section a set diagnosis = set([concept[1].lower() for concept in rconcepts['Diagnosis']]) # update pre-defined labels w/ 1 in case of label presence for d in diagnosis: if 'small cell lung carcinoma' == d: report_labels[rid]['cancer_scc'] = 1 if 'lung adenocarcinoma' == d or 'clear cell adenocarcinoma' == d or 'metastatic neoplasm' == d: report_labels[rid]['cancer_nscc_adeno'] = 1 if 'non-small cell squamous lung carcinoma' == d: report_labels[rid]['cancer_nscc_squamous'] = 1 if 'lung large cell carcinoma' == d: report_labels[rid]['cancer_nscc_large'] = 1 # update when no label has been set to 1 if sum(report_labels[rid].values()) == 0: report_labels[rid]['no_cancer'] = 1 return report_labels
37d6ae91c688e0ff02259dd2c3c64d3fdf0b7921
355,002
def isPandigital10(s): """Check if number is pandigital from 0-9, i.e. that it has all digits from 0 to 9.""" if len(s) != 10: return False for i in range(0, 10): if s.find(str(i)) == -1: return False return True
6529bb56e665cf4fde98624d9d58dbf2b3575f22
174,291
import collections import itertools def merge_mutation_sets( mutations_a, mutations_b): """Constructs all possible merges of mutations sets `mutations_a` and `mutations_b`. Merging two mutation sets involves combining all the mutations together into a combined mutation set. A valid mutation set has mutations to unique positions. For a given position P, if there are mutations in the both of the two sets, then a valid merge can include either the mutation to position P from set A or B. Thus, for M positions with overlap, this function returns 2^{M} merged mutation sets. >>> m1 = [(0, 2), (1, 3)] >>> m2 = [(0, 4), (3, 5)] >>> merge_mutation_sets(m1, m2) [((0, 2), (1, 3), (3, 5)), ((0, 4), (1, 3), (3, 5))] Args: mutations_a: An iterable of tuples encoding mutations (position, mutation). mutations_b: See `mutations_a`. Returns: All possible merges of mutation sets `mutations_a` and `mutations_b`. """ assert all(len(m) == 2 for m in mutations_a) assert all(len(m) == 2 for m in mutations_b) position_idx = 0 grouped_mutations = collections.defaultdict(list) for m in list(mutations_a) + list(mutations_b): position = m[position_idx] grouped_mutations[position].append(m) singletons = [] collisions = [] for position, muts in grouped_mutations.items(): if len(muts) == 1: singletons.append(muts[0]) else: collisions.append(muts) to_return = [] for c in itertools.product(*collisions): mutations = c + tuple(singletons) sorted_mutations = tuple(sorted(mutations, key=lambda m: m[position_idx])) to_return.append(sorted_mutations) to_return = sorted(to_return) return to_return
7294a96ef758e4aebef21ca50950f406c16370a5
173,860
def same_keys(a, b): """Determine if the dicts a and b have the same keys in them""" for ak in a.keys(): if ak not in b: return False for bk in b.keys(): if bk not in a: return False return True
841a6d715fdfcefb9a2557e01b7ccb586fd62c06
44,053
def print_badges(badges): """Return TeX lines for a list of badges.""" lines = [] for badge in badges: if badge == 'dividertag': lines.append('\n\\divider\\smallskip\n\n') elif badge == 'br': lines.append('\\\\\\smallskip') else: lines.append('\\cvtag{' + badge + '}\n') return lines
c13a3dafe96afd136972a13c13548910e357bb31
339,625
def modeladmin_register(modeladmin_class): """ Method for registering ModelAdmin or ModelAdminGroup classes with Wagtail. """ instance = modeladmin_class() instance.register_with_wagtail() return modeladmin_class
7694455b26a84e76f313c2121ebb4721fc658d19
507,684
def numpy_array_reshape(var, isSamples, n_dim): """ Reshape a numpy to a give dimensionality by adding dimensions with size one in front (broadcasting). If *isSamples* is true, keep the first dimension. :param var: the variable to be reshaped. :type var: numpy.ndarray :param isSamples: whether the variable is a sampled variable with the first dimension being the number of samples. :type isSamples: boolean :param n_dim: the dimensionality that the variable is reshaped to. :type n_dim: int :returns: the reshaped numpy array :rtype: numpy.ndarray """ if len(var.shape) < n_dim: if isSamples: var_reshape = var.reshape( *((var.shape[0],) + (1,) * (n_dim - len(var.shape)) + var.shape[1:])) else: var_reshape = var.reshape(*((1,) * (n_dim - len(var.shape)) + var.shape)) else: var_reshape = var return var_reshape
8d31d3e8856a71cd6b66d9ae5058dda33556fd28
552,818
def internal(fn): """ Decorator which does not affect functionality but it is used as marker which tells that this object is not interesting for users and it is only used internally """ return fn
fa9a31962a4f45f7794ec42fc4f2507c52c4535a
22,312
def determine_refframe(phdr): """Determine the reference frame and equinox in standard FITS WCS terms. Parameters ---------- phdr : `astropy.io.fits.Header` Primary Header of an observation Returns ------- out : str, float Reference frame ('ICRS', 'FK5', 'FK4') and equinox """ # MUSE files should have RADECSYS='FK5' and EQUINOX=2000.0 equinox = phdr.get('EQUINOX') radesys = phdr.get('RADESYS') or phdr.get('RADECSYS') if radesys == 'FK5' and equinox == 2000.0: return 'FK5', equinox elif radesys: return radesys, None elif equinox is not None: return 'FK4' if equinox < 1984. else 'FK5', equinox else: return None, None
0d15f35c044cb993e7568988aebbec15308e2656
123,234
import hashlib def hash_md5(file): """ 返回文件file的md5值 :param file: 文件 :return: md5值 """ hasher = hashlib.md5() # chunks()是方法,之前把括号漏了 for chunk in file.chunks(): hasher.update(chunk) return hasher.hexdigest()
4475e89adb963c7298eb8ab9066421c082d0e7db
107,377
def get_exponent(bits): """Given a value representing a float (in the machine), return the exponent. """ return ((bits >> 23) & 0xff)
e4e9d225cee5b86e2da5042228eebf9f2c13fa8e
485,390
import re def booleannet2bnet(rules): """Converts BooleanNet rules to BNet format. e.g., an input of "A*=B or C and not D" returns A, B | C & !D Also replaces ~ with ! Parameters ---------- rules : str BooleanNet formatted rules. Returns ------- str BNET formatted rules. """ s = re.sub("\s*\*\s*=\s*",",\t",rules) # replace "=" with ",\t" s = re.sub("\s+not\s+"," !",s, flags=re.IGNORECASE) # not -> ! s = re.sub("\(\s*not\s+","(!",s, flags=re.IGNORECASE) # not -> ! (with parens) s = re.sub("\s*~\s*"," !",s, flags=re.IGNORECASE) # ~ -> ! s = re.sub("\s+and\s+"," & ",s, flags=re.IGNORECASE) # and -> & s = re.sub("\s+or\s+"," | ",s, flags=re.IGNORECASE) # or -> | s = re.sub("False","0",s, flags=re.IGNORECASE) # False -> 0 (ignore case) s = re.sub("True","1",s, flags=re.IGNORECASE) # True -> 1 (ignore case) return s
d7a2c4a8d291d71690162dd0773d525ab9014a5b
402,704
def loadraw(path, static=False): """Loads raw file data from given path with unescaped HTML. Arguments: path (str): Path to the file to read. static (bool): If True, all the `{` and `}` will be replaced with `{{` and `}}` respectively. Example: >>> # $ cat path/to/file.html >>> # <p>{foo}</p> >>> >>> loadtxt("path/to/file.html") >>> b'<p>{foo}</p>' >>> >>> loadtxt("path/to/file.html", static=True) >>> b'<p>{{foo}}</p>' """ with open(path) as f: data = f.read().strip() if static: data = data.replace("{", "{{").replace("}", "}}") return data.encode()
438d4128bd72a81f46e581984d1cf53b3d11254a
19,581
def iptup_to_str(formatted_tuple: tuple[str, int]) -> str: """ Converts a tuple IP address into a string equivalent This function is like the opposite of ``ipstr_to_tup`` :param formatted_tuple: A two-element tuple, containing the IP address and the port. Must be in the format (ip: str, port: int) :type formatted_tuple: tuple[str, int] :return: A string, with the format "ip:port" :rtype: str """ return f"{formatted_tuple[0]}:{formatted_tuple[1]}"
ff3cb457a1396935ee0c9d6834fa8f17c65c4970
693,762
def define_names(r=11,c=11): """ Funzione che definisce i nomi delle coordinate degli spettri sul sample. I nomi sono del tipo r1c1,r1c2, ecc. Come default usa 11 colonne e 11 righe. Il primo nome è wn, che sta per wave number. """ #definisco i nomi da assegnare ai punti delli spettri di sampling #wn -> wave number r -> row c -> columns names = ['wn']+[f'r{k}c{i}' for k in range(1,r+1) for i in range(1,c+1)] return names
df32bf9b1b8520269efb14ed6f27f8aa011e182a
169,396
def filter_recursive(x_or_iterable): """ Filter out elements that are Falsy (where bool(x) is False) from potentially recursive lists. :param x_or_iterable: An element or a list. :return: If x_or_iterable is not an Iterable, then return x_or_iterable. Otherwise, return a filtered version of x_or_iterable. """ if isinstance(x_or_iterable, list): new_items = [] for sub_elem in x_or_iterable: filtered_sub_elem = filter_recursive(sub_elem) if filtered_sub_elem is not None and not ( isinstance(filtered_sub_elem, list) and len(filtered_sub_elem) == 0 ): new_items.append(filtered_sub_elem) return new_items else: return x_or_iterable
937cc5f1e82d1839c4dde7f29f6106f0a707b64f
304,769
def E(q, r0, x, y): """Return the electric field vector E=(Ex,Ey) due to charge q at r0.""" den = ((x-r0[0])**2 + (y-r0[1])**2)**1.5 return q * (x - r0[0]) / den, q * (y - r0[1]) / den
9934e43075016ea4377395fdf5ee260769d40986
156,650
import ipaddress def prefix_to_network(prefix): """Convert an IP prefix to an IP-address and network mask.""" ipaddr = ipaddress.ip_interface(prefix) # turn into ipaddress object address = ipaddr.ip mask = ipaddr.netmask return address, mask
ac521405d5bdd90f082bc4d0e5f434b7a5b7f3f7
697,476
def make_subsequences(x, y, step=1, max_len=2 ** 31): """ Creates views to all subsequences of the sequence x. For example if x = [1,2,3,4] y = [1,1,0,0] step = 1 the result is a tuple a, b, where: a = [[1], [1,2], [1,2,3], [1,2,3,4] ] b = [1,1,0,0] Note that only a view into x is created, but not a copy of elements of x. Parameters ---------- X : array [seq_length, n_features] y : numpy array of shape [n_samples] Target values. Can be string, float, int etc. step : int Step with which to subsample the sequence. max_len : int, default 2 ** 31 Step with which to subsample the sequence. Returns ------- a, b : a is all subsequences of x taken with some step, and b is labels assigned to these sequences. """ r = range(step-1, len(x), step) X = [] Y = [] for i in r: start = max(0, i - max_len) stop = i+1 X.append(x[start:stop]) Y.append(y[i]) return X, Y
6b3b14de8548fa1ec316273a48eb22ebc975021c
102,130
def list_to_string(string_arg): """ Some methods arguments parsing of a list to a string. """ if string_arg: return '.'.join(string_arg) else: return string_arg
59bb76e8f9d4956a55ab89441c3a18229e6a5c92
221,822
from typing import Dict def get_example_brand_map() -> Dict[str, str]: """ Return notebooks brand mapping based on simple regex. The mapping is from patterns found in menu_items to the items brand. The returned dictionary {key, value} has the following structure: key is the regex search pattern value is the value this pattern is mapped to :returns: dictionary with notebooks brand mapping """ return { "heineken": "heineken", "coca.cola": "coca-cola", "red.bull": "red bull", "pizza": "unbranded", "tee": "unbranded", "hamburger": "unbranded", "stella": "stella artois", "tee mit milch": "unbranded", "kaffee mit sucker": "unbranded", "rode wijn": "unbranded", "fles witte": "unbranded", }
171a3b5de7c3a8f893a3b4f632f62072e38ca5d5
680,002
def make_name_from_str(string, max_size=100): """ Return a name that is capitalized and without spaces """ return ''.join( '%s%s' % (w[0].upper(), w[1:]) for w in string.split() )[:max_size]
c2492dc09977a6a1ae1ff2476f466825b055d49d
360,131
def addVectors(v1, v2): """assumes v1, and v2 are lists of ints. Returns a list containing the pointwise sum of the elements in v1 and v2. For example, addVectors([4, 5], [1, 2, 3]) returns [5, 7, 3], and addVectors([], []) returns []. Does not modify inputs.""" if len(v1) > len(v2): result = v1 other = v2 else: result = v2 other = v1 for i in range(len(other)): result[i] += other[i] return result
e23cf80cd905b0a7ce957c0f569ae955c14161fc
444,105
def protobuf_name(entry): """ Return the protocol buffer field name for input metadata entry Returns: A string. Ex: "android_colorCorrection_availableAberrationModes" """ return entry.name.replace(".", "_")
54c63f5f616abd224857986b893b7e9c8ee3f8d6
372,827
from typing import Counter def compareLists(a, b): """ Compare two lists, return true if they are just the same under a permutation. Parameters ---------- a, b : list of any The two lists to compare. Returns bool whether a and b are the same under a permutation. """ return Counter(a) == Counter(b)
f23e2d1cf6e9c434c93f95ead4e548e05c4a912d
585,004
def get_new_size_zoom(current_size, target_size): """ Returns size (width, height) to scale image so smallest dimension fits target size. """ scale_w = target_size[0] / current_size[0] scale_h = target_size[1] / current_size[1] scale_by = max(scale_w, scale_h) return (int(current_size[0] * scale_by), int(current_size[1] * scale_by))
e0b42eab3d35ba5c662282cab1ffa798327ad92a
704,801
import csv def csv2dict(fname): """ read a csv file to a dict when keys and values are separate by a comma Parameters ---------- fname: csv fname with two columns separated by a comma Returns ------- a python dictionary """ reader = csv.reader(open(fname, 'r')) d = {} for row in reader: k, v = row d[k] = v return d
92ea03145e70c3358b44e62cf926eef8366eac58
135,514
def jaccard(a, b): """ Jaccard stability index """ a, b = set(a), set(b) return 1.*len(a.intersection(b))/len(a.union(b))
81cc164d4a78dd26ca6158539e0c1e3c06bdce60
577,362
def abbrev_key ( key: str, ) -> str: """ Abbreviate the IRI, if any key: string content to abbreviate returns: abbreviated IRI content """ if key.startswith("@"): return key[1:] key = key.split(":")[-1] key = key.split("/")[-1] key = key.split("#")[-1] return key
6cb2058f32d6320f1be118d8831cc074cd0cc56f
17,608
def cell_from_screenspace(screenspace_coords: tuple, tile_size: int): """ Helper function to convert from screenspace coordinates to tile row and column. Calculations based on texture base tile size; no boundary checking is performed. Parameters: screenspace_coords (Tuple[float, float]): The X and Y screeenspace coordinates of the probe location. Returns: Tuple[int, int]: Array containing the X and Y values of the corresponding tile coordinate. """ return tuple( map( lambda n: int(n * (1 / tile_size)), screenspace_coords ) )
717f2f6e60a9bd973ca32bba1c7173734fcb7266
595,175
def count_false_positives_for_given_class(class_list, class_c): """ Count the False positives for the given class """ false_positive_count = 0 for item in range(len(class_list)): if item != class_c: false_positive_count += class_list[item] # Return the false positive count return false_positive_count
24f5050bdc72cd2c9625f79accdb25a1151ccd08
518,614
import json def loadJsonFile(filePath: str) -> dict: """ Load json file. :param filePath: File path. :type filePath: str :returns: Json data. :rtype: dict """ with open(filePath) as fp: data = json.load(fp) return data
1cb95ce6b904e69edd88704fedcf963d93b3c1f1
97,471
import string def clean_document(document): """ Removes punctuation from a document, and converts everything to lowercase """ return document.translate(None, string.punctuation).lower()
bfbbc4fae38078715b9c3376f977ce5281547af8
452,676
def f2(a, b): """Returns True exactly when a is False and b is True.""" if not a and b: return True else: return False
f4b0dd7d7c9199ee11bad770e8fdb5ee69080be4
367,297
def expose(operation=None, action='GET', is_long=False): """ A decorator for exposing methods as BLL operations/actions Keyword arguments: * operation the name of the operation that the caller should supply in the BLL request. If this optional argument is not supplied, then the operation name will be the name of the method being decorated. * action the name of the action (typically ``GET``, ``PUT``, ``DELETE`` or ``POST``) that will be matched against the BLL request. If this optional argument is not supplied, then the dispatching mechanism will ignore the action. * is_long indicates that the method being decorated is a long-running function. Long-running methods may either be called once (via complete) or twice (via handle for validation and via for the rest) depending on their signature -- if the method has an argument (other than self), then it will be called twice, in which case the parameter will be populated with a boolean indicating whether it is being called via handle; in this case, the function should return a recommended polling interval. Note, if you override handle or complete, this decorations will be ignored! When a normal (short-running) method is called, its return value should just be the data portion of the response. The handle method will take care of building a full BllResponse structure and placing this return value in the data portion. Otherwise, if there are any problems, the method should just throw an appropriate exception. The handle method will catch the exception and package it up in an appropriate BllResponse object. The decorator can be applied multiple times to the same function, in order to permit a function to be called via multiple operations. For example:: class MySvc(SvcBase) @expose('add_stuff') @expose('update_stuff') def add_or_update(self): ... """ def decorate(f): f.exposed = True if not hasattr(f, 'operation'): f.operation = [] f.operation.append(operation or f.__name__) if action: f.action = action if is_long: f.is_long = is_long # normally a decorator returns a wrapped function, but here # we return f unmodified, after registering it return f return decorate
fd10b3460e575c673f68ea6a76f71d27c845c8b7
433,779
def common_prefix(n: int) -> str: """ For a given number of subgraphs, return a common prefix that yields around 16 subgraphs. >>> [common_prefix(n) for n in (0, 1, 31, 32, 33, 512+15, 512+16, 512+17)] ['', '', '', '', '1', 'f', '01', '11'] """ hex_digits = '0123456789abcdef' m = len(hex_digits) # Double threshold to lower probability that no subgraphs match the prefix return hex_digits[n % m] + common_prefix(n // m) if n > 2 * m else ''
6977533e5f3679335a9ab9a80ae39c75edf0dd04
470,942
def is_improvement( best_value: float, current_value: float, larger_is_better: bool, relative_delta: float = 0.0, ) -> bool: """ Decide whether the current value is an improvement over the best value. :param best_value: The best value so far. :param current_value: The current value. :param larger_is_better: Whether a larger value is better. :param relative_delta: A minimum relative improvement until it is considered as an improvement. :return: Whether the current value is better. """ if larger_is_better: return current_value > (1.0 + relative_delta) * best_value # now: smaller is better return current_value < (1.0 - relative_delta) * best_value
a8ea7f1bbf6e44f52cbda827b153b4286c86645a
287,500
def title_or_url(node): """ Returns the `display_name` attribute of the passed in node of the course tree, if it has one. Otherwise returns the node's url. """ title = getattr(node, 'display_name', None) if not title: title = str(node.location) return title
7a2a90dc683a77490ed005b66d2666151421f940
104,234
from typing import List from typing import Any def reverse(array: List[Any]) -> List[Any]: """ Returns a new array with elements in a reverse order of the input array. The first array element becomes the last, and the last array element becomes the first. """ return array[::-1]
3a6738f84b4dadbca41a4aa6d8c489a47600216f
348,371
def get_menu_item_params(source, func): """ Return the arguments to pass to pm.menuItem to create a menu item matching a shelf or shelf popup item. source is the name of the shelf/popup, and func is either pm.shelfButton or pm.menuItem. """ properties = ['label', 'image', 'annotation'] cmd = {} for prop in properties: kwargs = {} kwargs[prop] = True cmd[prop] = func(source, q=True, **kwargs) return cmd
3782491f02ce032f84370d8751c352c04445b80d
191,669
def lookup_clutter_geotype(geotype_lookup, population_density): """Return geotype based on population density Params: ====== geotype_lookup : list of (population_density_upper_bound, geotype) tuples sorted by population_density_upper_bound ascending """ highest_popd, highest_geotype = geotype_lookup[0] middle_popd, middle_geotype = geotype_lookup[1] lowest_popd, lowest_geotype = geotype_lookup[2] if population_density < middle_popd: return lowest_geotype elif population_density > highest_popd: return highest_geotype else: return middle_geotype
4bdcbdaa2e778b26432a9c49edde7ab099e8a031
91,260
def estimated_total(N: int, sample_mean: float) -> float: """Calculates the estimated population total given the sample mean.""" return sample_mean * N
452ec967fab046f03d4dd9060467831ffe68ad9e
317,953
import hashlib def hashkey(value): """ Provide a consistent hash that can be used in place of the builtin hash, that no longer behaves consistently in python3. :param str/int value: value to hash :return: hash value :rtype: int """ if isinstance(value, int): value = str(value) value = value.encode("utf-8") return int(hashlib.sha256(value).hexdigest(), 16)
a858840cd8eaec16897e6fc3df889f7bf78a7bbe
498,719
import re def _findFirst( pattern, src ): """ A helper function that simplifies the logic of using regex to find the first match in a string. """ results = re.findall( pattern, src ) if len(results) > 0: return results[0] return None
ced30ea0a31e22c0e78157ea193243ff04816b10
82,762
import logging def heart_rate(length_of_strip, count): """Determine the average heart rate from the ECG strip Another of the calculated data was the estimated average heart rate over the length of the ECG strip. To determine this, two values are necessary, the duration of the ECG strip and the number of peaks present. With these two values, the following formula was utilized to calculate the estimated average heart rate: Heart Rate = (# beats / duration of ECG strip) * (60 seconds / minute) With this formula, the average heart rate is found and returned by this function. Parameters ---------- length_of_strip : float Contains duration of ECG strip in seconds count : int Value containing the number of peaks present Returns ------- float Contains the average heart rate (beats per minute) """ logging.info("Determining the estimated average heart rate") mean_hr = count/length_of_strip * 60 # 60 sec / min return mean_hr
c9e59a47f53472e75e2be448c01ae903f2263f04
408,495
import math def chute_size(mass, velocity=3, drag=0.75, gravity=9.8, air_density=1.22): """ Determine the required size of a chute given a mass and a velocity. mass: mass of rocket in kg velocity: velocity of the rocket when it hits the earth in m/s drag: drag coefficient for chute """ return math.sqrt((8 * mass * gravity) / (math.pi * air_density * drag * velocity ** 2))
7714ce2328c929700dff053af02d3a28808ad73c
224,604
def gnome_sort(lst: list) -> list: """ Pure implementation of the gnome sort algorithm in Python Take some mutable ordered collection with heterogeneous comparable items inside as arguments, return the same collection ordered by ascending. Examples: >>> gnome_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> gnome_sort([]) [] >>> gnome_sort([-2, -5, -45]) [-45, -5, -2] >>> "".join(gnome_sort(list(set("Gnomes are stupid!")))) ' !Gadeimnoprstu' """ if len(lst) <= 1: return lst i = 1 while i < len(lst): if lst[i - 1] <= lst[i]: i += 1 else: lst[i - 1], lst[i] = lst[i], lst[i - 1] i -= 1 if i == 0: i = 1 return lst
5aae393eabd046c20f51125e405d211555ed9bdb
22,057
def valid_parentheses(parens): """Are the parentheses validly balanced? >>> valid_parentheses("()") True >>> valid_parentheses("()()") True >>> valid_parentheses("(()())") True >>> valid_parentheses(")()") False >>> valid_parentheses("())") False >>> valid_parentheses("((())") False >>> valid_parentheses(")()(") False """ d = {"(" : 1, ")" : -1} s = 0 for c in parens: s = s + d[c] if s < 0: return False return s == 0
12d65523e1cb7472191094dd54d4f2e12167e504
493,158
def should_attach_entry_state(current_api_id, session): """Returns wether or not entry state should be attached :param current_api_id: Current API selected. :param session: Current session data. :return: True/False """ return ( current_api_id == 'cpa' and bool(session.get('editorial_features', None)) )
c22c592c2b65f143d0df5c0735a0c21f7347ee71
27,573
def get_ancestors(cur, term_id): """Return a set of ancestors for a given term ID, all the way to the top-level (below owl:Thing) :param cur: database Cursor object to query :param term_id: term ID to get the ancestors of""" cur.execute( f"""WITH RECURSIVE ancestors(node) AS ( VALUES ('{term_id}') UNION SELECT object AS node FROM statements WHERE predicate IN ('rdfs:subClassOf', 'rdfs:subPropertyOf') AND object = '{term_id}' UNION SELECT object AS node FROM statements, ancestors WHERE ancestors.node = statements.stanza AND statements.predicate IN ('rdfs:subClassOf', 'rdfs:subPropertyOf') AND statements.object NOT LIKE '_:%' ) SELECT * FROM ancestors""", ) return set([x[0] for x in cur.fetchall()])
b051a83eac81d2efdbd8a5f314dd3868e95cdcea
547,235
import re def unpack_namedtuple(name: str) -> str: """Retrieve the original namedtuple class name.""" return re.sub(r"\bnamedtuple[-_]([^-_]+)[-_\w]*", r"\1", name)
896fd15577a9b23be3855b8e21262478025e7ae0
465,186