content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def fill_median(df): """Fill NaN with median.""" df = df.fillna(df.median().fillna(0).to_dict()) return df
b5ba61c19fae87c61f484c0431798abf7db5bd69
457,406
def find_tag(text, tag, start): """ Tuple `(start, end)` of `tag` in `text` starting at `start`. If `tag` is not found, `(-1, end)` is returned. """ i = text.find(tag, start) j = i + len(tag) result = (i, j) return result
8f25fb59130fab091060b0d33a06ad613686baf4
389,064
def dataframe_tptnfpfn(df, pos_label=True, labels=None): """Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2) >>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]] >>> columns=['Cat', 'Dog', 'Rabbit'] >>> x = np.array([[tc, pc] for (tc, row) in enumerate(matrix) for (pc, n) in enumerate(row) for i in range(n)]) >>> c = Confusion([(columns[i], columns[j]) for (i, j) in x], columns=['Actual', 'Predicted']) >>> c Predicted Cat Dog Rabbit Actual Cat 5 3 0 Dog 2 3 1 Rabbit 0 2 11 >>> dataframe_tptnfpfn(c, 'Rabbit') (11, 13, 1, 2) >>> dataframe_tptnfpfn(c.T, 'Rabbit') (11, 13, 2, 1) >>> c.mcc[2] 0.77901... """ labels = df.columns if labels is None else labels neg_labels = [label for label in labels if label != pos_label] tp = df[pos_label][pos_label] tn = sum(df[pred_label][true_label] for true_label in neg_labels for pred_label in neg_labels) fp = df[pos_label][neg_labels].sum() fn = sum(df[label][pos_label] for label in neg_labels) return tp, tn, fp, fn
00a1f59c7699f375c088f86825b3a29076bc1fda
576,936
def _get_metric_prefix(power: int, default: str = "") -> str: """Return the metric prefix for the power. Args: power (int): The power whose metric prefix will be returned. default (str): The default value to return if an exact match is not found. Returns: str: The metric prefix. """ metric_prefix = { 24: "Y", 21: "Z", 18: "E", 15: "P", 12: "T", 9: "G", 6: "M", 3: "k", -3: "m", -6: "μ", -9: "n", -12: "p", -15: "f", -18: "a", -21: "z", -24: "y", } return metric_prefix.get(power, default)
b35f5ff3691eafe87274a685d41f9c57161df1fb
44,060
def append_to_title(title: str, append_title: str) -> str: """ Append a title to a title avoiding duplication in title text, i.e. 'Steps Steps'. :param title: Title to append to. :param append_title: Other title to append to the title. :return: The appended title without title duplication. """ if title == append_title: return title return f'{title} {append_title}'
f661fbe8d04be9b9d6a83bbfc019fec66ec630c2
365,292
def nsecs_to_timespec(ns): """Return (s, ns) where ns is always non-negative and t = s + ns / 10e8""" # metadata record rep (and libc rep) ns = int(ns) return (ns / 10**9, ns % 10**9)
b1e8d9bf5804b9d1f59a3046ae33ebda577a197f
151,491
def fill_with_none(df, *cols): """ This function fills the NaN values with 'None' string value. """ for col in cols: df[col] = df[col].fillna('None') return df
547103126a2ebba05c9492b4edbf688dea31824e
512,039
def polynomiale(a : int, b : int, c : int, d : int, x : int) -> int: """Retourne la valeur de a*x^3 + b*x^2 + c*x + d """ return (a*x*x*x + b*x*x + c*x + d)
e54035ccb18c2257b754dcfbd77f756b464a0c76
250,237
def enforce_string(func): """ Decorator to enforce a string argument. """ def wrapper(self, *args): if type(args[0]) is not str: raise ValueError("Invalid type provided. Must be a string.") func(self, *args) return wrapper
2029596c1d4f72de040b66ec38556906206bdc01
555,605
def get_text(xml, tag): """Return the text from a given tag and XML element. """ elem = xml.find(tag) if elem is not None: return elem.text.strip()
ece7c28a98f8bf61a3d182a2109875b6a031dbaa
699,964
from typing import Optional def unflatten_dict(dict_: dict, separator: Optional[str] = ".") -> dict: """Unflattens a dictionary, reveres `flatten_dict` Args: dict_: The dictionary to unflatten separator: The sepearator that was used to flatten the dict """ result_dict = {} for key, value in dict_.items(): parts = key.split(separator) d = result_dict for part in parts[:-1]: if part not in d: d[part] = dict() d = d[part] d[parts[-1]] = value return result_dict
61e6288c2b22535cfad438bbb3cfa241676a51a4
265,185
from typing import Any import json def loads(data: str, **kwargs: Any) -> Any: """ Alias for `json.loads`. Arguments: data -- A string with valid JSON. kwargs -- List of additional parameters to pass to `json.loads`. Returns: An object created from JSON data. """ return json.loads(data, **kwargs)
ab1c081c630cf339d3a2674258d77b12bc2578f7
66,301
def almost_zero(x, atol: float = 1e-6): """ Returns true if `x` is within a given tolerance parameter """ return abs(x) < atol
44d869c4c47415371784eca4073bb0a2c4033eb3
152,722
def is_space_free(board, move): """Return true if the passed move is free on the passed board.""" return board[move] == ' '
5d2ebdc6747237448989bf6abf215b2c53c570d2
683,160
def masked_average(tensor, mask): """ Performs masked average of a given tensor at time dim. """ tensor_sum = (tensor * mask.float().unsqueeze(-1)).sum(1) tensor_mean = tensor_sum / mask.sum(-1).float().unsqueeze(-1) return tensor_mean
820d2ac679afba3a13841943afae050a22f7e354
253,988
def check_version_2(dataset): """Checks if json-stat version attribute exists and is equal or greater \ than 2.0 for a given dataset. Args: dataset (OrderedDict): data in JSON-stat format, previously \ deserialized to a python object by \ json.load() or json.loads(), Returns: bool: True if version exists and is equal or greater than 2.0, \ False otherwise. For datasets without the version attribute, \ always return False. """ if float(dataset.get('version')) >= 2.0 \ if dataset.get('version') else False: return True else: return False
bfc86b4d16750379a6ad9325f13ac267c0f414a3
641,350
import time def timer(function): """Print the duration of a function making use of decorators.""" def function_(*args,**kwargs): """Tested function.""" ti=time.time() result=function(*args,**kwargs) tf=time.time() dt=tf-ti print("[TIMER]: "+str(function.__name__)+" took "+str(dt)+" seconds.") return result return function_
93ab39c5760c73c535c44ac6d0c33d80f731af87
312,574
def aumentar(n, p): """ Somar porcentagem :param n: número a ser somado :param p: porcentagem a ser somada :return: resultado """ n = float(n) resultado = n + (n * p / 100) return resultado
80267aa21e9498696b490227c7f6a735a4b8c6b1
291,138
def Factorial(number:int): """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if not isinstance(number, int): raise ValueError("factorial() only accepts integral values") if number < 0: raise ValueError("factorial() not defined for negative values") return 1 if number == 0 or number == 1 else number * Factorial(number - 1)
bd2580a86b465ad7205ecb1a4dfacde94bb301a5
471,897
def get_geometry(dataset): """ Extract and return geometry coordinates as a list in a dictionary: returns { 'geometry': { 'type' : 'Polygon', 'coordinates': [...] } } or empty dictionary """ valid_data = dataset._gs.get('valid_data') return {'geometry': valid_data} if valid_data else dict()
5c149eaf29c99bf699e9014f60d00c039d6c6792
565,894
def get_backend_bucket_outputs(res_name, backend_name): """ Creates outputs for the backend bucket. """ outputs = [ { 'name': 'name', 'value': backend_name }, { 'name': 'selfLink', 'value': '$(ref.{0}.selfLink)'.format(res_name) } ] return outputs
45fd59e7e9c5bb4a13e05ea45283338bee125843
91,343
def generate_absolute_parameter(parameter_values): """Generate parameters list for absolute parameter type.""" return parameter_values
0d9d587f17e5ef7d2f3c89a3ae03bf7eafb9ae78
606,626
def makecard (name, front, back): """ Convert captured data for a flashcard into a dictionary Helper for md2json() function, which converts flashcard entries from Markdown to JSON. We allow several different ways to enter the flashcard entries in Markdown, and this function handles identifying those cases and putting the proper values into a dictionary Parameters ---------- name : string The name for the flashcard front : string The first string found after the name but before the "---" break. Usually the front of the flashcard back: string The string after the "---" break, which is usually the back of the flashcard Returns ------- dict A dictionary with the input strings matched to the proper 'name', 'front', and 'back' keys """ # Deal with options if front and not back: back=front front=name elif back and not front: front=name card = {'name':name, 'front':front, 'back':back} return card
f97c166bcea00ee46eed134284e65538fb160b3a
190,661
def hsv_to_rgb(h, s, v): """Convert HSV values RGB. See https://stackoverflow.com/a/26856771. :param h: Hue component of the color to convert. :param s: Saturation component of the color to convert. :param v: Value component of the color to convert. :rtype: tuple """ if s == 0.0: v *= 255 return (v, v, v) i = int(h * 6.0) # XXX assume int() truncates! f = (h * 6.0) - i p, q, t = ( int(255 * (v * (1.0 - s))), int(255 * (v * (1.0 - s * f))), int(255 * (v * (1.0 - s * (1.0 - f)))), ) v *= 255 i %= 6 if i == 0: return (v, t, p) if i == 1: return (q, v, p) if i == 2: return (p, v, t) if i == 3: return (p, q, v) if i == 4: return (t, p, v) if i == 5: return (v, p, q)
0b74f5ccbff722a139bea316c41f644aa2d7a36d
651,468
def _parse_logline_timestamp(t): """Parses a logline timestamp into a tuple. Args: t: Timestamp in logline format. Returns: An iterable of date and time elements in the order of month, day, hour, minute, second, microsecond. """ date, time = t.split(' ') month, day = date.split('-') h, m, s = time.split(':') s, ms = s.split('.') return (month, day, h, m, s, ms)
9b0ea2f6cfe4edef89eec6dbbddbdd258640c210
692,957
def response(status, data=''): """ Returns dictionary which is the response for the request. The dictionary contains 2 keys: status and data. """ d = {} d['status'] = status d['data'] = data return d
207724cc64e2092fa1b65aafaf369ce9a8133d1d
196,527
def distance_score(pos1: list, pos2: list, scene_x_scale: float, scene_y_scale: float): """ Calculate distance score between two points using scene relative scale. :param pos1: First point. :param pos2: Second point. :param scene_x_scale: X scene scale. :param scene_y_scale: Y scene scale. :return: Distance score. """ # Calculate distances dif_x = abs(pos1[0] - pos2[0]) dif_y = abs(pos1[1] - pos2[1]) # Calculate relative distances scale_x = dif_x / scene_x_scale scale_y = dif_y / scene_y_scale return 1 - (0.5 * scale_x + 0.5 * scale_y)
aa5b13f4aba6d8b9831d794d8d377610c5508896
493,172
def delete_zero_amount_exchanges(data, drop_types=None): """Drop all zero value exchanges from a list of datasets. ``drop_types`` is an optional list of strings, giving the type of exchanges to drop; default is to drop all types. Returns the modified data.""" if drop_types: dont_delete = lambda x: x["type"] not in drop_types or x["amount"] else: dont_delete = lambda x: x["amount"] for ds in data: ds["exchanges"] = list(filter(dont_delete, ds["exchanges"])) return data
8e9c214826398959b74e7bffc1e41ea635172d0a
692,439
import traceback def get_plot_frame(map_obj, key_map, cached=False): """ Returns an item in a HoloMap or DynamicMap given a mapping key dimensions and their values. """ if map_obj.kdims and len(map_obj.kdims) == 1 and map_obj.kdims[0] == 'Frame': # Special handling for static plots return map_obj.last key = tuple(key_map[kd.name] for kd in map_obj.kdims) if key in map_obj.data and cached: return map_obj.data[key] else: try: return map_obj[key] except KeyError: return None except StopIteration as e: raise e except Exception: print(traceback.format_exc()) return None
8746d78ac462d19d92b2d89bffdea0fe85c30a1d
436,090
def _get_slice_len(idx): """ Get the number of elements in a slice. Parameters ---------- idx : np.ndarray A (3,) shaped array containing start, stop, step Returns ------- n : int The length of the slice. Examples -------- >>> idx = np.array([5, 15, 5]) >>> _get_slice_len(idx) 2 """ start, stop, step = idx[0], idx[1], idx[2] if step > 0: return (stop - start + step - 1) // step else: return (start - stop - step - 1) // (-step)
39ab973ba9c6d41a6bab9478df1f3e0dd0f8888d
496,666
def _ConditionHelpText(intro): """Get the help text for --condition.""" help_text = """ {intro} *expression*::: (Required) Expression of the condition which evaluates to True or False. This uses a subset of Common Expression Language syntax. *title*::: (Required) Title for the expression, i.e. a short string describing its purpose. *description*::: (Optional) Description for the expression. This is a longer text which describes the expression. NOTE: An unsatisfied condition will not allow access via this binding.""".format(intro=intro) return help_text
3899206fc5bb60c6dec9bc0fc58dcce80cb0799b
653,663
def word_list_to_string(word_list, delimeter=" "): """Convert a list of words to a sentence. """ string = "" for word in word_list: string+=word+delimeter nchar = len(string) return str(string[0:nchar-1])
46a532a96429c61098fae12ac8995306cda9c586
418,215
def xml_get_attrs(xml_element, attrs): """Returns the list of necessary attributes Parameters: element: xml element attrs: tuple of attributes Returns: a dictionary of elements """ result = {} for attr in attrs: result[attr] = xml_element.getAttribute(attr) return result
77911646f3624dc089475927a8b1e14abd9caef7
628,315
def extract_unique_words(list_of_tup): """ :param list_of_tup: list of tuples :return: The unique words from all the reviews """ unique_wrs = set() for review in list_of_tup: for pair in review: unique_wrs.add(pair[0]) return sorted(list(unique_wrs))
5c5266fa964e5c961d30cbbf939fe5787feca393
362,138
from copy import deepcopy def get_nn(seqdict, positions, nn, base): """ Returns nn nearest neigbour bases on either side of the imput positions (i.e. a 2nn+1 mer) Parameters ---------- seqdict : dictionary in the format returned by seq_dict() positions : list containing positions in the format id_position or chr_position nn : int - number of nearest neighbours base : either a string (enter single base) or None Replaces the middle position of the kmer with the base indicated in base and adds it in addition to identical kmer Returns ------- nmers : list of nmer strings """ nmers = [] for pos in positions: loc = pos.split("_") join = deepcopy(loc) del join[-1] join = "_".join(join) seq = seqdict[join] if ((int(loc[-1]) - (nn + 1)) < 0) or ((int(loc[-1]) + nn) > len(seq)): print("skipped site {}".format(loc[-1])) # edge of sequence no neighbours continue nmer = seq[(int(loc[-1]) - (nn + 1)) : (int(loc[-1]) + nn)] nmers.append(nmer) if base != None: nmer_baseswitch = list(nmer) nmer_baseswitch[nn] = str(base) nmer_baseswitch = "".join(nmer_baseswitch) nmers.append(nmer_baseswitch) return nmers
f70167791eedfd565d79b969404bc462c0d6a52d
604,760
import json def get_threshold(filename, current_threshold, service, version): """ Get the threshold score :param filename: String, File that containes the best score. Ie, './path/file.py' :param current_threshold: Float, the latest score. Ie, 6.78 :param service: String, Service to evaluate. Ie, 'originationservice' :param version: String, Python version to test. Ie, 'python_3' :return: Float, The last score to evaluate. Ie, 7.89 """ try: with open(filename) as f: file_data = f.read() file_object = json.loads(file_data) except: file_object = {} try: threshold = file_object[version][service] except: threshold = current_threshold return file_object, threshold
b090368303dd6705f8bad41416a7f31d422d5153
474,077
import torch def invsoftplus(x): """Inverse of torch.nn.functional.softplus""" bound = 20.0 xa = torch.clamp(x, None, bound) res = torch.log(torch.exp(xa)-1.0)*(xa < bound) + xa*(xa >= bound) return res
d29379fcb4b371c5689117a4ba6ac8dc58ea690f
205,899
from bs4 import BeautifulSoup def strip_html(string: str): """ Use BeautifulSoup to strip out any HTML tags from strings. """ return BeautifulSoup(string, "html.parser").get_text()
796fc52ddd303906c7fd217275cb2a897e76767c
695,836
import re def extract_positivie_integer_value(text, key): """ Extract an integer value for a given key in a text Args: text (str): text to extract value from key (str): key to extract value for Raises: ValueError: value is not a positive integer Returns: int: extraced value """ found = re.search(fr'{key}=\d+', text) if not found: return None value = found.group(0).split('=')[1] try: integer_value = int(value) if integer_value < 0: raise ValueError() except ValueError: raise ValueError( f'"{key}=" must be followed by a positive integer in text') return integer_value
43257254883a343afbe27a5ee0dd814eaf9ddc3d
362,692
def pytest_report_header(config): """ return a string in test report header """ return "Hey this are the tests"
e64bf912f78e8524d99126569d0423c821158498
695,314
from typing import Any def clean(data: Any) -> Any: """Recursively cleans a `dict` or a `list` from 'None' values.""" if isinstance(data, list): return [x for x in map(clean, data) if x is not None] if isinstance(data, dict): result = {key: clean(value) for key, value in data.items()} result = {key: value for key, value in result.items() if value is not None} return result return data
5e98b2d83f3686a0e8beeb53165743d8e80713ce
143,119
def remove_sublists(lst): """ Returns a list where all sublists are removed :param lst: list :return: list >>> remove_sublists([[1, 2, 3], [1, 2]]) [[1, 2, 3]] >>> remove_sublists([[1, 2, 3], [1]]) [[1, 2, 3]] >>> remove_sublists([[1, 2, 3], [1, 2], [1]]) [[1, 2, 3]] >>> remove_sublists([[1, 2, 3], [2, 3, 4], [2, 3], [3, 4]]) [[1, 2, 3], [2, 3, 4]] """ curr_res = [] result = [] for elem in sorted(map(set, lst), key=len, reverse=True): if not any(elem <= req for req in curr_res): curr_res.append(elem) r = list(elem) result.append(r) return result
f41bb66a70dc15825ce4a57b41b0f326bde4fb84
68,419
import gzip import shutil def compress_gzip(file_path: str, out_path: str) -> str: """Compress a file into gzip. Args: file_path: Path to file out_dir: Path to compressed file Returns: Path to compressed file """ with open(file_path, 'rb') as f, gzip.open(out_path, 'wb') as out: shutil.copyfileobj(f, out) return out_path
10158a91dcd39411944f4f8a135e9114243b7cd7
307,495
from typing import List def drop_lowest(grades: List[float]) -> List[float]: """Drops the lowest number and returns the pruned collection Args: grades (List[float]): An array of number grades Returns: List[float]: The pruned list of grades """ new_grades = grades.copy() new_grades.remove(min(new_grades)) print(new_grades) return new_grades
950907b0cad3fa65d9b9c062dac1eb60f3a371c0
313,516
from typing import Dict def _parse_schemata_file_row(line: str) -> Dict[str, str]: """Parse RDTAllocation.l3 and RDTAllocation.mb strings based on https://github.com/torvalds/linux/blob/9cf6b756cdf2cd38b8b0dac2567f7c6daf5e79d5/arch/x86/kernel/cpu/resctrl/ctrlmondata.c#L254 and return dict mapping and domain id to its configuration (value). Resource type (e.g. mb, l3) is dropped. Eg. mb:1=20;2=50 returns {'1':'20', '2':'50'} mb:xxx=20mbs;2=50b returns {'1':'20mbs', '2':'50b'} raises ValueError exception for inproper format or conflicting domains ids. """ RESOURCE_ID_SEPARATOR = ':' DOMAIN_ID_SEPARATOR = ';' VALUE_SEPARATOR = '=' domains = {} # Ignore emtpy line. if not line: return {} # Drop resource identifier prefix like ("mb:") line = line[line.find(RESOURCE_ID_SEPARATOR) + 1:] # Domains domains_with_values = line.split(DOMAIN_ID_SEPARATOR) for domain_with_value in domains_with_values: if not domain_with_value: raise ValueError('domain cannot be empty') if VALUE_SEPARATOR not in domain_with_value: raise ValueError('Value separator is missing "="!') separator_position = domain_with_value.find(VALUE_SEPARATOR) domain_id = domain_with_value[:separator_position] if not domain_id: raise ValueError('domain_id cannot be empty!') value = domain_with_value[separator_position + 1:] if not value: raise ValueError('value cannot be empty!') if domain_id in domains: raise ValueError('Conflicting domain id found!') domains[domain_id] = value return domains
359672902330e30c8b188f6565b4242f8730ecea
60,053
def capitalized(piece_name: str) -> str: """Returns a capitalized version of a piece name Args: piece_name: Piece name Returns: Capitalized version """ return '%s%s' % (piece_name[0].upper(), piece_name[1:].lower())
98838f820e90f6b1540f537ed878324d02aefb87
73,579
def write_to_text_file(file_path, file_contents): """ Writes the given file_contents to the file_path in text format if current user's permissions grants to do so. :param file_path: Absolute path for the file :param file_contents: List<str> List of lines :return: void :rtype: void :raises: This method raises OSError if it cannot write to file_path. """ with open(file_path, mode='w', encoding='utf-8') as handler: for line in file_contents: handler.write("%s\n" % line) return file_path
5390092f05c1a449567ae701c2ca08b0ef4405c6
77,457
def list_(client, name=None, file_=None, dim_type=None, encoded=None, select=False): """Get a list of dimensions from a model. If select is true, then the current selection in Creo will be cleared even if no items are found. Args: client (obj): creopyson Client. name (str|list:str, optional): Dimension name; if empty then all dimensions are listed. `file_` (str, optional): Model name. Defaults is current active model. dim_type (str, optional): Dimension type filter. Defaults is `no filter`. Valid values: linear, radial, diameter, angular. encoded (boolean, optional): Whether to return the values Base64-encoded. Defaults is False. select (boolean, optional): If true, the dimensions that are found will be selected in Creo. Defaults is False. Returns: (list:dict): List of dimension information. name (str): Dimension name value (str|float): Dimension value; if encoded is True it is a str, if encoded is False it is a float. encoded (boolean): Whether the returned value is Base64-encoded. dwg_dim (boolean): Whether dimension is a drawing dimension rather than a model dimension. """ data = {} if file_ is not None: data["file"] = file_ else: active_file = client.file_get_active() if active_file: data["file"] = active_file["file"] if name is not None: if isinstance(name, (str)): data["name"] = name elif isinstance(name, (list)): data["names"] = name if dim_type is not None: data["dim_type"] = dim_type if encoded is not None: data["encoded"] = encoded if select is not None: data["select"] = select return client._creoson_post("dimension", "list", data, "dimlist")
7f15f89fe91ca1dbeddd03fdd011db8bedb1ad6f
287,154
def _get_QSlider(self): """ Get current value for QSlider """ return self.value()
9badb4a2ecbc93016f07f720f1d99431732fc6e7
143,193
def lcs(X, Y): """ Function for finding the longest common subsequence between two lists. In this script, this function is particular used for aligning between the ground-truth output string and the predicted string (for visualization purpose). Args: X: a list Y: a list Returns: a list which is the longest common subsequence between X and Y """ m, n = len(X), len(Y) L = [[0 for x in range(n + 1)] for x in range(m + 1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # Following code is used to print LCS index = L[m][n] # Create a character array to store the lcs string lcs = [''] * (index + 1) lcs[index] = '' # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] i = m j = n while i > 0 and j > 0: # If current character in X[] and Y are same, then # current character is part of LCS if X[i - 1] == Y[j - 1]: lcs[index - 1] = X[i - 1] i -= 1 j -= 1 index -= 1 # If not same, then find the larger of two and # go in the direction of larger value elif L[i - 1][j] > L[i][j - 1]: i -= 1 else: j -= 1 return lcs[:-1]
336040927b84f0e64d5682896fa4bd9cc18eaddf
540,038
import csv def load_data(path_to_csv, num_samples=None): """ Read the csv file given and return the path to images and steering angles """ image_path = [] steering_angle = [] with open(path_to_csv, "r", newline='') as f: recorded_data = csv.reader(f, delimiter=',', quotechar='|') for line in recorded_data: image_path.append(line[0]) steering_angle.append(float(line[1])) if num_samples is not None: image_path = image_path[:num_samples] steering_angle = steering_angle[:num_samples] return image_path, steering_angle
be02b6f02a01293b59de8a8acf63f676a64ac558
627,815
def restriction(d, keys): """Return the dictionary that is the subdictionary of d over the specified keys""" return {key: d.get(key) for key in keys}
9fdb2d2e5bea0d96380e592ffc6d7720b32ade30
693,979
def dms_to_degrees(v): """Convert degree/minute/second to decimal degrees.""" d = float(v[0][0]) / float(v[0][1]) m = float(v[1][0]) / float(v[1][1]) s = float(v[2][0]) / float(v[2][1]) return d + (m / 60.0) + (s / 3600.0)
163dc1a23c8f0e913d5a505c7cba58f3b2b72bb7
187,429
def convert_timedelta(duration): """ Summary: Convert duration into component time units Args: :duration (datetime.timedelta): time duration to convert Returns: days, hours, minutes, seconds | TYPE: tuple (integers) """ days, seconds = duration.days, duration.seconds hours = seconds // 3600 minutes = (seconds % 3600) // 60 seconds = (seconds % 60) return days, hours, minutes, seconds
4a0a0b89608e895963df2ec5e890db7a1ae313c9
571,056
def remove_useless_features(training_data): """Create features and targets Args: training_data (list): List of Dataframe containing data from each file. Returns: dict : Dictionary containing features and target for each file. """ data_dict = {} for key, data in training_data.items(): features = data.drop(columns=["_ID"]) data_dict[key] = features return data_dict
92ee3957bd8ccadd14bfd87a5f51818b63ba6462
273,258
import string import random def randstr(n=8): """ randstr creates a random string of numbers and upper/lowercase characters. >>> randstr() "0YH58H9E" >>> randstr(5) "0ds34" This code is slighty modified version of http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python """ chars = string.ascii_uppercase + string.digits return ''.join(random.choice(chars) for _ in range(n))
493dade04e2fe4c39323dbf404abb0ee1e062e0f
470,186
import yaml def yaml_load(path): """Returns content of YAML file at `path` as a Python object.""" with open(path, 'r', encoding='utf-8') as f: data_yaml = yaml.load(f, Loader=yaml.FullLoader) return data_yaml
abf0e4501c3963cf86ee2e83ba8b91c9410b7fbb
573,297
def contains_filepath(filepath1, filepath2): """ contains_filepath checks if file1 is contained in filepath of file2 """ return filepath2.startswith(filepath1)
4b6d7da1da171dadd41d6b4e24d8311d8b8d5f0b
484,414
def combine_dicts(seq): """Combine a list of dictionaries into single one.""" ret = {} for item in seq: ret.update(item) return ret
4d49e6fb1eec8cb3042a39a018da6f3bb9e3463b
117,541
import re def get_pagetext_mkiconf(pagetext): """Return the mkiconf vars found on most dashboard pages. These variables are largely the same as administered orgs, but could be useful elsewhere. Keeping this here is in case I could use this of scraping method later. Check the regex below for the expected string. The format will look like this: Mkiconf.action_name = "new_wired_status"; Mkiconf.log_errors = false; Mkiconf.eng_log_enabled = false; Mkiconf.on_mobile_device = false; Essentially Mkiconf.<property> = <JSON>; Args: pagetext (string): Text of a webpage Returns: (dict) All available Mkiconf vars. """ mki_lines = re.findall(' Mkiconf[!-:<-~]* =[ -:<-~]*;', pagetext) mki_dict = {} for line in mki_lines: mki_string = \ re.findall(r'[0-9a-zA-Z_\[\]\"]+\s*=\s[ -:<-~]*;', line)[0] # mki_key = <property>, mki_value = <JSON> mki_key, mki_value = mki_string.split(' = ', 1) if mki_value[-1] == ';': # remove trailing ; mki_value = mki_value[:-1] # If the value is double quoted, remove both "s if mki_value[0] == '"' and mki_value[-1] == '"': mki_value = mki_value[1:-1] mki_dict[mki_key] = mki_value return mki_dict
985e7305c9d84f60c1fb6e3e36ad827d542b8ec0
416,774
def bigquery_serialize_date(py_date): """ Convert a python date object into a serialized format that Bigquery accepts. Accurate to days. Bigguery format: 'YYYY-[M]M-[D]D' https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types Args: py_date (datetime.date): The date to convert. Returns: (str): The Serialized date. """ return py_date.strftime('%Y-%m-%d')
b730fdfe6696011601d466ad65010b5b566749e7
695,286
import logging import pkgutil import importlib def get_modules_by_name_prefix(prefix): """Get modules whose name starts with the prefix. :param prefix: a prefix used to select modules to be returned. :returns: a map of the modules to their names, with the prefix stripped. """ logger = logging.getLogger(__name__) name_module_map = {} for _, module_name, _ in pkgutil.iter_modules(): if not module_name.startswith(prefix): continue try: module = importlib.import_module(module_name) name_module_map[module_name[len(prefix):]] = module logger.info('Successfully imported "%s" module.', module_name) except ImportError: logger.exception( 'A module "%s" was found, but couldn\'t be imported', module_name ) return name_module_map
5f82f5dbae72381ce26311443137939df77bbe6b
537,474
def _paths_for_iter(diff, iter_type): """ Get the set for all the files in the given diff for the specified type. :param diff: git diff to query. :param iter_type: Iter type ['M', 'A', 'R', 'D']. :return: set of changed files. """ a_path_changes = {change.a_path for change in diff.iter_change_type(iter_type)} b_path_changes = {change.b_path for change in diff.iter_change_type(iter_type)} return a_path_changes.union(b_path_changes)
fe828c21277c1051aebc4c125b53228ab9c7cc12
645,380
from typing import Tuple def convert_hex_to_rgb(hx: str) -> Tuple[int, ...]: """ Takes a string with format "#FFFFFF" and converts the value into a proper hexadecimal value, usable for images. Parameters ---------- hx: str The hexadecimal value. Returns ------- Tuple[int, ...] A tuple of three integers corresponding respectively to the Red-Green-Blue (RGB) values. """ # Removes the "#" from the hexadecimal value. h = hx.lstrip('#') return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
023312b4115a98fffbb5ead2c8da7dc5b57d622d
356,068
def isreadable(f): """ Returns True if the file-like object can be read from. This is a common- sense approximation of io.IOBase.readable. """ if hasattr(f, 'readable'): return f.readable() if hasattr(f, 'closed') and f.closed: # This mimics the behavior of io.IOBase.readable raise ValueError('I/O operation on closed file') if not hasattr(f, 'read'): return False if hasattr(f, 'mode') and not any(c in f.mode for c in 'r+'): return False # Not closed, has a 'read()' method, and either has no known mode or a # readable mode--should be good enough to assume 'readable' return True
04530ed6bc40c19b22c0f3d694cb0418202e2949
670,306
def _get_equality(analysis_1: dict, analysis_2: dict) -> dict: """Compares the two input dictionaries and generates a new dictionary, representing the equality between the two. Args: analysis_1(dict): Eg: {'rs10144418': ['T', 'C'], 'rs1037256': ['G', 'A'],... } analysis_2(dict): Eg: {'rs10144418': ['A', 'C'], 'rs1037256': ['G', 'A'],... } Returns: compare_dict(dict): Eg: {'rs10144418': False, 'rs1037256': True,... } """ compare_dict = {} for snp in set(list(analysis_1.keys()) + list(analysis_2.keys())): if set(analysis_1.get(snp, [])) == set(analysis_2.get(snp, [])): compare_dict[snp] = True else: compare_dict[snp] = False return compare_dict
94859d1eb03bdfc656ab8fb70ce6eb4cabe89e35
608,461
def has_urn_and_labels(mi, urn, labels): """Returns true if it the monitoring_info contains the labels and urn.""" def contains_labels(mi, labels): # Check all the labels and their values exist in the monitoring_info return all(item in mi.labels.items() for item in labels.items()) return contains_labels(mi, labels) and mi.urn == urn
7dcfccfb148590c091c45a6af846bcc2d4072472
247,660
def getClientIP(request): """ Pull the requested client IP address from the X-Forwarded-For request header. If there is more than one IP address in the value, it will return the first one. For more info, see: 'def access_route' in https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/wrappers.py :param request: :return str: The client IP address, or none if neither the X-Forwarded-For header, nor REMOTE_ADDR are present in the environment. """ if request.access_route > 0: ip = request.access_route[0] else: ip = None return ip
4ed0d2693e805aab782a304dd0ab9a62bc1f91d4
60,242
def getSeqRegions(seqs, header, coordinates): """From sequence dictionary return spliced coordinates. Takes a sequence dictionary (ie from fasta2dict), the contig name (header) and the coordinates to fetch (list of tuples) Parameters ---------- seqs : dict dictionary of sequences keyed by contig name/ header header : str contig name (header) for sequence in seqs dictionary coordinates : list of tuples list of tuples of sequence coordinates to return [(1,10), (20,30)] Returns ------- result : str returns spliced DNA sequence """ # takes SeqRecord dictionary or Index, returns sequence string # coordinates is a list of tuples [(1,10), (20,30)] result = "" sorted_coordinates = sorted(coordinates, key=lambda tup: tup[0]) for x in sorted_coordinates: result += seqs[header][x[0] - 1 : x[1]] return result
2881c9cef621be24e77943b8d527c380499befff
97,038
def xor(a: bool, b: bool) -> bool: """Exclusive or (XOR)""" return a ^ b
bcb1db14eee93f10fe75c7eb918be0a3f4ee48c3
144,668
def _replace_in_single_or_double_quotes(val, from_, to): """Replace a value in a string enclosed in single or double quotes.""" return val.replace(f"'{from_}'", f"{to}").replace(f'"{from_}"', f"{to}")
5f1dfa6fae4ac6c669c8d27c749b26c822dbe0f3
430,761
from pathlib import Path from typing import List def get_files( d: Path, pattern: str, sort_lexicographical: bool = False, sort_numerical: bool = False, ) -> List[Path]: """Return a list of files in a given directory. Args: d: The path to the directory. pattern: The wildcard to filter files with. sort_lexicographical: Lexicographical sort. sort_numerical: Numerical sort. """ files = d.glob(pattern) if sort_lexicographical: return sorted(files, key=lambda x: x.stem) if sort_numerical: return sorted(files, key=lambda x: int(x.stem)) return list(files)
b9639e43c36ae132905a7154b1cfdb3b556c6e24
519,624
import torch import math def angle_normalize(angle: torch.Tensor) -> torch.Tensor: """ Normalize the `angle` to have a value in [-pi, pi] Args: angle: Tensor of angles of shape N """ TWO_PI = 2 * math.pi angle = torch.fmod(torch.fmod(angle, TWO_PI) + TWO_PI, TWO_PI) return torch.where(angle > math.pi, angle - TWO_PI, angle)
1ad2f5e99fde42d92fe6ba3a06d08650e5a84132
301,742
def mod_Goodman_Fos(sa, sm, Se, Sut): """ Computes the mod Goodman relation factor of safety :param sa: alternating stress :param sm: midrange stress :param Se: Endurance strength :param Sut: Ultimate tensile strength :return: factor of safety """ n_inv = sa/Se + sm / Sut return 1/n_inv
b98e8335929a8ef40569f25fd46dc7035090a20a
627,871
from typing import List from pathlib import Path import re def extracted_urls() -> List[str]: """ README.mdからURLを抽出する。 Returns ------- List[str] README.mdに含まれるURLのリスト。重複は除かれている。 """ file_path = Path(__file__).parents[1] / 'README.md' with open(file_path, mode='rt', encoding='utf-8') as f: readme = f.read() urls = re.findall(r'https?://[\w/:%#$&?~.=+-]+', readme) return list(set(urls))
0faf486395a3c0d6474977766f84561686b6fb7b
187,636
def get_sub_row_by(rows, **conditions): """Returns a table row that matches conditions.""" for table_row in rows(): if table_row.matches_conditions(**conditions): return table_row return None
b5c24f37bdd319b3f2c94a17bc0ee1b0ecddfc15
539,920
def is_templated_secret(secret: str) -> bool: """ Filters secrets that are shaped like: {secret}, <secret>, or ${secret}. """ try: if ( (secret[0] == '{' and secret[-1] == '}') or (secret[0] == '<' and secret[-1] == '>') or (secret[0] == '$' and secret[1] == '{' and secret[-1] == '}') ): return True except IndexError: # Any one character secret (that causes this to raise an IndexError) is highly # likely to be a false positive (or if a true positive, INCREDIBLY weak password). return True return False
4fa6c95bdfbb884b4452d57fea381c16665412ad
450,936
def pos_pow(z,k): """z^k if k is positive, else 0.0""" if k>=0: return z**k else: return 0.0
ba0a46e8711005b9ac0dbd603f600dfaa67fbdd4
18,713
def transpose(matrix): """Transpose a list of lists.""" return [list(t) for t in zip(*matrix)]
d584d6a8341488f5af7a2e217310ead17a5bbf37
545,573
from typing import Dict from typing import Any from warnings import warn def has_license_and_update(data: Dict[str, Any]) -> bool: """Check if license header exists anywhere in notebook and format. Args: data: object representing a parsed JSON notebook. Returns: Boolean: True if notebook contains the license header, False if it doesn't. """ has_license = False license_header = "#@title Licensed under the Apache License" for idx, cell in enumerate(data["cells"]): src_text = "".join(cell["source"]) if license_header in src_text: has_license = True # Hide code pane from license form metadata = cell.get("metadata", {}) metadata["cellView"] = "form" data["cells"][idx]["metadata"] = metadata if not has_license: warn(f"Missing license: {license_header}") return has_license
67f3f6d7b9f31961f138824482926dcf529f5409
633,670
def format_zone_df(df, name): """copies df, checks if it contains invalid geometry and adds col for zone area :param geopandas.geodataframe.GeoDataFrame df: GeoDataFrame where index = zone names, columns = ['geometry'] :param str name: the name of the data set :return: (*geopandas.geodataframe.GeoDataFrame*) -- the formatted df :raises ValueError: if the zone set contains invalid geometry """ # Check for invalid geometries invalid_geom = df.loc[~df.geometry.is_valid].index.tolist() if len(invalid_geom) > 0: raise ValueError(f"{name} contains invalid geometries: {invalid_geom}") df_copy = df.copy() df_copy.index.name = name df_copy = df_copy.reset_index() # change coordinate reference system to Pseudo-Mercator to get more accurate area df_copy = df_copy.to_crs("EPSG:3857") # get zone area df_copy[f"{name}_area"] = df_copy["geometry"].area return df_copy
d71fc4a678b18c6524f58cfafb7396eec9bde61d
313,350
import json def loader(filename): """ Load translation from file and return a dictionary with info. :param filename: filename info :type filename: str :return: dict object. :rtype: dict :raises: TypeError, ValueError """ if not isinstance(filename, str): raise TypeError("Expected basestring, got '%s' instead" % type(filename)) if filename == "": raise ValueError("Empty filename got.") return json.load(open(filename, "rU"))
1e978466509c9cc54265a448b8c4f9f997a14336
564,684
from typing import OrderedDict def as_ordered_dict(v, ctx, value_transform=None, additional_params=None): """Expects v to be a list containing single key/value pair entries, and transforms it into an ordered dictionary.""" if not isinstance(v, list): raise Exception("Expected list of key/value pairs, but got: %s (%s)" % (type(v), ctx)) i = 0 result = OrderedDict() if additional_params is None: additional_params = dict() for item in v: if not isinstance(item, dict) or len(item) == 0: raise Exception("Expected item %d to be a single key/value pair (%s)" % (i, ctx)) k, = item.keys() v, = item.values() result[k] = value_transform(v, "item %d, %s" % (i, ctx), **additional_params) if callable(value_transform) else v i += 1 return result
e89cc7189429d5aa819141242a0b3260ccd6a225
464,319
def get_full_path_file_name(folder_name, file_name): """ Build full path to file given folder and file name """ full_path_file_name = '' if folder_name > '': full_path_file_name = folder_name + '/' full_path_file_name += file_name return full_path_file_name
caac6524224c0bf49b65bc8281f3fac4847f5a46
546,694
from pathlib import Path import shutil def get_config(repo_path: Path, filename: str) -> Path: """Get a config file, copied from the test directory into repo_path. :param repo_path: path to the repo into which to copy the config file. :param filename: name of the file from the test directory. :return: the path to the copied config file. """ config_src = Path(__file__).parent / filename config_file = repo_path / config_src.name shutil.copy(config_src, config_file) return config_file
4ac87766cd61e4202a3b73bd373009f8b6f52d34
676,993
def getCenter(box): """ This function calculates the center of a bounding box. """ # get the corners of the box x1 = box[0] x2 = box[2] y1 = box[1] y2 = box[3] # find the middle along the x axis center_x = int((x1+x2)/2) # find the middle along the y axis center_y = int((y1+y2)/2) # return that position return (center_x, center_y)
d09a8954e1489f58a9bfa774fca3263eaa97c864
693,443
def top_files(query, files, idfs, n): """ Given a `query` (a set of words), `files` (a dictionary mapping names of files to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the filenames of the the `n` top files that match the query, ranked according to tf-idf. """ tfidfs = [] for file in files: score = 0 for word in query: score += idfs[word] * files[file].count(word) tfidfs.append((file, score)) tfidfs.sort(key=lambda x: x[1], reverse=True) return [j[0] for j in tfidfs[:n]]
67abbcf5d0938b7046d8192ea6e48d73cb47fed0
440,723
def chr2num(chr_name): """ Returns a numerical mapping for a primary chromosome name Assumes names are prefixed with "chr" """ chr_id = chr_name[3:] if chr_id == 'X': return 23 elif chr_id == 'Y': return 24 elif chr_id == 'M': return 25 return int(chr_id)
92504f7fa7edf0a0cf1b766c357df52a5325f7c2
447,698
import re def remove_reminders(text): """Remove reminder text from a string. Reminder text, as defined by magic cards, consists of complete sentences enclosed in parentheses. """ return re.sub(r'(\A|\ )\(.*?\.\"?\)+', '', text)
5282f1c6f6dd6f198782fc057d71306c4340bb74
342,309
def find_nearest_multiple(num, n): """Find the nearest multiple of n to num 1. num: a number, num must be larger than n to have a meaningful result. 2. n : a number to be multipled """ return int(round(num / n)) * n
753e68908ebd1ff3ae4e40b992ce048ffd83262e
522,514
from typing import Union def celsius_to_kelvin(temperature_in_celsius: Union[int, float]) -> float: """ >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(1) 274.15 >>> celsius_to_kelvin(-1) 272.15 >>> celsius_to_kelvin(-273.15) 0.0 >>> celsius_to_kelvin(-274.15) Traceback (most recent call last): ... ValueError: Argument must be greater than -273.15 >>> celsius_to_kelvin([-1, 0, 1]) Traceback (most recent call last): ... ValueError: Argument must be int or float >>> celsius_to_kelvin('one') Traceback (most recent call last): ... ValueError: Argument must be int or float """ if not isinstance(temperature_in_celsius, (float, int)): raise ValueError('Argument must be int or float') if temperature_in_celsius < -273.15: raise ValueError('Argument must be greater than -273.15') return float(temperature_in_celsius + 273.15)
1aa5b214e20c0d47a3ab50388132f174cd33dbde
30,152
def obfuscate_email(email): """Takes an email address and returns an obfuscated version of it. For example: [email protected] would turn into t**t@e*********m """ if email is None: return None splitmail = email.split("@") # If the prefix is 1 character, then we can't obfuscate it if len(splitmail[0]) <= 1: prefix = splitmail[0] else: prefix = f'{splitmail[0][0]}{"*"*(len(splitmail[0])-2)}{splitmail[0][-1]}' # If the domain is missing or 1 character, then we can't obfuscate it if len(splitmail) <= 1 or len(splitmail[1]) <= 1: return f"{prefix}" else: domain = f'{splitmail[1][0]}{"*"*(len(splitmail[1])-2)}{splitmail[1][-1]}' return f"{prefix}@{domain}"
36c230ed75fc75fc7ecd6dd2ea71a6b3310c4108
708,417
def unwrap(string): """ Converts a string to an array of characters. """ return [c for c in string]
2d23d612b4c8e49165cbaa2adc2ae59285ceda80
429,452
def get_attr(instance, name): """Get the value of an attribute from a given instance. :param instance: The instance. :type instance: object :param name: The attribute name. :type name: str """ return getattr(instance, name)
a2c92637c2b31356dee4dee32999c895385d4e07
252,076
def generate_state_table(p): """ generates table of state-integers that are allowed by the symmetries of the model Args: p - dictionary that contains the relevant system parameters Returns: state_table - list of all state_numbers that belong to the relevant Hilbertspace """ # generate list of state_numbers which are allowed by the symmetries state_table = [] for i in range(int(2**p['N'])): state_table.append(i) return state_table
5d0fe34e495bbecac0a571844609008cd4d9ab00
174,800
from typing import Tuple def calculate_broadcasted_elementwise_result_shape( first: Tuple[int, ...], second: Tuple[int, ...], ) -> Tuple[int, ...]: """Determine the return shape of a broadcasted elementwise operation.""" return tuple(max(a, b) for a, b in zip(first, second))
5d565b2b5f38c84ab1f1573f4200fc65d6ae8e6a
25,055
def parse_str_to_int(workflow_parameters): """Parse integers stored as strings to integers.""" for (key, val) in workflow_parameters.items(): try: if isinstance(val, str) and val[0] == "'": # The actual value of the int as str could be stored as: # '\'val\'', since ' is an escape character. workflow_parameters[key] = int(val[1:-1]) else: workflow_parameters[key] = int(val) except (ValueError, TypeError, KeyError): # Skip values and types which cannot be casted to integer. pass return workflow_parameters
420251a48ca371e300a9705f645393aacc99df27
394,692
def naive_ascii_decode(encoded_number: str, length: int) -> str: """ This function will decode an integer into a str if it's been encoded with naive ASCII encoding. :param encoded_number: The encoded integer as a string. :param length: The length(in bytes that the output string should be). :return: The decoded string. """ j=0 output_str='' length=length-1 for i in range(0,length): tmp=encoded_number[j] if tmp == '1': chars=3 else: chars=2 tmp=encoded_number[j:j+chars] val=int(tmp) output_str=output_str+chr(val) j=j+chars if len(encoded_number[j:]) < 2: break return output_str
1a774beabc0cb17c4ed58d433d315fbfb158d555
417,761
from typing import List def remove_nested_packages(packages: List[str]) -> List[str]: """Remove nested packages from a list of packages. >>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"]) ['a'] >>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"]) ['a', 'b', 'c.d', 'g.h'] """ pkgs = sorted(packages, key=len) top_level = pkgs[:] size = len(pkgs) for i, name in enumerate(reversed(pkgs)): if any(name.startswith(f"{other}.") for other in top_level): top_level.pop(size - i - 1) return top_level
04cacb569dbe68b61861462e754d62fd27b22ffe
584,748
def read_lines(f): """Convert a file into a list of strings, without line breaks.""" return [line.strip() for line in open(f)]
8392911f2163578ef9d075a11395f9859c4d90ad
213,012