content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def calc_s11_s22_s33(s2211, s1133): """Calculates s11, s22, s33 based on s22-s11 and s11-s33 using the constraint s11+s22+s33=0 """ s22 = 2.0*(s2211)/3.0 + s1133/3.0 s11 = s22 - s2211 s33 = s11 - s1133 return s11, s22, s33
0f65bb93ad6faf518435ebac6808152ca0e43a6f
401,870
def rank_as_string(list1, alphanum_index): """ Convert a ranked list of items into a string of characters based on a given dictionary `alph` of the format that contains the ranked items and a random alphanumeric to represent it. Parameters ---------- list1 : list A list of rankings to be converted to characters alph : dict A dictionary containing the items in list1 as keys and unique characters as the values. """ return ''.join([alphanum_index[l] for l in list1])
c3de9118abe5ead47e9e84e1682b9a16ead0b5fc
661,495
def is_version_string(string): """ Check if a string is version string like 3.0.4-7 or 4.0.37-dev. Only digits are allowed for version part. Non-digits are allowed for the revision part, like 4.0.37-dev. """ if not string: return False tokens = string.split("-") if len(tokens) > 2 or (len(tokens) == 2 and len(tokens[1]) > 10): return False versions = tokens[0].split(".") if len(versions) > 4: return False for ver in versions: if not ver.isdigit(): return False return True
96f0a75e6012b5670bc907f1d2447aaeed520bed
482,313
def function_label(fxn): """Return a (filename, first_lineno, func_name) tuple for a given code object. This is the same labelling as used by the cProfile module in Python 2.5. """ code = fxn.__code__ if isinstance(code, str): return ('~', 0, code) # built-in functions ('~' sorts at the end) else: return (code.co_filename, code.co_firstlineno, code.co_name)
f120da27fa4aea12155c6dbfaf5d49937122c7a5
307,618
import logging def verify_mention_index(original, reconstructed): """Verify that reconstruction succeeded relative to original mention_index.""" def df_to_strings(df): """Returns unique IDs for the mentions in df.""" return df.apply( lambda r: "{}:{}-{}".format(r["docid"], r["mention"], r["position"]), axis=1).values expected_records = set(df_to_strings(original)) got_records = set(df_to_strings(reconstructed)) missing = expected_records.difference(got_records) for missed in missing: logging.warning("Missing mention: %s", missed) return not missing
8a73c15345d696fe8a94a3e2c0a7fad10104fbec
221,818
def rfind(s, *args): """rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return s.rfind(*args)
c420af29df12f62feffad367ae03c500ced04561
597,361
def get_weekday_occurrence(day): """Calculate how often this weekday has already occurred in a given month. :type day: datetime.date :returns: weekday (0=Monday, ..., 6=Sunday), occurrence :rtype: tuple(int, int) """ xthday = 1 + (day.day - 1) // 7 return day.weekday(), xthday
7b22eefe629cd51312d7a8be0908438ab7fef7d6
115,929
def make_mmvt_boundary_definitions(cv, milestone): """ Take a Collective_variable object and a particular milestone and return an OpenMM Force() object that the plugin can use to monitor crossings. Parameters ---------- cv : Collective_variable() A Collective_variable object which contains all the information for the collective variable describine this variable. In fact, the boundaries are contours of the function described by cv. This variable contains information like the groups of atoms involved with the CV, and the expression which describes the function. milestone : Milestone() A Milestone object which describes the boundary between two Voronoi cells. This variable contains information like the values of the variables which will be entered into the Force() object. Returns ------- myforce : openmm.Force() An OpenMM force object which does not affect atomic motion, but allows us to conveniently monitor a function of atomic position. """ myforce = cv.make_force_object() myforce.setForceGroup(1) variable_names_list = cv.add_parameters(myforce) cv.add_groups_and_variables(myforce, cv.get_variable_values_list( milestone)) return myforce
45baaaa70ea24cb564c529cd885597415561a25d
704,283
def class_to_path(cls): """Turn Class (Class or instance) into module path""" return '%s.%s' % (cls.__module__, cls.__name__)
9d16346d50a8e3116790d88a7670ad8568b40edb
347,438
def uniqued(iterable): """Return list of unique hashable elements preserving order. >>> uniqued('spamham') ['s', 'p', 'a', 'm', 'h'] """ seen = set() return [i for i in iterable if i not in seen and not seen.add(i)]
3b2bd1d793a4786d7c31da2e21f30b45b9782f64
555,696
def get_license_link_for_filename(filename, urls): """ Return a link for `filename` found in the `links` list of URLs or paths. Raise an exception if no link is found or if there are more than one link for that file name. """ path_or_url = [l for l in urls if l.endswith(f"/{filename}")] if not path_or_url: raise Exception(f"Missing link to file: {filename}") if not len(path_or_url) == 1: raise Exception(f"Multiple links to file: {filename}: \n" + "\n".join(path_or_url)) return path_or_url[0]
60a445209988214e402fa8612ac1bc371eb01c2c
97,682
def longest_loc_length(book): """ Return the length of the longest location key string. """ loc_length = 0 for loc_string in book.keys(): if len(loc_string) > loc_length: loc_length = len(loc_string) return loc_length
99878c70d91608688d19fc974f86e401ade800cc
89,153
def collapse(values): """Collapse multiple values to a colon-separated list of values""" if isinstance(values, str): return values if values is None: return 'all' if isinstance(values, list): return ';'.join([collapse(v) for v in values]) return str(values)
2b3896ede1d989f6bb303e1b46823751724c8d01
309,865
from typing import List def sum_of_multiples(limit: int, factors: List[int]) -> int: """Sum of Multiples Args: limit: the limit factors: a list of numbers to find multiples of Returns: the sum of all multiples of the factors up to, but not including the limit """ # set comprehension (not a list, to avoid repeated nums) return sum({ i for m in factors if m != 0 for i in range(m, limit, m) })
92a524c388e88f33ae113fd1a649b622388e1763
169,445
def read_block(data, startrow): """ The function returns a block of rows with some data in a row. A blank line separates the block. :param data: Data is a list of tuples, where each tuple represents a row. The element for tuple is Cell. :param startrow: Starting row, where function finding block. :return: Returns a list of lists. The inner list represents columns and the outer row list. Cell values are strings. """ ret = [] def convert(x): """ Function that convert openpyxl Cell to readable value """ if x.value is None: return '' return str(x.value).strip() empty = False rowidx = startrow starting = True heading = [convert(x) for x in data[startrow]] heading = [x for x in heading if len(x) > 0] columns = len(heading) sliced_data = [row[:columns] for row in data] for row in sliced_data[startrow:]: rowidx += 1 row = [convert(x) for x in row] for c in row: if c: break else: if starting: continue # all values empty if empty: break empty = True continue ret.append(row) empty = False starting = False return ret, rowidx
f9008594d762718c894627a9ba0edd688e7a9bb0
514,955
def get_tld_from_domain(domain): """Get the top level domain from a domain string. Args: domain: string with a full domain, eg. www.google.com Returns: string: TLD or a top level domain extracted from the domain, eg: google.com """ return '.'.join(domain.split('.')[-2:])
9de0680731430a7895a5e62adc9720f3f5c19512
505,631
def search_tag(resource_info, tag_key): """Search tag in tag list by given tag key.""" return next( (tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key), None, )
5945631a3de7032c62c493369e82dd330ef2bc47
704,483
def import_from(import_string): """ Imports a function from python module import string """ fn_name = import_string.split('.')[-1] module_name = '.'.join(import_string.split('.')[:-1]) module = __import__(module_name, fromlist=[fn_name]) return getattr(module, fn_name)
805ea07b9cc387754a4436dae2587944cdea25d2
106,571
import torch from typing import List def reconstruct_encoding_constraints( x: torch.Tensor, feature_pos: List[int], binary_cat: bool ) -> torch.Tensor: """ Reconstructing one-hot-encoded data, such that its values are either 0 or 1, and features do not contradict (e.g., sex_female = 1, sex_male = 1) Parameters ---------- x: instance where we want to reconstruct categorical constraints feature_pos: list with positions of categorical features in x binary_cat: If true, categorical datas are encoded with drop_if_binary Returns ------- Tensor with reconstructed constraints """ x_enc = x.clone() if binary_cat: for pos in feature_pos: x_enc[:, pos] = torch.round(x_enc[:, pos]) else: binary_pairs = list(zip(feature_pos[:-1], feature_pos[1:]))[0::2] for pair in binary_pairs: # avoid overwritten inconsistent results temp = (x_enc[:, pair[0]] >= x_enc[:, pair[1]]).float() x_enc[:, pair[1]] = (x_enc[:, pair[0]] < x_enc[:, pair[1]]).float() x_enc[:, pair[0]] = temp if (x_enc[:, pair[0]] == x_enc[:, pair[1]]).any(): raise ValueError( "Reconstructing encoded features lead to an error. Feature {} and {} have the same value".format( pair[0], pair[1] ) ) return x_enc
b960ecf246e6df92eed90ae2183d274e571c1cd9
165,382
def dedent(doc_string): """Remove any common leading whitespace from every line in text. This functionality is similar to python's `textwrap.dedent` functionality https://docs.python.org/3/library/textwrap.html#textwrap.dedent Args: doc_string (str): A docstring style string Returns: str: A string optimized for stardoc rendering """ lines = doc_string.splitlines() if not lines: return doc_string # If the first line is empty, use the second line first_line = lines[0] if not first_line: first_line = lines[1] # Detect how much space prepends the first line and subtract that from all lines space_count = len(first_line) - len(first_line.lstrip()) # If there are no leading spaces, do not alter the docstring if space_count == 0: return doc_string else: # Remove the leading block of spaces from the current line block = " " * space_count return "\n".join([line.replace(block, "", 1).rstrip() for line in lines])
6ed6aecc4736c6f6b3a7bf19501cf691cdcccfd2
325,260
def prob_mass_green_from_ndvi(ndvi, old_min=0.3, old_max=0.9): """ Calculate probability mass for greenness from NDVI values :param ndvi: :param old_min: :param old_max: :return: """ if ndvi < old_min: return 0 elif ndvi >= old_max: return 1 else: new_max = 1 new_min = 0 old_range = old_max - old_min new_range = new_max - new_min return (((ndvi - old_min) * new_range) / old_range) + new_min
cba7ac7679d79d8b6d997c63fe7f9a406a00f023
658,700
from bs4 import BeautifulSoup def extract_math_envs(file): """ Extract the math environments that are contained in the file (e.g. within '$...$'). :return: A list of the math environments as strings. """ soup = BeautifulSoup(file) def remove_special_chars(math_env): math_env = math_env.replace('amp;', '') return math_env math_envs = [remove_special_chars(str(tag)) for tag in list(soup.find_all('math'))] return math_envs
cfb77d1b380c01ccaf8cdcfee5528555a2631570
182,903
def assert_equal_length(psg, hyp, sample_rate): """ Return True if the PSG and HYP have equal lengths in seconds """ return psg.shape[0] / sample_rate == hyp.total_duration
968776dee6058b137c3c4445e0e8e87b4223e96c
679,172
import torch import re def dtype_byte_size(dtype: torch.dtype): """ Returns the size (in bytes) occupied by one parameter of type `dtype`. Example: ```py >>> dtype_byte_size(torch.float32) 4 ``` """ if dtype == torch.bool: return 1 / 8 bit_search = re.search("[^\d](\d+)$", str(dtype)) if bit_search is None: raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") bit_size = int(bit_search.groups()[0]) return bit_size // 8
12a30fb0ce1dbec998a3ac48d3196886e0f477b0
484,953
def emtpy_cols(cols, rows, plas, model): """ Helper function for shrink_dict. Iterates over the given model and removes all numbers of the coordinates from the items in the model. this way there will be remaining lists of empty cols, rows and plas. Returns a list of the 3 lists. """ for (x_co, y_co, z_co) in model.keys(): # remove all coordinate components from the corresponding list. if x_co in cols: cols.remove(x_co) if y_co in rows: rows.remove(y_co) if z_co in plas: plas.remove(z_co) #print("empty cols returns cols, rows, plas:", cols, rows, plas) return [cols, rows, plas]
410b13b0b0d527237c794be04f708e31cf39293f
651,196
def q_liq_top(rho_top_liq, L_septum, L_top): """ Calculates the specific flow rate of the liquid for 1 m of drain septum Parameters ---------- rho_top_liq : float The destiny of liquid at top of column, [kg/m**3] L_top : float The flow rate of liquid at top of column, [kg/s] L_septum : float The length of drain septum, [m] Returns ------- q_liq_top : float The specific flow rate of the liquid for 1 m of drain septum at top of column, [m**2/s] References ---------- Дытнерский, страница 239, формула 6.39 """ return L_top / (rho_top_liq * L_septum)
5aaf515f2c932ddec67c20734f7bf711b67025b8
618,892
def dot(a, b, out=None): """ Dot product of two arrays. Specifically, - If both `a` and `b` are 1-D arrays, it is inner product of vectors (without complex conjugation). - If both `a` and `b` are 2-D arrays, it is matrix multiplication, but using ``a @ b`` is preferred. - If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply` and using ``cunumeric.multiply(a, b)`` or ``a * b`` is preferred. - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over the last axis of `a` and `b`. - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a sum product over the last axis of `a` and the second-to-last axis of `b`:: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) Parameters ---------- a : array_like First argument. b : array_like Second argument. out : ndarray, optional Output argument. This must have the exact shape that would be returned if it was not present. If its dtype is not what would be expected from this operation, then the result will be (unsafely) cast to `out`. Returns ------- output : ndarray Returns the dot product of `a` and `b`. If `out` is given, then it is returned. Notes ----- The cuNumeric implementation is a little more liberal than NumPy in terms of allowed broadcasting, e.g. ``dot(ones((3,1)), ones((4,5)))`` is allowed. Except for the inner-product case, only floating-point types are supported. See Also -------- numpy.dot Availability -------- Multiple GPUs, Multiple CPUs """ return a.dot(b, out=out)
266ea378f94e668355e3a58d1beb9ab6c7d65210
626,421
def x2bool(s): """Helper function to convert strings from the config to bool""" if isinstance(s, bool): return s elif isinstance(s, str): return s.lower() in ["1", "true"] raise ValueError()
2850c3ab0421619a087d88181f3b6e2c6ffa9e9a
16,718
def int2fixed(i): """Convert an integer to fixed point""" return i << 16
7505fa97238dd2440b4aaf46483fc452a145e68a
49,707
import re def remove_comments(contents): """ Remove the comments from the contents """ contents = re.sub(re.compile(r"#.*?\n", re.DOTALL), "", contents) # remove all occurrences of #COMMENT from line return contents
26dce5172c16b68b1ab5a1b64b1dd2f4d49b0aaf
95,679
from typing import Mapping def update_nested(original_dict, update_dict): """Update a nested dictionary with another nested dictionary. Has equivalent behaviour to :obj:`dict.update(self, update_dict)`. Args: original_dict (dict): The original dictionary to update. update_dict (dict): The dictionary from which to extract updates. Returns: original_dict (dict): The original dictionary after updates. """ for k, v in update_dict.items(): nested_dict = v if isinstance(v, Mapping): # Mapping ~= any dict-like object nested_dict = original_dict.get(k, {}) if nested_dict is not None: nested_dict = update_nested(nested_dict, v) original_dict[k] = nested_dict return original_dict
a1a372ac4d26066c3fe32cd4ee1a49fff6972cd9
701,714
def __to_unsigned(val): """ convert signed (2 complement) value to unsigned """ if val < 0: val = ~(-val - 1) return val
95815e89c11f547f0b56d35f89321a9323cd16f8
293,270
def minify_graphql_call(call: str) -> str: """ Minify GraphQL call. Right now this just strips leading whitespace from all lines which is enough to reduce size by ~50%. """ return "\n".join(line.lstrip() for line in call.strip().splitlines())
157fbc7a2072a19aae9a11bf8de37c7aa0d9fbeb
476,108
from typing import List from typing import Dict import json def load_umls_kb(umls_path: str) -> List[Dict]: """ Reads a UMLS json release and return it as a list of concepts. Each concept is a dictionary. """ with open(umls_path) as f: print(f'Loading umls concepts from {umls_path}') umls_concept_list = json.load(f) print(f'Number of umls concepts: {len(umls_concept_list)}') return umls_concept_list
d53a1948a35f05d1afb856e18cc770b99b4960c2
398,437
def get_direction(ball_vector: list) -> int: """Get direction to navigate robot to face the ball Args: ball_vector (list of floats): Current vector of the ball with respect to the robot. Returns: int: 0 = forward, -1 = right, 1 = left """ if -0.13 <= ball_vector[1] <= 0.13: return 0 return -1 if ball_vector[1] < 0 else 1
d21f350a6a9ff7339874b0bba3d4ba3897c17195
292,513
def is_in(sequence, part): """ returns true if 2-item list 'part' is in list 'sequence' """ assert len(part) == 2 for i in range(0, len(sequence) - 1): if sequence[i: i + 2] == part: return True return False
bfded09ef7905381c07d0bb54b6cdf898160165c
243,311
def parse_keys(keys): """ Parse keys for complex __getitem__ and __setitem__ Parameters ---------- keys : string | tuple key or key and slice to extract Returns ------- key : string key to extract key_slice : slice | tuple Slice or tuple of slices of key to extract """ if isinstance(keys, tuple): key = keys[0] key_slice = keys[1:] else: key = keys key_slice = (slice(None),) return key, key_slice
a2b56095fa8fdd2a7433b03958dd8e2dee4475a6
182,582
def is_scoped_package(name): """ Return True if name contains a namespace. For example:: >>> is_scoped_package('@angular') True >>> is_scoped_package('some@angular') False >>> is_scoped_package('linq') False >>> is_scoped_package('%40angular') True """ return name.startswith(('@', '%40',))
22d54aaf967f8556686a023f296f70d38a864496
632,161
def rotmol(numpoints, coor, lrot): """Rotate a molecule :param numpoints: the number of points in the list :type numpoints: int :param coor: the input coordinates :type coor: [[float, float, float]] :param lrot: the left rotation matrix :type lrot: [[float, float, float]] :return: the rotated coordinates :rtype: [[float, float, float]] """ out = [] for i in range(numpoints): out.append([]) out[i].append( lrot[0][0] * coor[i][0] + lrot[1][0] * coor[i][1] + lrot[2][0] * coor[i][2] ) out[i].append( lrot[0][1] * coor[i][0] + lrot[1][1] * coor[i][1] + lrot[2][1] * coor[i][2] ) out[i].append( lrot[0][2] * coor[i][0] + lrot[1][2] * coor[i][1] + lrot[2][2] * coor[i][2] ) return out
54ea0ff42e6a97ba9f94b2e366e880eef697b39d
317,929
def split_cubic_into_two(p0, p1, p2, p3): """Split a cubic Bezier into two equal parts. Splits the curve into two equal parts at t = 0.5 Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. Returns: tuple: Two cubic Beziers (each expressed as a tuple of four complex values). """ mid = (p0 + 3 * (p1 + p2) + p3) * .125 deriv3 = (p3 + p2 - p1 - p0) * .125 return ((p0, (p0 + p1) * .5, mid - deriv3, mid), (mid, mid + deriv3, (p2 + p3) * .5, p3))
064465614c96c769bd585e7fd0238180ac306de4
483,568
def unroll_rids(rids): """Recursively unroll rid id ranges into individual rids.""" if not rids: return [] m = rids[0] if m[1]: return ['R%d' % r for r in range(int(m[0]), int(m[1])+1)] + unroll_rids(rids[1:]) return ['R%s' % m[0]] + unroll_rids(rids[1:]) return []
f8dea8f8ffd69315a48f7fdb22eac49390214ea7
129,209
def sort_points_by_X(points): """ Sort a list of points by their X coordinate Args: points: List of points [(p1_x, p1_y), (p2_x, p2_y), ...] Returns: List of points sorted by X coordinate """ points.sort() return points pass
5445cce3467dd026c66a694b725e7185248184b5
512,537
import requests from bs4 import BeautifulSoup def scrape_reviews(isbn): """ Scrape reviews from book's Goodreads webpage using BeautifulSoup 4. Return a list of tuples (names,rating,reviews) """ book_page_url = f"https://www.goodreads.com/api/reviews_widget_iframe?did=0&format=html&hide_last_page" \ f"=true&isbn={isbn}&links=660&min_rating=&page=2&review_back=fff&stars=000&text=000" webpage = requests.get(book_page_url) soup = BeautifulSoup(webpage.content, "html.parser") reviews_raw = soup.find_all('div', class_='gr_review_text') # find containers containing text of the review reviews = [review.text.strip() for review in reviews_raw] # delete unnecessary whitespace names_raw = soup.find_all('a', itemprop="discussionUrl") # find names of the review authors names = [name.text for name in names_raw] ratings_raw = soup.find_all('span', class_="gr_rating") # find ratings of the review ratings = [rating.text.count("★") for rating in ratings_raw] # convert starred rating into integer value full_reviews = list(zip(names, ratings, reviews)) # make a list of tuples containing full info about reviews return full_reviews
cf387e368c7c97cee1f8bced4551e40d5fa9a3ee
666,574
import operator def filtered_join (sep, strings, pred = None) : """Return a string which is the concatenation of the items in the iterable `strings` for which `pred` is true, separated by `sep`. >>> filtered_join ("-", ["", "abc", "ced"]) 'abc-ced' >>> filtered_join ("-", [" ", "abc", "ced"]) ' -abc-ced' """ if pred is None : pred = operator.truth return sep.join (s for s in strings if pred (s))
f2062339413c5572646284112df7856039f7c35e
643,658
import re def to_alnum(string: str) -> str: """Returns a string that is a copy of `string` with all non-alphanumeric characters removed.""" return re.sub(r'\W+', '', string)
4e2d228d8ced764b021ab3840980225201e3ec02
479,651
def get_info(information): """ Retrieves title of the source For example, from the information below, HYPERLINK("https://drive.google.com/open?id=0B9q-Bz2y-5byRWZwRHptZmk0eU0","Baby And Her Health") Returns `Baby And Her Health` """ information = information.lower() if information.startswith("=hyperlink"): splits = information.split(",") return splits[1].split("\"")[1].strip() return information.strip()
ff3576efd3cd32cdfbe8c844971021381d5cea93
608,394
def verify_row_contains_rating(sheet_row: tuple, window=None) -> bool: """ Função que retorna apenas as linhas onde o campo de `avaliação concreta` é marcado com `SIM`. Arguments: sheet_row (tuple): tupla de valores guardados na linha Return: bool: indica se a linha contém ou não avaliação """ rating_cell = sheet_row[6] contains_rating = False if rating_cell and (rating_cell.lower() == 'x'): contains_rating = True return contains_rating
419b8a9bcc86629416e5686762f2c65513237fec
517,623
def get_or_default(arr, index, default_value=None): """ Get value at index from list. Return default value if index out of bound :type arr: list :param arr: List to get value from :type index: int :param index: Index to get value for :type default_value: Any :param default_value: Default value :rtype: Any :return: Value to get """ return arr[index] if len(arr) > index else default_value
09d93323d29920fa34521feb6fcb66870a8342fa
210,528
def get_range(context, range_str): """Should be given a range_str like '<start_index>:<end_index', e.g. '1:4' returns a string: e.g. 1,2,3 """ rargs = [int(s) for s in range_str.split(':')] return ','.join([str(d) for d in range(*rargs)])
879ad99e2c35d18efb1a565caa800231deb17968
602,550
def sub2indSH (m,n): """ i = sub2indSH(m,n) Convert Spherical Harmonic (m,n) indices to array index i Assumes that i iterates from 0 (Python style) """ i = n**2 + n + m return i
9700b78c8a06e58d207307e6b00f3948ba88e02b
630,607
from typing import Dict from typing import List def dict_to_list(d: Dict) -> List: """ Converts a dictionary to a list Args: d: Input dictionary Returns: Outputs list """ ret = [] for i in d.items(): ret.append(i[1]) return ret
4970433803a84b754c5c1237e671fa155d5f14f8
272,668
def get_rectangle_in_an_image(np_array, bounding_rectangle_of_polygon): """ :param np_array: a numpy array :type np_array: numpy.ndarray (https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) :param bounding_rectangle_of_polygon: tuple or list with coordinates of the start point of the rectangle and the width and height of this rectangle - (x, y, width, height) or [x, y, width, height] :type bounding_rectangle_of_polygon: tuple - () or list - (). The tuple or list should have four elements. :return: the part of 'np_array' indicated by 'bounding_rectangle_of_polygon' :rtype numpy.ndarray (https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) """ return np_array[ bounding_rectangle_of_polygon[1]: bounding_rectangle_of_polygon[1] + bounding_rectangle_of_polygon[3], bounding_rectangle_of_polygon[0]: bounding_rectangle_of_polygon[0] + bounding_rectangle_of_polygon[2]]
ba01aad5e2b34f16b3736e352ae9feac2965ad60
183,423
def intToBitString(a, bit = 256): """ Converts an integer to a binary string representation (without '0b') :param a: The integer to convert (integer) :param bit: The size of the representation in bit (integer) :return: Binary string representation (String) """ str = bin(a)[2:] return (bit-len(str))*"0" + str
288f9b77063ca23f544ae561780e47c9f5bac684
604,514
from typing import Any import inspect def istype(obj: Any) -> bool: """Return True if object is a class, function, or method type""" return inspect.isclass(obj) or inspect.isfunction(obj) or inspect.ismethod(obj)
5ca59d323afbd80ca9c08c54b9a66da38bc2df79
138,701
def _test_case_status(test_case) -> str: """Get the status of a test case based on an etree node.""" if test_case.find('failure') is not None: return 'fail' if test_case.find('skipped') is not None: return 'skip' return 'pass'
fb07b69bb61e2140bc2c894c7942de1c0e37f233
208,043
def parse_domain_directive(directive): """Parse a domain directive (i.e. from CLI). Args: directive (str): Domain directive of the form name,dx,lat_min,lat_max,lon_min,lon_max Returns: dict : Domain dictionary Raises: ValueError : If the domain cannot be parsed. """ name, *directives = directive.split(',') dx, lat_min, lat_max, lon_min, lon_max = map(float, directives) return dict( name=name, dx=dx, lat_min=lat_min, lat_max=lat_max, lon_min=lon_min, lon_max=lon_max )
b614c1c69d4a660fdac8f1bb0987d2b8a1efecfc
558,419
def remove_prefix(text, prefix): """Removes the prefix `prefix` from string `text` in case it is present.""" return text[len(prefix):] if text.startswith(prefix) else text
e7d5b43b36e6e58cba5ce74eeca003e5354fa364
94,175
def get_variable_parent_name(var): """Get the name of the parent if it exists or return the variable name otherwise.""" if hasattr(var, "parent") and var.parent is not None: return var.parent.name else: return var.name
e16421d9cc94b1260133068eb6a2933702857dc5
376,898
import functools import signal def reset_signal_handlers(func): """ Decorator that resets signal handlers from the decorated function. Useful for workers where we actively want handlers defined on the supervisor to be removed, because they wouldn't work on the worker process. """ @functools.wraps(func) def wrapped(*args, **kwargs): signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGCHLD, signal.SIG_DFL) return func(*args, **kwargs) wrapped.__wrapped__ = func return wrapped
ed367e7f93e3694e41b55ded867d710569e724c0
171,786
def isInt(x) -> bool: """Decide whether or not something is either an integer, or is castable to integer. :param x: The object to type-check :return: True if x is an integer or if x can be casted to integer. False otherwise :rtype: bool """ try: int(x) except (TypeError, ValueError): return False return True
90ef72722ecea1b45c3961a5247945a80bd2df47
406,056
def sort_matrix(mat): """Sorts a 2D matrix, first by its rows and then by its columns. Parameters ---------- mat : pd.DataFrame Matrix to sort. Returns ------- pd.DataFrame Sorted matrix. """ freqs = (mat > 0).sum(axis=1) order = list(freqs.sort_values(ascending=False).index) mat_sorted = mat.ix[order] mat_sorted = mat_sorted.T.sort_values(by=order, ascending=False).T return mat_sorted
91b96670ca2b2e791b33ce1294e647994e021c22
503,249
import string import random def random_string_generator(size=6, chars=string.ascii_uppercase + string.digits): """ Generate random string Args: size: length of the string chars: sequence of chars to use Returns: random string of length "size" """ return ''.join(random.choice(chars) for _ in range(size))
4b9e9ef10664c57b6839f549f6ca9aac9fa78fdc
651,449
def tree_similarity_ratio(ted, t1, t2): """ Return the similarity ratio from 0 to 1 between two trees given their edit distance `ratio` idea from [DiffLib](https://fossies.org/dox/Python-3.5.1/difflib_8py_source.html) """ # print(ted) # import networkx as nx # empty_tree = nx.DiGraph() # print('#nodes', # t1.number_of_nodes(), # t2.number_of_nodes()) # print('ted against empty_tree', # salzburg_ted(t1, empty_tree), # salzburg_ted(t2, empty_tree)) return 1 - 2 * ted/(t1.number_of_nodes() + t2.number_of_nodes())
5ed52f83aaafeaa64e9597ed628cf83c8fd9a454
639,373
def parse_maddr_str(maddr_str): """ The following line parses a row like: {/ip6/::/tcp/37374,/ip4/151.252.13.181/tcp/37374} into ['/ip6/::/tcp/37374', '/ip4/151.252.13.181/tcp/37374'] """ return maddr_str.replace("{", "").replace("}", "").split(",")
1a1ca1d846c650a3c01dca04a3debf921186d1a7
79,392
def str_in_list(l1, l2): """Check if one element of l1 is in l2 and if yes, returns the name of that element in a list (could be more than one. Examples -------- >>> print(str_in_list(['time', 'lon'], ['temp','time','prcp'])) ['time'] >>> print(str_in_list(['time', 'lon'], ['temp','time','prcp','lon'])) ['time', 'lon'] """ return [i for i in l1 if i.lower() in l2]
3fa5c4394108179192162e1974497e3004d7494f
195,983
def get_cleaned_text(text): """Returns cleaned text (convert to string, change to lowercase, etc)""" cleaned_text = str(text) cleaned_text = cleaned_text.lower() return cleaned_text
24fa5c1392107256a4d4d5fe47014361fbcc623d
523,071
def assets_keys(scope='module'): """Mock keys fixture.""" return ['result', 'allowance']
c02b9d214ef48f169679698544081eeecf44fe42
515,208
import typing def part2(func: typing.Callable[[str, typing.Any], None]): """ Decorator to wrap around the solution method for Part 2. The first positional argument is the puzzle input. The second argument is the return value from Part 1's solution function. Example; ``` @utils.part2 def solutionTwo(data: str, previous: int): answer = previous * math.pi utils.printAnswer(str(answer)) ``` """ global _part2SolutionFunc _part2SolutionFunc = func return func
9a2689dd625c6ed953e7da60396a5742a06071df
614,165
import math def deg2rad(deg): """Convert degrees to radians""" return deg / (180 / math.pi)
8c203eded49e36ad829b8bba0ae5ce4064cf35ee
144,431
import itertools def chunk(it, n): """Yield successive n-sized chunks from it. >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(chunk(l, 3)) [(1, 2, 3), (4, 5, 6), (7, 8, 9)] >>> list(chunk(l, 2)) [(1, 2), (3, 4), (5, 6), (7, 8), (9,)] """ it = iter(it) return iter(lambda: tuple(itertools.islice(it, n)), ())
e9264dfcc124e001ce55845731d4e64b21a3eba2
227,763
import re def clean(l): """ Removes nan and personal pronouns from l and returns a list of NER uniques. """ non_nan = [re.sub(r'(?:^|, |s|S|)(?:h|H)(?:e|i).?(?:, |$)', '', str(item)) for item in l] non_nan = [item for item in non_nan if item != 'nan' and item != ''] return list(set(non_nan))
841f67bc6c7dad57e779fa175b61f16954d1f533
151,509
def FormatKeyValue(data): """Formats a dictionary as "key=value" parameters. The keys are sorted to have a stable order. @type data: dict @rtype: list of string """ return ["%s=%s" % (key, value) for (key, value) in sorted(data.items())]
4e6e4d1aeaed3c2b2f12feede3a8ef9cc9402574
225,788
from datetime import datetime def convert_to_git_timestamp(timestamp: str) -> str: """ Converts the timestamp to a git timestamp. :param timestamp: The timestamp to convert. :return: The git timestamp. """ date = datetime.strptime(str(timestamp), '%Y%m%d%H%M') return date.strftime("%Y-%m-%dT%H:%M:%SZ")
cd9155502b6f56412ebfdc0ca07a7faa23d58d27
415,176
def avg(values): """Return the average of a set of values.""" return sum(values) / len(values)
624a11e4bf43f07c13d00a5a4f18a46114b7f65e
248,136
def area_slice(cube, start_longitude, end_longitude, start_latitude, end_latitude): """ Subset a cube on area. Function that subsets a cube on a box (start_longitude, end_longitude, start_latitude, end_latitude) This function is a restriction of masked_cube_lonlat(); Arguments --------- cube: iris.cube.Cube input cube. start_longitude: float Western boundary longitude. end_longitude: float Eastern boundary longitude. start_latitude: float Southern Boundary latitude. end_latitude: float Northern Boundary Latitude. Returns ------- iris.cube.Cube smaller cube. """ # Converts Negative longitudes to 0 -> 360. standard start_longitude = float(start_longitude) end_longitude = float(end_longitude) start_latitude = float(start_latitude) end_latitude = float(end_latitude) region_subset = cube.intersection( longitude=(start_longitude, end_longitude), latitude=(start_latitude, end_latitude)) region_subset = region_subset.intersection(longitude=(0., 360.)) return region_subset
5b81baf1ccc511637b8045b995c005e8a69d6910
497,123
def _limit_grouped_results(results, limit): """Limit a grouped set of results """ return results[:limit] if limit else results
a28997163161db21f788b125e14877189c976b46
292,071
def tau(x, k): """Calculate tau_i^k = x_i/x_{k-1}. :raise ValueError if matrix is not LU decomposable. """ if x[k - 1] == 0: raise ValueError('Matrix isn\'t LU decomposable.') t = x / x[k - 1] t[:k] = 0 return t.reshape((x.shape[0], 1))
7ea1ace717fab4e39461e3b5034b5dd9caca3e79
277,396
def median(numbers): """ Return the median of the list of numbers. see: http://mail.python.org/pipermail/python-list/2004-December/294990.html """ # Sort the list and take the middle element. n = len(numbers) copy = sorted(numbers) if n & 1: # There is an odd number of elements return copy[n // 2] else: return (copy[n // 2 - 1] + copy[n // 2]) / 2.0
fabda42b2bfeb8ff893ef82e4178bc351d7454b3
252,810
def mean(x, old_mean, old_num_samples): """ Incremental update (using unbiased formula) of sample mean. Parameters ---------- x : numpy.ndarray, shape=(1, n) New point. old_mean : numpy.ndarray, shape=(1, n) Old sample mean. old_num_samples : int Old number of samples. Returns ------- new_mean : numpy.ndarray, shape=(1, n) Updated sample mean. References ---------- Lughofer, Edwin. Evolving fuzzy systems-methodologies, advanced concepts and applications. Vol. 53. Berlin: Springer, 2011. """ new_num_samples = old_num_samples + 1 new_mean = (old_num_samples / new_num_samples) * old_mean + \ ((1 / new_num_samples) * x) return new_mean
ef4442e52de988a6275fff85161518f86d37dac5
131,490
def newPlayer(name, password): """Create player dict""" player = {'name':name,'password':password,'stats':{},'vars':{},'exp':0} player['stats']['health'] = 10 player['vars']['health'] = 10 player['stats']['attack'] = 1 player['stats']['defense'] = 1 player['vars']['defense'] = 0 return player
679a52b836ddbeb5dc757fa430ecc9083dbe1589
405,073
def quarticCoefficients_ellipse_to_Quarticipynb(a, b, x, y, r): """ Calculates coefficients of the quartic expression solving for the intersection between a circle with radius r and ellipse with semi-major axis a semi-minor axis b, and the center of the circle at x and y. Coefficients for the quartic of form x**4 + A*x**3 + B*x**2 + C*x + D = 0 """ A = -4*a**2*x/(a**2 - b**2) B = 2*a**2*(a**2*b**2 - a**2*r**2 + 3*a**2*x**2 + a**2*y**2 - b**4 + b**2*r**2 - b**2*x**2 + b**2*y**2)/(a**4 - 2*a**2*b**2 + b**4) C = 4*a**4*x*(-b**2 + r**2 - x**2 - y**2)/(a**4 - 2*a**2*b**2 + b**4) D = a**4*(b**4 - 2*b**2*r**2 + 2*b**2*x**2 - 2*b**2*y**2 + r**4 - 2*r**2*x**2 - 2*r**2*y**2 + x**4 + 2*x**2*y**2 + y**4)/(a**4 - 2*a**2*b**2 + b**4) return A, B, C, D
4f3e4e44e5bb7f3ffc3130990c98be7f0c98df5e
565,882
def getCurrentTournament(c): """ Returns the current Tournament ID""" c.execute("SELECT * FROM CurrentTournament;") tournament = c.fetchone()[0] return tournament
1357ce964fc0fd2f037e3d42857e5d9cfc725f27
565,500
def to_int(text): """ extract digits from text """ return ''.join([char for char in text if char.isdigit()])
c791dd4d2057d658ad96beeafd31e7e9767324ea
655,727
from typing import Any def optional(**kwargs: Any) -> dict: """ Take a set of keyword arguments and return a dict with only the not-None values. Returns: dict """ return {key: value for key, value in kwargs.items() if value is not None}
97b50729f2749088b189f2aeddae96d00bc9163e
607,044
def is_after(t1, t2): """Takes 2 time objects, returns True if t1 follows t2 chronologically, otherwise False """ t1_seconds = t1.second + t1.minute*60 + t1.hour*3600 t2_seconds = t2.second + t2.minute*60 + t2.hour*3600 return t1_seconds > t2_seconds
76278acd2443264a8145981351b1c67a2b6b4876
90,002
import re def _redact_volatile(output: str) -> str: """ Replace some volatile values, like temp paths & memory locations. >>> _redact_volatile("<__main__.A at 0x10b80ce50>") '<__main__.A at 0x...>' >>> _redact_volatile("/tmp/abcd234/pytest-accept-test-temp-file-0.py") '/tmp/.../pytest-accept-test-temp-file-0.py' """ mem_locations = re.sub(r" 0x[0-9a-fA-F]+", " 0x...", output) temp_paths = re.sub(r"/tmp/[0-9a-fA-F]+", "/tmp/...", mem_locations) return temp_paths
6a53bf858618c255134c54707550afa4b3934d3b
591,293
def fahrenheit2celcius(F): """ Convert Fahrenheit to Celcius :param F: Temperature in Fahrenheit :return: Temperature in Celcius """ return 5.0 / 9.0 * (F - 32)
c51d4eaeb456bcffc58e74d7cc0b61ce6c8ee1f8
266,793
def cf_record_prob_lose2(winrate, numwins, maxwins=5): """Probability of winning `numwins` game in an event that stops at two losses. >>> pct(cf_record_prob_lose2(0.6, 5)) 23.3 >>> pct(cf_record_prob_lose2(0.45, 3)) 11.0 """ if numwins == maxwins: return pow(winrate, numwins) + numwins*pow(winrate, numwins)*(1-winrate) else: return pow(winrate, numwins)*pow(1-winrate, 2)*(numwins+1)
d8338833eae0088532ff71681f7fed958fd8a565
340,748
def to_absolute_path_for_docker_volumes(context, path): """ Return absolute path to use in docker volume command :param context: test context :param path: relative path :return: absoulte path to use in docker -v """ host_pwd = context.config.userdata['host_pwd'] return "%s/%s" % (host_pwd, path)
8ec0013d61e62b2aadb2aec048569a0454aeabac
248,858
def readline_skip_comments(f): """ Read a new line while skipping comments. """ l = f.readline().strip() while len(l) > 0 and l[0] == '#': l = f.readline().strip() return l
c4b36af14cc48b1ed4cd72b06845e131015da6c6
823
def offsets_to_cell_num(y_offset, x_offset): """ :param y_offset: The y_offset inside a block. Precondition: 0 <= y_offset < 3 :param x_offset: The x_offset inside a block. Precondition: 0 <= x_offset < 3 :return: The cell number inside a block """ return 3 * y_offset + x_offset
44b4a20533c9531d40e999bfda022ba649a994ce
376,856
def has_target_log_prob(kernel_results): """Returns `True` if `target_log_prob` is a member of input.""" return getattr(kernel_results, 'target_log_prob', None) is not None
fc462b768a16f98ff97d6bd697ecbbdbb01960b0
517,037
def v(n,d): """Maximum e such that d^e divides n.""" if n<1 or d<2: return -1 count=0 while n%d==0: n//=d count+=1 return count
2348ad188cb386c0ca7a612139b962a1f1d77010
510,758
def get_matching_paren(exp: str) -> int: """ Returns the index of the right parenthesis which matches the first left parenthesis. exp[0] should be a left parenthesis """ if exp[0] != '(': raise ValueError('Given string must begin with \'(\' character') left = 1 right = 0 i = 1 while left > right: if exp[i] == '(': left += 1 elif exp[i] == ')': right += 1 i += 1 return i - 1
2d6a3cc4bca6981b7545fdfb4446718d7a6e1e16
528,831
def get_error_res(eval_id): """Creates a default error response based on the policy_evaluation_result structure Parameters: eval_id (String): Unique identifier for evaluation policy Returns: PolicyEvalResultStructure object: with the error state with the given id """ return { "id": eval_id, "result": { "message": f"No evaluation with the id {eval_id} ongoing", "status": "ERROR", "confidenceLevel": "0", }, }
ebb80435b6f0c590dc30a9095559cbbbd1da5662
688,883
def get_lr_run_identifier(lrs): """Computes the run identifier for the given learning rates. Search identifier will not contain w_eval. Args: lrs (dict): That that contains the learning rate for every searched learning rate. Returns: str: String that uniquely represents a run with the given learning rates. """ run_identifier = "" for val in ['w_search', 'alpha', 'beta']: try: run_identifier += f"{val}-{lrs[val]}_" except KeyError: break if 'w_eval' in lrs.keys(): run_identifier += f"w_eval-{lrs['w_eval']}_" run_identifier = run_identifier[:-1] return run_identifier
35f6e8cfd00eef98f22da00df299f9ca6f8c909d
338,743
import logging def load_joint_order(handle): """ Loads a joint order from the given handle. :param io.file handle :rtype list[str] """ logging.info('Loading joint order') result = [line.strip() for line in handle] logging.info('Loaded {} joints'.format(len(result))) return result
608eecefd17a2ea2c04aae3faa3b008e87a813ac
126,686
def lemmatise(tokens): """ Lemmatise nested list of tokens Parameters ---------- tokens: list a nested list containing lists of tokens or a list of spacy dcs Returns ------- lemmas: list a nested list of lemmas """ lemmas = [[word.lemma_ for word in comment] for comment in tokens] return lemmas
292c53c066da41911bc2d7e77cec120581c7c7ad
105,332
def confirm(name, really=False): """ Helper function to deal with user confirming :param String name: Value we are deleting :param boolean really: Are you sure you want to delete this? :return: Flag to indicate if they confirmed :rtype: boolean """ if not really: confirm = input(f"Are you sure you want to delete: {name}?\n" f"Press y to confirm [must be lowercase]:") else: confirm = input(f"Are you REALLY SURE you want to delete: {name}?\n" f"Press y to confirm [must be lowercase]:") if confirm == "y": return True else: return False
b4fa7fea8484b4c63551ebafa2af13c0a5a4e89c
404,823
import re def trailing_whitespace(source): """ Checks each item in source list for a trailing whitespace :param source: list of lines to check for trailing whitespace :return: List of offending line numbers with trailing whitespace, otherwise None """ lines = [] for counter, line in enumerate(source): l = line.rstrip('\n\r') if re.search(r'\s+$', l): lines.append(counter + 1) return lines if lines else None
308ab4afca8d30b2923f3f42cf765739be8a0403
491,183