content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import re def pgrg_splitter(pgrg_str: str) -> tuple: """ Break up a stored page range into its components. >>> pgrg_splitter("1-5") ('1', '5') """ retVal = (None, None) # pgParts = pgrg_str.split("-") # pgParts = re.split("[-–—]") # split for dash or ndash pgParts = [n.strip() for n in re.split("[-–—]", pgrg_str)] try: pgStart = pgParts[0] except IndexError as e: pgStart = None try: pgEnd = pgParts[1] except IndexError as e: pgEnd = None retVal = (pgStart, pgEnd) return retVal
ee09b239a3c9d62d8a9d8876ae9220ca781b4464
462,453
def get_data(input_string): """ >>> get_data("hi=mom") ('hi', 'mom') >>> get_data("hi=mom # with a comment.") ('hi', 'mom') >>> get_data("# nothing here.") ('', '') """ input_string= input_string.strip() input_string, _, _ = input_string.partition("#") input_string= input_string.rstrip() name, _, value = input_string.partition('=') return name, value
a6f631a9beda62bac4be513736febdf5a651f9f5
465,524
def _map_mobility( dementia: int, falls: int, visual_impairment: int, visual_supervisation: int, ) -> bool: """Maps historic patient's mobility status to True or False.""" if dementia + falls + visual_impairment + visual_supervisation > 0: return True else: return False
11c506e12c6b4c6ffcaf44102c598e29862e59b0
220,704
def strToBool(val): """ Helper function to turn a string representation of "true" into boolean True. """ if isinstance(val, str): val = val.lower() return val in ['true', 'on', 'yes', True]
545754dc7f599bed7a0e75f0d9122bc15b358298
501,120
import requests from bs4 import BeautifulSoup def get_soup(url): """Given a url, returns a BeautifulSoup object of that page's html""" web_page = requests.get(url) return BeautifulSoup(web_page.text, "html.parser")
eedabb426d409f63f0eaf71105f1f329ad7ee1e5
671,956
from datetime import datetime def add_date_to_filename(filename): """ Add current date to a filename. Args: filename (str) Returns: new_filename (str): filename with added date. """ now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("%d-%m-%Y_%H:%M") new_filename = '_'.join([filename, dt_string]) return new_filename
230af86ef7d3d5b8d13d42363c7222f7998bed58
561,174
import torch def load_model(model, filename, optimizer=None, learning_scheduler=None): """ Load the given torch model from the given file. Loads the model by reference, so the passed in model is modified. An optimizer and learning_scheduler object can also be loaded if they were saved along with the model. This can, for instance, allow training to resume with the same optimizer and learning_scheduler state. Parameters ---------- model : torch.nn.Module The pytorch module which should have its state loaded. WARNING: The parameters of this model will be modified. filename: Union[str, Path] The file that contains the state of the model optimizer: torch.optim.Optimizer The pytorch optimizer object which should have its state loaded. WARNING: The state of this object will be modified. optimizer: Union[torch.optim._LRScheduler, object] The pytorch learning rate scheduler object which should have its state loaded. WARNING: The state of this object will be modified. Returns ---------- Optional[int] Model is loaded by reference, so nothing is returned if loading is successful. If the file to load isn't found, returns -1. """ try: model_state_info = torch.load(filename) except FileNotFoundError: return -1 model.load_state_dict(model_state_info['model_state_dict']) if optimizer is not None: optimizer.load_state_dict(model_state_info['optimizer_state_dict']) if learning_scheduler is not None: learning_scheduler.load_state_dict(model_state_info['learning_scheduler_state_dict'])
d1fb4c908de2edd4def7a7f207846116b7a98b81
549,484
def bootstrap_context(value, max_value): """ Returns a Bootstrap contextual string based on the closeness to the max_value Args: value (int): Current value max_value (int): The maximum possible, used to determine a percentage Returns: (str): One of the following Bootstrap contextual strings: 'primary', 'success', 'info', 'warning', 'danger' """ percentage = value / max_value * 100 if percentage >= 80: return 'primary' elif 80 > percentage and percentage >= 60: return 'success' elif 60 > percentage and percentage >= 40: return 'info' elif 40 > percentage and percentage >= 20: return 'warning' else: return 'danger'
451c715143a6321f29e5330b4c4e871a47548813
130,809
import logging def get_batch_size(num_replicas, num_samples, steps): """Calculate and return batch size for numpy inputs. Args: num_replicas: Number of devices over which the model input is distributed. num_samples: Total number of input samples in the input numpy arrays. steps: Number of steps that we run the model for. Returns: batch size used to create the Dataset object from the input numpy arrays. """ if num_samples % steps != 0: logging.warning('The number of input samples %d is not evenly ' 'divisible by the number of steps %d. ' 'Some samples will not be processed as expected.' % (num_samples, steps)) global_batch_size = num_samples // steps if global_batch_size % num_replicas != 0: logging.warning('The total number of batches per step %d is not evenly ' 'divisible by the number of replicas %d used in ' 'DistributionStrategy. Some samples will not be processed ' 'as expected.' % (global_batch_size, num_replicas)) return global_batch_size // num_replicas
81d555130feb2fa81eb019a2525dc84d60a905d2
261,057
def get_number_docs(index_name, es): """ Return the number of indexed documents in ElasticSearch :param index_name: ElasticSearch index file :param es: ElasticSearch object :return: int """ res = es.count(index=index_name) return res['count']
6fb43003d33a1177e1b1ed8da26513db1124a3d3
586,668
def strip_string(value): """Remove all blank spaces from the ends of a given value.""" return value.strip()
0f66367ffc2c651488875ace33e6a44b453c3262
670,700
def trap_eq_factory(x_n, dt, f): """Factory function to return a function for evaluating the trapezoidal integration function. This returns a function of x_(n+1) (x at the next time step) for the given current x (x_n), time step (dt), and function (f). :param x_n: one-dimensional numpy array giving the values of x at the current time step. :param dt: Time step. :param f: Function of x. :returns: trap_eq, callable which takes x_(n+1) and evaluates the trapezoidal formula. """ def trap_eq(x_n_1): """Simply write up the trapezoidal formula.""" return x_n_1 - x_n - dt / 2 * (f(x_n) + f(x_n_1)) # Return our new function. return trap_eq
ea597986cb19252e625cf0aaae5065a6ff3f43d0
554,013
def jobs_to_delete(expected_jobs, actual_jobs): """ Decides on jobs that need to be deleted. Compares lists of (service, instance) expected jobs to a list of (service, instance, tag) actual jobs and decides which should be removed. The tag in the actual jobs is ignored, that is to say only the (service, instance) in the actual job is looked for in the expected jobs. If it is only the tag that has changed, then it shouldn't be removed. :param expected_jobs: a list of (service, instance) tuples :param actual_jobs: a list of (service, instance, config) tuples :returns: a list of (service, instance, config) tuples to be removed """ not_expected = [job for job in actual_jobs if (job[0], job[1]) not in expected_jobs] return not_expected
68c589e019045afe48952ebd23a491ee659f5e7b
255,562
def get_conn_str(db_name): """Returns the connection string for the passed in database.""" return f'postgresql://postgres:postgres123@localhost:5432/{db_name}'
0197fada49a60f22bc716e65692db4c96f91a0af
636,403
import struct def parse_ipv4(address): """ Given a raw IPv4 address (i.e. as an unsigned integer), return it in dotted quad notation. """ raw = struct.pack('I', address) octets = struct.unpack('BBBB', raw)[::-1] ipv4 = b'.'.join([('%d' % o).encode('ascii') for o in bytearray(octets)]) return ipv4
80fe6335b91cf4323e01ca18a370e86d65b91f45
442,325
import json def pj(jdb): """Dumps pretty JSON""" return json.dumps(jdb,sort_keys=True,indent=4)
7235ef14a5a55cee58a5cde72bc65b4b56c66755
663,958
def calcular_iva_propina_total_factura(costo_factura: int) -> str: """ IVA y propina Parámetros: costo_factura (int): Costo de la factura del restaurante, sin impuestos ni propina Retorno: str: Cadena con el iva, propina y total de la factura, separados por coma """ iva = costo_factura * 0.19 propina = costo_factura * 0.10 total = iva + propina + costo_factura cadena = str(round(iva)) + "," + str(round(propina)) + "," + str(round(total)) return cadena
d0946472e5c43551e607a3413fe3cbe5cf888368
471,175
def _compute_win_probability_from_elo(rating_1, rating_2): """Computes the win probability of 1 vs 2 based on the provided Elo ratings. Args: rating_1: The Elo rating of player 1. rating_2: The Elo rating of player 2. Returns: The win probability of player 1, when playing against 2. """ m = max(rating_1, rating_2) # We subtract the max for numerical stability. m1 = 10**((rating_1 - m) / 400) m2 = 10**((rating_2 - m) / 400) return m1 / (m1 + m2)
150a0593152439e1cb5ed57cd7718c79ffe7cf20
570,687
def bytes_to_index(lead, tail): """ Map a pair of ShiftJIS bytes to the WHATWG index. """ lead_offset = 0x81 if lead < 0xA0 else 0xC1 tail_offset = 0x40 if tail < 0x7F else 0x41 return (lead - lead_offset) * 188 + tail - tail_offset
edf98e19d9283b2deaf442e29d50469ea6bc0954
80,623
import re def redundant(search): """returns true if search consists of just an eventtype (e.g. 'eventtype=foo' or 'eventtype="foo bar")""" return re.match('^eventtype=(?:"[^"]*")|(?:[^"][^ ]*)$', search) != None
ca5762651fd9111304c8ecc8de33fed05b3127ce
546,341
def filter_attached_for_up(items, service_names, attach_dependencies=False, item_to_service_name=lambda x: x): """This function contains the logic of choosing which services to attach when doing docker-compose up. It may be used both with containers and services, and any other entities that map to service names - this mapping is provided by item_to_service_name.""" if attach_dependencies or not service_names: return items return [ item for item in items if item_to_service_name(item) in service_names ]
d25374831d0455d93e294ee366f98b44b2d89d0d
330,647
def check_for_chr(sam): """ Check sam file to see if 'chr' needs to be prepended to chromosome """ if 'chr' in sam.references[0]: return True return False
22297aa592faab69d4f7293975738e51fdbacc24
599,037
def verify_input(user_input, correct_input): """Returns True if the user_input is inside correct_input (list) False in other way.""" if user_input in correct_input: return True else: return False
4a3905dddfdebcc8b8d242c0e9033ce135668cd6
340,219
def build_slice_path( data_root, data_suffix, experiment_name, variable_name, time_index, xy_slice_index, index_precision=3 ): """ Returns the on-disk path to a specific slice. The path generated has the following form: <root>/<variable>/<experiment>-<variable>-z=<slice>-Nt=<time><suffix> <slice> and <time> are zero-padded integers formatted according to an optional precision parameter. Takes 7 arguments: data_root - String specifying the root on-disk path for the slice. data_suffix - String specifying the path suffix for the slice. experiment_name - String specifying the experiment that generated the slice. variable_name - String specifying the variable associated with the slice. time_index - Non-negative index specifying the time step associated with the slice. xy_slice_index - Non-negative index specifying the XY slice. index_precision - Optional non-negative integer specifying the precision used when formatting "<slice>" and "<time>". If omitted, defaults to 3. Returns 1 value: slice_name - String specifying the constructed path. """ return "{:s}/{:s}/{:s}-{:s}-z={:0{index_precision}d}-Nt={:0{index_precision}d}.png".format( data_root, variable_name, experiment_name, variable_name, xy_slice_index, time_index, index_precision=index_precision )
68a6f29693f244a6e3ba8a9cd88bd3c14fa75e4d
219,828
def _module_descriptor_file(module_dir): """Returns the name of the file containing descriptor for the 'module_dir'.""" return "{}.descriptor.txt".format(module_dir)
aa29da3e708e63376604c71bf40189b2256e46bb
287,739
def beta_pruning_actions(state): """ Return actions available given a state, we're essentially creating a binary tree, where each parent has two nodes to choose from :param state: The current state :return: The available actions given the current state """ match state: case "a": val = ["a1", "a2"] case "b": val = ["b1", "b2"] case "c": val = ["c1", "c2"] case "d": val = ["d1", "d2"] case "e": val = ["e1", "e2"] case "f": val = ["f1", "f2"] case "g": val = ["g1", "g2"] case _: val = [] # Cases e-m are leaves, so should have no possible actions return val
e9865c0e1ade4d124bb27d491977e570e6df76ed
59,638
import math def get_utm_zone(x, y): """Get EPSG code for utm zone containing x/y lng/lat coordinates.""" utm_code = (math.floor((x + 180)/6) % 60) + 1 lat_code = 6 if y > 0 else 7 epsg_code = int('32%d%02d' % (lat_code, utm_code)) return epsg_code
7ff1ac5c15376ee2b154be5a2612709c0f802427
515,689
import unicodedata def normalize_nfkc(text): """Applies NFKC normalization e.g. ™ to TM, ...""" return unicodedata.normalize("NFKC", text)
5a717be987aaf01320fde844b8f4091459987f15
140,157
from pathlib import Path def _lines_to_set(path): """ Converts lines from the file in the specified path to set of strings which are lines in the file. Returns empty set when file doesn't exist. """ out = set() if Path(path).is_file(): with open(path) as f: out = set(f.read().splitlines()) return out
2f2827bf3ff5c5aff044aacbc5ea1e466403ab94
584,100
def frontiers_from_bar_to_time(seq, bars): """ Converts the frontiers (or a sequence of integers) from bar indexes to absolute times of the bars. The frontier is considered as the end of the bar. Parameters ---------- seq : list of integers The frontiers, in bar indexes. bars : list of tuple of floats The bars, as (start time, end time) tuples. Returns ------- to_return : list of float The frontiers, converted in time (from bar indexes). """ to_return = [] for frontier in seq: bar_frontier = bars[frontier][1] if bar_frontier not in to_return: to_return.append(bar_frontier) return to_return
ea86d14725a6761ba90ba4b62b7f78d687e6a269
48,145
def pythonize(string): """Transforms 'SillyCamelCase' to 'silly_camel_case'""" normed = string[0].lower() for char in string[1:]: if char.isupper(): normed += '_' normed += char.lower() return normed
ee9564e71aee8adedf884c0d0f49f388c7c87f18
357,518
def query(df, query): """ Filter a dataset under a condition --- ### Parameters *mandatory :* - query (*str*): your query as a string (see [pandas doc]( http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html#pandas.DataFrame.query)) --- ### Example **Input** | variable | wave | year | value | |:--------:|:-------:|:--------:|:-----:| | toto | wave 1 | 2014 | 300 | | toto | wave 1 | 2015 | 250 | | toto | wave 1 | 2015 | 100 | | toto | wave 1 | 2016 | 450 | ```cson query: 'value > 350' ``` **Output** | variable | wave | year | value | |:--------:|:-------:|:--------:|:-----:| | toto | wave 1 | 2016 | 450 | """ df = df.query(query) return df
7fb2db6f9a8be3993f8a968892260ad0dd725b55
523,694
from typing import Counter def most_common_elems(lst): """Returns the most common elements from a list. >>> most_common_elems([2, 2, 1]) [2] >>> sorted(most_common_elems([2, 1])) [1, 2] >>> sorted(most_common_elems([3, 2, 1, 3, 2, 4, 5, 7, 3, 1, 1])) [1, 3] """ c = Counter() for elem in lst: c[elem] += 1 mc = c.most_common() return [elems for elems, count in mc if count == mc[0][1]]
9b98a27344626d9db1dc13ca001464c5400c986b
450,276
import re def strip_quotes(s: str) -> str: """Strip a double quote at the beginning and end of the string, if any.""" s = re.sub('^"', '', s) s = re.sub('"$', '', s) return s
d8ff112648fd071ad80bd1303ae1c6123b50468b
187,510
def popis_pozici(pozice): """Popíše pozici pro lidi např: >>> popis_pozici(0, 0) 'a1' """ radek, sloupec = pozice return "abcdefgh"[sloupec] + "12345678"[radek]
efb2df8715b30c04bfdeb82684084f2037ad5e7e
671,470
import random def split_train_test(all_instances, n=None): """ Randomly split `n` instances of the dataset into train and test sets. :param all_instances: a list of instances (e.g. documents) that will be split. :param n: the number of instances to consider (in case we want to use only a subset). :return: two lists of instances. Train set is 8/10 of the total and test set is 2/10 of the total. """ random.seed(12345) random.shuffle(all_instances) if not n or n > len(all_instances): n = len(all_instances) train_set = all_instances[: int(0.8 * n)] test_set = all_instances[int(0.8 * n) : n] return train_set, test_set
68d2d94fcc4d5241e053556fcb4c2e50edfd2396
137,646
def compress(v, slen): """ Take as input a list of integers v and a bytelength slen, and return a bytestring of length slen that encode/compress v. If this is not possible, return False. For each coefficient of v: - the sign is encoded on 1 bit - the 7 lower bits are encoded naively (binary) - the high bits are encoded in unary encoding """ u = "" for coef in v: # Encode the sign s = "1" if coef < 0 else "0" # Encode the low bits s += format((abs(coef) % (1 << 7)), '#09b')[2:] # Encode the high bits s += "0" * (abs(coef) >> 7) + "1" u += s # The encoding is too long if len(u) > 8 * slen: return False u += "0" * (8 * slen - len(u)) w = [int(u[8 * i: 8 * i + 8], 2) for i in range(len(u) // 8)] x = bytes(w) return x
ce45538933efa74e2673d713eae14a9b47e5c020
67,274
def format_path_data(path_data): """ Args: path_data (list or str): Either a list of paths, or just one path. Returns: list: A list of paths """ assert isinstance(path_data, str) or isinstance(path_data, list) if isinstance(path_data, str): path_data = [path_data] return path_data
5e281848d7424f0957f09eda7b9e75314f4f645c
249,616
def avg_words_per_sent(sent_count, word_count): """return the average number of words per sentence""" result = word_count/sent_count return result
04dc6ccf4fde0c61c336f21d166cc370b7c088df
466,934
def get_key_val_of_max_key(dict_obj): """Returns the key-value pair with the largest key in the given dict. Example: -------- >>> dict_obj = {5: 'g', 3: 'z'} >>> print(get_key_val_of_max_key(dict_obj)) (5, 'g') """ return max(dict_obj.items(), key=lambda item: item[0])
d8d6a6836f0c8c0e8e914dd4cdd97f9bf703c5e4
605,233
def _encode_bool(name, value, dummy0, dummy1): """Encode a python boolean (True/False).""" return b"\x08" + name + (value and b"\x01" or b"\x00")
5c6612ed9919286c0cab29b023b69f7872d40ed8
394,762
def get_ip_port(socket_str): """ Returns ip and port :param socket_str: ipv4/6:port :return: address, port """ splitter_index = socket_str.rindex(':') address = socket_str[0:splitter_index] port = socket_str[splitter_index + 1:] return address, port
5a641bc83f81389d6a7ce30610a62476870d3bea
417,230
import re def barcode_is_10xgenomics(s): """ Check if sample sheet barcode is 10xGenomics sample set ID 10xGenomics sample set IDs of the form e.g. 'SI-P03-C9' or 'SI-GA-B3' are also considered to be valid. Arguments: s (str): barcode sequence to validate Returns: Boolean: True if barcode is 10xGenomics sample set ID, False if not. """ return bool(re.match(r'^SI\-[A-Z0-9]+\-[A-Z0-9]+$',s))
4e94ba4606c0a78afda876644d472aecc645aa2e
166,726
def Residuals(xs, ys, inter, slope): """Computes residuals for a linear fit with parameters inter and slope. Args: xs: independent variable ys: dependent variable inter: float intercept slope: float slope Returns: list of residuals """ res = [y - inter - slope*x for x, y in zip(xs, ys)] return res
cce5519c6adddf95b29712d51c698aeb1d531fa4
200,091
def set_compare(a, b): """ Compare two iterables a and b. set() is used for comparison, so only unique elements will be considered. Parameters ---------- a : iterable b : iterable Returns ------- tuple with 3 elements: (what is only in a (not in b), what is only in b (not in a), what is common in a and b) """ a, b = set(a), set(b) return (a-b, b-a, a.intersection(b))
db8e3674198c411355486062cde0258dbaecc5fb
164,394
def outName(finpName): """Returns output filename by input filename""" i = finpName.rfind('.') if i != -1: finpName = finpName[0:i] return finpName + '.hig'
b23092a5356bd6f37ac76bab5af422feb446a3f3
654,353
def bounds(a): """Return a list of slices corresponding to the array bounds.""" return tuple([slice(0,a.shape[i]) for i in range(a.ndim)])
fa9c7c8ed51d5c10ecd4392a72c6efe379a9407b
696,738
import hashlib def sha256(code, input): """sha256 <string> -- Create a sha256 hash of the input string""" return code.say(hashlib.sha256(input.group(2)).hexdigest())
58935c8513a158725ed8e2f42be4c7fdda16c390
124,193
def legendre_polynomial(x: float, n: int) -> float: """Evaluate n-order Legendre polynomial. Args: x: Abscissa to evaluate. n: Polynomial order. Returns: Value of polynomial. """ if n == 0: return 1 elif n == 1: return x else: polynomials = [1, x] for k in range(1, n): new = ((2 * k + 1) * x * polynomials[-1] - k * polynomials[-2]) / (k + 1) polynomials.append(new) return polynomials[-1]
9c1890f54ae0a91b8d4cd8771f7a944fd3f7e7ab
638,006
def compute_adaptive_order(freq, order_min, order_max): """ Computes the superlet order for a given frequency of interest for the fractional adaptive SLT (FASLT) according to equation 7 of Moca et al. 2021. This is a simple linear mapping between the minimal and maximal order onto the respective minimal and maximal frequencies. Note that `freq` should be ordered low to high. """ f_min, f_max = freq[0], freq[-1] assert f_min < f_max order = (order_max - order_min) * (freq - f_min) / (f_max - f_min) # return np.int32(order_min + np.rint(order)) return order_min + order
4ffd3dbff4d62437a479b527a0363afb27c3556b
364,996
def check_param(var, datatype): """Checks if a variable is the correct data type. If it's not correct, return the error message to raise. Parameters ----------- var the variable to check. datatype the data type to compare against. Returns ---------- str the error message to raise. """ if isinstance(var, datatype): return '' return f"{[name for name, value in locals().items() if var == value][0]} expects '{datatype.__name__}' not '{type(var)}'"
51c8ed53e516b3f6b53c2f584ca94f82ed2dd60d
596,530
def split_into_characters(s: str) -> list[str]: """ >>> split_into_characters("PyCon") ['P', 'y', 'C', 'o', 'n'] """ return [character for character in s]
db6a8f5235dec5b9995b682c1c03472fac67ac6a
530,435
def pre_post_delete_callback(req, form, storable): """ Called before or after an item is deleted. The return value from a postdelete callback has no effect. """ return True
536fc7adee4aac56c32983b60b283e6340d9bee9
444,822
def partition(word: str, partitions: int) -> int: """ Find a bucket for a given word. :param word: :param partitions: :return: """ a = ord('a') z = ord('z') value = ord(word[0].lower()) if partitions > 1 and a <= value <= z: pos = value - a return int(pos * (partitions - 1) / (z - a + 1)) + 1 # Catch-all for numbers, symbols and diacritics. return 0
ddf981ca7cdd5ad3bd45f524c706c5901bfeb892
77,084
def getRowUnit(sudoku, i): """ Finds a cell's peers in the row that it is in. Peers are the other numbers in the puzzle. Input sudoku : 9x9 numpy array of integers. i: row index of cell in the puzzle. Output temp_row : numpy list of the cell's peers in the specified row. """ temp_row = [] for y in range(0, 9): temp_row.append(sudoku[i][y]) return temp_row
8b129d54cfea218401a508329278287a537a9436
506,110
def rosenbrock(x, y): """Rosenbrock function, minimum at (1,1) with value of 0""" return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
dea89459bda6cae4b7b2e44f4cfd6f9d135cb46a
537,820
def get_roi(countours, img_height, img_width): """ Computes bounding box which must contain all the passed contours Arguments: contours -- numpy array of shape [num_points, 1, 2] img_height -- int, image height img_width -- int, image width Returns: 4 numbers representing x and y coordinates of bottom left and upper right corners of the resulting ROI """ miny, maxy = float('inf'), -float('inf') minx, maxx = float('inf'), -float('inf') for item in countours[:, :]: x, y = item[0] miny = min(y, miny) maxy = max(y, maxy) minx = min(x, minx) maxx = max(x, maxx) offset = 15 minx = max(minx - offset, 0) maxx = min(maxx + offset, img_width) miny = max(miny - offset, 0) maxy = min(maxy + offset, img_height) return int(minx), int(maxx), int(miny), int(maxy)
a849ee8e21c1b951b112f7f93db4389ce9a1dc45
440,209
from email.mime.text import MIMEText import uuid def new_message(from_email, to_email): """Creates an email (headers & body) with a random subject""" msg = MIMEText('Testing') msg['Subject'] = uuid.uuid4().hex[:8] msg['From'] = from_email msg['To'] = to_email return msg.as_string(), msg['subject']
4895121a4193df9c07dfaf4dc4e48c4c8909360d
251,414
import base64 def base64_encode(string): """ Encodes data with MIME base64 This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies. """ return base64.b64encode(string)
d1632c2952fc470a322926aae6a32a6cbe3cc930
613,735
def select_columns_by_type(df, dtypes): """Return the list of columns which are of object or datetime type Parameters ---------- df: pandas.DataFrame Returns ------- List[str] """ return [ column_name for column_name, column_type in df.dtypes.to_dict().items() if column_type in dtypes ]
23ae845c52df0d4ff26b5c691ff8298f6187772e
490,030
import importlib def is_openeye_installed(oetools=('oechem', 'oequacpac', 'oeiupac', 'oeomega')): """ Check if a given OpenEye tool is installed and Licensed. If the OpenEye toolkit is not installed, returns False. Parameters ---------- oetools : str or iterable of strings, Optional, Default: ('oechem', 'oequacpac', 'oeiupac', 'oeomega') Set of tools to check by their string name. Defaults to the complete set that YANK *could* use, depending on feature requested. Only checks the subset of tools if passed. Also accepts a single tool to check as a string instead of an iterable of length 1. Returns ------- all_installed : bool True if all tools in ``oetools`` are installed and licensed, False otherwise. """ # Complete list of module: License function name. tools_license = {'oechem': 'OEChemIsLicensed', 'oequacpac': 'OEQuacPacIsLicensed', 'oeiupac': 'OEIUPACIsLicensed', 'oeomega': 'OEOmegaIsLicensed'} # Cast oetools to tuple if its a single string. if type(oetools) is str: oetools = (oetools,) # Check if the input oetools are known. if not set(oetools).issubset(set(tools_license)): raise ValueError("Expected an OpenEye tools subset of {}, but instead " "got {}".format(tuple(tools_license), oetools)) # Try loading the module. for tool in oetools: try: module = importlib.import_module('openeye.' + tool) except ImportError: return False # Check that we have the license. if not getattr(module, tools_license[tool])(): return False return True
0e434bef7bf9eaad11bb03993bf46b30875633cf
419,181
def recvall(sock, size: int): """Receive data of a specific size from socket. If 'size' number of bytes are not received, None is returned. """ buf = b"" while size: newbuf = sock.recv(size) if not newbuf: return None buf += newbuf size -= len(newbuf) return buf
6a0f6814cdaf6847d467f4c5620c3897b1ff2ac8
35,183
def _check_for_too_many_exclusions(exclude_instances, available_instances, delta, groups_members): """ Check whether the amount of exluded instances will make it possible to scale down by the given delta. :param exclude_instances: A list of node instance IDs to exclude. :param available_instances: A list of all available instance IDs. For groups this should include both the group instance IDs and the member node instance IDs. :param delta: How much to scale by. This is expected to be negative. :param groups_members: A dict of group instances with their members, e.g. produced by get_groups_with_members :return: A string detailing problems if there are any, or an empty string if there are no problems. """ if groups_members: excluded_groups = set() # For groups, we must add all group instances to the exclusions that # contain an excluded node instance as one of their members, AND we # must add all group instances that are excluded, as the # exclude_instances list could legitimately contain both for inst in exclude_instances: for group, members in groups_members.items(): if inst in members or inst == group: excluded_groups.add(group) planned_group_instances = len(groups_members) + delta if planned_group_instances < len(excluded_groups): return ( 'Instances from too many different groups were excluded. ' 'Target number of group instances was {group_count}, but ' '{excluded_count} excluded groups.'.format( group_count=planned_group_instances, excluded_count=len(excluded_groups), ) ) else: planned_num_instances = len(available_instances) + delta if planned_num_instances < len(exclude_instances): return ( 'Target number of instances is less than excluded ' 'instance count. Target number of instances was ' '{target}. Excluded instances were: ' '{instances}. '.format( target=planned_num_instances, instances=', '.join(exclude_instances), ) ) # No problems found, return no error return ''
dca3588e02c8eaf60c6511dfedb3a3b281d64992
609,614
def is_word(s): """ String `s` counts as a word if it has at least one letter. """ for c in s: if c.isalpha(): return True return False
524ed5cc506769bd8634a46d346617344485e5f7
706,470
def unstream(data, version_tag, bits_per_value, int_size): """ This function is a pythonic adaptation of Reddit user bxny5's unstream function for decoding minecraft chunkheightmap data, written in perl. https://www.reddit.com/r/Minecraft/comments/bxny75/fun_with_chunk_data_heightmap_edition/ """ legacy = True if version_tag.value > 2230: # 2230 == MC version 1.15.2 ( this is the cut off ) legacy = False bl = 0 result = [] value = 0 for byte in data: for num in range(int_size): bit = (byte >> num) & 0x01 value = (bit << bl) | value bl += 1 if bl >= bits_per_value: result.append(value) value = 0 bl = 0 if not legacy: bl = 0 return result
59e69159315a7ee0c7384be7f198f6906d1daa8d
153,502
def get_client_region(client): """Gets the region from a :class:`boto3.client.Client` object. Args: client (:class:`boto3.client.Client`): The client to get the region from. Returns: string: AWS region string. """ return client._client_config.region_name
6727f8e21fee77a2d869c1c4f3aa077a22145f1d
67,098
def all_equal(values: list): """Check that all values in given list are equal""" return all(values[0] == v for v in values)
8ed08f63959367f3327554adc11b1286291963d8
708,786
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim): """ Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate, given both the observed interleaved and standard decay parameters. :param irb_decay: Observed decay parameter in irb experiment with desired gate interleaved between Cliffords :param rb_decay: Observed decay parameter in standard rb experiment. :param dim: Dimension of the Hilbert space, 2**num_qubits :return: Estimated gate infidelity (1 - fidelity) of the interleaved gate. """ return ((dim - 1) / dim) * (1 - irb_decay / rb_decay)
09f5b504ffffb047dc903a19bd51753c46cca7c2
675,239
def expected_errors(snippets): """Get and normalize expected errors from snippet.""" out = snippets.pop(0) assert out.startswith("[GraphQLError(") return " ".join(out.split()).replace("( ", "(").replace('" "', "")
57ff4693779ef221daf400d0b2fef68bfbd4d581
635,424
def float_to_str(value: float) -> str: """Converts double number to string using {.12g} formatter.""" return format(value, ".12g")
404855c3c17ff19c3ef6275f0d5584b6e8f73350
228,721
def rotate_patches_90deg(patches): """ Rotate patch dictionary as if original image is rotated by 90-degree CCW. """ def rot_pos(i, j): """ Board Coordinates: i 9 ... 1 ------ 1 j | | ... ------ 9 """ return (10 - j, i) def rot_patch(patch): """ Image coordinates: |---->x | \|/ y """ return { "image": patch["image"].transpose([1, 0, 2])[::-1] } return { rot_pos(*pos): rot_patch(patch) for (pos, patch) in patches.items() }
f488cb151b869d740c47464816329e730a12f3f0
668,965
from pathlib import Path def default_sftp_path(this_path, default_path): """ If ``this_path`` exists, return it as a path, else, return the ``pathlib.Path.name`` of the default path """ return Path(this_path) if this_path else Path(Path(default_path).name)
4b63a77a318593c80f830e810d516ca3aa2fcc75
380,687
import re def _is_abbreviation_for(abbreviated, full): """ >>> _is_abbreviation_for('yr', 'years') True >>> _is_abbreviation_for('years', 'years') True >>> _is_abbreviation_for('szco', 'years') False Thanks to Michael Brennan http://stackoverflow.com/questions/7331462/check-if-a-string-is-a-possible-abbrevation-for-a-name/7332054#7332054 """ abbreviated = abbreviated.strip() if abbreviated: pattern = ".*".join(abbreviated) return bool(re.match("^" + pattern, full, re.IGNORECASE))
05e90d501c93e17cd56fa33df73d4b64149da8ec
199,095
def get_strict_smarts_for_atom(atom): """ For an RDkit atom object, generate a simple SMARTS pattern. Parameters ---------- atom: rdkit.Chem.Atom RDKit atom. Results ------- symbol: str SMARTS symbol of the atom. """ symbol = atom.GetSmarts() if "[" not in symbol: symbol = "[" + symbol + "]" return symbol
7f6d8f79056f9dd08b99369f02f7d795fbd5866f
194,376
def get_type(transaction): """ :return: the type of the transaction """ return transaction['type']
4f66830f7c1e3bdc5d6b2c4ccc5db493014b9e5f
697,943
def _convert_space_to_shape_index(space): """Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing). Parameters ---------- space : str, values=('feature', 'sample') Feature or sample space. Returns ------- return : int, values=(0, 1) Index location of the desired space. """ if space == 'feature': return 1 if space == 'sample': return 0
20ec5aad29366929973b2bfa8e503a5bcbbb9a3a
638,398
def compss_wait_on(obj): """ Dummy compss_wait_on :param obj: The object to wait on. :return: The same object defined as parameter """ return obj
cb433878c460a507d98c1c3a8880626f804b201f
28,565
def snake_to_title_case(text): """Converts column_title to "Column Title" """ return ' '.join(map(lambda x: x.capitalize(), text.split('_')))
fa9accb2650d0ad20bc235e28db16debd625f565
177,646
def formatMultiplier(stat : float) -> str: """Format a module effect attribute into a string, including a sign symbol and percentage symbol. :param stat: The statistic to format into a string :type stat: float :return: A sign symbol, followed by stat, followed by a percentage sign. """ return f"{'+' if stat >= 1 else '-'}{round((stat - (1 if stat > 1 else 0)) * 100)}%"
5ab9df157d54a5414fc9cba46d0f73512a8a6c4c
43,002
def get_datatype(value): """ Determine most appropriate SQLite datatype for storing value. SQLite has only four underlying storage classes: integer, real, text, and blob. For compatibility with other flavors of SQL, it's possible to define columns with more specific datatypes (e.g. 'char', 'date'), but since these are still mapped to the underlying storage classes there's not much point in using them when generating native SQLite SQL. Therefore, this function takes an incoming value and attempts to guess the best SQLite datatype for storing it. This can then be used to help decide the schema of the column where the value will be stored. It defaults to the text datatype, not the super-general blob datatype, because read_csv reads each row in as text rather than binary data. Unlike in other SQL flavors, misdefining a column's datatype affinity is not fatal, because in the end any type of value can be stored in any column. In the end, the datatype returned by this function is just a suggestion for SQLite. See: * https://www.sqlite.org/datatype3.html * http://ericsink.com/mssql_mobile/data_types.html * http://www.techonthenet.com/sqlite/datatypes.php """ try: int(value) return 'INTEGER' except ValueError: try: float(value) return 'REAL' except ValueError: return 'TEXT'
d70c935e463b6ba9e92422a33e1cfcc9fcf7cb1f
508,765
def __get_topic_info(model, count_vectorizer, n_top_words): """ A utility method that generates the detailed topic information :param model: LDA model trained int topic_modeller method :param count_vectorizer: vectorizer object to get statistical results :param n_top_words: num of words for each topic :return: topic info """ words = count_vectorizer.get_feature_names() topic_info = {} for topic_idx, topic in enumerate(model.components_): topic_info[topic_idx] = [words[i] for i in topic.argsort()[:-n_top_words - 1:-1]] return topic_info
024ba487efdca6510074a01bb2154890aaed96f7
294,713
def convert_field_format(fieldAsArray): """ Description: converts the polygon given as nested arrays to nested tuples. Parameters: fieldAsArray: [ [ [x, y], ... ], ... ] Return: ( ( (x, y), ... ), ... ) """ return tuple( tuple( tuple(vertex) for vertex in ring) for ring in fieldAsArray )
6cc2e47435dcc9581ed60d45f9c5786d0010886c
484,566
def consecutive(span): """ Check if a span of indices is consecutive :param span: the span of indices :return: whether the span of indices is consecutive """ return [i - span[0] for i in span] == range(span[-1] - span[0] + 1)
6d80f0184e09d9b374ded8707a0198ebd7431599
453,762
def set_defaults(hotpotato): """ Set default values for keys in a dictionary of input parameters. Parameters ---------- hotpotato : dictionary Dictionary of input parameters gathered from a configuration script Returns ------- hotpotato : dictionary Input dictionary with keys set to default values """ # Default S/N threshold for ON pointings = 8 if hotpotato['on_cutoff']=='': hotpotato['on_cutoff'] = 7.5 # Default S/N threshold for OFF pointings = 6 if hotpotato['off_cutoff']=='': hotpotato['off_cutoff'] = 6.0 # Default cluster radius = 1 ms if hotpotato['cluster_radius']=='': hotpotato['cluster_radius'] = 1.0e-3 return hotpotato
9ce2583b3873b0c9102461eec21dc43682928508
458,016
def standardize_severity_string(severity): """ Returns the severity string in a consistent way. Parameters ---------- severity : str The severity string to standardize. Returns ------- severity : str The standardized severity string. """ return severity.title()
a52e3f0b299d25d56425f2c5cdd69bb43825e8c3
606,176
def parent(index: int) -> int: """Gets parent's index. """ return index // 2
fd00111ac33ff77f28f30d2f5f0bcf375206f705
110,153
def split_rows(sentences, column_names): """ Creates a list of sentence where each sentence is a list of lines Each line is a dictionary of columns :param sentences: :param column_names: :return: """ new_sentences = [] root_values = ['0', 'ROOT', 'ROOT', 'ROOT', 'ROOT', 'ROOT', '0', 'ROOT', '0', 'ROOT'] start = [dict(zip(column_names, root_values))] for sentence in sentences: rows = sentence.split('\n') sentence = [dict(zip(column_names, row.split())) for row in rows if row[0] != '#'] sentence = start + sentence new_sentences.append(sentence) return new_sentences
444733a9c169bedae8dc0045cd696cafed7085e2
709,383
import torch def _linear_interpolation_utilities(v_norm, v0_src, size_src, v0_dst, size_dst, size_z): """ Computes utility values for linear interpolation at points v. The points are given as normalized offsets in the source interval (v0_src, v0_src + size_src), more precisely: v = v0_src + v_norm * size_src / 256.0 The computed utilities include lower points v_lo, upper points v_hi, interpolation weights v_w and flags j_valid indicating whether the points falls into the destination interval (v0_dst, v0_dst + size_dst). Args: v_norm (:obj: `torch.Tensor`): tensor of size N containing normalized point offsets v0_src (:obj: `torch.Tensor`): tensor of size N containing left bounds of source intervals for normalized points size_src (:obj: `torch.Tensor`): tensor of size N containing source interval sizes for normalized points v0_dst (:obj: `torch.Tensor`): tensor of size N containing left bounds of destination intervals size_dst (:obj: `torch.Tensor`): tensor of size N containing destination interval sizes size_z (int): interval size for data to be interpolated Returns: v_lo (:obj: `torch.Tensor`): int tensor of size N containing indices of lower values used for interpolation, all values are integers from [0, size_z - 1] v_hi (:obj: `torch.Tensor`): int tensor of size N containing indices of upper values used for interpolation, all values are integers from [0, size_z - 1] v_w (:obj: `torch.Tensor`): float tensor of size N containing interpolation weights j_valid (:obj: `torch.Tensor`): uint8 tensor of size N containing 0 for points outside the estimation interval (v0_est, v0_est + size_est) and 1 otherwise """ v = v0_src + v_norm * size_src / 256.0 j_valid = (v - v0_dst >= 0) * (v - v0_dst < size_dst) v_grid = (v - v0_dst) * size_z / size_dst v_lo = v_grid.floor().long().clamp(min=0, max=size_z - 1) v_hi = (v_lo + 1).clamp(max=size_z - 1) v_grid = torch.min(v_hi.float(), v_grid) v_w = v_grid - v_lo.float() return v_lo, v_hi, v_w, j_valid
7e664fec2d3198c8124131541f2d07658a9f1f83
672,935
def MakePartition(block_dev, part): """Helper function to build Linux device path for storage partition.""" return '%s%s%s' % (block_dev, 'p' if block_dev[-1].isdigit() else '', part)
3e21c773a69b7c49bb4aad4210b9d168099565ef
35,041
def fixture_sample_id() -> str: """Return a sample id""" return "sample"
781a9824ad1faffdbda867c2f8df3b335c285fbc
252,329
from typing import Dict from typing import List from typing import OrderedDict def order_dict(value: Dict, ordering: List, ignore_missing=False) -> OrderedDict: """ Convert a dict to an OrderedDict with key order provided by ``ordering``. """ new_value = OrderedDict() for elem in ordering: if elem in value: new_value[elem] = value[elem] elif not ignore_missing: new_value[elem] = None return new_value
150fdc9f954cc939966410199a95ecbef22f2a4c
449,555
def acenx(n, asx=25., agx=5.): """n-th analyser center (starting from 0!) in x, given its size (asx) and gap between two (agx) in mm """ return (asx + agx) * n
6cc02676a9f0134fbc9deea93dcfe34b3113f358
140,654
def search_for_pod_info(details, operator_id): """ Get operator pod info, such as: name, status and message error (if failed). Parameters ---------- details : dict Workflow manifest from pipeline runtime. operator_id : str Returns ------- dict Pod informations. """ info = {} try: if "nodes" in details["status"]: for node in [*details["status"]["nodes"].values()]: if node["displayName"] == operator_id: info = {"name": node["id"], "status": node["phase"], "message": node["message"]} except KeyError: pass return info
678b6bab7fbcab9223ceaa735f4e8b83d0d3676e
522,758
def CollectSpecies(species_data): """ Returns the list of unique species label present in the input list. this function is mostly used in the last test.py """ species_list= [] for item in range(len(species_data)): species_label= species_data[item][0] species_list.append(species_label) return species_list
239cd3f102a9b5070ad4fd42470103e2ba5a5216
561,254
def _pyval_field_major_to_node_major(keys, values, depth): """Regroup each field (k, v) from dict-of-list to list-of-dict. Given a "field-major" encoding of the StructuredTensor (which maps each key to a single nested list containing the values for all structs), return a corresponding "node-major" encoding, consisting of a nested list of dicts. Args: keys: The field names (list of string). Must not be empty. values: The field values (list of python values). Must have the same length as `keys`. depth: The list depth at which dictionaries should be created. Returns: A nested list of dict, with depth `depth`. """ assert keys if depth == 0: return dict(zip(keys, values)) nvals = len(values[0]) assert all(nvals == len(values[i]) for i in range(1, len(values))) return [ _pyval_field_major_to_node_major(keys, value_slice, depth - 1) for value_slice in zip(*values) ]
b98d867d6b47fdbf494ed81b709a28440b0731c9
269,305
def solution(A, B): # O(N) """ Find common elements in 2 lists. >>> solution([1, 2, 3, 7, 1, 5], [7, 3, 6]) [7, 3] >>> solution([2, 4, 5, 10, 1, 2, 4, 4], [10, -1, 3]) [10] >>> solution([4, 5, 2, 2, 1], [3, 6, -1]) [] """ elements = {} # O(1) for value in A: # O(N) elements[value] = True # O(1) common_elements = [] # O(1) for value in B: # O(N) if value in elements: # O(1) common_elements.append(value) # O(1) return common_elements # O(1)
309f83713e4162e8d8c48712c83e32b474279d01
541,144
import re def get_perf_event(data, separator=" "): """ From data, Read the numbers provided by perf :param data: The output to process :param separator: In perf, it is usally number+<separator>+descriptor> :return: A dict of all the values found by perf """ data = str(data) result = dict() line = re.findall("\d+(?:,\d+)*" + separator + "(?:[^\s]+)", data) for counter in line: value = re.findall("\d+(?:,\d+)*", counter)[0] name = re.findall("\d+(?:,\d+)*" + separator + "([^\s]+)", counter)[0] result[name] = int(value.replace(',', '')) return result
a79adfcc8c26512fda30386ddd0f8e9183144a10
563,075
def create_mosaic_pars(mosaic_wcs): """Return dict of values to use with AstroDrizzle to specify output mosaic Parameters ----------- mosaic_wcs : object WCS as generated by make_mosaic_wcs Returns -------- mosaic_pars : dict This dictionary can be used as input to astrodrizzle.AstroDrizzle with the syntax 'AstroDrizzle(filenames, **mosaic_pars)' """ mosaic_pars = dict( driz_sep_rot=mosaic_wcs.orientat, driz_sep_scale=mosaic_wcs.pscale, driz_sep_outnx=mosaic_wcs.array_shape[1], driz_sep_outny=mosaic_wcs.array_shape[0], driz_sep_ra=mosaic_wcs.wcs.crval[0], driz_sep_dec=mosaic_wcs.wcs.crval[1], driz_sep_crpix1=mosaic_wcs.wcs.crpix[0], driz_sep_crpix2=mosaic_wcs.wcs.crpix[1], final_rot=mosaic_wcs.orientat, final_scale=mosaic_wcs.pscale, final_outnx=mosaic_wcs.array_shape[1], final_outny=mosaic_wcs.array_shape[0], final_ra=mosaic_wcs.wcs.crval[0], final_dec=mosaic_wcs.wcs.crval[1], final_crpix1=mosaic_wcs.wcs.crpix[0], final_crpix2=mosaic_wcs.wcs.crpix[1] ) return mosaic_pars
e9a8a499ce3a9196fcaf4f57c4bda4aa25905655
668,496
from datetime import datetime def str_to_datetime(dt_str: str) -> datetime: """ Converts a datetime in string format to datetime format. Parameters ---------- dt_str : str Represents a datetime in string format, "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S" Returns ------- datetime Represents a datetime in datetime format Example ------- >>> from pymove.utils.datetime import str_to_datetime >>> time_1 = '2020-06-29' >>> time_2 = '2020-06-29 12:45:59' >>> print(type(time_1), type(time_2)) '<class 'str'> <class 'str'>' >>> print( str_to_datetime(time_1), type(str_to_datetime(time_1))) '2020-06-29 00:00:00 <class 'datetime.datetime'>' >>> print(str_to_datetime(time_2), type(str_to_datetime(time_2))) '2020-06-29 12:45:59 <class 'datetime.datetime'>' """ if len(dt_str) == 10: return datetime.strptime(dt_str, '%Y-%m-%d') else: return datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
75ab00a545d56abdf475bba0e405972f13c0a30e
512,883
def reformat_large_tick_values(tick_val, pos): """ Turns large tick values (in the billions, millions and thousands) such as 4500 into 4.5K and also appropriately turns 4000 into 4K (no zero after the decimal). """ if tick_val >= 1000000000: val = round(tick_val/1000000000, 1) new_tick_format = '{:}B'.format(val) elif tick_val >= 1000000: val = round(tick_val/1000000, 1) new_tick_format = '{:}M'.format(val) elif tick_val >= 1000: val = round(tick_val/1000, 1) new_tick_format = '{:}K'.format(val) elif tick_val < 1000: new_tick_format = round(tick_val, 1) else: new_tick_format = tick_val # make new_tick_format into a string value new_tick_format = str(new_tick_format) # code below will keep 4.5M as is but change values such as 4.0M to 4M since # that zero after the decimal isn't needed index_of_decimal = new_tick_format.find(".") if index_of_decimal != -1: value_after_decimal = new_tick_format[index_of_decimal+1] if value_after_decimal == "0": # remove the 0 after the decimal point since it's not needed new_tick_format = new_tick_format[0:index_of_decimal] + new_tick_format[index_of_decimal+2:] return new_tick_format
5d39e9406afc1c33aa364ff3cd353585ec609e61
604,223