content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _bytes_chr_py3(i): """ Returns a byte string of length 1 whose ordinal value is i in Python 3. Do not call directly, use bytes_chr instead. """ return bytes([i])
b6cd1e5e7214d02c29a594e639fbddac901a1362
12,593
def guess_type(v, consumer='python'): """Guess the type of a value (None, int, float or string) for different types of consumers (Python, SQLite etc.). For Python, use isinstance() to check for example if a number is an integer. >>> guess_type('1') 1 >>> guess_type('1', 'sqlite') 'integer' >>> guess_type('1.0') 1.0 >>> guess_type('1.0', 'sqlite') 'real' >>> guess_type('abc') 'abc' >>> guess_type('abc', 'sqlite') 'text' >>> >>> value_type = lib.base3.guess_type(value) >>> if isinstance(value_type, int) or isinstance(value_type, float): >>> ... """ if consumer == 'python': if v is None: return None try: return int(v) except ValueError: try: return float(v) except ValueError: return str(v) if consumer == 'sqlite': if v is None: return 'string' try: int(v) return 'integer' except ValueError: try: float(v) return 'real' except ValueError: return 'text'
a9361d5ce7f070f09dca267afb4ffcae866040eb
12,595
import torch def array_from_skew_matrix(x, device=torch.device("cpu"), dtype=torch.float32): """ Receives a skew matrix and returns its associated 3-element vector (array). :param x: Skew matrix (3x3) :return: Associated array (3-element). :param device: Device to allocate new tensors. Default: torch.device("cpu"). :param dtype: Data type for new tensors. Default: torch.float32. """ # We are only slicing the last index in order to keep last dimension. return torch.hstack((x[:, 2, 1:2], x[:, 0, 2:], x[:, 1, 0:1]))
54dcb699db154e8c995dc324888b633451cfb7fc
12,596
def binary(img,th=128): """generate binary image Args: img : image array th : threshold """ img[img<th] = 0 img[img>=th] = 255 return img
627c3fc928886facbae8ca4cf692f543f4cbca40
12,597
import json def hello(event, context): # pylint: disable=unused-argument """Hello lambda function. Args: event (dict): Contains information from the invoking service (service defines the event structure) context (obj): Contains methods and properties that provide information about the invocation, function, and runtime environmenti. (function name, version, memory limits, request id and etc.) Returns: response (dict): Contains request response from the handler (200 status code and event data) """ body = { "message": "Go Serverless v2.0! Your function executed successfully!", "input": event, } response = {"statusCode": 200, "body": json.dumps(body)} return response
fabe319ab98cfcdd9208b021a6b4e42d6aa46a05
12,599
from typing import List from typing import Dict def single__intent_topk_precision_score( intent_prediction: List[Dict[str, str]], y_true: List[str], k: int = 1, ) -> float: """Compute the Precision of a single utterance with multi-intents Precision of a single utterance is defined as the proportion of correctly predicted labels to the total number of the true label. It can be formulated as .. math:: \\text{Precision of single utterance}=\\frac{|\\text{pred}_i \\cap \\text{true}_i|}{|\\text{true}_i|} Args: intent_prediction (a list of dictionaries): A sorted intent prediction (by score) of a single utterance. y_true (a list of strings): The corresponding true intent of that utterance. Note that it can be more than one intents. k (an integer): The top k prediction of intents we take for computing precision. Returns: precision score (a float): precision of a single utterance given top k prediction. Examples: >>> intent_prediction, _ = model.predict("I like apple.") >>> print(intent_prediction) [ {"intent": "blabla", "score": 0.7}, {"intent": "ohoh", "score": 0.2}, {"intent": "preference", "score": 0.1}, ] >>> precision = single__intent_topk_precision_score( intent_prediction=intent_prediction, y_true=["preference", "ohoh", "YY"], k=2, ) >>> print(precision) 0.333333 """ # noqa top_k_pred = [pred["intent"] for pred in intent_prediction[: k]] precision_score = ( len(set(y_true) & set(top_k_pred)) / len(y_true) ) return precision_score
3b67849670f80a3fa148249a6fe41ce4627546e5
12,602
def _deal_with_axis(obj, axis): """Handle the `axis` parameter Parameters ---------- obj: DimArray object axis: `int` or `str` or `tuple` or None Returns ------- newobj: reshaped obj if axis is tuple otherwise obj idx : axis index name : axis name """ # before applying the function on the collapsed array if type(axis) in (tuple, list): idx = 0 newobj = obj.flatten(axis, insert=idx) #idx = obj.dims.index(axis[0]) # position where the new axis has been inserted #ax = newobj.axes[idx] ax = newobj.axes[0] name = ax.name else: newobj = obj idx, name = obj._get_axis_info(axis) return newobj, idx, name
ae0eec4bdf7f172f9617e9f9d1330d75b08f8e97
12,610
def simple_bet(pressure, n_monolayer, c_const): """A simple BET equation returning loading at a pressure.""" return (n_monolayer * c_const * pressure / (1 - pressure) / (1 - pressure + c_const * pressure))
601701b608a48fe634d028023068fcadc636499b
12,613
from typing import Container from typing import Iterable def match_tags(search: Container[str], tags: Iterable[str]): """Check if the search constraints satisfy tags. The search tags should be uppercased. All !tags or -tags cannot be present, all +tags must be present, and at lest one normal tag must be present (if they are) to pass. """ if not tags: return True has_all = '<ALL>' in search # None = no normal tags, True = matched one, False = not matched one. matched = None for tag in tags: tag = tag.upper() start = tag[0:1] if start == '!' or start == '-': if tag[1:] in search: return False elif start == '+': if tag[1:] not in search: return False else: if matched is None: matched = False if has_all or tag in search: matched = True return matched is not False
0a6ee5f233900eb50ad72613aa73f227a836b4dd
12,617
from typing import Dict from typing import Any from typing import Iterator from typing import Tuple def flatten(dictionary: Dict[str, Any]) -> Dict[str, Any]: """ >>> flatten({'foo':{'bar':{'baz': 0}, 'deadbeef': 1}, '42': 3}) {'foo.bar.baz': 0, 'foo.deadbeef': 1, '42': 3} """ def iterate(data: Dict[str, Any], prefix: str) -> Iterator[Tuple[str, Any]]: for key, value in data.items(): prefixed_key = prefix + key if isinstance(value, dict): for prefixed_subkey, val in iterate(value, prefixed_key + '.'): yield prefixed_subkey, val else: yield prefixed_key, value return dict(iterate(dictionary, ""))
401f2f8894690a0c1171d26378ac4a5178dd705a
12,621
def subdivide_stats(data): """ If a key contains a ., create a sub-dict with the first part as parent key """ ret = {} for key, value in data.items(): if '.' in key: parent, subkey = key.split('.', 2) if parent not in ret: ret[parent] = {} ret[parent][subkey] = value else: ret[key] = value return ret
65e47db5c75118c1939a8ecdd3ad581a053da893
12,625
import re def parentdir(file_path): """ Get the parent directory of a file or directory. Goes by the path alone, so it doesn't follow symlinks. On Windows, paths must be converted to use / before passing. This function is not the same as os.path.dirname(); for example, dirname will not give us the correct answer for any of: . ./ .. ../ Note: still doesn't always correctly handle paths starting with / and containing . or .., e.g., parentdir('/foo/..') Dependencies: modules: re """ # remove trailing /'s parentdir = re.sub('/*$', '', file_path) # are there no /'s left? if '/' not in parentdir: if parentdir == '': return '/' # it was /, and / is its own parent if parentdir == '.': return '..' if parentdir == '..': return '../..' return '.' # remove the last component of the path parentdir = re.sub('/*[^/]*$', '', parentdir) if parentdir == '': return '/' return parentdir
baec28e9b6f0017566b91cd2b442a9eb783a144f
12,627
def _Int(s): """Try to convert s to an int. If we can't, just return s.""" try: return int(s) except ValueError: assert '.' not in s # dots aren't allowed in individual element names return s
8f7fcf70717fe30ba991c8cff63cecefe5c01daf
12,628
def strlist_with_or (alist): """Return comma separated string, and last entry appended with ' or '.""" if len(alist) > 1: return "%s or %s" % (", ".join(alist[:-1]), alist[-1]) return ", ".join(alist)
1202e76d34f84618bb6b310bbc43c835f3c94104
12,629
def values_dict(items): """Given a list of (key, list) values returns a dictionary where single-element lists have been replaced by their sole value. """ return {k: v[0] if len(v) == 1 else v for k, v in items}
7abcf62ab334cecc6e6996bad73ff10e5eecdf89
12,636
def DetermineServiceFromUrl(url): """Takes a DFA service's URL and returns the service name. Args: url: string The DFA service's URL. Returns: string The name of the service this URL points to. """ return url.split('/')[-1]
213e1a4dbb5eb3ed643e0ace300b4ac5b6c6c745
12,640
def scrub_response(response): """ Drop irrelevant headers. """ headers = response["headers"] for header in [ "CF-Cache-Status", "CF-RAY", "Cache-Control", "Connection", "Date", "Expect-CT", "NEL", "Report-To", "Server", "Transfer-Encoding", "cf-request-id", "Set-Cookie", ]: headers.pop(header, None) return response
8f1a9f9499df1fbaf7147ccdda8c7854c4c638ec
12,646
def check_necessary_conds(val_inf, muls): """ The necessary conditions for a rational solution to exist are as follows - i) Every pole of a(x) must be either a simple pole or a multiple pole of even order. ii) The valuation of a(x) at infinity must be even or be greater than or equal to 2. Here, a simple pole is a pole with multiplicity 1 and a multiple pole is a pole with multiplicity greater than 1. """ return (val_inf >= 2 or (val_inf <= 0 and val_inf%2 == 0)) and \ all(mul == 1 or (mul%2 == 0 and mul >= 2) for mul in muls)
58463ac2855d07eb36e1850cec3208d69d5a545c
12,647
def get_rect_footprint(l_m=4.8, w_m=1.83): """ Get rectangular footprint of length (x, longitudinal direction) and width (y, lateral direction) l_m : length (default 4.8) w_m : width (default 1.83) Return Values ============= footprint_x : tuple of x coordinates of the footprint footprint_y : tuple of y coordinates of the footprint """ l_half_m = l_m * 0.5 w_half_m = w_m * 0.5 footprint_x, footprint_y = zip((l_half_m, w_half_m), (-l_half_m, w_half_m), (-l_half_m, -w_half_m), (l_half_m, -w_half_m), (l_half_m, w_half_m)) return footprint_x, footprint_y
dd40304c404226543023c1f81bca5aac81e70eec
12,649
def _parse_source_file_list_blob_key(blob_key): """Parse the BLOB key for source file list. Args: blob_key: The BLOB key to parse. By contract, it should have the format: `${SOURCE_FILE_LIST_BLOB_TAG}.${run_id}` Returns: - run ID """ return blob_key[blob_key.index(".") + 1 :]
a7f5c7ccee1404e17b90cb6cd58922ec162d33e3
12,652
def prop_FC(csp, newVar=None): """ Do forward checking. That is check constraints with only one uninstantiated variable. Remember to keep track of all pruned variable,value pairs and return """ constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons() pruned = [] for constraint in constraints: if constraint.get_n_unasgn() != 1: continue # skip to the next constraint # If we get here, get the single unassigned variable var = constraint.get_unasgn_vars()[0] for val in var.cur_domain(): # Check if the var = val satisfies the constraint if not constraint.has_support(var, val): if (var, val) not in pruned: # Then prune this value from var's domain var.prune_value(val) pruned.append((var, val)) # After looking at all values in the var's domain, check if it is now empty if var.cur_domain_size() == 0: return False, pruned return True, pruned
3956cf0ae03a03c0dbc3504ab2ed2a20b8343d90
12,654
def pad(val: str) -> str: """Pad base64 values if need be: JWT calls to omit trailing padding.""" padlen = 4 - len(val) % 4 return val if padlen > 2 else (val + "=" * padlen)
3ab1c91fde1522f15a766730f73e44c97dbeda1a
12,664
def word_remove(text, wordlist): """ This function takes a list of text strings and a list of words. It returns the list of text strings with the words appearing in the wordlist removed. """ # Create new emoty list for the cleaned text clean_text = [] # Seperate ALL words from each other and write them with lower case wordlist = ' '.join(wordlist).lower().split() # Loop over every chunk and remove the words from the wordlist for i in range(len(text)): chunk = text[i] # take chunk chunkwords = chunk.split() # split into single words resultwords = [word for word in chunkwords if word.lower() not in wordlist] # remove words from wordlist chunkclean = ' '.join(resultwords) # gather all words into a string again clean_text.append(chunkclean) # append the chunk to the list outside the loop return(clean_text)
8dac46d54345efedf7bb117af3e4eb67704c0f85
12,666
def fs_write(obj, file_path): """ Convenience function to write an Object to a FilePath Args: obj (varies): The Object to write out file_path (str): The Full path including filename to write to Returns: The object that was written """ try: with open(str(file_path), 'w') as f: f.write(obj) return obj except TypeError as e: raise e
c94db2399283a26529bf4416f5b05a93fafb4e07
12,667
import json def get_json(inp_dict): """Converts a given dictionary to prettified JSON string. Parameters ---------- inp_dict: map Input dictionary to be converted to JSON. Returns ------- Prettified JSON string """ return json.dumps(inp_dict, indent=4)
9404064536a12595fe9b601363eee07b09a97bc8
12,668
import calendar def month_delta(date, months): """Add or subtract months from date.""" day = date.day # subtract one because months are not zero-based month = date.month + months - 1 year = date.year + month // 12 # now add it back month = month % 12 + 1 days_in_month = calendar.monthrange(year, month)[1] if day >= days_in_month: day = days_in_month try: return date.replace(year, month, day) except ValueError: raise OverflowError('date value out of range')
afa064af13c67be776a7f01ce48fc6ed2f33f581
12,672
def get_attribute(obj, key): """ Get an attribute from an object, regardless of whether it is a dict or an object """ if not isinstance(obj, dict): return getattr(obj, key) return obj[key]
bb20ac5809cf89b8043ff1fc60b9e4775ca95d18
12,673
from typing import List def compute_sigma_for_given_alpha(bundles:List[float],alpha:float)->float: """ This is a helper function to compute_alpha5_using_binary_search. the function computes one side of the inequality . :param bundles: valuations of the bags from B1 to Bk, were k is number of agents :param alpha: the potential alpha5- sigma is computed with it :return sigma: one side of the inequality >>> bundles=[0.74,0.75,0.50,1.02] >>> alpha = 0.92 >>> round(compute_sigma_for_given_alpha(bundles=bundles,alpha=alpha),6) 0.331522 >>> bundles=[0.74,0.75,0.72] >>> alpha = 0.9 >>> compute_sigma_for_given_alpha(bundles=bundles,alpha=alpha) 0.0 >>> bundles=[0.74,0.73] >>> alpha = 0.99 >>> round(compute_sigma_for_given_alpha(bundles=bundles,alpha=alpha),6) 0.265152 """ sum=0 count=0 for bundle in bundles: if(bundle/alpha)<0.75: count+=1 sum+=0.75-bundle/alpha return sum+(1/8)*count
08ae1c84f13de03b5404158de146b05b9efbfdce
12,681
def _makeScriptOrder(gpos): """ Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front. """ scripts = [] for scriptRecord in gpos.ScriptList.ScriptRecord: scripts.append(scriptRecord.ScriptTag) if "DFLT" in scripts: scripts.remove("DFLT") scripts.insert(0, "DFLT") return sorted(scripts)
6c67698c3d084c8e8f038e05a8d8e53811220a15
12,684
import torch from typing import Tuple from typing import List def concat_enc_outs( input: torch.LongTensor, enc_out: torch.Tensor, mask: torch.BoolTensor, embedding_size: int, padding_idx: int, ) -> Tuple[torch.Tensor, torch.BoolTensor]: """ Concatenate Encoder Outputs. Does the whole "FiD" thing; each query/document pair is independently encoded in the Encoder, so we need to concatenate all the outputs prior to sending to the decoder. :param input: [bsz, seqlen] original input to the encoder :param enc_out: [bsz * n_docs, seqlen] output representations from the encoder :param mask: encoder mask :param embedding_size: emb/hidden size of the enc representations :param padding_idx: pad token index; used for mask purposes. :return (new_out, new_mask): return the encoder output and encoder mask, appropriately concatenated. """ bsz, n_docs = input.size(0), enc_out.size(0) // input.size(0) split_enc_out = enc_out.split([n_docs] * bsz, dim=0) split_mask = mask.split([n_docs] * bsz, dim=0) concat_outs: List[torch.Tensor] = [] concat_lengths = [] for i in range(bsz): mask_i = split_mask[i].view(-1) out_i = split_enc_out[i].reshape(-1, embedding_size)[mask_i] concat_outs.append(out_i) concat_lengths.append(out_i.size(0)) new_out = enc_out.new(bsz, max(concat_lengths), embedding_size) new_mask: torch.BoolTensor = mask.new(bsz, max(concat_lengths)) # type: ignore new_out.fill_(padding_idx) new_mask.fill_(False) for i, (out_i, length_i) in enumerate(zip(concat_outs, concat_lengths)): new_out[i, :length_i] = out_i new_mask[i, :length_i] = True return new_out, new_mask
6b1794966229a8f7658afcb70a5e91a652e6b1c5
12,685
import math def poids_attirance(p, dist): """ Calcule le poids d'attraction d'une neurone vers une ville. """ d = p[0] * p[0] + p[1] * p[1] d = math.sqrt(d) d = dist / (d + dist) return d
4a997566d19dc7e436a3a1704be7b5ac74424266
12,688
def dedup(records): """Remove any identical records from the list. Args: records (list(dict)): the list of dicts to be filtered. Returns: list(dict): the list of records with any duplicates removed. The list returned contains records in the same order as the original list. """ seen = set() filtered = [] for record in records: key = tuple(sorted(record.items())) if key not in seen: seen.add(key) filtered.append(record) return filtered
f3aadddf1458a08d36331a74722e12057d8ab8f9
12,689
import inspect def is_functional_member(member): """ Check whether a class member from the __dict__ attribute is a method. This can be true in two ways: - It is literally a Python function - It is a method descriptor (wrapping a function) Args: member (object): An object in the class __dict__. Returns: bool: `True` if the member is a function (or acts like one). """ return ( inspect.isfunction(member) or ( inspect.ismethoddescriptor(member) and isinstance(member, (classmethod, staticmethod)) ) )
268068600689a7935c9a8b26aa14ca09f9679228
12,690
def convert_x1y1x2y2_to_XcYcWH(box): """ Convert box from dictionary of {"x1":,"y1":,"x2":,"y2"} to {"x_centre":,"y_centre":,"width":,"height":} Assumption 1: point 1 is the top left and point 2 is the bottom right hand corner """ assert box["x1"] <= box["x2"] assert box["y1"] <= box["y2"] width = box["x2"] - box["x1"] height = box["y2"] - box["y1"] x_centre = round(box["x1"] + width/2) y_centre = round(box["y1"] + height/2) return {"x_centre":x_centre,"y_centre":y_centre,"width":width,"height":height}
e7da7353b64b969b4c51dc7ece06729b05bad31e
12,691
def edit_distance(s1: str, s2: str) -> int: """The minimum number of edits required to make s1 equal to s2. This is also known as the Levenshtein distance. An edit is the addition, deletion, or replacement of a character. """ if not s1: return len(s2) if not s2: return len(s1) M = [[0 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)] # M[i1][i2] is the edit distance between s1[:i1] and s2[:i2]. for i1 in range(len(s1) + 1): M[i1][0] = i1 for i2 in range(len(s2) + 1): M[0][i2] = i2 for i1 in range(1, len(s1) + 1): for i2 in range(1, len(s2) + 1): cost = 0 if s1[i1 - 1] == s2[i2 - 1] else 1 M[i1][i2] = min( [ 1 + M[i1 - 1][i2], 1 + M[i1][i2 - 1], cost + M[i1 - 1][i2 - 1], ]) return M[len(s1)][len(s2)]
bd433f8b52dd9826032ced7ece0fb7df8b5ad8cc
12,697
def _remap_cortex_out(cortex_out, region, out_file): """Remap coordinates in local cortex variant calls to the original global region. """ def _remap_vcf_line(line, contig, start): parts = line.split("\t") if parts[0] == "" or parts[1] == "": return None parts[0] = contig try: parts[1] = str(int(parts[1]) + start) except ValueError: raise ValueError("Problem in {0} with \n{1}".format( cortex_out, parts)) return "\t".join(parts) def _not_filtered(line): parts = line.split("\t") return parts[6] == "PASS" contig, start, _ = region start = int(start) with open(cortex_out) as in_handle: with open(out_file, "w") as out_handle: for line in in_handle: if line.startswith("##fileDate"): pass elif line.startswith("#"): out_handle.write(line) elif _not_filtered(line): update_line = _remap_vcf_line(line, contig, start) if update_line: out_handle.write(update_line)
03357f276c6733508f17197a3300f1d55271e486
12,699
def _album_is_reviewed(album, user_key): """Check if an album has been reviewed. Args: album: An Album entity user_key: A stringified user key, or None. Returns: If user_key is None, returns True if and only if the album has any reviews at all. If user_key is not None, returns True if and only if the album has been reviewed by the specified user. """ if user_key is None or user_key == "": return len(album.reviews) > 0 for review in album.reviews: if str(review.author.key()) == user_key: return True return False
fd3b495ccdbc7a61398bc63a28fd5ab8378152f0
12,701
import sqlite3 def load_history_db(history_db): """ Load simulation history from provided db. In case no db is given, returns an empty history :param history_db: :return: """ history = {} if history_db is not None: conn = sqlite3.connect(history_db) cursor = conn.cursor() for robot_string, fitness in cursor.execute('SELECT * FROM history'): history[robot_string] = (float(fitness),) cursor.close() conn.close() return history
06055c6c48f8757513808e44d85f802ab0acd456
12,702
def upload_location(instance, filename, **kwargs): """Upload location for profile image""" return f"accounts/{instance.username}/{filename}"
c662bbb095f8180aa330a2566c9d9aaf372712b0
12,704
import collections from typing import Mapping def namedtuple(typename, field_names, default_values=()): """ Overwriting namedtuple class to use default arguments for variables not passed in at creation of object Can manually set default value for a variable; otherwise None will become default value """ T = collections.namedtuple(typename, field_names) T.__new__.__defaults__ = (None,) * len(T._fields) if isinstance(default_values, Mapping): prototype = T(**default_values) else: prototype = T(*default_values) T.__new__.__defaults__ = tuple(prototype) return T
b0fba5ba73037e7bdb5db05d10a8b96f953fc829
12,708
def length_along_path(pp, index): """ Get the lenth measured along the path up to the given index. """ index = min(index, len(pp) - 1) # beware of the end diff_squared = (pp[:index] - pp[1:index+1]) ** 2 distances = diff_squared.sum(1) return (distances ** 0.5).sum() # == sum(pp[j].distance(pp[j+1]) for j in range(index))
a7eea4b411860c51fb5f64a690a9d4832c8b98a9
12,709
def isWithin(rect1, rect2): """Checks whether rectangle 1 is within rectangle 2 Parameters: rect1: list of coordinates [minx, maxy, maxx, miny] rect2: list of coordinates [minx, maxy, maxx, miny] Returns: True if rect1 within rect2 else False """ minx1, maxy1,maxx1, miny1 = rect1 minx2, maxy2,maxx2, miny2 = rect2 if minx1 < minx2 or maxx1 > maxx2 or miny1 < miny2 or maxy1 > maxy2: return False return True
d7adca34b7cfb4294316090e18c164db0a34e818
12,714
def doolittle(matrix_a): """ Doolittle's Method for LU-factorization. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices (L,U) :rtype: tuple """ # Initialize L and U matrices matrix_u = [[0.0 for _ in range(len(matrix_a))] for _ in range(len(matrix_a))] matrix_l = [[0.0 for _ in range(len(matrix_a))] for _ in range(len(matrix_a))] # Doolittle Method for i in range(0, len(matrix_a)): for k in range(i, len(matrix_a)): # Upper triangular (U) matrix matrix_u[i][k] = float(matrix_a[i][k] - sum([matrix_l[i][j] * matrix_u[j][k] for j in range(0, i)])) # Lower triangular (L) matrix if i == k: matrix_l[i][i] = 1.0 else: matrix_l[k][i] = float(matrix_a[k][i] - sum([matrix_l[k][j] * matrix_u[j][i] for j in range(0, i)])) # Handle zero division error try: matrix_l[k][i] /= float(matrix_u[i][i]) except ZeroDivisionError: matrix_l[k][i] = 0.0 return matrix_l, matrix_u
03ba90c29dfb67ffe1edf939b49f3ab537931831
12,715
def getRequest(request): """ Get an openid request from the session, if any. """ return request.session.get('openid_request')
f6ebcb13e631365f53ae3a362eaf2dba614d7344
12,719
def flatten_df(df): """Flatten the df to an array Args: df(pd.DataFrame): a dataframe Returns: an array """ return df.values.flatten()
4faedf1059fa60c2ee3af95cd6f01e7d3cadd97e
12,723
from typing import Counter def duplicated(v): """Returns a generator expression of values within v that appear more than once """ return (x for x, y in Counter(v).items() if y > 1)
bf854dfde83c9d998f3f0b5f5553254be6347a4c
12,727
def _readonly_array_copy(x): """Return a copy of x with flag writeable set to False.""" y = x.copy() y.flags["WRITEABLE"] = False return y
ffd973bb354a642362a7382934f879c9dfa95c3b
12,728
import re def str_list_to_list_str(str_list, regex_pattern='[A-Z]\d+'): """ Turn a string of a list into a list of string tokens. Tokens determined by regex_pattern """ p = re.compile(regex_pattern) return p.findall(str_list)
99d3bbccadc0676dac6854ee717f8aef3bb878a6
12,729
def flagger(value): """ Conversion routine for flags. Accepts ints or comma-separated strings. :param str value: The value to convert. :returns: A value of an appropriate type. """ try: # Convert as an integer return int(value) except ValueError: # Convert as a comma-separated list return [v.strip() for v in value.split(',')]
cdc3fab338fd7f25499e25593302fb209f9be2a4
12,732
import time def time_func(func, kwargs): """ Time a function. Return the time it took to finish and subsequent result. """ start = time.time() res = func(**kwargs) finish = time.time() - start return finish, res
78f73058a90048f8de24915f1f8ba56bda79cc6a
12,734
def gen_end(first_instruction_address): """ Generate an end record. """ # specify the size of each column col2_size = 6 # content for each column col1 = "E" col2 = hex(first_instruction_address)[2:].zfill(col2_size).upper() return col1 + col2
d5df69b33cfb4f99aa9dbc5e003b713637fa1eff
12,738
def variantMetadata_object(processed_request): """ Builds the variantAnnotation object. Since we only have one model for this object we keep it simple. """ beacon_variant_metadata_v1_0 = { "default": { "version": "beacon-variant-metadata-v1.0", "value": { "geneId": "", "HGVSId": "", "transcriptId": "", "alleleId": "", "variantClassification": "", "variantType": "", "disease": "", "proteinChange": "", "clinVarId": "", "pubmedId": "", "timestamp": "", "info": { } } }, "alternativeSchemas": [] } return beacon_variant_metadata_v1_0
4bf6dc519fcca02ea63d0f94af55adffe29ad9f8
12,744
def find_closest_stores(friends, stores): """ Finds the closest store to each friend based on absolute distance from the store. Parameters: friends: Dictionary with friend names as keys and point location as values. stores: Dictionary with store names as keys and point locations as values. Returns: Dictionary with friends names as keys and the store closest to them as values. >>> friends1 = {'rob': 10, 'bob': 12} >>> stores1 = {'walmart': 11, 'costco': 12} >>> find_closest_stores(friends1, stores1) {'rob': 'walmart', 'bob': 'costco'} >>> friends2 = {'bob': 12} >>> stores2 = {'target': 12, 'costco': 12} >>> find_closest_stores(friends2, stores2) {'bob': 'costco'} # My doctests >>> friends3 = {'joe': 10, 'jack': 20} >>> stores3 = {'target': 5, 'walmart': 16} >>> find_closest_stores(friends3, stores3) {'joe': 'target', 'jack': 'walmart'} >>> friends4 = {'bob': 12} >>> stores4 = {'target': 12, 'costco': 12, 'apple': 12} >>> find_closest_stores(friends4, stores4) {'bob': 'apple'} >>> friends5 = {'joe': 0, 'jack': 2.5} >>> stores5 = {'target': 1.25, 'walmart': 1} >>> find_closest_stores(friends5, stores5) {'joe': 'walmart', 'jack': 'target'} """ return {names: min([(abs(distance - locations), store) \ for store, distance in stores.items()])[1] \ for names, locations in friends.items()}
ca879f6f442a4d734bf9e3c7b0313cd31ea2a026
12,748
def bash_quote(*args): """Quote the arguments appropriately so that bash will understand each argument as a single word. """ def quote_word(word): for c in word: if not (c.isalpha() or c.isdigit() or c in '@%_-+=:,./'): break else: if not word: return "''" return word return "'{0}'".format(word.replace("'", "'\"'\"'")) return ' '.join(quote_word(word) for word in args)
cb25adb60ea98cb6887e89a6a4f5097bb8f4843f
12,752
def get_area(root): """Extracts the ash cloud total area Values returned are in this order" 1. Total ash area 2. Total ash area unit""" area = root.alert.total_area.attrib.get('value') area_unit = root.alert.total_area.attrib.get('units') return area, area_unit
ea5a908e4226359aeb962f66c4ed4691d8d93a1b
12,754
def question_data_path(instance, filename): """Returns Questions data path.""" # question data will be uploaded to MEDIA_ROOT/question_<id>/<filename> return 'question_{0}/{1}'.format(instance.title.replace(" ", "_"), filename) # return 'question_{0}/{1}'.format(instance.id, filename)
dc268bb4e3ff0d00ac3bb8ba8299ce0629951487
12,757
def _compscale(data): """ Automatically computes a scaling for the wavefunctions in the plot. Args: data (dict): The data neccesarry for computing the scale factor. Needs to contain 'wfuncs' and 'energies'. Returns: scale (float): The computed scale. """ wfuncs = data['wfuncs'].T energies = data['energies'] scale = 1e6 # choose an arbitray large number for index in range(len(energies) - 1): new_scale = (energies[index + 1] - energies[index]) / ( abs(min(wfuncs[index + 1])) + max(wfuncs[index])) if new_scale < scale: scale = new_scale return scale
0c33313c86c38568a1713de28e5f5b44b2b0207c
12,758
from functools import reduce def equal(list_): """ Returns True iff all the elements in a list are equal. >>> equal([1,1,1]) True """ return reduce( lambda a, x: a and (x[0] == x[1]), zip(list_[1:], list_[:-1]), True, )
65b8a9b5652ecd6b3cc9709dd7e56b4e1258caf4
12,760
def stocking_event_dict(db): """return a dictionary representing a complete, valid upload event. This dictionary is used directly to represent a stocking event, or is modified to verify that invalid data is handled appropriately. """ event_dict = { "stock_id": None, "lake": "HU", "state_prov": "ON", "year": 2015, "month": 4, "day": 20, "site": "Barcelona", "st_site": None, "latitude": 44.5, "longitude": -81.5, "grid": "214", "stat_dist": "NC2", "species": "LAT", "strain": "SLW", "no_stocked": 18149, "year_class": 2014, "stage": "y", "agemonth": 18, "mark": "ADCWT", "mark_eff": 99.5, "tag_no": 640599, "tag_ret": 99, "length": 107.44, "weight": 563.8153159, "condition": 1, "lot_code": "LAT-SLW-13", "stock_meth": "b", "agency": "MNRF", "notes": "FIS ID = 73699", # new "hatchery": "CFCS", "agency_stock_id": "P1234", } return event_dict
bed85f03438700754d52a0d858d7a41ee5079406
12,762
async def consume_aiter(iterable): """consume an async iterable to a list""" result = [] async for item in iterable: result.append(item) return result
897c8e9380f9c631f2dd8721884ec1ccbe462d48
12,769
import ipaddress def validate_ip(ip): """ Checks if an IP address is valid for lookup. Will return False if an IP address is reserved or invalid. Resource: https://en.wikipedia.org/wiki/Reserved_IP_addresses """ try: return not ipaddress.ip_address(ip).is_private except ValueError: return False
5d10a41e6bc6d645cbef24e8e4128baaf67aa997
12,772
def add_links(self, value): """ This creates a Link header from the links Parameters ---------- self : lib.schema.riak.objects.Link The Link schema object value : dict The headers of the request to add the links to """ links = getattr(self, 'links', []) if links: value['Link'] = ', '.join( link._as_dict()['location'] for link in links) return value
3d507ce928b227399ca325d5a55cab6b5ae07791
12,777
import json def getUrnJson(data): """Returns URN to entity in JSON data""" decodedJson = json.loads(data) return decodedJson["urn:lri:property_type:id"]
af1761acb9322f295af3500cc4ecc519da16d7b1
12,781
def type_to_str(_type : type | tuple, sep : str =" or "): """ Converts type or tuple of types to string e. g. <class 'bin_types.functions.Function'> -> function For tuples will separate types with argument sep, standard sep is " or " """ if isinstance(_type, tuple): types = [] for i in _type: types.append(type_to_str(i)) return sep.join(types) if _type is None: return "none" res = str(_type) main_part = str(_type).find("'")+1 end_main_part = str(_type).rfind("'") res = res[main_part:end_main_part] res = res.split(".")[-1] # removes modules names return res.lower()
04589e24aef9db1d302b8d4d439d7d5e1ba70e49
12,782
def Imu_I0c1c2c3c4(mu, c): """ I(mu, c) where c = (I0, c1, c2, c3, c4) """ return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.))
6553deaff09f4a3e00364b271095b5e80472b3a1
12,789
def isinstance_qutip_qobj(obj): """Check if the object is a qutip Qobj. Args: obj (any): Any object for testing. Returns: Bool: True if obj is qutip Qobj """ if ( type(obj).__name__ == "Qobj" and hasattr(obj, "_data") and type(obj._data).__name__ == "fast_csr_matrix" ): return True return False
3c140e012d0df97852e84c50a37e6464e107fe2e
12,790
def get_color_specifier(basecolor, number): """Build an OpenGL color array for the number of specified vertices.""" color = [float(x) for x in basecolor] if len(color) == 3: return ("c3d", color * int(number)) elif len(color) == 4: return ("c4d", color * int(number))
b7c14272aa393c66fdedc109b90f9c8fce6118b0
12,791
def _unlParseNodePart(nodePart): """ Parse the Node part of a UNL Arguments: nodePart: The node part of a UNL Returns: unlList: List of node part parameters in root to position order. """ if not nodePart: if nodePart is None: return None else: return [''] return nodePart.split('-->')
443c7f67b5deae47448bf93ff874acfb77cb83c3
12,796
def calc_raid_partition_sectors(psize, start): """Calculates end sector and converts start and end sectors including the unit of measure, compatible with parted. :param psize: size of the raid partition :param start: start sector of the raid partion in integer format :return: start and end sector in parted compatible format, end sector as integer """ if isinstance(start, int): start_str = '%dGiB' % start else: start_str = start if psize == -1: end_str = '-1' end = '-1' else: if isinstance(start, int): end = start + psize else: # First partition case, start is sth like 2048s end = psize end_str = '%dGiB' % end return start_str, end_str, end
a96e442d5915a108fbbf18838e2c4a311677eced
12,799
def chunks(sentences, number_of_sentences): """ Split a list into N sized chunks. """ number_of_sentences = max(1, number_of_sentences) return [sentences[i:i+number_of_sentences] for i in range(0, len(sentences), number_of_sentences)]
a11c06c60e2230b611fd669a1342e17970e27ba5
12,800
import torch def pos_def(ws, alpha=0.001, eps=1e-20): """Diagonal modification. This method takes a complex Hermitian matrix represented by its upper triangular part and adds the value of its trace multiplied by alpha to the real part of its diagonal. The output will have the format: (*,2,C+P) Arguments --------- ws : tensor An input matrix. The tensor must have the following format: (*,2,C+P) alpha : float A coefficient to multiply the trace. The default value is 0.001. eps : float A small value to increase the real part of the diagonal. The default value is 1e-20. """ # Extracting data D = ws.dim() P = ws.shape[D - 1] C = int(round(((1 + 8 * P) ** 0.5 - 1) / 2)) # Finding the indices of the diagonal ids_triu = torch.triu_indices(C, C) ids_diag = torch.eq(ids_triu[0, :], ids_triu[1, :]) # Computing the trace trace = torch.sum(ws[..., 0, ids_diag], D - 2) trace = trace.view(trace.shape + (1,)) trace = trace.repeat((1,) * (D - 2) + (C,)) # Adding the trace multiplied by alpha to the diagonal ws_pf = ws.clone() ws_pf[..., 0, ids_diag] += alpha * trace + eps return ws_pf
f18cc9087d8ad0cef859b57d524b453ad11dd429
12,801
def dot_s(inputa,inputb): """Dot product for space vectors""" return inputa[:,0]*inputb[:,0] + inputa[:,1]*inputb[:,1] + inputa[:,2]*inputb[:,2]
7991192fa07b953cd2e8e3d5439769eebf0e1608
12,803
import pickle def pickle_serialize(data): """ Serialize the data into bytes using pickle Args: data: a value Returns: Returns a bytes object serialized with pickle data. """ return pickle.dumps(data)
9c8809ab7bbd0375e9d94d6baae95e26166e6c56
12,805
def strip_cstring(data: bytes) -> str: """Strip strings to the first null, and convert to ascii. The CmdSeq files appear to often have junk data in the unused sections after the null byte, where C code doesn't touch. """ if b'\0' in data: return data[:data.index(b'\0')].decode('ascii') else: return data.decode('ascii')
c315e84debe7eef239afd4c856d45f4d2a776af2
12,810
def getTitles(db): """ Gets all the books titles in the whole database :param db: database object :return: sorted books titles """ data = [] for book in db.find('books'): data.append(book['Title']) return sorted(data)
f63d2138cef4d2ad51767ad62abacce5169bb3a2
12,813
def give_coordinates(data): """ Get ground-truth coordinates (X,Y,Z, room label) where the measurement was taken, given the JSOn structure as an input. """ message = {} message['true_coordinate_x'] = data['raw_measurement'][1]['receiver_location']['coordinate_x'] message['true_coordinate_y'] = data['raw_measurement'][1]['receiver_location']['coordinate_y'] try: message['true_coordinate_z'] = data['raw_measurement'][1]['receiver_location']['coordinate_z'] except: pass try: message['true_room'] = data['raw_measurement'][1]['receiver_location']['room_label'] except: pass return message
d412afbe08d4b1660ab9a12d1e567e4c4e4258fc
12,816
def orders_by_dow(data_frame): """ Gives orders_count by day of week. :param data_frame: DataFrame containing orders data. :return: DataFrame of order_ids count by day of week. """ grouped = data_frame.groupby(['order_dow'], as_index=False) # count by column: 'order_id' count = grouped.agg({'order_id': 'count'}).rename( columns={'order_id': 'order_id_count'}) count['week_day'] = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] return count
bfca97ced614fb8c309f8edc482fc2136914759b
12,818
def is_user_logged(app): """Check for auth_tkt cookies beeing set to see if user is logged in.""" cookies = app.cookies if 'auth_tkt' in cookies and cookies['auth_tkt']: return True return False
67e670fd70787b35bc9b8d9a724512bfc4e7bac8
12,819
import re def mqtt_wildcard(topic, wildcard): """Returns True if topic matches the wildcard string. """ regex = wildcard.replace('.', r'\.').replace('#', '.*').replace('+', '[^/]*') if re.fullmatch(regex, topic): return True return False
fd7a3a5e8af1e6172decd62f2ba8294dfe07124c
12,824
def distinct_brightness(dictionary): """Given the brightness dictionary returns the dictionary that has no items with the same brightness.""" distinct, unique_values = {}, set() for char, brightness in dictionary.items(): if brightness not in unique_values: distinct[char] = brightness unique_values.add(brightness) return distinct
7f7bb5dba9bab113e15cc4f90ddd4dfda7bb5f01
12,826
import torch def norm(x): """ Normalize a tensor to a tensor with unit norm (treating first dim as batch dim) :param x: :return: """ b = x.size()[0] n = torch.norm(x.view(b, -1), p=2, dim=1) while len(n.size()) < len(x.size()): n = n.unsqueeze(1) n.expand_as(x) return x/n
b40ba939c80db85e2ac8377b21ea7a17589b1c0f
12,828
def get_unobs_nd_names(gname): """ For a graph named gname, this method returns a list of the names of its unobserved nodes (i.e., either [], or ["U"] or ["U1", "U2"]) Parameters ---------- gname : str Returns ------- list[str] """ if gname in ["G2", "G3", "G5", "G6", "G10", "G11u", "G15", "G16"]: li = ["U"] elif gname in ["G7", "G7up"]: li = ["U1", "U2"] else: li = [] return li
3450293f464b1e7cc7ab343888a606bd96d0f094
12,830
from typing import Counter def getRepeatedList(mapping_argmat, score_mat_size): """ Count the numbers in the mapping dictionary and create lists that contain repeated indices to be used for creating the repeated affinity matrix for fusing the affinity values. """ count_dict = dict(Counter(mapping_argmat)) repeat_list = [] for k in range(score_mat_size): if k in count_dict: repeat_list.append(count_dict[k]) else: repeat_list.append(0) return repeat_list
fa2449379bf8bf2051c2492d56de11c2ee0191e4
12,837
def _get_text_alignment(point1, point2): """Get the horizontal and vertical text alignment keywords for text placed at the end of a line segment from point1 to point2 args: point1 - x,y pair point2 - x,y pair returns: ha - horizontal alignment string va - vertical alignment string""" x1, x2, y1, y2 = point1[0], point2[0], point1[1], point2[1] if(x1 < x2): ha = 'left' else: ha = 'right' if(y1 < y2): va = 'bottom' else: va = 'top' return(ha, va)
317860030bf86750207bc891c236ad2618c686b1
12,839
def normalize_rectangle(rect): """Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis. Input should be of the format (x0, y0, x1, y1). (x0, y0) and (x1, y1) define the lower left and upper right corners of the rectangle, respectively.""" assert len(rect) == 4, 'Rectangles must contain 4 coordinates' x0, y0, x1, y1 = rect assert x0 < x1, 'Invalid X coordinates' assert y0 < y1, 'Invalid Y coordinates' dx = x1 - x0 dy = y1 - y0 if dx > dy: scaled = float(dx) / dy upper_x, upper_y = 1.0, scaled else: scaled = float(dx) / dy upper_x, upper_y = scaled, 1.0 assert 0 < upper_x <= 1.0, 'Calculated upper X coordinate invalid' assert 0 < upper_y <= 1.0, 'Calculated upper Y coordinate invalid' return (0, 0, upper_x, upper_y)
b1a011948adb52bb6dea068116ab3a564ab2a1f8
12,840
import inspect import warnings def valid_func_args(func, *args): """ Helper function to test that a function's parameters match the desired signature, if not then issue a deprecation warning. """ keys = inspect.signature(func).parameters.keys() if set(args) == set(keys): return True label = getattr(func, '__name__', str(func)) msg = ( f'{label}({", ".join(keys)}) is deprecated, please override ' f'with {label}({", ".join(args)})' ) warnings.warn(msg, DeprecationWarning) return False
4872817033ea55881442e69711b620b2853407f1
12,843
import shutil def binary_available() -> bool: """Returns True if the GitHub CLI binary (gh) is availabile in $PATH, otherwise returns False. """ return shutil.which("gh") is not None
e959757ccce6d162b225fd6ef986a7e248c606fa
12,845
def get_file_date_part(now, hour) -> str: """ Construct the part of the filename that contains the model run date """ if now.hour < hour: # if now (e.g. 10h00) is less than model run (e.g. 12), it means we have to look for yesterdays # model run. day = now.day - 1 else: day = now.day date = '{year}{month:02d}{day:02d}'.format( year=now.year, month=now.month, day=day) return date
42c2beddccba755f66061364463f8ad759d3c020
12,851
from pathlib import Path import tempfile def get_basetemp() -> Path: """Return base temporary directory for tests artifacts.""" tempdir = Path(tempfile.gettempdir()) / "cardano-node-tests" tempdir.mkdir(mode=0o700, exist_ok=True) return tempdir
e34ffc5cae1373977f1b46ab4b68106e1bef3313
12,852
def mutate_string(string, pos, change_to): """ Fastest way I've found to mutate a string @ 736 ns >>> mutate_string('anthony', 0, 'A') 'Anthony' :param string: :param pos: :param change_to: :return: """ string_array = list(string) string_array[pos] = change_to return ''.join(string_array)
c6119076411b57f9ded2e899d40b6b82bb5f7836
12,855
def with_last_degree(template_layers_config, degree): """ Change the degree of the last -- or actually penultimate -- layer in a layered micro-service application, while keeping the average service time for a user request constant. """ assert len(template_layers_config) >= 2 layers_config = [ layer_config for layer_config in template_layers_config] layers_config[-1] = \ layers_config[-1]._replace(average_work=layers_config[-1].average_work/degree) layers_config[-2] = \ layers_config[-2]._replace(degree=degree) return layers_config
f09bec9e27586349c679a66070bc4bac0dcba5d1
12,859
def GetErrorOutput(error, new_error=False): """Get a output line for an error in regular format.""" line = '' if error.token: line = 'Line %d, ' % error.token.line_number code = 'E:%04d' % error.code error_message = error.message if new_error: error_message = 'New Error ' + error_message return '%s%s: %s' % (line, code, error.message)
4661c74fcef9f13c0aad3d74e827d9eea20f86ef
12,861
def deunicode(s): """Returns a UTF-8 compatible string, ignoring any characters that will not convert.""" if not s: return s return str(s.decode('utf-8', 'ignore').encode('utf-8'))
baaf99acec746c266059c07e03a1ee4a7e76f46a
12,862
def constructUniformAllelicDistribution(numalleles): """Constructs a uniform distribution of N alleles in the form of a frequency list. Args: numalleles (int): Number of alleles present in the initial population. Returns: (list): Array of floats, giving the initial frequency of N alleles. """ divisor = 100.0 / numalleles frac = divisor / 100.0 distribution = [frac] * numalleles return distribution
45e834d2129586cb6ff182e1a8fe6ecb1ae582ae
12,864
def id_record(rec): """Converts a record's id to a blank node id and returns the record.""" rec['id'] = '_:f%s' % rec['id'] return rec
1ee5a9e9600299b56543c92a77cadb1826bb9bb7
12,868
def obj_ext(value): """ Returns extention of an object. e.g. For an object with name 'somecode.py' it returns 'py'. """ return value.split('.')[-1]
7ef6f1009145a0acc543130c41d2082a14412b6d
12,869
import torch def binary_hyperplane_margin(X, Y, w, b, weight=1.0): """ A potential function based on margin separation according to a (given and fixed) hyperplane: v(x,y) = max(0, 1 - y(x'w - b) ), so that V(ρ) = ∫ max(0, y(x'w - b) ) dρ(x,y) Returns 0 if all points are at least 1 away from margin. Note that y is expected to be {0,1} Needs separation hyperplane be determined by (w, b) parameters. """ Y_hat = 2*Y-1 # To map Y to {-1, 1}, required by the SVM-type margin obj we use margin = torch.relu(1-Y_hat*(torch.matmul(X, w) - b)) return weight*margin.mean()
0f038dc2ae9def9823b3f440a087ede52dcee717
12,870
def get_homologs(homologs_fname): """Extract the list of homolog structures from a list file :param homologs_fname: file name with the list of homologs :type homologs_fname: str :returns homologs_list containing the pdb codes of the homolog structures in the input file :rtype tuple """ homologs_list = [] with open(homologs_fname, 'r') as fhandle: for line in fhandle: homologs_list.append(line.rstrip()[:-2].lower()) return tuple(homologs_list)
1db108f30a3ef274cba918c5e1c056c6797a5bca
12,874
def _GetFields(trace=None): """Returns the field names to include in the help text for a component.""" del trace # Unused. return [ 'type_name', 'string_form', 'file', 'line', 'docstring', 'init_docstring', 'class_docstring', 'call_docstring', 'length', 'usage', ]
acf8a1c62853f7648082689002b3ced2689892fe
12,877
def get_valid_values(value, min_value, max_value): """Assumes value a string, min_value and max_value integers. If value is in the range returns True. Otherwise returns False.""" valid_values = [i for i in range(min_value, max_value + 1)] try: value = int(value) except ValueError: return False if value in valid_values: return True return False
4385f8328cfbe6497f7a723be37e54f0a86f9fbf
12,883