content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def load_file(file_location): """ Opens a given file and returns its contents. :param str file_location: The absolute path to the file :rtype: str :return: The contents of the file """ with open(file_location, 'r') as file_contents: contents = file_contents.read() return contents
61b78432cffa4c22adc9af31bbad63bf8777737b
302
def upperLeftOrigin( largeSize, smallSize ): """ The upper left coordinate (tuple) of a small rectangle in a larger rectangle (centered) """ origin = tuple( map( lambda x: int( ( (x[0]-x[1])/2 ) ), zip( largeSize, smallSize )) ) return origin
bda31fc5eb021f40a62b00949ced940ef171005f
310
def is_square_inside(row, col, rows, cols): """Check if row and col is square inside grid having rows and cols.""" return row not in (0, rows - 1) and col not in (0, cols - 1)
f0cdcbc6d9bee6a41fd0cc84b16ffaf0638a522c
311
def clean_repository_clone_url( repository_clone_url ): """Return a URL that can be used to clone a tool shed repository, eliminating the protocol and user if either exists.""" if repository_clone_url.find( '@' ) > 0: # We have an url that includes an authenticated user, something like: # http://[email protected]:9009/repos/some_username/column items = repository_clone_url.split( '@' ) tmp_url = items[ 1 ] elif repository_clone_url.find( '//' ) > 0: # We have an url that includes only a protocol, something like: # http://bx.psu.edu:9009/repos/some_username/column items = repository_clone_url.split( '//' ) tmp_url = items[ 1 ] else: tmp_url = repository_clone_url return tmp_url
c1d274e907d73aceaa5f1e2c52336edf1638cd8a
312
def add(n1, n2): """Adds the 2 given numbers""" return n1 + n2
ca670819dab8230e355e1b236d9cc74ed0b3b868
314
import torch def kl_reverse(logu: torch.Tensor) -> torch.Tensor: """ Log-space Csiszar function for reverse KL-divergence D_f(p,q) = KL(q||p). Also known as the exclusive KL-divergence and negative ELBO, minimizing results in zero-forcing / mode-seeking behavior. Args: logu (torch.Tensor): ``p.log_prob``s evaluated at samples from q. """ return -logu
fcc9035de183cb6d5b51e169dd764ff92ab290aa
317
import numbers def is_number(item): """Check if the item is a number.""" return isinstance(item, numbers.Number)
6c3fb6817a0eda2b27fcedd22763461dceef6bc1
323
def xml_attr_or_element(xml_node, name): """ Attempt to get the value of name from the xml_node. This could be an attribute or a child element. """ attr_val = xml_node.get(name, None) if attr_val is not None: return attr_val.encode('utf-8').strip() for child in xml_node.getchildren(): if child.tag == name: return child.text.encode('utf-8').strip() return None
4ec061a9a865291d8d26d8de474141175d5aab28
328
def get_coinbase_candle_url(url, timestamp_from, pagination_id): """Get Coinbase candle URL.""" start = timestamp_from.replace(tzinfo=None).isoformat() url += f"&start={start}" if pagination_id: url += f"&end={pagination_id}" return url
a1bb4e975060ba5e3438b717d1c2281349cd51f1
330
def subplot_index(nrow, ncol, k, kmin=1): """Return the i, j index for the k-th subplot.""" i = 1 + (k - kmin) // ncol j = 1 + (k - kmin) % ncol if i > nrow: raise ValueError('k = %d exceeds number of rows' % k) return i, j
2d2b7ef9bf9bc82d06637157949ca9cb3cc01105
333
def _split_keys(keypath, separator): """ Splits keys using the given separator: eg. 'item.subitem[1]' -> ['item', 'subitem[1]']. """ if separator: return keypath.split(separator) return [keypath]
2f67a35a2e08efce863d5d9e64d8a28f8aa47765
334
def spacify(string, spaces=2): """Add spaces to the beginning of each line in a multi-line string.""" return spaces * " " + (spaces * " ").join(string.splitlines(True))
7ab698d8b38a6d940ad0935b5a4ee8365e35f5da
336
def frohner_cor_3rd_order(sig1,sig2,sig3,n1,n2,n3): """ Takes cross-sections [barns] and atom densities [atoms/barn] for three thicknesses of the same sample, and returns extrapolated cross section according to Frohner. Parameters ---------- sig1 : array_like Cross section of the thinnest of the three samples. sig2 : array_like Cross section of the mid-thickness of the three samples. sig3 : array_like Cross section of the thickest of the three samples. n1 : float Atom density of the thinnest sample n2 : float Atom density of the mid-thickness sample n3 : float Atom density of the thickest sample Returns ------- sig0 : array_like The extrapolated cross section from sig1, sig2, and sig3 """ # two terms in the numerator numer1 = (n1*sig2-n2*sig1)*(n3**2-n1**2-(n1-n3)/(n1-n2)*(n2**2-n1**2)) numer2 = (n1*n2**2-n1**2*n2)*(sig3-sig2-(n1-n3)/(n1-n2)*(sig2-sig1)) denom = (n1-n2)*(n3**2-n1**2) - (n1-n3)*(n2**2-n1**2) return (numer1-numer2)/denom
d6f0b39368c19aeda899265eb187190bb4beb944
343
def split_and_filter(intermediate_str, splitter): """ Split string with given splitter - practically either one of "," or "/'". Then filter ones that includes "https" in the split pickles :param intermediate_str : string that in the middle of parsing :param splitter :return: chunk of string(s) as a list """ intermediate_split = intermediate_str.split(splitter) intermediate_filter = [elem for elem in intermediate_split if 'https' in elem] return intermediate_filter[0]
a4b800df1aca89ca1e8eedfc65a5016a995acd48
345
def count_ref_alleles(variant, *traits): """Count reference allels for a variant Parameters ---------- variant : a Variant as from funcgenom the variant for which alleles should be counted *traits : str the traits for which alleles should be counted Returns ------- int the reference allele count """ return ( ''.join(variant.traits[trait]['alleles'] for trait in traits) .replace(',', '.') .count('.') )
10ea3468f5de8f2b77bb97b27b888af808c541b7
349
import random def random_in_range(a: int, b: int) -> int: """ Return a random number r with a <= r <= b. """ return random.randint(a, b)
611c2754ace92eac4951f42e1e31af2f441ed0c2
351
def about(template): """ Attach a template to a step which can be used to generate documentation about the step. """ def decorator(step_function): step_function._about_template = template return step_function return decorator
7c00256e39481247857b34dcd5b7783a39b0a8bd
359
import torch def _extend_batch_dim(t: torch.Tensor, new_batch_dim: int) -> torch.Tensor: """ Given a tensor `t` of shape [B x D1 x D2 x ...] we output the same tensor repeated along the batch dimension ([new_batch_dim x D1 x D2 x ...]). """ num_non_batch_dims = len(t.shape[1:]) repeat_shape = (new_batch_dim, *(1 for _ in range(num_non_batch_dims))) return t.repeat(repeat_shape)
7ee1d0930f843a9d31bcc4934d675109f3b2df9b
360
def split_component_chars(address_parts): """ :param address_parts: list of the form [(<address_part_1>, <address_part_1_label>), .... ] returns [(<char_0>, <address_comp_for_char_0), (<char_1>, <address_comp_for_char_1),.., (<char_n-1>, <address_comp_for_char_n-1)] """ char_arr = [] for address_part, address_part_label in address_parts: # The address part of the tuple (address_part, address_part_label) for c in address_part: char_arr.append((c, address_part_label)) return char_arr
f4f3dd59378a689e9048cee96b8d6f12e9d8fe21
361
def adjacency_matrix(edges): """ Convert a directed graph to an adjacency matrix. Note: The distance from a node to itself is 0 and distance from a node to an unconnected node is defined to be infinite. Parameters ---------- edges : list of tuples list of dependencies between nodes in the graph [(source node, destination node, weight), ...] Returns ------- out : tuple (names, adjacency matrix) names - list of unique nodes in the graph adjacency matrix represented as list of lists """ # determine the set of unique nodes names = set() for src, dest, _ in edges: # add source and destination nodes names.add(src) names.add(dest) # convert set of names to sorted list names = sorted(names) # determine initial adjacency matrix with infinity weights matrix = [[float('Inf')] * len(names) for _ in names] for src, dest, weight in edges: # update weight in adjacency matrix matrix[names.index(src)][names.index(dest)] = weight for src in names: matrix[names.index(src)][names.index(src)] = 0 # return list of names and adjacency matrix return names, matrix
b8743a6fa549b39d5cb24ae1f276e911b954ee5a
365
def estimate_Cn(P=1013, T=273.15, Ct=1e-4): """Use Weng et al to estimate Cn from meteorological data. Parameters ---------- P : `float` atmospheric pressure in hPa T : `float` temperature in Kelvin Ct : `float` atmospheric struction constant of temperature, typically 10^-5 - 10^-2 near the surface Returns ------- `float` Cn """ return (79 * P / (T ** 2)) * Ct ** 2 * 1e-12
b74dd0c91197c24f880521a06d6bcd205d749448
366
def _card(item): """Handle card entries Returns: title (append " - Card" to the name, username (Card brand), password (card number), url (none), notes (including all card info) """ notes = item.get('notes', "") or "" # Add card info to the notes notes = notes + ("\n".join([f"{i}: {j}" for i, j in item.get('card', "").items()])) return f"{item['name']} - Card", \ item.get('card', {}).get('brand', '') or "", \ item.get('card', {}).get('number', "") or "", \ "", \ notes
fc7d5e4b960019b05ffe7ca02fd3d1a94d69b303
375
def get_natural_num(msg): """ Get a valid natural number from the user! :param msg: message asking for a natural number :return: a positive integer converted from the user enter. """ valid_enter = False while not valid_enter: given_number = input(msg).strip() if given_number.isdigit(): num = int(given_number) valid_enter = True return num
77bed94bf6d3e5ceb56d58eaf37e3e687e3c94ba
381
import types def copy_function(old_func, updated_module): """Copies a function, updating it's globals to point to updated_module.""" new_func = types.FunctionType(old_func.__code__, updated_module.__dict__, name=old_func.__name__, argdefs=old_func.__defaults__, closure=old_func.__closure__) new_func.__dict__.update(old_func.__dict__) new_func.__module__ = updated_module.__name__ return new_func
e09022f734faa1774a3ac592c0e12b0b007ae8e3
382
def get_recipes_from_dict(input_dict: dict) -> dict: """Get recipes from dict Attributes: input_dict (dict): ISO_639_1 language code Returns: recipes (dict): collection of recipes for input language """ if not isinstance(input_dict, dict): raise TypeError("Input is not type dict") recipes = input_dict return recipes
e710d9629d10897d4aae7bf3d5de5dbbe18196c5
389
def lerp(a,b,t): """ Linear interpolation between from @a to @b as @t goes between 0 an 1. """ return (1-t)*a + t*b
12cb8690ba5e5f2a4c08c1cd29d3497513b63438
394
def generate_annotation_dict(annotation_file): """ Creates a dictionary where the key is a file name and the value is a list containing the - start time - end time - bird class. for each annotation in that file. """ annotation_dict = dict() for line in open(annotation_file): file_name, start_time, end_time, bird_class = line.strip().split('\t') if file_name not in annotation_dict: annotation_dict[file_name] = list() annotation_dict[file_name].append([start_time, end_time, bird_class]) return annotation_dict
f40f210075e65f3dbe68bb8a594deb060a23ad8b
395
def extract_jasmine_summary(line): """ Example SUCCESS karma summary line: PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.205 secs / 0.001 secs) Exmaple FAIL karma summary line: PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.21 secs / 0.001 secs) """ # get totals totals = line.split(' Executed ')[1].split(' ') executed_tests, total_tests = int(totals[0]), int(totals[2]) # get failed if 'SUCCESS' in line: failed_tests = 0 else: failed_tests = int(totals[3][1:]) return { 'total_tests': total_tests, 'executed_tests': executed_tests, 'failed_tests': failed_tests, 'passed_tests': executed_tests - failed_tests }
f795ff015555cc3a2bd2d27527ae505a6dde9231
396
def degrees_of_freedom(s1, s2, n1, n2): """ Compute the number of degrees of freedom using the Satterhwaite Formula @param s1 The unbiased sample variance of the first sample @param s2 The unbiased sample variance of the second sample @param n1 Thu number of observations in the first sample @param n2 The number of observations in the second sample """ numerator = (s1**2/n1 + s2**2/n2)**2 denominator = ((s1**2/n1)**2)/(n1-1) + ((s2**2/n2)**2)/(n2-1) degrees_of_freedom = numerator/denominator return degrees_of_freedom
5f076e33584c61dca4410b7ed47feb0043ec97cb
397
def get_range_to_list(range_str): """ Takes a range string (e.g. 123-125) and return the list """ start = int(range_str.split('-')[0]) end = int(range_str.split('-')[1]) if start > end: print("Your range string is wrong, the start is larger than the end!", range_str) return range(start, end+1)
a88d9780ac2eba1d85ae70c1861f6a3c74991e5c
399
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float: """Return an linearly annealed epsilon Epsilon will decrease over time until it reaches `target_episode` (epsilon) | max_e ---|\ | \ | \ | \ min_e ---|____\_______________(episode) | target_episode slope = (min_e - max_e) / (target_episode) intercept = max_e e = slope * episode + intercept Args: episode (int): Current episode min_e (float): Minimum epsilon max_e (float): Maximum epsilon target_episode (int): epsilon becomes the `min_e` at `target_episode` Returns: float: epsilon between `min_e` and `max_e` """ slope = (min_e - max_e) / (target_episode) intercept = max_e return max(min_e, slope * episode + intercept)
fab650085f271f1271025e23f260eb18e645a9ba
402
def extractYoloInfo(yolo_output_format_data): """ Extract box, objectness, class from yolo output format data """ box = yolo_output_format_data[..., :6] conf = yolo_output_format_data[..., 6:7] category = yolo_output_format_data[..., 7:] return box, conf, category
ff28a5ce5490c61722ca06b0e09b9bd85ee7e111
408
def replace_umlauts(s: str) -> str: """ Replace special symbols with the letters with umlauts (ä, ö and ü) :param s: string with the special symbols (::) :return: edited string """ out = s.replace('A::', 'Ä').replace('O::', 'Ö').replace('U::', 'Ü').replace('a::', 'ä').replace('o::', 'ö') \ .replace('u::', 'ü') return out
8fad1f1017a3fd860d7e32fd191dd060b75a7bb8
410
import torch import math def sample_random_lightdirs(num_rays, num_samples, upper_only=False): """Randomly sample directions in the unit sphere. Args: num_rays: int or tensor shape dimension. Number of rays. num_samples: int or tensor shape dimension. Number of samples per ray. upper_only: bool. Whether to sample only on the upper hemisphere. Returns: lightdirs: [R, S, 3] float tensor. Random light directions sampled from the unit sphere for each sampled point. """ if upper_only: min_z = 0 else: min_z = -1 phi = torch.rand(num_rays, num_samples) * (2 * math.pi) # [R, S] cos_theta = torch.rand(num_rays, num_samples) * (1 - min_z) + min_z # [R, S] theta = torch.acos(cos_theta) # [R, S] x = torch.sin(theta) * torch.cos(phi) y = torch.sin(theta) * torch.sin(phi) z = torch.cos(theta) lightdirs = torch.cat((x[..., None], y[..., None], z[..., None]), dim=-1) # [R, S, 3] return lightdirs
7f7657ff66d0cffea6892dffdf49ba6b52b9def9
414
def date_handler(obj): """make datetime object json serializable. Notes ----- Taken from here: https://tinyurl.com/yd84fqlw """ if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError
741867e05e1b5f3e9d0e042b3b1576fb61ab0219
415
import base64 import struct def tiny_id(page_id): """Return *tiny link* ID for the given page ID.""" return base64.b64encode(struct.pack('<L', int(page_id)).rstrip(b'\0'), altchars=b'_-').rstrip(b'=').decode('ascii')
1a37b814ff9845949c3999999b61f79b26dacfdc
417
def gen_all_holds(hand): """ Generate all possible choices of dice from hand to hold. hand: sorted full yahtzee hand Returns a set of tuples, where each tuple is sorted dice to hold """ # start off with the original hand in set set_holds = set([(hand)]) # now iterate with all sub hands with one element removed for item in hand: list_hand = list(hand) list_hand.remove(item) # add to set_holds this sub hand set_holds.add(tuple(list_hand)) # also add to set_holds the recursion of this sub hand # set functionality also takes care of repeated sub hands set_holds.update(gen_all_holds(tuple(list_hand))) return set_holds
5c8af5040f619fabef56918d399b5a1cab8893a4
424
def langstring(value: str, language: str = "x-none") -> dict: """Langstring.""" return { "langstring": { "lang": language, "#text": value, } }
dca23a329cfc87d8cfa52cd2b009ce723b7d2270
425
def absModuleToDist(magApp, magAbs): """ Convert apparent and absolute magnitude into distance. Parameters ---------- magApp : float Apparent magnitude of object. magAbs : float Absolute magnitude of object. Returns ------- Distance : float The distance resulting from the difference in apparent and absolute magnitude [pc]. """ d = 10.0**(-(magAbs - magApp) / 5.0 + 1.0) return d
a7d98ff479114f08e47afefc97a1119f5e8ff174
428
import base64 def decoded_anycli(**kwargs): """ Return the decoded return from AnyCLI request - Do not print anything :param kwargs: keyword value: value to display :return: return the result of AnyCLI in UTF-8 :Example: result = cli(url=base_url, auth=s, command="show vlan") decoded_anycli(result) """ value = kwargs.get('value', None) return base64.b64decode(value['result_base64_encoded']).decode('utf-8')
223c4f9aabfef530896729205071e7fb8f9c8301
429
import tqdm def generate_formula_dict(materials_store, query=None): """ Function that generates a nested dictionary of structures keyed first by formula and then by task_id using mongo aggregation pipelines Args: materials_store (Store): store of materials Returns: Nested dictionary keyed by formula-mp_id with structure values. """ props = ["pretty_formula", "structure", "task_id", "magnetic_type"] results = list(materials_store.groupby("pretty_formula", properties=props, criteria=query)) formula_dict = {} for result in tqdm.tqdm(results): formula = result['_id']['pretty_formula'] task_ids = [d['task_id'] for d in result['docs']] structures = [d['structure'] for d in result['docs']] formula_dict[formula] = dict(zip(task_ids, structures)) return formula_dict
ae232c806972262029966307e489df0b12d646f5
430
def shape_extent_to_header(shape, extent, nan_value=-9999): """ Create a header dict with shape and extent of an array """ ncols = shape[1] nrows = shape[0] xllcorner = extent[0] yllcorner = extent[2] cellsize_x = (extent[1]-extent[0])/ncols cellsize_y = (extent[3]-extent[2])/nrows if cellsize_x != cellsize_y: raise ValueError('extent produces different cellsize in x and y') cellsize = cellsize_x header = {'ncols':ncols, 'nrows':nrows, 'xllcorner':xllcorner, 'yllcorner':yllcorner, 'cellsize':cellsize, 'NODATA_value':nan_value} return header
957b59e7f464901a5430fd20ab52f28507b55887
433
import logging def logged(class_): """Class-level decorator to insert logging. This assures that a class has a ``.log`` member. :: @logged class Something: def __init__(self, args): self.log(f"init with {args}") """ class_.log= logging.getLogger(class_.__qualname__) return class_
cd58e355151ab99aa1694cbd9fb6b710970dfa19
434
import math def _generate_resolution_shells(low, high): """Generate 9 evenly spaced in reciprocal space resolution shells from low to high resolution, e.g. in 1/d^2.""" dmin = (1.0 / high) * (1.0 / high) dmax = (1.0 / low) * (1.0 / low) diff = (dmin - dmax) / 8.0 shells = [1.0 / math.sqrt(dmax)] for j in range(8): shells.append(1.0 / math.sqrt(dmax + diff * (j + 1))) return shells
52fa4309f2f34a39a07d8524dd7f226e3d1bae6a
436
def get_page_url(skin_name, page_mappings, page_id): """ Returns the page_url for the given page_id and skin_name """ fallback = '/' if page_id is not None: return page_mappings[page_id].get('path', '/') return fallback
6ead4824833f1a7a002f54f83606542645f53dd6
437
def abort_multipart_upload(resource, bucket_name, object_name, upload_id): """Abort in-progress multipart upload""" mpupload = resource.MultipartUpload(bucket_name, object_name, upload_id) return mpupload.abort()
93535c2404db98e30bd29b2abbda1444ae4d0e8a
443
def double(n): """ Takes a number n and doubles it """ return n * 2
8efeee1aa09c27d679fa8c5cca18d4849ca7e205
444
import random def random_sources(xSize, ySize, zSize, number): """ returns a list of random positions in the grid where the sources of nutrients (blood vessels) will be """ src = [] for _ in range(number): x = random.randint(0, xSize-1) y = random.randint(0, ySize-1) z = random.randint(0, zSize-1) if (x, y, z) not in src: src.append((x,y,z)) return src
17dab43ea2468a11e3720ff0f7eb33b605371496
452
def sort_terms(node, parent_children, hierarchy): """Recursively create a list of nodes grouped by category.""" for c in parent_children.get(node, []): hierarchy.append(c) sort_terms(c, parent_children, hierarchy) return hierarchy
5ae737206f3859c01da6b8e9475db688e53a8d13
454
def sequence_accuracy_score(y_true, y_pred): """ Return sequence accuracy score. Match is counted only when two sequences are equal. """ total = len(y_true) if not total: return 0 matches = sum(1 for yseq_true, yseq_pred in zip(y_true, y_pred) if yseq_true == yseq_pred) return matches / total
b1345aaa6fd0161f648a1ca5b15c921c2ed635ad
457
def load_content(sentence_file): """Load input file with sentences to build LSH. Args: sentence_file (str): Path to input with txt file with sentences to Build LSH. Returns: dict: Dict with strings and version of string in lower case and without comma. """ sentences = {} with open(sentence_file) as content: for line in content: line = line.strip() line_clean = line.replace(",", "") line_clean = line_clean.lower() sentences[line_clean] = line return sentences
31c3104179e995d59cffbea92caf2d32decc572c
458
def rare_last_digit(first): """Given a leading digit, first, return all possible last digits of a rare number""" if first == 2: return (2,) elif first == 4: return (0,) elif first == 6: return (0,5) elif first == 8: return (2,3,7,8) else: raise ValueError(f"Invalid first digit of rare number: {first}")
2b15d35a6281d679dce2dedd7c1944d2a93e8756
459
def fermat_number(n: int) -> int: """ https://en.wikipedia.org/wiki/Fermat_number https://oeis.org/A000215 >>> [fermat_number(i) for i in range(5)] [3, 5, 17, 257, 65537] """ return 3 if n == 0 else (2 << ((2 << (n - 1)) - 1)) + 1
4427ab7171fd86b8e476241bc94ff098e0683363
461
def get_id_ctx(node): """Gets the id and attribute of a node, or returns a default.""" nid = getattr(node, "id", None) if nid is None: return (None, None) return (nid, node.ctx)
cbca8573b4246d0378297e0680ab05286cfc4fce
462
import torch def get_meshgrid_samples(lower, upper, mesh_size: tuple, dtype) ->\ torch.Tensor: """ Often we want to get the mesh samples in a box lower <= x <= upper. This returns a torch tensor of size (prod(mesh_size), sample_dim), where each row is a sample in the meshgrid. """ sample_dim = len(mesh_size) assert (len(upper) == sample_dim) assert (len(lower) == sample_dim) assert (len(mesh_size) == sample_dim) meshes = [] for i in range(sample_dim): meshes.append( torch.linspace(lower[i], upper[i], mesh_size[i], dtype=dtype)) mesh_tensors = torch.meshgrid(*meshes) return torch.cat( [mesh_tensors[i].reshape((-1, 1)) for i in range(sample_dim)], dim=1)
98a2c7b064d7b23824b547d0fc0a16eb37cb0923
471
from functools import reduce def getattrs(o, *attrs, **kwargs): """ >>> getattrs((), '__iter__', '__name__', 'strip')('_') 'iter' >>> getattrs((), 'foo', 'bar', default=0) 0 """ if 'default' in kwargs: default = kwargs['default'] c = o for attr in attrs: try: c = getattr(c, attr) except AttributeError: return default return c else: return reduce(getattr, attrs, o)
64d55154d2399c7097476a8335eae81749588286
473
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" ratings = [m.score for m in movies] mean = sum(ratings) / max(1, len(ratings)) return round(mean, 1)
6f837ff251e6221227ba4fa7da752312437da90f
483
import re def is_regex(regex, invert=False): """Test that value matches the given regex. The regular expression is searched against the value, so a match in the middle of the value will succeed. To specifically match the beginning or the whole regex, use anchor characters. If invert is true, then matching the regex will cause the test to fail. """ # pylint: disable=unused-argument # args defined by test definition rex = re.compile(regex) def is_regex_test(conf, path, value): match = rex.search(value) if invert and match: return u'"{0}" matches /{1}/'.format(value, regex) if not invert and not match: return u'"{0}" does not match /{1}/'.format(value, regex) return None return is_regex_test
0db71b3dae2b2013650b65ecacfe6aed0cd8366b
488
def build_varint(val): """Build a protobuf varint for the given value""" data = [] while val > 127: data.append((val & 127) | 128) val >>= 7 data.append(val) return bytes(data)
46f7cd98b6858c003cd66d87ba9ec13041fcf9db
493
def MAKEFOURCC(ch0: str, ch1: str, ch2: str, ch3: str) -> int: """Implementation of Window's `MAKEFOURCC`. This is simply just returning the bytes of the joined characters. `MAKEFOURCC(*"DX10")` can also be implemented by `Bytes(b"DX10")`. Args: ch0 (str): First char ch1 (str): Second char ch2 (str): Third char ch3 (str): Fourth char Returns: int: The integer representation of given characters. **Reference**: `Microsoft <https://goo.gl/bjtMFA>`__ """ return (ord(ch0) << 0) | (ord(ch1) << 8) | (ord(ch2) << 16) | (ord(ch3) << 24)
91afd9dcc8f1cd8c5ef167bdb560c8bf2d89b228
496
def get_present_types(robots): """Get unique set of types present in given list""" return {type_char for robot in robots for type_char in robot.type_chars}
75c33e0bf5f97afe93829c51086100f8e2ba13af
498
def SFRfromLFIR(LFIR): """ Kennicut 1998 To get Star formation rate from LFIR (8-1000um) LFIR in erg s-1 SFR in Msun /year """ SFR = 4.5E-44 * LFIR return SFR
4adf401bbf2c6547cea817b52eb881531db8c798
502
def points_from_x0y0x1y1(xyxy): """ Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] """ [x0, y0, x1, y1] = xyxy return "%s,%s %s,%s %s,%s %s,%s" % ( x0, y0, x1, y0, x1, y1, x0, y1 )
8a7d766145dc31e6619b290b8d96a95983f9cc01
505
def get_basic_track_info(track): """ Given a track object, return a dictionary of track name, artist name, album name, track uri, and track id. """ # Remember that artist and album artist have different entries in the # spotify track object. name = track["name"] artist = track['artists'][0]['name'] album = track['album']['name'] uri = track["uri"] track_id = track['id'] output = {"name": name, "artist": artist, "album": album, "uri": uri, "id": track_id} return output
925f7bb00482e946ad7a6853bac8b243d24145c7
506
from datetime import datetime def temporal_filter(record_date_time, time_or_period, op): """ Helper function to perform temporal filters on feature set :param record_date_time: datetime field value of a feature :type record_date_time: :class:`datetime.datetime` :param time_or_period: the time instant or time span to use as a filter :type time_or_period: :class:`datetime.datetime` or a tuple of two datetimes or a tuple of one datetime and one :class:`datetime.timedelta` :param op: the comparison operation :type op: str :return: a comparison expression result :rtype: bool """ d = datetime.strptime(record_date_time, "%Y-%m-%dT%H:%M:%SZ") result = None # perform before and after operations if op in ['BEFORE', 'AFTER']: query_date_time = datetime.strptime( time_or_period.value, "%Y-%m-%dT%H:%M:%SZ") if op == 'BEFORE': return d <= query_date_time elif op == 'AFTER': return d >= query_date_time # perform during operation elif 'DURING' in op: low, high = time_or_period low = datetime.strptime(low.value, "%Y-%m-%dT%H:%M:%SZ") high = datetime.strptime(high.value, "%Y-%m-%dT%H:%M:%SZ") result = d >= low and d <= high if 'BEFORE' in op: result = d <= high elif 'AFTER' in op: result = d >= low return result
9f76d6a6eb96da9359c4bbb80f6cfb1dfdcb4159
507
def perform_variants_query(job, **kwargs): """Query for variants. :param job: API to interact with the owner of the variants. :type job: :class:`cibyl.sources.zuul.transactions.JobResponse` :param kwargs: See :func:`handle_query`. :return: List of retrieved variants. :rtype: list[:class:`cibyl.sources.zuul.transactions.VariantResponse`] """ return job.variants().get()
c779080e2ef8c1900c293f70996e17bae932b142
516
from unittest.mock import patch def method_mock(cls, method_name, request): """ Return a mock for method *method_name* on *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, method_name) request.addfinalizer(_patch.stop) return _patch.start()
b14d991c42e0c05a51d9c193c3769b1e1e71dd1f
520
def _return_xarray_system_ids(xarrs: dict): """ Return the system ids for the given xarray object Parameters ---------- xarrs Dataset or DataArray that we want the sectors from Returns ------- list system identifiers as string within a list """ return list(xarrs.keys())
8380d1c2ae9db48eb4b97138dcd910d58085073e
521
def sub(a, b): """Subtracts b from a and stores the result in a.""" return "{b} {a} ?+1\n".format(a=a, b=b)
dcc0ddfc9dbefe05d79dea441b362f0ddfe82627
522
def factory(name, Base, Deriveds): """Find the base or derived class by registered name. Parameters ---------- Base: class Start the lookup here. Deriveds: iterable of (name, class) A list of derived classes with their names. Returns ------- class """ Derived = Base for (nm, NmCl) in Deriveds: if nm == name: Derived = NmCl break return Derived
1bce29651004cf1f04740fd95a4f62c6c2277a72
523
def find_expired(bucket_items, now): """ If there are no expired items in the bucket returns empty list >>> bucket_items = [('k1', 1), ('k2', 2), ('k3', 3)] >>> find_expired(bucket_items, 0) [] >>> bucket_items [('k1', 1), ('k2', 2), ('k3', 3)] Expired items are returned in the list and deleted from the bucket >>> find_expired(bucket_items, 2) ['k1'] >>> bucket_items [('k2', 2), ('k3', 3)] """ expired_keys = [] for i in range(len(bucket_items) - 1, -1, -1): key, expires = bucket_items[i] if expires < now: expired_keys.append(key) del bucket_items[i] return expired_keys
476fd079616e9f5c9ed56ee8c85171fcb0ddb172
524
import typing def empty_iterable() -> typing.Iterable: """ Return an empty iterable, i.e., an empty list. :return: an iterable :Example: >>> from flpy.iterators import empty_iterable >>> empty_iterable() [] """ return list()
904fe365abf94f790f962c9a49f275a6068be4f0
525
def feature_selection(data, features): """ Choose which features to use for training. :param data: preprocessed dataset :param features: list of features to use :return: data with selected features """ return data[features]
6303e52a9c64acfbb5dcfd115b07b3bef2942821
527
from typing import Optional import yaml def get_repo_version(filename: str, repo: str) -> Optional[str]: """Return the version (i.e., rev) of a repo Args: filename (str): .pre-commit-config.yaml repo (str): repo URL Returns: Optional[str]: the version of the repo """ with open(filename, "r") as stream: pre_commit_data = yaml.safe_load(stream) pre_config_repo = next( (item for item in pre_commit_data["repos"] if item["repo"] == repo), None ) if pre_config_repo: return pre_config_repo["rev"] return None
821653bdeb60a86fce83fb3a05609996231ec5d4
531
def recast_to_supercell(z, z_min, z_max): """Gets the position of the particle at ``z`` within the simulation supercell with boundaries ``z_min`` y ``z_max``. If the particle is outside the supercell, it returns the position of its closest image. :param z: :param z_min: :param z_max: :return: """ sc_size = (z_max - z_min) return z_min + (z - z_min) % sc_size
2d144a656a92eaf3a4d259cf5ad2eadb6cfdf970
534
def b2str(data): """Convert bytes into string type.""" try: return data.decode("utf-8") except UnicodeDecodeError: pass try: return data.decode("utf-8-sig") except UnicodeDecodeError: pass try: return data.decode("ascii") except UnicodeDecodeError: return data.decode("latin-1")
05cbe6c8072e1bf24cc9ba7f8c8447d0fa7cbf7f
539
def get_cookie_date(date): """ Return a date string in a format suitable for cookies (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date) :param date: datetime object :return: date string in cookie format """ return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
f2b4d6decab72cf1f25754bc7e290f62eae92156
540
def valuedict(keys, value, default): """ Build value dictionary from a list of keys and a value. Parameters ---------- keys: list The list of keys value: {dict, int, float, str, None} A value or the already formed dictionary default: {int, float, str} A default value to set if no value Returns ------- dict A dictionary Notes ----- This standalone and generic function is only required by plotters. """ if isinstance(value, dict): return {key: value.get(key, default) for key in keys} else: return dict.fromkeys(keys, value or default)
44283bac3be75c3569e87a890f507f7cff4161b6
542
def dep_graph_parser_parenthesis(edge_str): """Given a string representing a dependency edge in the 'parenthesis' format, return a tuple of (parent_index, edge_label, child_index). Args: edge_str: a string representation of an edge in the dependency tree, in the format edge_label(parent_word-parent_index, child_word-child_index) Returns: tuple of (parent_index, edge_label, child_index) """ tokens = edge_str.split("(") label = tokens[0] tokens = tokens[1].split(", ") parent = int(tokens[0].split("-")[-1]) - 1 child = int(",".join(tokens[1:]).split("-")[-1][:-1]) - 1 return (parent, label, child)
a3f96ebec6fdcb00f3f64ea02e91147df16df196
544
import math def intersection_angle(m1, m2): """ Computes intersection angle between two slopes. """ return math.degrees(math.atan((m2-m1) / (1+m1*m2)))
244192d3d1fe74130d64350606e765d8f2d4831b
545
import html def formatTitle(title): """ The formatTitle function formats titles extracted from the scraped HTML code. """ title = html.unescape(title) if(len(title) > 40): return title[:40] + "..." return title
0a47e88ac024561dce18be140895dfd0825a9c37
548
import unicodedata def has_alphanum(s): """ Return True if s has at least one alphanumeric character in any language. See https://en.wikipedia.org/wiki/Unicode_character_property#General_Category """ for c in s: category = unicodedata.category(c)[0] if category == 'L' or category == 'N': return True return False
3ac778e5f415bce4fa1e8667a1599ca73367b733
551
def is_remote(path): """Determine whether a file is in a remote location (which can be handled) based on prefix of connection string.""" for token in ["s3://", "http://", "https://"]: # add if path.startswith(token): return True return False
b459e20104b6e0e326a86ef44b53e18a335ded96
552
def route_distance(route): """ returns the distance traveled for a given tour route - sequence of nodes traveled, does not include start node at the end of the route """ dist = 0 prev = route[-1] for node in route: dist += node.euclidean_dist(prev) prev = node return dist
227b6476f6abd9efdf690062e0d4034c4ece2408
553
def update_datapackage(datapackage, mappings): """Update the field names and delete the `maps_to` properties.""" for i, resource in enumerate(datapackage['resources']): fields = [] for field in resource['schema']['fields']: fiscal_key = mappings[i][field['name']] if fiscal_key not in ('_unknown', '_ignored'): field.update({'name': fiscal_key}) del field['maps_to'] if 'translates_to' in field: del field['translates_to'] fields.append(field) resource['schema']['fields'] = fields return datapackage
f56cf5917331a55d2ac0d5783e0b9c3962eccb5f
558
def mel_to_hz(mel): """From Young et al. "The HTK book", Chapter 5.4.""" return 700.0 * (10.0**(mel / 2595.0) - 1.0)
8306b95bcdf866dda0759a71c2d5d538155173df
564
def generate_resource_link(pid, resource_path, static=False, title=None): """ Returns a valid html link to a public resource within an autogenerated instance. Args: pid: the problem id resource_path: the resource path static: boolean whether or not it is a static resource title: the displayed text. Defaults to the path Returns: The html link to the resource. """ return '<a target=_blank href="/api/autogen/serve/{}?static={}&pid={}">{}</a>'.format( resource_path, "true" if static else "false", pid, resource_path if not title else title )
c2523e254d93ecc36198ffea6f2f54c48dfe529d
566
def complex_to_xy(complex_point): """turns complex point (x+yj) into cartesian point [x,y]""" xy_point = [complex_point.real, complex_point.imag] return xy_point
2984b70c3015cb69a0f7dfd62bd022bb26310852
571
def addr(arr): """ Get address of numpy array's data """ return arr.__array_interface__['data'][0]
910c893dc47e3f864e915cdf114c3ed127f3ea43
578
def zipper(sequence): """Given a sequence return a list that has the same length as the original sequence, but each element is now a list with an integer and the original element of the sequence.""" n = len(sequence) rn = range(n) data = zip(rn,sequence) return data
af7f0c495d920e54ea033696aefc27379b667102
579
def stitch_frame(frames, _): """ Stitching for single frame. Simply returns the frame of the first index in the frames list. """ return frames[0]
833ceb66f9df61e042d1c936c68b8a77566545c4
581
def demandNameItem(listDb,phrase2,mot): """ put database name of all items in string to insert in database listDb: list with datbase name of all items phrase2: string with database name of all items mot: database name of an item return a string with database name of all items separated with ',' """ for i in range(len(listDb)): mot = str(listDb[i]) phrase2 += mot if not i == len(listDb)-1: phrase2 += ',' return phrase2
67af8c68f0ba7cd401067e07c5de1cd25de9e66c
590
def replace_text_comment(comments, new_text): """Replace "# text = " comment (if any) with one using new_text instead.""" new_text = new_text.replace('\n', ' ') # newlines cannot be represented new_text = new_text.strip(' ') new_comments, replaced = [], False for comment in comments: if comment.startswith('# text ='): new_comments.append('# text = {}'.format(new_text)) replaced = True else: new_comments.append(comment) if not replaced: new_comments.append('# text = {}'.format(new_text)) return new_comments
4b1284966eb02ca2a6fd80f8f639adcb4f1fde6c
595
def height(tree): """Return the height of tree.""" if tree.is_empty(): return 0 else: return 1+ max(height(tree.left_child()),\ height(tree.right_child()))
a469216fc13ed99acfb1bab8db7e031acc759f90
598
def max_power_rule(mod, g, tmp): """ **Constraint Name**: DAC_Max_Power_Constraint **Enforced Over**: DAC_OPR_TMPS Power consumption cannot exceed capacity. """ return ( mod.DAC_Consume_Power_MW[g, tmp] <= mod.Capacity_MW[g, mod.period[tmp]] * mod.Availability_Derate[g, tmp] )
2c1845253524a8383f2256a7d67a8231c2a69485
599
import requests def get_mc_uuid(username): """Gets the Minecraft UUID for a username""" url = f"https://api.mojang.com/users/profiles/minecraft/{username}" res = requests.get(url) if res.status_code == 204: raise ValueError("Users must have a valid MC username") else: return res.json().get("id")
fceeb1d9eb096cd3e29f74d389c7c851422ec022
600
def annualize_metric(metric: float, holding_periods: int = 1) -> float: """ Annualize metric of arbitrary periodicity :param metric: Metric to analyze :param holding_periods: :return: Annualized metric """ days_per_year = 365 trans_ratio = days_per_year / holding_periods return (1 + metric) ** trans_ratio - 1
0c84816f29255d49e0f2420b17abba66e2387c99
605
def read_gold_conll2003(gold_file): """ Reads in the gold annotation from a file in CoNLL 2003 format. Returns: - gold: a String list containing one sequence tag per token. E.g. [B-Kochschritt, L-Kochschritt, U-Zutat, O] - lines: a list list containing the original line split at "\t" """ gold = [] lines = [] with open(gold_file, encoding="utf-8") as f: for line in f: if line == "\n": continue line = line.strip().split("\t") gold.append(line[3]) lines.append(line) return gold, lines
1e11513c85428d20e83d54cc2fa2d42ddd903341
607
def get_bsj(seq, bsj): """Return transformed sequence of given BSJ""" return seq[bsj:] + seq[:bsj]
d1320e5e3257ae22ca982ae4dcafbd4c6def9777
608
import re def parse_year(inp, option='raise'): """ Attempt to parse a year out of a string. Parameters ---------- inp : str String from which year is to be parsed option : str Return option: - "bool" will return True if year is found, else False. - Return year int / raise a RuntimeError otherwise Returns ------- out : int | bool Year int parsed from inp, or boolean T/F (if found and option is bool). Examples -------- >>> year_str = "NSRDB_2018.h5" >>> parse_year(year_str) 2018 >>> year_str = "NSRDB_2018.h5" >>> parse_year(year_str, option='bool') True >>> year_str = "NSRDB_TMY.h5" >>> parse_year(year_str) RuntimeError: Cannot parse year from NSRDB_TMY.h5 >>> year_str = "NSRDB_TMY.h5" >>> parse_year(year_str, option='bool') False """ # char leading year cannot be 0-9 # char trailing year can be end of str or not 0-9 regex = r".*[^0-9]([1-2][0-9]{3})($|[^0-9])" match = re.match(regex, inp) if match: out = int(match.group(1)) if 'bool' in option: out = True else: if 'bool' in option: out = False else: raise RuntimeError('Cannot parse year from {}'.format(inp)) return out
a91efb0614e7d0ad6753118f9b4efe8c3b40b4e2
615