content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def is_ascii(byte_string): """Check if a byte string is ascii""" try: byte_string.decode('ascii') except UnicodeEncodeError: return False return True
dbe637acf20877ba85d6db9fd05178f0f161f399
230,105
from functools import reduce def every(args): """Return True if all elements of args are True.""" return reduce(lambda x, y: x and y, args, True)
3ffbc3dc79f388a978dab0b74ff7da2afab5adb7
475,354
def reverse(text): """ Reverse text """ return text[::-1]
8b95e7cf9d91e5e25117ecc87fb56a44f3f99760
567,706
def get_landing_url(sending_profile): """Get url for landing page.""" return f"http://{sending_profile['landing_page_domain']}"
8d2724bb5c4b17d9a58f88d71fcf1135ea3fcd42
211,480
import torch def convert_y_to_one_hot(y, nc): """Converts a tensor of labels to a one_hot encoded version""" new_y = torch.zeros([len(y), nc], dtype=torch.uint8, device='cpu') y = y.view(-1, 1) new_y.scatter_(1, y, 1) return new_y
706f8dea4ae209bdd6097384aa530cd641de357d
493,467
def git_line(*items): """Formats items into a space separated line.""" return b" ".join(items) + b"\n"
750a207ef0b93fec633a6b08c5e7703893032f3e
97,465
def uniquify_key(dict, key, template="{} ({})"): """ rename key so there are no duplicates with keys in dict e.g. if there is already a key named "dog", the second key will be reformatted to "dog (2)" """ n = 1 new_key = key while new_key in dict: n += 1 new_key = template.format(key, n) return new_key
eccf1659c674dc52af95ce4ba62b950e19645a26
395,620
def squared_error(x, y): """ Squared error, element wise :param x: (B,d) :param y: (B,d) :return: (B,) """ d = x - y z = d * d z = z.view(z.shape[0], -1) return z
2267ada210c4e9cd071bfe593c13a29f8eceded3
355,291
from datetime import datetime def is_sierra_export(file_handle: str) -> bool: """ Returns only file handles that follow Sierra export naming schema Args: file_handle: file handle Returns: boolean """ if not isinstance(file_handle, str): return False if len(file_handle) != 25: return False if file_handle[:11] not in ("BookOpsQCb.", "BookOpsQCn."): return False try: datetime.strptime(file_handle[11:], "%Y%m%d%H%S%f") except ValueError: return False return True
762a3d1b09daa3c19c71cd7bec7c4801c25dec70
509,284
def next_perm_string(digits): """Generate next Lexographic permutation, digits is string""" i = -1 for i_ in range(1, len(digits)): if int(digits[i_-1]) < int(digits[i_]): i = i_ if i == -1: return False suffix = digits[i:] prefix = digits[:i-1] pivot = digits[i-1] j = 0 for j_ in range(i, len(digits)): if int(digits[j_]) > int(pivot): j = j_ suffix = suffix[:j-i] + pivot + suffix[j-i+1:] pivot = digits[j] new_digits = prefix + pivot + suffix[::-1] return new_digits
26eaff40fd33029d1b7f421560a1a83ae550323a
420,506
def _coord_names(frame): """Name the coordinates based on the frame. Examples -------- >>> _coord_names('icrs')[0] 'ra' >>> _coord_names('altaz')[0] 'delta_az' >>> _coord_names('sun')[0] 'hpln' >>> _coord_names('galactic')[0] 'glon' >>> _coord_names('ecliptic')[0] 'elon' >>> _coord_names('turuturu')[0] Traceback (most recent call last): ... ValueError: turuturu: Unknown frame """ if frame in ["icrs", "fk5"]: hor, ver = "ra", "dec" elif frame == "altaz": hor, ver = "delta_az", "delta_el" elif frame == "sun": hor, ver = "hpln", "hplt" elif frame == "galactic": hor, ver = "glon", "glat" elif frame == "ecliptic": hor, ver = "elon", "elat" else: raise ValueError(f"{frame}: Unknown frame") return hor, ver
916132071835040811fa1d2f4313969fa9c5c686
153,022
def fmt_app_name(appname): """Format a sysl_pb2.AppName as a syntactically valid string.""" return ' :: '.join(appname.part)
531f60a311136d7a97767287a64298dc2add59d4
590,788
def insert_term(c, term): """Inserts the term into the database and returns the ID. """ c.execute( 'INSERT OR IGNORE INTO search_term (term) VALUES (?);', (term,) ) c.execute('SELECT id FROM search_term WHERE term=?;', (term,)) search_id = c.fetchone()[0] return search_id
f78ca2479586864531d16c92222474d4db1b61e7
129,128
def pipeline_upto_step_4(pipeline_upto_step_3): """ PyTest Fixture: returns a pipeline that executes once per session up to step 4. """ kaldi, ds, pd, m = pipeline_upto_step_3 # Step 4 # ====== # Make a transcription interface and transcribe unseen audio to elan. t = kaldi.new_transcription('transcription_w') t.link(m) t.transcribe_algin('/recordings/untranscribed/audio.wav') return (kaldi, ds, pd, m, t)
2d76d512b73b9ba26e6afdc49e6886e0246f4f80
473,271
def flatten(inp): """ The function to flatten a nested list or tuple of lists, tuples or ranges, with any number of nested levels. From StackOverflow by James Brady (http://stackoverflow.com/users/29903/james-brady) http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python/406822#406822 """ out = [] for el in inp: if isinstance(el, (list, tuple, range)): out.extend(flatten(el)) else: out.append(el) return out
bb0d28b5d070d36661faabe45352a2fd480774b7
514,820
def make_gain_db(conf): """Generate a db domain gain function Args: conf: a dict {'db': #float} 'db': the gaining value Returns: The db gain function, which could be applied on a float amplitude value """ db = conf['db'] def gain_db(x): return min(0.997, x * pow(10, db / 20)) return gain_db
58f1763de67ff5f94b0cd897821e967a7cb59834
214,939
import time def timeme(method): """@timeme decorator. Place before any function you want timed. Example: @timeme def print_after_three(s): time.sleep(3) return s print_after_three("testing timeme") >> ('print_after_three', 3003, 'ms') """ def wrapper(*args, **kw): startTime = int(round(time.time() * 1000)) result = method(*args, **kw) endTime = int(round(time.time() * 1000)) print(method.__name__, endTime - startTime,'ms') return result return wrapper
15bd7bc0b99f81cd3d61ec792f69ae8f0636ead4
549,890
def roll(*parts: str) -> str: """ formats parts of a roll into a string Returns: The string of the sum of the parts """ return " + ".join(parts)
9b7dd8501a2d8a0af5452c8742ab956c8d511439
212,841
import ctypes def _get_openblas_version(openblas_dynlib): """Return the OpenBLAS version None means OpenBLAS is not loaded or version < 0.3.4, since OpenBLAS did not expose its version before that. """ get_config = getattr(openblas_dynlib, "openblas_get_config") get_config.restype = ctypes.c_char_p config = get_config().split() if config[0] == b"OpenBLAS": return config[1].decode('utf-8') return None
b53d1c03f7da36d5b2b62e3f7464d3e2ce89d197
101,734
def column_names(row, colnames): """ Pair items in row with corresponding column name. Return dictionary keyed by the column names. """ mapped = {col_name: val for val, col_name in zip(row, colnames)} return mapped
73875baef09eb48b1ea9f8be7a7537bfa3dabfa7
289,831
import re def framework_name_from_image(image_name): """Extract the framework and Python version from the image name. Args: image_name (str): Image URI, which should take the form '<account>.dkr.ecr.<region>.amazonaws.com/sagemaker-<framework>-<py_ver>-<device>:<tag>' Returns: tuple: A tuple containing: str: The framework name str: The Python version """ # image name format: <account>.dkr.ecr.<region>.amazonaws.com/sagemaker-<framework>-<py_ver>-<device>:<tag> sagemaker_pattern = re.compile('^(\d+)(\.)dkr(\.)ecr(\.)(.+)(\.)amazonaws.com(/)(.*)(:)(.*)$') sagemaker_match = sagemaker_pattern.match(image_name) if sagemaker_match is None: return None, None else: # extract framework and python version name_pattern = re.compile('^sagemaker-(tensorflow|mxnet)-(py2|py3)-(cpu|gpu)$') name_match = name_pattern.match(sagemaker_match.group(8)) if name_match is None: return None, None else: return name_match.group(1), name_match.group(2)
d464b7ff4f2c3ad3f521baf7667b5391d816298f
351,603
def context_get(stack, name): """ Find and return a name from a ContextStack instance. """ return stack.get(name)
a5a9a50c54e8f0f685e0cf21991e5c71aee0c3d6
703,501
def validate_graph_colors(graph): """ Validates that each graph node has a color distinct from the colors of its neighbors. :param graph: the graph to examine :return: boolean indicating whether the graph nodes have valid colors """ for graph_node in graph: print(graph_node.color + ': ' + ', '.join(str(o.color) for o in graph_node.neighbors)) if graph_node.color in (o.color for o in graph_node.neighbors): return False return True
e2c3add1621027fd263d8466161ddc832a27f640
129,134
from typing import Union def _get_address_from_instance_response(instance_response: dict) -> Union[str, None]: """ Extracts the instance's IP address (public if possible, private if not) from the boto3 response dict :param instance_response: Boto3 response dict :return: IP address of the instance (public if possible, private if not) """ if instance_response['Reservations']: instance = instance_response['Reservations'][0]['Instances'][0] return instance['PublicIpAddress'] if 'PublicIpAddress' in instance else instance['PrivateIpAddress'] else: return None
08c7623ec2d1e0af8a36b3fafdf8439ae818c80f
646,160
from typing import Dict from typing import List def _get_status_dict(status: str) -> Dict[str, str]: """Return status dict from status message.""" status_list: List[List[str]] = [] for line in status.splitlines(): line = line.lstrip() line = line.replace(". ", ";") line = line.replace(".", "") lines: List[str] = line.split(";") if len(lines) > 1: status_list.append(lines) return {k[0]: k[1] for k in status_list}
013ac69613983f481c76c12b5de0e9617d4d54be
233,221
from typing import OrderedDict def eliminate_except_param(loaded_param, not_eliminate): """ Ex: loaded2 = torch.load(os.path.join('model2-baseline', 'checkpoint.pth')) loaded2 = eliminate_except_param(loaded2, ['net.1.weight', 'net.1.bias']) loaded.update(loaded2) :param loaded_param: An OrderedDict. :param not_eliminate: A list of key. :return adict: OrderedDict with keys in not_eliminate and their values. """ assert type(not_eliminate) == list keep_key = [] keep_value = [] for key, value in loaded_param.items(): if key in not_eliminate: keep_key.append(key) keep_value.append(value) adict = OrderedDict() for i, j in zip(keep_key, keep_value): adict[i] = j return adict
d6c6cb562376921392dd3caf20648fa0a69df7fc
174,149
import itertools from typing import MutableSequence from typing import Sequence from typing import Hashable def is_matrix(item: object) -> bool: """Returns whether 'item' is an adjacency matrix. Args: item (object): instance to test. Returns: bool: whether 'item' is an adjacency matrix. """ if isinstance(item, tuple) and len(item) == 2: matrix = item[0] labels = item[1] connections = list(itertools.chain(matrix)) return ( isinstance(matrix, MutableSequence) and isinstance(labels, Sequence) and not isinstance(labels, str) and all(isinstance(i, MutableSequence) for i in matrix) and all(isinstance(n, Hashable) for n in labels) and all(isinstance(e, int) for e in connections)) else: return False
81b3d58e4b7eb24d254470cb7b77280eac49a24d
380,322
import csv def read_scores(input, delimiter, score_index=3): """ Reads the scores from a bed file into a list of floats :param input: Input file object :param delimiter: delimiter character, e.g. tab, comma, or space :param score_index: column index of the score value :return: A list of scores (still strings) """ scores = list() reader = csv.reader(input, delimiter=delimiter) for row in reader: scores.append(row[score_index]) return scores
a000bdfe87ae58f203f1b360baa040541cd00f47
213,950
def init_field(height=20, width=20): """Creates a field by filling a nested list with zeros.""" field = [] for y in range(height): row = [] for x in range(width): row.append(0) field.append(row) return field
0b61b12bec1ad506da357715139bef37b407b576
659,400
import asyncio import functools def call_later(delay, fn, *args, **kwargs) -> asyncio.Handle: """ Call a function after a delay (in seconds). """ loop = asyncio.get_event_loop() callback = functools.partial(fn, *args, **kwargs) handle = loop.call_later(delay, callback) return handle
86d157ed0f5f8dc7f806af9871a71057dc36222c
9,959
def _get_course_id(store, course_data): """Returns the course ID.""" return store.make_course_key(course_data['org'], course_data['number'], course_data['run'])
9ae140da648e9d85469bdfee2779fb6562343d47
563,451
def compute_leading_dashes_y(alignment, ind_x, seq_x, seq_y, scoring_matrix, alignment_matrix): """ int, str, str, int, str, str, dict of dict, list of list -> int, str, str, int, int Helper function that takes the current alignment strings and score and then computes the next pair in the alignment with the remaining values in the y alignment string being dashes. Returns the current position in seq_x and seq_y as well as the current score and alignment strings. """ alignment[1] = seq_x[ind_x - 1] + alignment[1] alignment[2] = '-' + alignment[2] ind_x -= 1 alignment[0] += scoring_matrix[alignment[1][0]][alignment[2][0]] return alignment[0], alignment[1], alignment[2], ind_x
87033b508505fd5ea57e9af7135d8b2f4145d93d
597,063
def sort_string(string: str) -> str: """Sort a string into alphabetical order.""" return "".join(sorted(string))
f6ef6c20bb48e39253c14f9cafff692d75d47916
348,645
def parse_line(line): """ Parse each line of the file to get age and number of friends :param line: a line form the file :return: a Tuple with age and number of friends """ fields = line.split(',') age = int(fields[2]) num_friends = int(fields[3]) return age, num_friends
40f858101388c7212033c9d1ab64363c49b8366d
333,633
def _checkshape(shape, maxshape): """Return True if the shape is consistent with the maximum allowed shape. Each element of shape must be less than or equal to the corresponding element of maxshape, unless the latter is set to None, in which case the value of the shape element is unlimited. Parameters ---------- shape : tuple of int Shape to be checked. maxshape : tuple of int Maximum allowed shape Returns ------- bool True if the shape is consistent. """ for i, j in [(_i, _j) for _i, _j in zip(maxshape, shape)]: if i is not None and i < j: return False return True
31a1c438598b895e0c660e39ca92a1bfbf92474f
166,539
from typing import Any import pickle def pickle_load(file_name: str) -> Any: """ Load the pickle file Args: file_name (str): file name Returns: Any: python object type """ with open(file_name, 'rb') as file: return pickle.load(file)
28942a1d8724628790dc2145cfce36913a481bdf
529,095
def _ssl_cn(server_hostname): """ Return the common name (fully qualified host name) from the SERVER_HOSTNAME. """ host_port = server_hostname.rsplit(":", 1) # SERVER_HOSTNAME includes the port if len(host_port) == 2: if host_port[-1].isdigit(): return host_port[-2] return server_hostname
428c7623b282caef5bd23e76cdce0bbf663837ea
608,697
def rquicksort(arr): """Recursive quicksort""" if len(arr) <= 1: return arr return rquicksort([i for i in arr[1:] if i < arr[0]]) + \ [arr[0]] + \ rquicksort([i for i in arr[1:] if i > arr[0]])
8690739311a34d654eadb84b64184ce3576057b2
566,833
from typing import List import re def split_authors(authors: str) -> List: """ Split author string into authors entity lists. Take an author line as a string and return a reference to a list of the different name and affiliation blocks. While this does normalize spacing and 'and', it is a key feature that the set of strings returned can be concatenated to reproduce the original authors line. This code thus provides a very graceful degredation for badly formatted authors lines, as the text at least shows up. """ # split authors field into blocks with boundaries of ( and ) if not authors: return [] aus = re.split(r'(\(|\))', authors) aus = list(filter(lambda x: x != '', aus)) blocks = [] if len(aus) == 1: blocks.append(authors) else: c = '' depth = 0 for bit in aus: if bit == '': continue if bit == '(': # track open parentheses depth += 1 if depth == 1: blocks.append(c) c = '(' else: c = c + bit elif bit == ')': # track close parentheses depth -= 1 c = c + bit if depth == 0: blocks.append(c) c = '' else: # haven't closed, so keep accumulating continue else: c = c + bit if c: blocks.append(c) listx = [] for block in blocks: block = re.sub(r'\s+', ' ', block) if re.match(r'^\(', block): # it is a comment listx.append(block) else: # it is a name block = re.sub(r',?\s+(and|\&)\s', ',', block) names = re.split(r'(,|:)\s*', block) for name in names: if not name: continue name = name.rstrip().lstrip() if name: listx.append(name) # Recombine suffixes that were separated with a comma parts: List[str] = [] for p in listx: if re.match(r'^(Jr\.?|Sr\.?\[IV]{2,})$', p) \ and len(parts) >= 2 \ and parts[-1] == ',' \ and not re.match(r'\)$', parts[-2]): separator = parts.pop() last = parts.pop() recomb = "{}{} {}".format(last, separator, p) parts.append(recomb) else: parts.append(p) return parts
f6c3952f2b8a2a06411d4acfcda97f55adcd1ba9
54,012
import asyncio def swait(co): """Sync-wait for the given coroutine, and return the result.""" return asyncio.get_event_loop().run_until_complete(co)
3fca650eadce043602a07c909a0988846e6405e0
675,574
import torch def test_clf(args, model, test_loader, crit): """ Tests the classification model over the test set. """ model.eval() loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(args.device), target.to(args.device) output = model(data) # loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss loss += crit(output, target).item() * data.shape[0] # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() loss /= len(test_loader.dataset) acc = 100. * correct / len(test_loader.dataset) print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.1f}%)'.format( loss, correct, len(test_loader.dataset), acc), flush=True) return loss, acc
036f86dba4165dba761bdb1bf13613fb40f184bd
571,976
import torch def gaussian_kld(mu_left, sigma_left, mu_right, sigma_right): """ Provided by @anirudh Compute KL divergence between a bunch of univariate Gaussian distributions with the given means and log-variances. We do KL(N(mu_left, logvar_left) || N(mu_right, logvar_right)). """ logsigma_left = sigma_left.log() logsigma_right = sigma_right.log() logvar_left = 2 * logsigma_left logvar_right = 2 * logsigma_right gauss_klds = 0.5 * (logvar_right - logvar_left + (torch.exp(logvar_left) / torch.exp(logvar_right)) + ((mu_left - mu_right) ** 2.0 / torch.exp(logvar_right)) - 1.0) assert len(gauss_klds.size()) == 2 return gauss_klds return torch.sum(gauss_klds, 1)
9ddf9bc7dac2e40e169fd2f87bb782022ecfd12d
362,946
def thousands_separated(number): """Separate an integer with thousands commas for presentation.""" return f"{number:,}"
b853bb8a14b9f24ac13dc3def6c87ed8ab985831
411,001
def AND_nobias(x1: int, x2: int) -> int: """ [summary] AND operator wituout bias term Args: x1 (int): 1st input for AND x2 (int): 2nd input for AND Returns: int: result of AND operator """ (w1, w2, theta) = (0.5, 0.5, 0.7) tmp = w1 * x1 + w2 * x2 if tmp <= theta: return 0 else: return 1
e58a125a9c21233b8de7a044e5c0acdfdb29d1fa
18,009
def _tag_block(block, tag): """Add the open and close tags to an input block.""" return f'<{tag}\n' + block + f'\n{tag}>\n'
bdd53897ec782b37e150592838ea11c58ae1d793
102,048
def sql_name(raw_name): """ Cleaned column name. Args: raw_name: raw column name Returns: cleaned name suitable for SQL column """ sql_name = raw_name for to_replace in ['"', ' ', '\\', '/', '(', ')', '.']: sql_name = sql_name.replace(to_replace, '_') return sql_name.strip()
faa72162ed8e048833972f93a155dc002f44a1a8
647,135
import torch def batch_unpadding(_input, lens, right=True): """ :param: _input: m x n tensor :param: lens: list with size of m :param: right: eliminate padding from right if true """ if right: return torch.cat([x[:lens[i]] for i, x in enumerate(_input) if lens[i] > 0 ]) else: return torch.cat([x[-lens[i]:] for i, x in enumerate(_input) if lens[i] > 0 ])
143077351e69ba3b4662ef5d30616169def7219f
538,397
import torch def image_pt_to_np(image): """ Convert a PyTorch image to a NumPy image (in the OpenCV format). """ image = image.cpu().clone() image = image.permute(1, 2, 0) image_mean = torch.tensor([0.485, 0.456, 0.406]) image_sd = torch.tensor([0.229, 0.224, 0.225]) image = image * image_sd + image_mean image = image.clip(0, 1) return image
4a7a83bf604c17df728b5c9f1d7ced2d3c2bef41
246,637
import random def generate_tag_info() -> dict: """ Generates metadata used for creating a tag record Returns: Tag metadata (dict) """ def simulate_tag(): dataset_name = "test_dataset" dataset_set = f"set_{str(random.randint(0, 10))}" version = f"version_{str(random.randint(0, 10))}" return [dataset_name, dataset_set, version] return { meta: [simulate_tag() for _ in range(random.randint(1, 10))] for meta in ["train", "evaluate", "predict"] }
cc847bd62d9767af94ed868040077c215a66e04d
518,883
import six def _bytes(*vals): """ This is a private utility function which takes a list of byte values and creates a binary string appropriate for the current Python version. It will return a `str` type in Python 2, but a `bytes` value in Python 3. Values should be in byte range, (0x00-0xff):: _bytes(1, 2, 3) == six.b('\\x01\\x02\\x03') :param vals: arguments are a list of unsigned bytes. :return: a `str` in Python 2, or `bytes` in Python 3 """ return six.b('').join(six.int2byte(v) for v in vals)
49d3648ed733b1d80824d97695b32486d0e6d8b3
75,057
from typing import Any def safe_lower(obj: Any) -> Any: """Return lowercase string if the provided obj is a string, otherwise return the object itself. :return: Any """ if isinstance(obj, str): return obj.lower() return obj
a1487fa3ac686feeb2c6cf1d5cc67a9036b25ca8
408,739
def to_bytes(value) : """ Decodes value to bytes. Args: value : Value to decode to bytes Returns: :obj:`bytes` : Return the value as bytes: if type(value) is :obj:`bytes`, return value; if type(value) is :obj:`str`, return the string encoded with UTF-8; otherwise, returns bytes(value). """ if value is None : return value elif type(value) is bytes : return value elif type(value) is str : return value.encode('utf-8') else : return bytes(value)
e38b7348c84d570caa2891b1d3be8fa789eda615
73,180
def my_add(a, b): """Adds two inputs Parameters ---------- a : int, float b : int, float Returns ------- sum : int, float Sum of a and b """ if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): raise TypeError('Input to my_add should be either integers or floats') return a + b
55d7133ee33aec9a5ac2cc891de4be5ec7f8140a
519,550
import requests def get_swapi_resource(url, params=None, timeout=10): """Returns a response object decoded into a dictionary. If query string < params > are provided the response object body is returned in the form on an "envelope" with the data payload of one or more SWAPI entities to be found in ['results'] list; otherwise, response object body is returned as a single dictionary representation of the SWAPI entity. Parameters: url (str): a url that specifies the resource. params (dict): optional dictionary of querystring arguments. timeout (int): timeout value in seconds Returns: dict: dictionary representation of the decoded JSON. """ if params: return requests.get(url, params, timeout=timeout).json() else: return requests.get(url, timeout=timeout).json()
fbf3e163c153ad5d362aef2fe4d245c275da45f4
557,768
def config_dict_changed(module): """ return true if 'config' dict in hash is different between desired and current config """ current_config = module.custom_current_config.get('config') desired_config = module.custom_desired_config.get('config') return current_config != desired_config
29c15e5ade086fcb443698f3df941c1278d578f2
344,262
def positive_integer(anon, obj, field, val): """ Returns a random positive integer (for a Django PositiveIntegerField) """ return anon.faker.positive_integer(field=field)
f6dc73ea33731d4788e72598f266df9c3436d322
85,864
def nthwords2int(nthword): """Takes an "nth-word" (eg 3rd, 21st, 28th) strips off the ordinal ending and returns the pure number.""" ordinal_ending_chars = 'stndrh' # from 'st', 'nd', 'rd', 'th' try: int_output = int(nthword.strip(ordinal_ending_chars)) except Exception as e: raise Exception('Illegal nth-word: ' + nthword) return int_output
10338beff5fdafb612efc090e6d0edd39c757c1b
486,925
def falsy_to_none_callback(ctx, param, value): # noqa: U100 """Convert falsy object to ``None``. Some click arguments accept multiple inputs and instead of ``None`` as a default if no information is passed, they return empty lists or tuples. Since pytask uses ``None`` as a placeholder value for skippable inputs, convert the values. Examples -------- >>> falsy_to_none_callback(None, None, ()) is None True >>> falsy_to_none_callback(None, None, []) is None True >>> falsy_to_none_callback(None, None, 1) 1 """ return value if value else None
9168083987696f7749ca8444356d32f08bde7e91
19,122
import io def make_buffer(cls=io.BytesIO, initial_value=None, name=None, noclose=False): """ Construct a new in-memory file object aka "buf". :param cls: Class of the file object. Meaningful values are BytesIO and StringIO. :param initial_value: Passed directly to the constructor, this is the content of the returned buffer. :param name: Associated file path. Not assigned if is None (default). :param noclose: If True, disables the .close function. :return: Instance of `cls`. """ buf = cls(initial_value) if initial_value else cls() if name is not None: buf.name = name if noclose: buf.close = lambda: None return buf
925d027fffea3c229d74971369a406ed78af3805
451,202
def __toCurveString(c): """ Returns the string description of the curve. :param c: The curve :type c: Curve :return: str -- The curve's name if not empty, otherwise, the curve's plotname """ if c.name: return c.name return c.plotname
f54ddc1d5fe96a034c8eb83f7a54b6c1e37de5c0
602,987
def getChunks(dsets,nbchunks): """ Splits dataset object into smaller chunks Parameters: * dsets (dict): dataset * nbchunks (int): number of data chunks to be created Returns: * dict: chunks from dataset stored as dictionaries """ ret = [] for ichunk in range(nbchunks): datagrp = {} for groupnm in dsets: alldata = dsets[groupnm] surveys = {} for inp in alldata: datalist = alldata[inp] nrpts = len(datalist) start = int(ichunk * nrpts / nbchunks) end = int((ichunk+1) * nrpts / nbchunks) datalist = datalist[start:end] surveys.update({inp: datalist}) datagrp.update({groupnm: surveys}) ret.append(datagrp) return ret
d693ad68b142816b5d43bde37f01d757ced60298
670,579
def is_supdict(X, Y): """ checks whether X contains Y, i.e., whether X is a "super-dictionary" of Y. returns bool. """ return set(X.items()).issuperset(set(Y.items()))
214bc3f6727f5c13239c6c4409b572d1de021176
493,042
import requests from typing import Any def tid_repo_prompt(image_data_url: str): """ Prompt for TID repo image selection :param image_data_url: base url of the TID repo imaegs :return: download link of the image or None """ entry_number: int = int(input("Please enter image number: ")) - 1 try: response: requests.Response = requests.get(image_data_url) except Exception as error: print("[red]Perhaps you are not connected to the internet. Mind checking it again?") else: if not response.ok: print(f"[red]Oops, something went wrong {response.status_code}") return image_data: Any = response.json() if entry_number >= len(image_data): entry_number: int = 1 file_name = image_data[entry_number]["image_name"] file_type = image_data[entry_number]["file_type"] return f"https://raw.githubusercontent.com/Muhimen123/TID/main/images/{file_name}.{file_type}"
049bd987d8f10bee0e01a7c660bd2bf949846de7
66,134
def checkDecimal(string): """Checks if the string has a decimal place""" for i in string: if i == '.': return True return False
63e8e10f320bd88b1e0e19839112af889d5f5189
183,239
def _ParseChannelData(data): """Parse a CSV string containing Chrome channel data from omahaproxy. Args: data: A string of CSV data from omahaproxy. Returns: A list of dictionaries. Each dictionary represents a channel release and contains information about that release. """ data = data.strip() rows = data.split('\n') keys = rows[0].split(',') rows = rows[1:] results = [] for row in rows: entries = row.split(',') channel_data = {} for i in range(len(keys)): channel_data[keys[i]] = entries[i] results.append(channel_data) return results
f20dbd9708f4f4b14d6a3d34599f6bf2ccde0354
264,758
from typing import Tuple def _get_middle_tunes(qx: float, qy: float) -> Tuple[float, float]: """ Get the tunes with the factional part in the middle between the qx and qy fractional parts, but with the same integer part. """ qx_frac, qy_frac = qx % 1, qy % 1 qmid_frac = 0.5 * (qx_frac + qy_frac) qx_mid = int(qx) + qmid_frac qy_mid = int(qy) + qmid_frac return qx_mid, qy_mid
0f954bed6f3ee61aae94bd3629a050f46ea8b0d8
509,206
def format_usage(usage, rate): """format the resource usage to show integer if greater than the rate, otherwise show one decimal place.""" usage = float(usage) / rate if usage < 1: usage = round(usage, 1) else: usage = int(round(usage, 0)) return usage
109f94d98882d16adb080154bae8c3f295664616
417,178
import hashlib def get_hash(path): """ Returns the SHA256 hash of a file. # Arguments path: str. Path to the file to produce a hash for. # Return value 64-character lowercase string of hexadecimal digits representing the 32-byte SHA256 hash of the file content. """ with open(path, 'rb') as fh: data = fh.read() sha = hashlib.sha256() sha.update(data) return sha.hexdigest()
6ba9733fa97872a7885b71773f04501113ae36e3
395,488
def get_prob_from_odds( odds, outcome ): """ Get the probability of `outcome` given the `odds` """ oddFor = odds[ outcome ] oddAgn = odds[ 1-outcome ] return oddFor / (oddFor + oddAgn)
b4507dde8285c357cb17c1b749657a2c634efa63
656,305
def fill_class_weights(weights, max_id=-1): """ Gets a dictionary of labels with their weights and creates a list with size of the labels filled with those weights. Missing labels in the dictionary would get value 1. Args: weights: dictionary of weights for labels, labels as keys and weights are their values max_id: the largest label id in the dataset, default=-1 would consider the largest label in the weights dictionary as max_id Returns: weights_list: list of weights for labels """ if max_id < 0: max_id = 0 for l in weights.keys(): max_id = max(max_id, l) all_weights = [1.0] * (max_id + 1) for i in range(len(all_weights)): if i in weights: all_weights[i] = weights[i] return all_weights
edc47e8ce74460d32848a88ecc34d99a27fc83a8
147,478
def compute_flesch_reading_ease(total_syllables, total_words, total_sentences): """ Computes readability score from summary statistics :param total_syllables: number of syllables in input text :param total_words: number of words in input text :param total_sentences: number of sentences in input text :return: A readability score: the lower the score, the more complex the text is deemed to be """ return ( 206.85 - 1.015 * (total_words / total_sentences) - 84.6 * (total_syllables / total_words) )
8b0bc43274766dd0f2e3f7b585f79bf1ccd427dc
44,609
def cleaner(f): # Wrapper function """Makes printed text easier to read by creating border around the text""" def wrap(*args, **kwargs): print("==" * 20) f(*args, **kwargs) print("==" * 20) print("\n") return wrap
d6aee194cb96b293425e43729abf67432976d220
489,565
def tokenize_sentence(untokenized_str): """ Returns a tokenized string Args: untokenized_str : a given sentence Returns: list of words from the given sentence """ return [word for word in untokenized_str.split(" ")]
144b345db971d02a53124ae6705f1cfcb1c7d130
162,110
def convert_to_string(argument): """ Args: argument (bool or None): O bool que vai ser convertido para string Returns: str: Vai retornar sim/não ou nulo de acordo com o parâmetro """ if argument is None: return 'nulo' elif argument: return 'sim' else: return 'não'
572c8bb23a05ef9ebfcd97cd236ce734ad86ce87
205,723
def clang_is_loc_in_range(location, source_range): """Returns whether a given Clang location is part of a source file range.""" if source_range is None or location is None: return False start = source_range.start stop = source_range.end file = location.file if file != start.file or file != stop.file: return False line = location.line if line < start.line or stop.line < line: return False return start.column <= location.column <= stop.column
fcbbef53fd320200a95d3a09a2c07b53b59ef079
318,193
from datetime import datetime import pytz def parse_datetime(x): """ Parses datetime with timezone formatted as: `[day/month/year:hour:minute:second zone]` Example: `>>> parse_datetime('13/Nov/2015:11:45:42 +0000')` `datetime.datetime(2015, 11, 3, 11, 45, 4, tzinfo=<UTC>)` Due to problems parsing the timezone (`%z`) with `datetime.strptime`, the timezone will be obtained using the `pytz` library. """ dt = datetime.strptime(x[1:-7], "%d/%b/%Y:%H:%M:%S") dt_tz = int(x[-6:-3]) * 60 + int(x[-3:-1]) return dt.replace(tzinfo=pytz.FixedOffset(dt_tz))
784f2b43363f9c70f4eee4ee7bf8ad5ede835d3e
498,687
def yatch(dice): """ Score the dice based on rules for YACHT. """ points = 0 if dice.count(dice[0]) == len(dice): points = 50 return points
2606336c162f97d5c0a6a53ae905cf410395de03
86,466
def jsonapi_errors(jsonapi_errors): """Construct api error according to jsonapi 1.0 :param iterable jsonapi_errors: an iterable of jsonapi error :return dict: a dict of errors according to jsonapi 1.0 """ return {'errors': [jsonapi_error for jsonapi_error in jsonapi_errors], 'jsonapi': {'version': '1.0'}}
6e357794ebd952d8f51fd350b8ad36521c50973d
260,628
import base64 def _urlsafe_b64encode(s: bytes) -> bytes: """ Base 64 URL safe encoding with no padding. :param s: input str to be encoded :return: encoded bytes """ return base64.urlsafe_b64encode(s).rstrip(b"=")
50b007c54f516b4ccc3b48ca89b10bed3853517a
640,153
import torch import math def rand_sphere(size): """ Randomly sample on the sphere uniformly See http://corysimon.github.io/articles/uniformdistn-on-sphere/ Our convention is 0 < theta < pi ; -pi < phi < pi :param size: torch.size or list of ints, size of returned tensors :return: theta, phi """ theta = torch.acos(1 - 2 * torch.rand(size)) phi = 2 * math.pi * torch.rand(size) - math.pi return theta, phi
fe8a54da47c13b736e5b46839969b9899bbc6769
107,442
def _run_patched(mover, patches, inputs): """Run the move with the given patches for the given inputs""" for p in patches: p.start() change = mover.move(inputs) for p in patches: p.stop() return change
5875244e1310dcfd2e22889c36029c872d0c4eb8
106,487
def random_walk_step(r, p0, W, pt): """ r = probability of restart p0 = initial probability vector W = column-normalized adjacency matrix pt = probability vector at time step t pt = probability vector at time step t + 1 """ #print 'r', r #print 'W', W #print 'pt', pt #print 'p0', p0 #pt1 = (1 - r) * W.dot(pt) + r * p0 pt1 = (1 - r) * W * pt + r * p0 return pt1
047ae6ff08a1a6f0bef579ab026a46c747de5953
646,099
def count_hosts(facts): """Count the number of unique hosts""" hosts = set([fact['certname'] for fact in facts]) return len(hosts)
40e1dc335b864fdd66f9d83e11a27418890a0c00
146,599
def from_c_string(addr): """utf-8 decode a C string into a python string""" if addr is None: return None if type(addr) == str: return addr return addr.decode('utf-8')
df5b4da226c2cdb35bc4490233f10c04b559c111
404,522
def is_proto_only_paramater(parameter: dict): """Whether the parameter is only included in the proto file and not the driver API.""" return parameter.get("proto_only", False)
c14660f235937078a4c0a3e87a824752244b316d
501,594
from typing import List def _read_get_graph_source_citation_section(jcamp_dict: dict) -> List[str]: """ Extract and translate from the JCAMP-DX dictionary the SciData JSON-LD citations in the 'sources' section from the '@graph' scection. :param jcamp_dict: JCAMP-DX dictionary to extract citations from :return: List for citation from SciData JSON-LD """ citation = [] if "$ref author" in jcamp_dict: citation.append(f'{jcamp_dict["$ref author"]} :') if "$ref title" in jcamp_dict: citation.append(f'{jcamp_dict["$ref title"]}.') if "$ref journal" in jcamp_dict: citation.append(f'{jcamp_dict["$ref journal"]}') if "$ref volume" in jcamp_dict: citation.append(f'{jcamp_dict["$ref volume"]}') if "$ref date" in jcamp_dict: citation.append(f'({jcamp_dict["$ref date"]})') if "$ref page" in jcamp_dict: citation.append(f'{jcamp_dict["$ref page"]}') return citation
dafe4fd793dd0e47b690d6c1fd745ca89265de39
701,610
def pde_string(w, rhs_description, ut = 'u_t', print_imag=False): """ Prints a pde based on: w: weights vector rhs_description: a list of strings corresponding to the entries in w ut: string descriptor of the time derivative print_imag: whether to print the imaginary part of the weights Returns: pde: string with the pde """ pde = ut + ' = ' first = True for i in range(len(w)): if w[i] != 0: if not first: pde = pde + ' + ' if print_imag==False: pde = pde + "(%.5f)" % (w[i].real) + rhs_description[i] + "\n " else: pde = pde + "(%.5f %0.5fi)" % (w[i].real, w[i].imag) + rhs_description[i] + "\n " first = False return pde
965f06d335bc9daa700fd85fa5450d1713f04e6d
265,482
def binary_search(lis, elem, start, end): """ Return index of matched position of elem in lis between index start and end (inclusive) or return -1 :param lis: Sorted list :param elem: element to search """ assert 0 <= start <= end < len(lis) if end == start: # If there is only one element to search, check that element only if lis[start] == elem: return start return -1 mid = (start + end) // 2 mid_elem = lis[mid] if mid_elem == elem: return mid if mid_elem < elem: # If middle element is less than our required element then search in the right of array if end > mid: return binary_search(lis, elem, mid + 1, end) return -1 if mid_elem > elem: # If middle element is larger than our required element then search in the left of array if start < mid: return binary_search(lis, elem, start, mid - 1) return -1
7b903803b38aa23b2c124a6e23dc14b9bb1c8e28
601,259
import torch def generate_deck_matrix(deck, card_index, v): """ Generate a binary matrix of shape len(deck) * V * V, where row c in the i_th channel represents the i_th card is of color c """ matrix = torch.zeros((len(deck), v, v)) for i in range(card_index, len(deck)): c = deck[i] for j in range(v): matrix[i][c][j] = 1 return matrix
a7a81b7c066df17306fa1ce6970c4f4f14602979
477,033
def signed_int_str(input_int: int): """ Converts an integer into a string that includes the integer's sign, + or - :param int input_int: the input integer to convert to a signed integer string :return str signed_int_str: the signed integer string """ if input_int >= 0: return '+' + str(input_int) else: return str(input_int)
b6ea5e9ccdb8a30273d3bb790a4c9bc663daedcc
653,256
def parse_ins_string(string): """ split up an instruction file line to get the observation names Parameters ---------- string : str instruction file line Returns ------- obs_names : list list of observation names """ istart_markers = ["[","(","!"] iend_markers = ["]",")","!"] obs_names = [] idx = 0 while True: if idx >= len(string) - 1: break char = string[idx] if char in istart_markers: em = iend_markers[istart_markers.index(char)] # print("\n",idx) # print(string) # print(string[idx+1:]) # print(string[idx+1:].index(em)) # print(string[idx+1:].index(em)+idx+1) eidx = min(len(string),string[idx+1:].index(em)+idx+1) obs_name = string[idx+1:eidx] if obs_name.lower() != "dum": obs_names.append(obs_name) idx = eidx + 1 else: idx += 1 return obs_names
73a2cc8395e65df116eabad3d5f2a7fbb1e6f52b
470,660
def is_substring_in_list(needle, haystack): """ Determine if any string in haystack:list contains the specified needle:string as a substring. """ for e in haystack: if needle in e: return True return False
f85ac189ec622aa91d543b5a2d82bc4edcbf0802
650,081
from typing import OrderedDict def aks_get_versions_table_format(result): """Format get-versions upgrade results as a summary for display with "-o table".""" master = result.get('controlPlaneProfile', {}) result['masterVersion'] = master.get('kubernetesVersion', 'unknown') master_upgrades = master.get('upgrades', []) result['masterUpgrades'] = ', '.join(master_upgrades) if master_upgrades else 'None available' agents = result.get('agentPoolProfiles', []) versions, upgrades = [], [] for agent in agents: version = agent.get('kubernetesVersion', 'unknown') agent_upgrades = agent.get('upgrades', []) upgrade = ', '.join(agent_upgrades) if agent_upgrades else 'None available' name = agent.get('name') if name: # multiple agent pools, presumably version = "{}: {}".format(name, version) upgrade = "{}: {}".format(name, upgrades) versions.append(version) upgrades.append(upgrade) result['nodePoolVersion'] = ', '.join(versions) result['nodePoolUpgrades'] = ', '.join(upgrades) # put results in an ordered dict so the headers are predictable table_row = OrderedDict() for k in ['name', 'resourceGroup', 'masterVersion', 'masterUpgrades', 'nodePoolVersion', 'nodePoolUpgrades']: table_row[k] = result.get(k) return [table_row]
d2614ce9c40b5e59c070fc9123e85c05f358fc77
157,244
from datetime import datetime def get_age(year_of_birth): """ Returns the age of the person. """ return datetime.now().year - year_of_birth
0934a2ab17592055418e353f65ee189996f5bbab
55,517
from datetime import datetime def ms_since_epoch(dt): """ Get the milliseconds since epoch until specific a date and time. Args: dt (datetime): date and time limit. Returns: int: number of milliseconds. """ return (dt - datetime(1970, 1, 1)).total_seconds() * 1000
3a7630c0930949f06573292729156c2e881107bd
676,086
import io import zipfile def zip_dict(data, **kwargs): """ Zips a dictionary ``{ str: bytes }``. @param data dictionary @param kwargs see :epkg:`*py:zipfile:ZipFile` @return bytes """ if not isinstance(data, dict): raise TypeError("data must be a dictionary") buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w", **kwargs) as fz: for k, v in sorted(data.items()): if not isinstance(k, str): raise TypeError("Keys must be a string.") if not isinstance(v, bytes): raise TypeError("Values must be bytes.") fz.writestr(k, v) return buffer.getvalue()
b344c169c19da3cebeb97768f0f880068d7dd947
636,222
def maptosequence(fseq,iseq): """ Map a sequence of floats, each element in range 0.0-1.0, to an another sequence of values, find the elements whose indexes are equivalent to a relative position in a range 0-1.0. :param fseq: A list of float values :param iseq: A list of target values :return: A list of integer values equivalent to range of floats. """ equiv_seq = [] folds = len(iseq)-1 for i in fseq: if i<0 or i>1.0: print("Error: Sequence of floats should be only values " "between 0.0 and 1.0") return None equiv_seq.append(iseq[round(float(i)*folds)]) return(equiv_seq)
1573527b5717650cb1211d4e536c5fe819a17312
276,489
def _determinant_3d(H): """ Returns the determinants of a batched 3-D matrix """ detH = (H[..., 0, 0] * (H[..., 1, 1] * H[..., 2, 2] - H[..., 2, 1] * H[..., 1, 2]) + H[..., 0, 1] * (H[..., 1, 2] * H[..., 2, 0] - H[..., 1, 0] * H[..., 2, 2]) + H[..., 0, 2] * (H[..., 1, 0] * H[..., 2, 1] - H[..., 2, 0] * H[..., 1, 1])) return detH
d5945135567e1691039fa54e184a1058244f1b9b
329,986
from typing import List import copy def selection_sort(x: List) -> List: """Selection sort repeatedly swaps the minimum element of a list with the left-most unsorted element, building up a new list that's fully sorted. It has an average time complexity of Θ(n^2) due to the nesting of its two loops. Time complexity for the worst case, when the list is sorted in reverse order, is O(n^2). Time complexity for the best case, when the list is already sorted in the correct order, is Ω(n^2). >>> selection_sort([4, 2, 3, 1, 0, 5]) [0, 1, 2, 3, 4, 5] :param x: list to be sorted :return: new sorted list """ a_list = copy.deepcopy(x) # To avoid modifying the original list length = len(a_list) for i in range(length): unsorted_min_idx = i for idx, element in enumerate(a_list[i:]): if element < a_list[unsorted_min_idx]: unsorted_min_idx += idx a_list[i], a_list[unsorted_min_idx] = a_list[unsorted_min_idx], a_list[i] return a_list
182de87b38bb4dedb2d8798841e12e8bf550e6b5
452,005
import unicodedata def normalized_name(text): """ Strip umlauts and accents from names. Convert input strings to lowercase, convert umlauts, strip accents, replace hyphens with whitespace and remove redundant whitespace. :param text: The input string. :type text: String. :returns: The processed string. :rtype: String. """ text = text.lower() text = text.replace('ß', 'ss') text = text.replace('ä', 'ae') text = text.replace('ö', 'oe') text = text.replace('ü', 'ue') text = text.replace('-', ' ') text = ' '.join(text.split()) text = unicodedata.normalize('NFD', text) text = text.encode('ascii', 'ignore') text = text.decode('utf-8') return text
4aac4f6a086c1dd65cbfa53d820c0880eeb6e447
314,666