content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def dict2channel_data(task_dict): """ Given a task_dictionary (obtained with dict(task)) will return group_name and channel_data ready to be sent to django channel. Returned ``channel_data`` (second item of returned tuple) will have ``type`` trandformed as follows: new_type = <shortname>.<original type with removed dashes> Example: task_name = 'papermerge.core.tasks.ocr_document_task' type = 'task-received' will result in newly update type: 'ocrdocumenttask.taskreceived' which will map to channels handler ocrdocumenttask_taskreceived """ ret_dict = {} orig_type = task_dict.pop('type') orig_task_name = task_dict.pop('task_name') orig_short_name = orig_task_name.split('.')[-1] short_name = orig_short_name.replace('_', '') _type = orig_type.replace('-', '') new_type = f"{short_name}.{_type}" ret_dict['type'] = new_type ret_dict.update(task_dict) # First item in tuple is django channel group name == task_short # Second item in tuple task_dict with new ``type`` key return orig_short_name, ret_dict
298826364aed99659f7dfae6dc63ef70020cc59e
438,046
def cfm2m3s(cfm): """convert flow cfm to meter^3/second""" return cfm / 2118.880003
7b37ebb63d53ee0dc835c6dc11a24fe133e84f56
520,269
def _get_build_filename(build): """A unique but semi-readable filename to reference the build""" return "%s-%s-%s.build" % (build.project.domain.name, build.project.name, build.id)
16121cf6ffaf94f981e03c6513d553e3c3a04b56
156,154
def elements_of_list_same(iterator): """Check is all elements of an iterator are equal. :param iterator: a iterator :type iterator: ``list`` :rtype: ``bool`` Usage:: >>> from haproxyadmin import utils >>> iterator = ['OK', 'ok'] >>> utils.elements_of_list_same(iterator) False >>> iterator = ['OK', 'OK'] >>> utils.elements_of_list_same(iterator) True >>> iterator = [22, 22, 22] >>> utils.elements_of_list_same(iterator) True >>> iterator = [22, 22, 222] >>> utils.elements_of_list_same(iterator) False """ return len(set(iterator)) == 1
a08554e6c22b567dde77f79ca30804996eeb9b51
369,074
def yesno(value, icaps=True): """ Return 'yes' or 'no' according to the (assumed-bool) value. """ if (value): str = 'Yes' if icaps else 'yes' else: str = 'No' if icaps else 'no' return str
9bff0a577c81c900159d9650e78a75c6869e94b9
652,071
def i16_pcm(wav): """Convert audio to 16 bits integer PCM format.""" if wav.dtype.is_floating_point: return (wav.clamp_(-1, 1) * (2**15 - 1)).short() else: return wav
d8f0695be89f997f94dd51ccd06529eaf0cf95c3
147,206
def CollapsePath(path_tokens): """ CollapsePath() takes a list of Strings argument representing a directory-like path string (for example '/SUB1A/Sub2A/../Sub2B/sub3b/../sub3c/entry'), and replaces it with a version which should contain no '..' patterns. (In the example above, it returns /SUB1A/Sub2B/sub3c/entry') """ new_ptkns = [] ndelete = 0 i = len(path_tokens) - 1 while i >= 0: if path_tokens[i] == '..': ndelete += 1 else: if (ndelete > 0) and (path_tokens[i] != ''): # Note: "path_tokens[i] != '')" means "/a/b//c" <-> "/a/b/c" ndelete -= 1 else: if len(path_tokens[i]) > 0: new_ptkns.append(path_tokens[i]) i -= 1 new_ptkns.reverse() if ndelete > 0: return ndelete # <-- useful to let caller know an error ocurred return new_ptkns
afd4766b5bf688fdb1e9d0d18266f27914c9ee4f
600,865
def get_topic_name(num_partitions, msg_size_bytes): """Generate test-topic names describing message characteristics""" return "parts{}-size{}".format(num_partitions, msg_size_bytes)
925b4762069e0b5f7642926a7cfd57ba027169ce
491,522
def filter_by_name(cases, names): """Filter a sequence of Simulations by their names. That is, if the case has a name contained in the given `names`, it will be selected. """ if isinstance(names, str): names = [names] return sorted( [x for x in cases if x.name in names], key=lambda x: names.index(x.name) )
64c3f4b0b77ba8106b276b74e6a01bd3f6c91ce4
75,015
def omega(delta_lambda): """Calculate the Buchdahl chromatic coordinate.""" return delta_lambda/(1 + 2.5*delta_lambda)
b8659be24bd94b85bf8d82ee4a7b9991628de1ba
102,476
def merge(*dicts): """Returns a dict that consists of the rest of the dicts merged with the first. If a key occurs in more than one map, the value from the latter (left-to-right) will be the value in the result.""" d = dict() for _dict in dicts: d.update(_dict) return d
9a624f0b440b1bf0281918abaa7988968495a39d
73,917
def _build_visited_site_rule_info(client, url): """Creates a UserListRuleInfo object targeting a visit to a specified URL. Args: client: An initialized Google Ads client. url: The string URL at which the rule will be targeted. Returns: A populated UserListRuleInfo object. """ user_visited_site_rule = client.get_type( "UserListRuleItemInfo", version="v6" ) # Use a built-in parameter to create a domain URL rule. user_visited_site_rule.name = "url__" user_visited_site_rule.string_rule_item.operator = client.get_type( "UserListStringRuleItemOperatorEnum", version="v6" ).EQUALS user_visited_site_rule.string_rule_item.value = url user_visited_site_rule_info = client.get_type( "UserListRuleInfo", version="v6" ) rule_item_group_info = user_visited_site_rule_info.rule_item_groups.add() rule_item_group_info.rule_items.append(user_visited_site_rule) return user_visited_site_rule_info
12c04398416b233e6c42451d7c1b5fed1e8a7aec
244,237
from typing import Any def is_boolean(value: Any) -> bool: """Checks if value type is boolean. Parameters ---------- value: Any The value to check. Returns ------- bool: True if value is boolean, False otherwise. """ bool_values = ("yes", "y", "true", "t", "1", "no", "n", "false", "f", "0", "") return isinstance(value, bool) or str(value).lower() in bool_values
35f9ddcea21bc04eace7c9480e28b2494930c2d0
412,518
def spacing(area, shape): """ Returns the spacing between grid nodes Parameters: * area ``(x1, x2, y1, y2)``: Borders of the grid * shape Shape of the regular grid, ie ``(ny, nx)``. Returns: * ``[dy, dx]`` Spacing the y and x directions """ x1, x2, y1, y2 = area ny, nx = shape dx = float(x2 - x1) / float(nx - 1) dy = float(y2 - y1) / float(ny - 1) return [dy, dx]
71e803ac463651f67d4f77f876af201cae719059
209,015
import math def pdf(x, mu: float = 0, sigma: float = 1): """Probability density function""" return (1 / (math.sqrt(2 * math.pi) * abs(sigma)) * math.exp(-(((x - mu) / abs(sigma)) ** 2 / 2)))
ba239b8060e92213c5278849026e96a99cec47cc
193,375
import re def _get_ip_from_response(response): """ Filter ipv4 addresses from string. Parameters ---------- response: str String with ipv4 addresses. Returns ------- list: list with ip4 addresses. """ ip = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b', response) return ip
ac36a3b729b0ce4ba13a6db550a71276319cbd70
707,238
def get_library_version() -> str: """ Returns the version of minecraft-launcher-lib """ return "3.2"
11edc1daa5811f51cfc73ef399c85a7933dc3b2f
192,074
def mixin(cls): """ Decorator applied to a class that indicates the class is a mixin and should not participate in interface verification until it is part of another class. Example: class MyInterface(Interface): @staticmethod @abstractmethod def Method1(): pass @staticmethod @abstractmethod def Method2(): pass # Don't check that Method matches MyInterface, as Mixin isn't based on # MyInterface yet. @mixin class Mixin1(Interface): @staticmethod @override def Method1(): pass @mixin class Mixin2(Interface): @staticmethod @override def Method2(): pass class MyObject(Mixin1, Mixin2, MyInterface): pass """ setattr(cls, "__mixin", cls) return cls
df40e2631736220b624dd8e08d4e6f52250aa5f7
373,543
import six def remove_nones(in_dict): """ Recursively remove keys with a value of ``None`` from the ``in_dict`` collection """ try: return dict( (key, remove_nones(val)) for key, val in six.iteritems(in_dict) if val is not None ) except (ValueError, AttributeError): return in_dict
f742d716fbeb148ca292a7b9f7e8f0ff7eb7e7dc
336,564
def get_mod(modulePath): """Import a module.""" return __import__(modulePath, globals(), locals(), [''])
ccecb2d3c24dc1bc78f08bbedebde0206b2bce7e
344,869
import re def isComment(line, comment): """ Is the line a comment. """ if re.match(str('[ \t]*' + comment), line): return True else: return False
db1d030eac29829650cabf451c315b3470b37a77
296,055
from typing import Dict def merge_default_parameters(hyperparams: Dict, default: Dict) -> Dict: """ Checks if the input parameter hyperparams contains every necessary key and if not, uses default values or raises a ValueError if no default value is given. Parameters ---------- hyperparams: dict Hyperparameter as passed to the recuorse method. default: dict Dictionary with every necessary key and default value. If key has no default value and hyperparams has no value for it, raise a ValueError Returns ------- dict Dictionary with every necessary key. """ keys = default.keys() dict_output = dict() for key in keys: if isinstance(default[key], dict): hyperparams[key] = ( dict() if key not in hyperparams.keys() else hyperparams[key] ) sub_dict = merge_default_parameters(hyperparams[key], default[key]) dict_output[key] = sub_dict continue if key not in hyperparams.keys(): default_val = default[key] if default_val is None: # None value for key depicts that user has to pass this value in hyperparams raise ValueError( "For {} is no default value defined, please pass this key and its value in hyperparams".format( key ) ) elif isinstance(default_val, str) and default_val == "_optional_": # _optional_ depicts that value for this key is optional and therefore None default_val = None dict_output[key] = default_val else: if hyperparams[key] is None: raise ValueError("For {} in hyperparams is a value needed".format(key)) dict_output[key] = hyperparams[key] return dict_output
9299dc66910aba10575cf5726236a92cbba2e393
343,245
import random def random_selection(population, fitness, eq): """ Selection of the best two candidates given fitness function :param population: list of numpy array :param fitness: function to fit :param eq: params to fitness function :return: tuple of two more promising individuals (numpy vectors) """ result = list(map(lambda x: (x, fitness(eq, x)), population)) result.sort(key=lambda x: x[1], reverse=True) limit = int(len(population)/2) x = random.choice(result[:limit])[0] y = random.choice(result[:limit])[0] #return x, y return result[0][0], result[1][0]
208f6d958bfdaf339233abd69c4918cf6a75cf5b
662,549
def cross(x, y): """Calculate the cross product of two vectors. The two input vectors must have the same dimension :math:`d <= 3`. This function calls the `cross` method of :class:`~taichi.Vector`. Args: x (:class:`~taichi.Matrix`): The first input vector. y (:class:`~taichi.Matrix`): The second input vector. Returns: The cross product of two vectors. Example:: >>> x = ti.Vector([1., 0., 0.]) >>> y = ti.Vector([0., 1., 0.]) >>> cross(x, y) [0., 0., 1.] """ return x.cross(y)
992c34e8433ec07193ebc47a40e2b808ebbebfc1
453,434
def hyperfactorial(k: int) -> int: """ Returns the hyperfactorial of the number, the product of all positive integers to the power of themselves smaller or equal to the number. By convention an empty product is considered 1, meaning hyperfactorial(0) will return 1. :param k: A positive integer :return: The hyperfactorial of that integer """ result = 1 for i in range(1, k + 1): result *= i**i return result
0cff03cc91909461de2a0a6c607a029b4aba5c8d
280,734
def max_value_1_highest_weight_value_ratio(weight_value_tuples, max_capacity): """ Solution: Compute the max value by finding the item with the highest weight to value ratio and use it as many times as possible until we need to find a smaller one that fits into the knapsack but still has the greatest weight to value ratio. This algorithm won't always find the right solution (see tests), but is much faster than the optimal solution and uses O(1) space. Complexity: Time: O(n * lg{n}) (where n=number of items) (sorting the input first) Space: O(1) """ # Sort tuples by the highest weight to value ratio descending weight_value_tuples.sort(key=lambda tup: tup[1] / tup[0], reverse=True) # Repeatedly add the highest weight-to-value tuple that still fits into # the knapsack until nothing else will fit total_value = 0 for weight, value in weight_value_tuples: while max_capacity >= weight: total_value += value max_capacity -= weight return total_value
00ef3d3c0b155fc47b189ac52660eaf8aba4cf0a
591,322
def cast_string_to_int_error(what): """ Retrieves the "can not cast from string to integer" error message. :param what: Environment variable name. :return: String - Can not cast from string to integer. """ return "ERROR: " + what + " value cannot be cast from string to int"
9c3645d9cdf9fc90893ab5a7762cea6ccfd8c73e
177,125
def form_neg_pair(info, mode='trn'): """ Returns a list of 2 indices correspondign to index values of info which store different characters. """ y = info[info.Mode == mode] curr_ind = y.Char.sample(1).index.values[0] curr_char = y.Char.loc[curr_ind] new_ind = y[~y.Char.isin([curr_char])].sample(1).index.values[0] return [curr_ind, new_ind]
1c3a83d41154507a794a270e4d35e5a6bbde5d70
437,427
def append_story_content(elements, content_type, content): """ Append content to story_content list in markdown elements """ if 'story_content' not in elements: elements['story_content'] = [] elements['story_content'].append((content_type, content)) return elements
cdc9b9b3349dd1c7faf5a04218164daad9f7899f
397,306
def cell_multiply(c, m): """ Multiply the coordinates (cube or axial) by a scalar.""" return tuple( m * c[i] for i in range(len(c)) )
43647e4ba857a0eca616a391a614f16494202e4b
406,749
def get_loc_lab(lat, lon): """Construct the USGS location label Construct a lat/lon location label such as n01e002 that is part of the labels used by the "Staged Products" HTTPS web directory access for USGS 1-arcsecond DEM TIFF files. Args: lat (int): Latitude lon (int): Longitude Returns: str, label describing lat/lon cell """ return ("sn"[lat > 0] + f"{abs(lat):>02d}" + "we"[lon > 0] + f"{abs(lon):>03d}")
f6f789f480a9998fdecc2420802a0e818ae37c1e
598,980
def set_dtypes_features(df, groups, dtypes): """Split the columns of a df according to their given group. Parameters: ----------- df : pandas.DataFrame The data frame to be splitted. groups : pandas.Series Series with the features' names or indexs as index and the group as values. group : scalar Scalar to look for in the groups series. The dtype will be set on the matched features. dtypes: python type or np.dtype Matched features will be set to this type Returns: -------- pandas.DataFrame Data frame with casted dtypes. """ _dtypes = dict() for group, dtype in dtypes.items(): # Get the names of the features to set the dtype features = groups[groups == group].index for f in features: _dtypes[f] = dtype return df.astype(_dtypes)
e0f96b8e686921b8b6f1c5a5359a02d79b0acd7b
374,213
import re def count_words(word, sentence): """Count the number of occurrences of a word in the sentence""" match = re.compile(word) return len(match.findall(sentence))
c6fc464b884bafd335a1d25052408afff2eae2dc
404,687
import math def getDirectedDist(obj1, obj2, metrics): """ Returns delX, delY, delZ, delO from obj1 to obj2 """ (x1, y1, z1) = metrics[obj1][0] (x2, y2, z2) = metrics[obj2][0] return [x2-x1, y2-y1, z2-z1, math.atan2((y2-y1),(x2-x1))%(2*math.pi)]
a08e4d6a4c1709f3183994dce9614df1b9c37939
469,659
def insert_trace_index_as_event_attribute(log, trace_index_attr_name="@@traceindex"): """ Inserts the current trace index as event attribute (overrides previous values if needed) Parameters ----------- log Log trace_index_attr_name Attribute name given to the trace index """ for i in range(len(log._list)): for j in range(len(log._list[i])): log._list[i][j][trace_index_attr_name] = i + 1 return log
f2ed24f88b2e45b2397ecb8e78e07b1b6a9aa0fc
162,078
def extract_sample_qc_status(qc_file_handle, file_label): """Parses a MEND QC results file handle to "PASS" or "FAIL". QC results parsing to something else (or failing to parse) indicate a major failure in the QC script and should interrupt analysis. The qc_file_handle is as provided by TarFile.extractfile, ie, in raw bytes""" # Expected File format (example. Has PASS\n or FAIL\n at end of second line # input uniqMappedNonDupeReadCount estExonicUniqMappedNonDupeReadCount qc\n # sample1.readDist.txt 22333444.5 10999888.765 PASS\n status = qc_file_handle.readlines()[1][-5:-1].decode("utf-8") if not status in ["PASS", "FAIL"]: print("ERROR: MEND QC file {} parsed status as '{}' - expected PASS or FAIL!".format(file_label, status)) raise ValueError return status
1fc99c6b61c790bc424a62ace8da4becaa7f6c8b
145,632
from datetime import datetime def datetime_to_unix_ms(dt: datetime) -> int: """Convert a Python ``datetime`` object to a Unix millisecond timestamp. This is necessary as the timestamps Cook returns in its API are in milliseconds, while the Python ``datetime`` API uses seconds for Unix timestamps. """ return int(dt.timestamp() * 1000)
63b0ed18c800616bfeba2503a26b52d51f452411
591,984
def pl (listoflists): """ Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None """ for row in listoflists: if row[-1] == '\n': print(row, end=' ') else: print(row) return None
1b9bdcbbf46d14477a9ef0165d680e5a48c8dac7
199,459
def product_except_self(nums: list[int]) -> list[int]: """Computes the product of all the elements of given array at each index excluding the value at that index. Note: could also take math.prod(nums) and divide out the num at each index, but corner cases of num_zeros > 1 and num_zeros == 1 make code inelegant. Args: nums: Returns: Examples: >>> product_except_self([]) [] >>> product_except_self([1,2,3,4]) [24, 12, 8, 6] >>> product_except_self([-1,1,0,-3,3]) [0, 0, 9, 0, 0] """ """ALGORITHM""" ## INITIALIZE VARS ## nums_sz = len(nums) # DS's/res nums_products_except_i = [1] * nums_sz ## Multiply against product of all elements PRECEDING i total_product = 1 for i in range(nums_sz): nums_products_except_i[i] *= total_product total_product *= nums[i] ## Multiply against product of all elements FOLLOWING i total_product = 1 for i in reversed(range(nums_sz)): nums_products_except_i[i] *= total_product total_product *= nums[i] return nums_products_except_i
15090d4873b0dec9ea6119e7c097ccda781e51fa
708,576
from pathlib import Path def get_final_path(output_path: Path, set_type: str, samp_name: str) -> Path: """Get path of output file Arguments: output_path {Path} -- root of output path set_type {str} -- data set type samp_name {str} -- name of sample Returns: Path -- complete path to output file """ return output_path.joinpath(set_type, samp_name + '.json')
0406a6e6684c8f42b781f0a1d53a05a9ca3fb7cb
617,338
def icevol_corr_prep(record, agelabel, age_in_ky): """ Prepare ``record`` for the ice volume correction. Converts all numbers to actual number dtypes, converts Age to integer years and sets it as index. Parameters ---------- record : pandas DataFrame A pandas DataFrame containing the data to prepare. agelabel : string The column label for the age data. age_in_ky : Boolean If True, ages will be converted from kyrs to years. """ record = record.convert_objects(convert_numeric=True, convert_dates=False, convert_timedeltas=False, copy=False) if age_in_ky: record[agelabel] = record[agelabel] * 1000 record[agelabel] = record[agelabel] // 1 record.set_index(agelabel, inplace=True) return record
ec0c0d14230f655ebced932b7a99701e36e4d537
235,564
def url_build(*parts): """Join parts of a url into a string.""" url = "/".join(p.strip("/") for p in parts) return url
aebc2e6118f77d8439c7b7819d8eada54b417f4d
133,783
def dimension_matrice(matrice: list, n: int) -> bool: """ Description: Vérifie si la matrice est de taille n. Paramètres: matrice: {list} -- Matrice à vérifier. n: {int} -- Taille de la matrice. Retourne: {bool} -- True si la matrice est de taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 3) True """ if len(matrice) == n and len(matrice[0]) == n: return True else: return False
b2922341af4fbed473fb7d459d2e4850cb979fe0
488,721
def colored(msg, color=None, background=None, bold=None, underline=None): """ Return string formatted using ANSI escape codes. Supports 256 colors. https://upload.wikimedia.org/wikipedia/en/1/15/Xterm_256color_chart.svg :param string: String to format. :param color: Color of text. :param background: Color of background. :param bold: True if text should be bold. :param underline: True if text should be underlined. """ prefix = "" if color is not None: prefix += "\x1b[38;5;{}m".format(color) if background is not None: prefix += "\x1b[48;5;{}m".format(background) if bold: prefix += "\x1b[1m" if underline: prefix += "\x1b[4m" suffix = "" if prefix: suffix = "\x1b[0m" return "{}{}{}".format(prefix, msg, suffix)
54e0dee61ff755862e48800bf7be8d47ea359806
442,123
def get_arn(vpc_id, region, account_id): """Creates a vpc ARN.""" return f'arn:aws:ec2:{region}:{account_id}:vpc/{vpc_id}'
2ac5a32d2246ccd689fccca5470889b54e48df37
176,385
def calculate(triangle): """Returns the maximum total from top to bottom by starting at the top of the specified triangle and moving to adjacent numbers on the row below""" def calculate_helper(row, col): """Returns the maximum path value of a specified cell in the triangle""" if row == len(triangle): return 0 return triangle[row][col] + max( calculate_helper(row + 1, col), calculate_helper(row + 1, col + 1) ) return calculate_helper(0, 0)
2c7d3c96841db960414e043aaebdae83b81eaf7d
537,291
def precision(xs, ys): """Precision of list `xs` to list `ys`.""" return len([x for x in xs if x in ys]) / float(len(xs)) if xs else 0.
601866550480572c79e397b8a2e9a6fcbcc83e10
567,918
import requests def check_uri(uri, timeout=5): """ Checks if a uri returns response of 200 if it is requested Will return True if the response is 200, false otherwise :param uri: URI to request :param timeout: how long to return False, if we do not get a response :return: True/False :rtype: bool """ try: r = requests.get(url=uri, timeout=timeout) return r.status_code == 200 except (requests.ConnectTimeout, requests.RequestException): return False
fdb5f34facef287d47900508e124e81b88c57fc7
593,274
def str_input(prompt: str) -> str: """Prompt user for string value. Args: prompt (str): Prompt to display. Returns: str: User string response. """ return input(f"{prompt} ")
ac6c3c694adf227fcc1418574d4875d7fa637541
4,474
def linear_extrap(x1, x2, x3, y1, y2): """ return y3 such that (y2 - y1)/(x2 - x1) = (y3 - y2)/(x3 - x2) """ return (x3-x2)*(y2-y1)/(x2-x1) + y2;
9f45b7443ded484c2699e9bd545a3d551a39313e
100,750
import torch def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int = -1, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: size (int): size of mask chunk_size (int): size of chunk num_left_chunks (int): number of left chunks <0: use full chunk >=0: use num_left_chunks device (torch.device): "cpu" or "cuda" or torch.Tensor.device Returns: torch.Tensor: mask Examples: >>> subsequent_chunk_mask(4, 2) [[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]] """ ret = torch.zeros(size, size, device=device, dtype=torch.bool) for i in range(size): if num_left_chunks < 0: start = 0 else: start = max((i // chunk_size - num_left_chunks) * chunk_size, 0) ending = min((i // chunk_size + 1) * chunk_size, size) ret[i, start:ending] = True return ret
e06afa21778e92725e07445048ab60a2cfa24af0
671,190
def deltaf(series, baseline): """calculate deltaf over f for a signal (1D array)""" deltaf = series - baseline return deltaf / baseline
06899e35b6229aca983bdc01207bddba53b56c6f
593,627
import yaml def read_types(infile): """ Reads types definitions from a file. """ with open(infile, "r") as stream: return yaml.safe_load(stream)
f325a5a69eb1c718fe80ed9c77528354b86a15ae
351,564
def normdirpath(path): """Make a directory path end with /""" if not path.endswith('/') and path != '': path += '/' return path
32ab35955e1a3b60e18c3ec36f469989fa42d135
233,092
import ast def safe_eval_maths(expr): """ Safely evaluates a maths expression, such as (2**32-1) or (400|0x1000) Will throw a ValueError exception on error Note: This is still susceptible to memory or CPU exhaustion by putting in large numbers. """ allowed = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.operator, ast.unaryop, ast.Num) try: tree = ast.parse(expr, mode='eval') valid = all(isinstance(n, allowed) for n in ast.walk(tree)) if valid: return eval(expr, {"__builtins__": None}) except Exception as e: raise ValueError("Refusing to execute " + expr + str(e))
54dcf13679dffa13c02bb7920f7d24b1626e3285
587,625
def _get_command_name(command_raw): """Return command name by splitting up DExTer command contained in command_raw on the first opening paranthesis and further stripping any potential leading or trailing whitespace. """ command_name = command_raw.split('(', 1)[0].rstrip() return command_name
c6e4df2c5086ca8d7e082c5eea3607b10d6497bd
445,350
def subtract(a, b): """Subtraction applied to two numbers Args: a (numeric): number to be subtracted b (numeric): subtractor Raises: ValueError: Raised when inputs are not numeric """ try: return a - b except: raise ValueError("inputs should be numeric")
7cfa9607145fb1713309fcb2e543a3a528aa26f1
19,389
def compute_breakdown(tp, start_ts=None, end_ts=None, process_name=None): """For each userspace slice in the trace processor instance |tp|, computes the self-time of that slice grouping by process name, thread name and thread state. Args: tp: the trace processor instance to query. start_ts: optional bound to only consider slices after this ts end_ts: optional bound to only consider slices until this ts process_name: optional process name to filter for slices; specifying this argument can make computing the breakdown a lot faster. Returns: A Pandas dataframe containing the total self time taken by a slice stack broken down by process name, thread name and thread state. """ bounds = tp.query('SELECT * FROM trace_bounds').as_pandas_dataframe() start_ts = start_ts if start_ts else bounds['start_ts'][0] end_ts = end_ts if end_ts else bounds['end_ts'][0] tp.query(""" DROP VIEW IF EXISTS modded_names """) tp.query(""" CREATE VIEW modded_names AS SELECT slice.id, slice.depth, slice.stack_id, CASE WHEN slice.name LIKE 'Choreographer#doFrame%' THEN 'Choreographer#doFrame' WHEN slice.name LIKE 'DrawFrames%' THEN 'DrawFrames' WHEN slice.name LIKE '/data/app%.apk' THEN 'APK load' WHEN slice.name LIKE 'OpenDexFilesFromOat%' THEN 'OpenDexFilesFromOat' WHEN slice.name LIKE 'Open oat file%' THEN 'Open oat file' ELSE slice.name END AS modded_name FROM slice """) tp.query(""" DROP VIEW IF EXISTS thread_slice_stack """) tp.query(""" CREATE VIEW thread_slice_stack AS SELECT efs.ts, efs.dur, IFNULL(n.stack_id, -1) AS stack_id, t.utid, IIF(efs.source_id IS NULL, '[No slice]', IFNULL( ( SELECT GROUP_CONCAT(modded_name, ' > ') FROM ( SELECT p.modded_name FROM ancestor_slice(efs.source_id) a JOIN modded_names p ON a.id = p.id ORDER BY p.depth ) ) || ' > ' || n.modded_name, n.modded_name )) AS stack_name FROM experimental_flat_slice({}, {}) efs LEFT JOIN modded_names n ON efs.source_id = n.id JOIN thread_track t ON t.id = efs.track_id """.format(start_ts, end_ts)) tp.query(""" DROP TABLE IF EXISTS thread_slice_stack_with_state """) tp.query(""" CREATE VIRTUAL TABLE thread_slice_stack_with_state USING SPAN_JOIN( thread_slice_stack PARTITIONED utid, thread_state PARTITIONED utid ) """) if process_name: where_process = "AND process.name = '{}'".format(process_name) else: where_process = '' breakdown = tp.query(""" SELECT process.name AS process_name, thread.name AS thread_name, CASE WHEN slice.state = 'D' and slice.io_wait THEN 'Uninterruptible sleep (IO)' WHEN slice.state = 'DK' and slice.io_wait THEN 'Uninterruptible sleep + Wake-kill (IO)' WHEN slice.state = 'D' and not slice.io_wait THEN 'Uninterruptible sleep (non-IO)' WHEN slice.state = 'DK' and not slice.io_wait THEN 'Uninterruptible sleep + Wake-kill (non-IO)' WHEN slice.state = 'D' THEN 'Uninterruptible sleep' WHEN slice.state = 'DK' THEN 'Uninterruptible sleep + Wake-kill' WHEN slice.state = 'S' THEN 'Interruptible sleep' WHEN slice.state = 'R' THEN 'Runnable' WHEN slice.state = 'R+' THEN 'Runnable (Preempted)' ELSE slice.state END AS state, slice.stack_name, SUM(slice.dur)/1e6 AS dur_sum, MIN(slice.dur/1e6) AS dur_min, MAX(slice.dur/1e6) AS dur_max, AVG(slice.dur/1e6) AS dur_mean, PERCENTILE(slice.dur/1e6, 50) AS dur_median, PERCENTILE(slice.dur/1e6, 25) AS dur_25_percentile, PERCENTILE(slice.dur/1e6, 75) AS dur_75_percentile, PERCENTILE(slice.dur/1e6, 95) AS dur_95_percentile, PERCENTILE(slice.dur/1e6, 99) AS dur_99_percentile, COUNT(1) as count FROM process JOIN thread USING (upid) JOIN thread_slice_stack_with_state slice USING (utid) WHERE dur != -1 {} GROUP BY thread.name, stack_id, state ORDER BY dur_sum DESC """.format(where_process)).as_pandas_dataframe() return breakdown
d92df5f4dc06ae4f705b7daa014915d372253cde
457,895
from typing import Tuple from typing import Union import requests def check_url(url: str) -> Tuple[bool, Union[str, requests.Response]]: """Returns information on the availability of the url Parameters ---------- url : str The url to test Returns ------- Tuple[bool, Union[str, Response]] Whether the url is available and a string reponse """ try: response = requests.head(url, allow_redirects=False) return True, response except requests.exceptions.SSLError: return False, "SSL error" except requests.exceptions.ConnectionError: return False, "Connection error" except requests.exceptions.InvalidSchema: return False, "Invalid schema" except requests.exceptions.MissingSchema: return check_url("https://" + url)
09ed074bd8f71288788a4265e98f23aa953a6969
44,599
import re def file_matches_regexps(filename, patterns): """Does this filename match any of the regular expressions?""" return any(re.match(pat, filename) for pat in patterns)
b64f28c1391c04de56269f32ee5e0a25cff2811a
396,874
import torch def clamp_ref(x, y, l_inf): """ Clamps each element of x to be within l_inf of each element of y """ return torch.clamp(x - y , -l_inf, l_inf) + y
d3fd0dd46d4cf821c3faa62ff00a314ea4575304
182,448
def split_query_into_tokens(query): """ Splits query string into tokens for parsing by 'tokenize_query'. Returns list of strigs Rules: Split on whitespace Unless - inside enclosing quotes -> 'user:"foo bar"' - end of last word is a ':' -> 'user: foo' Example: >>> split_query_into_tokens('user:foo user: bar user"foo bar' foo bar) => ['user:foo', 'user: bar', 'user"foo bar"', 'foo', 'bar'] """ tokens = [] token = "" quote_enclosed = False quote_type = None end_of_prev_word = None for idx, char in enumerate(query): next_char = query[idx + 1] if idx < len(query) - 1 else None token += char if next_char and not char.isspace() and next_char.isspace(): end_of_prev_word = char if char.isspace() and not quote_enclosed and end_of_prev_word != ":": if not token.isspace(): tokens.append(token.strip(" ")) token = "" if char in ("'", '"'): if not quote_enclosed or quote_type == char: quote_enclosed = not quote_enclosed if quote_enclosed: quote_type = char if not token.isspace(): tokens.append(token.strip(" ")) return tokens
6f4bee48f9f10511022eac363d1f2e9df6bdcecf
325,194
def convert_name(name, to_version=False): """This function centralizes converting between the name of the OVA, and the version of software it contains. OneFS OVAs follow the naming convention of <VERSION>.ova :param name: The thing to covert :type name: String :param to_version: Set to True to covert the name of an OVA to the version :type to_version: Boolean """ if to_version: return name.rstrip('.ova') else: return '{}.ova'.format(name)
2800c22e2af5a6ad3d537a9713c473e6d44101c6
690,519
def hex_list(items): """ Return a string of a python-like list string, with hex numbers. [0, 5420, 1942512] --> '[0x0, 0x152C, 0x1DA30]' """ return '[{}]'.format(', '.join('0x%X' % x for x in items))
775166e908ae9202e330d76fc82c9c45a4388cca
117,893
def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs): """A reply handler for commands that haven't been added to the reply list. Returns empty strings for stdout and stderr. """ return '', ''
e73bd970030c4f78aebf2913b1540fc1b370d906
706,860
def contains(text, pattern): """Return a boolean indicating whether pattern occurs in text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) index = 0 if len(pattern) == 0: return True for letter in text: if index > 0 and letter != pattern[index]: index = 0 if letter == pattern[index]: index += 1 if index > len(pattern) - 1: return True return False
2b69f1e6e0ee730c65ba671e2c99a99fcb30f367
195,908
def seminorm_loop(x, p, display = False): """ Calculate for a given complex vector and some 1 <= p < inf the l_p-semi-norm using loops and scalar arithmetic """ if p < 1: raise ValueError("p must be >= 1") # Using scalar arithmetic to calculate each elements absolute value raised to p x_abs_p = x.real**2 + x.imag**2 * (1j) x_abs_p = ((x_abs_p.real + x_abs_p.imag) ** 0.5) ** p # Sum all elements with an uneven index sum = 0 for j in range(1, len(x_abs_p)+1, 2): # Since arrays in python are zero-based, substract 1 from j j -= 1 sum += x_abs_p[j] # Raise to 1/p to get the l_p-semi-norm result = sum**(1/p) if display: print(result) return result
31717d937f729e80824b7f756ce8cd75ad38b75f
265,828
def min_distinct(expr): """ Function ``MIN(DISTINCT expr)`` """ return min(expr).distinct()
30a6445149daa8e2ad5113182c5c35c3e9996107
449,794
import re def is_single_symbol(expr): """Returns ``True`` if the expression is a single symbol, possibly surrounded with white-spaces >>> is_single_symbol('hello') True >>> is_single_symbol('hello * world') False """ expr = expr.strip() single_symbol = re.compile("^[a-zA-Z_]+[a-zA-Z_0-9]*$") m = single_symbol.match(expr) return m is not None
350c1653b28a0a4c6986023453cc9cef06df3f25
137,272
def day_to_lookup(day): """Turns a day into its lookup key in the full year hash""" return day.strftime('%Y-%m-%d')
c0ccf7c0b2957843c3ef618a2685fb44472cde79
514,154
def do_sort(reverse=False): """ Sort a sequence. Per default it sorts ascending, if you pass it `True` as first argument it will reverse the sorting. *new in Jinja 1.1* """ def wrapped(env, context, value): return sorted(value, reverse=reverse) return wrapped
2254464025c9701d402c0417174731fdaf397d48
437,932
def _parse_commit_response(commit_response_pb): """Extract response data from a commit response. :type commit_response_pb: :class:`._generated.datastore_pb2.CommitResponse` :param commit_response_pb: The protobuf response from a commit request. :rtype: tuple :returns': The pair of the number of index updates and a list of :class:`._generated.entity_pb2.Key` for each incomplete key that was completed in the commit. """ mut_result = commit_response_pb.mutation_result index_updates = mut_result.index_updates completed_keys = list(mut_result.insert_auto_id_key) return index_updates, completed_keys
e23ce5ee97c9bc3f4d4cf48d93d0d4932e0c8432
242,661
def validate_pause_time(pause_time: str) -> str: """Validate pause time.""" if not pause_time.startswith("PT"): raise ValueError("PauseTime should look like PT#H#M#S") return pause_time
82e7f9041bd5f774e8e9c088e829bded4796503e
508,611
import string import random def generate_filename(size=10, chars=string.ascii_uppercase + string.digits, extension='png'): """Creates random filename Args: size: length of the filename part, without dot and extention chars: character range to draw random characters from extension: extension to be added to the returned filenam Returns: random filame with extension """ filename = ''.join(random.choice(chars) for _ in range(size)) return filename + '.' + extension
171c635f849b262894bb09749c1f22a76133dacc
120,974
from typing import List from typing import Any def _unique(x: List[Any]) -> List[Any]: """Uniquify a list, preserving order.""" return list(dict.fromkeys(x))
3be8ac99fba1ff2ef8e3b0c0000686697038dbff
461,318
import mpmath def pdf(x, mu=0, sigma=1): """ Log-normal distribution probability density function. """ if x <= 0: return mpmath.mp.zero x = mpmath.mpf(x) lnx = mpmath.log(x) return mpmath.npdf(lnx, mu, sigma) / x
ae9ffb6bee3deab68e5f5a19c4153cb017af2909
433,252
def _generate_scope_signature (scoped): """Returns the signature for the scope of a scoped Topic Maps construct. This function returns the signature for the scope only. No other properties of the scoped construct are taken into account. :param scoped: the scoped Topic Maps construct :type scoped: `Scoped` :rtype: frozenset """ return frozenset(scoped.get_scope())
a72a1a8e82f3dce32440f912f81b0e1c1d7bf893
247,778
def create_health_check(lock): """ Return health check function that captures whether the lock is acquired """ def health_check(): d = lock.is_acquired() return d.addCallback(lambda b: (True, {"has_lock": b})) return health_check
fc77f8c42f271fd98051f91771d99ccc8aec7a9e
34,199
def get_igmp_status(cli_output): """ takes str output from 'show ip igmp snooping | include "IGMP Snooping" n 1' command and returns a dictionary containing enabled/disabled state of each vlan """ search_prefix = "IGMP Snooping information for vlan " vlan_status={} counter = 0 line_list = cli_output.splitlines() for line in line_list: if line.startswith(search_prefix): vlan_status.update({line.strip(search_prefix):line_list[counter+1].strip('IGMP snooping ')}) counter += 1 return vlan_status
150b3f1213f82f3ccc70ba922fc8e4602349e660
514,899
def linear_interpolate(a, b, v1, v2, i): """Linear interpolation""" if v1 == v2: return a else: return a + (b - a) * (i - v1) / (v2 - v1)
dd686797f5311ff08ef5c0f7bb3642344ce8c705
33,401
import time def total_time(func): """ Calculate the running time of the function :param func: the function need to been calculated :return: func's result """ def call_fun(*args, **kwargs): start_time = time.time() f = func(*args, **kwargs) end_time = time.time() print('[INFO]:%s() run time:%ss' % (func.__name__, end_time - start_time)) return f return call_fun
30879a8364106eb759922b63ae81319ed38dda34
585,392
def comp(current_command): """Return comp Mnemonic of current C-Command""" #remove the dest part of command if exists (part before =) command_without_dest = current_command.split("=")[-1] #remove jump part of command if exists (part after ;) comp_command = command_without_dest.split(";")[0] return comp_command
1da3cf0070669a584c84050acf154a65f697686b
177,428
import itertools def groupby(iterable, keyfunc): """ Group iterable by keyfunc :param iterable: iterable obj :param keyfunc: group by keyfunc :return: dict {<keyfunc result>: [item1, item2]} """ data = sorted(iterable, key=keyfunc) return { k: list(g) for k, g in itertools.groupby(data, keyfunc) }
8d695e0a03256fc5042eb75cad613e62c6dea89d
503,170
import hashlib def md5(filename: str) -> str: """Generate the md5 hash for a file with given filename. :param filename: Name of the file to generate the MD5 hash for. :return: md5 hash of the file. """ hash = hashlib.md5() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash.update(chunk) return hash.hexdigest()
c9cafcf15e9e10b802f3da7efee39f251252de22
412,894
import calendar def DateTimeToTimestamp(value): """Returns an integer timestamp from a datetime. Args: value: The datetime to convert. Returns: An integer representing the number of seconds since the epoch. """ return int(calendar.timegm(value.timetuple()))
01d722ddc5a1e80f00886bbc733a706b5a9f7e81
359,182
import random def random_partitioner(stream_record): """Generate a random partition_key.""" random_key = str(random.randint(0, 10**12)) return random_key
09091b57f3f0908970457910d003a155108fbd29
138,189
def red_channel(image): """Return the red channel.""" return image[:, :, 0]
d07be3edc46d96f3e96f7816a92834282a5f4445
141,732
import torch def unsorted_segment_sum(data, segment_ids, num_segments): """ Computes the sum along segments of a tensor. Similar to tf.unsorted_segment_sum, but only supports 1-D indices. :param data: A tensor whose segments are to be summed. :param segment_ids: The 1-D segment indices tensor. :param num_segments: The number of segments. :return: A tensor of same data type as the data argument. """ assert ( len(segment_ids.shape) == 1 and segment_ids.shape[0] == data.shape[0] ) segment_ids = segment_ids.view( segment_ids.shape[0], *((1,) * len(data.shape[1:])) ) segment_ids = segment_ids.expand(data.shape) shape = [num_segments] + list(data.shape[1:]) tensor = ( torch.zeros(*shape, device=segment_ids.device) .scatter_add_(0, segment_ids, data.float()) ) tensor = tensor.type(data.dtype) return tensor
4777e5dfe0edd1c5918ab53b600e930a84753c3a
68,838
from typing import Tuple def _convergent(continued_fractions: Tuple[int, ...],) -> Tuple[int, int]: """Get the convergent for a given continued fractions sequence of integers :param continued_fractions: Tuple representation of continued fraction :return: reduced continued fraction representation of convergent """ num, den = 1, 0 for u in reversed(continued_fractions): num, den = den + num * u, num return num, den
c5263b5046e07fb9b19f20ede2080112013bbe4f
652,523
def normalise(array, nodata): """Sets pixels with nodata value to zero then normalises each channel to between 0 and 1""" array[array == nodata] = 0 return (array - array.min(axis=(1, 2))[:, None, None]) / ( (array.max(axis=(1, 2)) - array.min(axis=(1, 2)))[:, None, None])
fecae49ba376095d3636d1b4e944d1c19d79da31
300,240
def days_in_minutes(days): """ Returns int minutes for float DAYS. """ return days * 60 * 24
37f464879e45ea7f183a50ce5a394564b636753e
620,503
def alphabet_position(letter): """Returns an index number based on the passed letter's position in the alphabet""" mapping = "abcdefghijklmnopqrstuvwxyz" ind = mapping.index(letter) return ind
bf9ac53878a88249c7d018ca432cb7add57940b8
317,299
import requests import time def post_grafana_annotation(grafana_url, grafana_api_key, tags, text): """ Create annotation in a grafana instance. """ return requests.post( grafana_url + "/api/annotations", json={ 'tags': tags, 'text': text, 'time': int(time.time() * 1000), 'isRegion': False }, headers={ 'Authorization': f'Bearer {grafana_api_key}' } ).text
0b925725384dedd73d6260e8b1099de192b4f903
441,142
def extract_ranges(dfi): """Extract example ranges """ ranges = dfi[['example_chrom', 'example_start', 'example_end', 'example_idx']].drop_duplicates() ranges.columns = ['chrom', 'start', 'end', 'example_idx'] return ranges
2fa01976b5f1ea8da76ea9175eeb8a036015c7e9
194,589
def format_gro_coord(resid, resname, aname, seqno, xyz): """ Print a line in accordance with .gro file format, with six decimal points of precision Nine decimal points of precision are necessary to get forces below 1e-3 kJ/mol/nm. @param[in] resid The number of the residue that the atom belongs to @param[in] resname The name of the residue that the atom belongs to @param[in] aname The name of the atom @param[in] seqno The sequential number of the atom @param[in] xyz A 3-element array containing x, y, z coordinates of that atom """ return "%5i%-5s%5s%5i % 13.9f % 13.9f % 13.9f" % (resid,resname,aname,seqno,xyz[0],xyz[1],xyz[2])
ceeeeeafe4f7484fa17ee4ebd79363209c8f7391
708,895
def multiGF8( input1, input2, modP8): """ multiGF8 - multiply 2 number on a Galois Field defined by a polynomial. Args: input1: first number to multiply. input2: second number to multiply. modP8: polynomial defining the Galos Field. Returns: the multiplication result. """ state1 = 0x0 for i in range(8): #print( 'i: {:2x}, input1: {:4x}, input2: {:4x}, state1: {:4x}' # ''.format(i,input1,input2,state1)) if input2&0x1: state1 ^= input1 input2 >>= 1 input1 <<= 1 if input1&0x100: input1 ^= modP8 return state1
cd11d536639fc0c80ef15240b83ff5833ea6ff73
287,834
def make_message(article: dict, hashtags: str) -> str: """ Action: make Telegram message from API response :param article: dictionary from API response with individual article data :param hashtags: list of hashtags, inserted at the end of the channel message :return: string with assembled individual article info (title, abstract, hashtags, web link) """ title = article['title'] abstract = article['abstract'] link_web = article['url'][0]['value'] return f'\n*{title}*\n\n{abstract}\n\n{hashtags}\n\n*Link:*\n{link_web}'
325708ca457f688840efe4a65046fad3e2f15d11
189,787
from typing import Any def is_reference(key: Any) -> bool: """Is this key a reference to output from elsewhere in the chores. A reference has the form ^chore(.output)? where `chore` is the name of the node you are consuming output from and `output` is either a name or a number to tell which part of the output to take. :param key: A key to test :returns: `True` if its a reference """ return isinstance(key, str) and key.startswith('^')
4e68a9903c57435ff73b7f652a8d6d9efded5ca9
616,164
def captioned_button(req, symbol, text): """Return symbol and text or only symbol, according to user preferences.""" return symbol if req.session.get('ui.use_symbols') \ else u'%s %s' % (symbol, text)
b2f4be2fe0dac6b0d0b90ca91d00a625d674517c
600,190
def class_name(obj): """Returns the class name of the specified object. """ return obj.__class__.__name__
83b6b4beb2277b1c6ee8e78824bff5b95fda401c
543,134