content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_num_examples(data): """ Gets number of examples in a data dictionary and asserts each is equal. """ lengths = [] for k, v in data.items(): lengths.append(len(v)) assert all(length == lengths[0] for length in lengths) return lengths[0]
1de9a184b7575499a1139f50c2ad4879fb759459
580,061
import random def get_random(floor, ceiling): """ Helper function to get a random number. """ return random.randrange(floor, ceiling + 1)
c1842389e6021fcd75a71208470755e32c7b779c
580,064
import copy def sacred_copy(o): """Perform a deep copy on nested dictionaries and lists. If `d` is an instance of dict or list, copies `d` to a dict or list where the values are recursively copied using `sacred_copy`. Otherwise, `d` is copied using `copy.deepcopy`. Note this intentionally loses subcl...
31f03a985ccf9a483869ccc2ffd7b4ba078dabec
580,065
def id(process, longname, flag, value): """Identity function: returns value""" return value
458232c673dac7b2e6767a6483486e057e04cf60
580,066
import re def get_product_class(satellite_name, product_name): """ Set Product Class, processing level and product type from the acquisition identifier Only being done for Sentinel 1A and 1B acquisitions For others, they are set to None TO DO: Currently this is done only for Sentinel acquisitions...
70d473f9ead8d2e4290e6f71f56feb375a0f4f31
580,070
def photon_generation(wave_len, energy): """Determine number of photons in a bundle Parameters ---------- wave_len : float Wavelength associated with a particular bundle energy : float Energy in a bundle Returns ------- nphoton : float Number of photons in a...
c0b1aa263ec81e16b37314b9506b0a2456aa8dfa
580,082
def dict2opts(d): """ Turns a dictionary into a list of strings representing command-line options. Keys of the dictionary should already be in option format, i.e. with leading hyphens. Values are arguments of options. None values should be used for options without arguments. Options with multiple argu...
a7df19b3b5eb8d13c93d0d24e051b156877e50fa
580,083
from typing import Optional async def check_name_and_abbreviation( db, ref_id: str, name: Optional[str] = None, abbreviation: Optional[str] = None ) -> Optional[str]: """ Check of an OTU name and abbreviation are already in use. Returns an error message if the ``name`` or ``abbreviation`` are already...
001b834a73a619e1f08d6d1333d31be832c13e87
580,090
def add_main_category(row, categories_dict): """ Add the item's main category to the row :param row: A dict containing metadata for one item :param categories_dict: A dict mapping subcategories to main categories, as a Spark broadcast variable :return: A dict containing the original data plus th...
270e29525d06bb22a224ddb9d6e4ecd47c264ce2
580,091
def freq_seq_chars(counts): """Calculate frequencies of characters (symbols) in a sequence based on characters' counts. Args: counts (list): result of the `count_seq_chars` function seqlen (int): length of a sequence Returns: A list of frequencies corresponding to alphabet E...
107dffc4594f874e384416f662e357b373abba58
580,097
from typing import Any def set_placeholder(field: Any, text: str) -> Any: """ Pass a Django form field and set a placeholder widget attribute, HTML Input with placeholder attribute with value as text passed Args: field: Django form field (usually a CharField), this nee...
0f292b4545bf8db53aee8453f94438efc920d84e
580,098
import math def cbrt(x): """Returns the cube root of x.""" if x >= 0: return math.pow(x, 1.0 / 3.0) else: return -math.pow(abs(x), 1.0 / 3.0)
63faeaf946b506baa8379dac6b80b6599a117709
580,101
def get_default_redirect(request, fallback_url, redirect_field_name="next", session_key_value="redirect_to"): """ Returns the URL to be used in login procedures by looking at different values in the following order: - a REQUEST value, GET or POST, named "next" by default. - LOGIN_REDIRECT_URL -...
818cd6c4c12ce497ca65cc249cccf53f4c04009a
580,106
import requests def get_all_subgroups(groupsio_token): """ Returns a dictionary where keys are subgroup ids and values are subgroup names """ MAX_GROUPS=100 url = 'https://api.groups.io/v1/getsubgroups' key = groupsio_token data = [ ('group_name','dcppc'), ('limit',MAX_G...
b20dc3354d1fa8ac634ec2d3c79e6ff48dc0cd3d
580,107
import re def mainpart (path): """ Removes typical strings from file names of ultrasound files, which can be problematic for checking correspondence of ultrasound files, e.g. 'xxx_Track0' --> 'xxx'. """ rmvs = ['_Track[0-9]+$', 'US$', '_corrected'] for i in rmvs: path = re.sub(i, '...
8dad62eefaa87505271381f8cb000aeb9de3bdb9
580,110
from functools import reduce def deep_get(dictionary, *keys): """Deeply gets a key sequence from a dictionary. Gets a key sequence from a nested dictionary or returns `None` if the key sequence doesn't exist. :param dictionary: The dictionary to get from :type dictionary: dict :param *keys: T...
e539abe3e20f8edb0b0ce9cdaab7a6a3c75c2b37
580,113
from typing import Dict from typing import Any def GetAttributeCount(dict_term: Dict[str, Any]) -> int: """Calculate the attribute count of a term in its dictionary form. The attribute count of a rule is the sum of the number of ports, protocols, IP ranges, tags and target service account. Note: The goal of...
b5792a02dac956f437825b232638dec575f27180
580,115
import torch def right_shift_to_zero(x, bits): """Right shift with quantization towards zero implementation. Parameters ---------- x : torch.int32 or torch.int64 input tensor. bits : int number of bits to shift. Returns ------- torch.int32 or torch.int64 right...
c83ffdec97dfc57c7f44e14467495b7105cb969a
580,119
def replicate_multilabel_document(document_tuple): """ Takes a document and a set of labels and returns multiple copies of that document - each with a single label For example, if we pass ('foo', ['a', 'b']) to this function, then it will return [ ('foo', 'a'), ('foo', 'b') ] :param document_tu...
947363515ec95ae11af1024690b2412b204859ef
580,121
import re def str_cleaner(data_array, column_name): """Clean up formatting of technology description strings in imported data. In the imported EIA data, the strings that describe the technology and performance level have inconsistent formatting and often have leading or trailing spaces that make late...
d765e4a17bb6f2b32f5b3373baa3ac5c03a92b14
580,122
def get_positive_axis(axis, ndims, axis_name="axis", ndims_name="ndims"): """Validate an `axis` parameter, and normalize it to be positive. If `ndims` is known (i.e., not `None`), then check that `axis` is in the range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or `axis + ndims` (otherwise). If `...
33f21bc3522cb431bdb8c2e0f70dfc7b53882195
580,124
def base26int(s, _start=1 - ord('A')): """Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799 """ return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
d45999b4f09dd76c802fc3ae8065fb80770350a2
580,126
def affine(x, W, b): """Apply affine transformation to `x` by computing `Wx + b` and return a list with the dimensions of `b`. Args: x (list): List that is to be transformed. 1 dimensional. W (list): List representing the transformation. 2 dimensional. b (list): List that is added t...
eec8b62e031a357c48c2505d265fda94b26638c8
580,127
def normalize_data(train_data, test_data): """Normalize features with different scales and ranges. Subtract the mean of the feature and divide by the standard deviation. Test data is *not* used when calculating the mean and std. Args: train_data: (numpy.darray) Training data. test_data: (numpy.darray) Testing...
23c2f20eb3ca097aaedd793adb185e219d04bcf4
580,128
def get_pg_config() -> dict: """ Ask DB connections params""" host = input('host: ') db = input('db: ') user = input('user: ') password = input('password: ') return { "PG_PROPERTIES": { "user": user, "password": password, "driver": "org.postgresql.Driver" }, ...
0800eee1223f5582e776f5e602785eedd07d996f
580,136
def joint_map(*mappings): """ Combine multiple `field_map` and `property_map` instances together to map an attribute to multiple API fields. Note: when "getting", the first one will be used. When "setting", they will all be set in parallel. """ def fget(self): return mappings[0].fget(self) ...
1a7897cf32e7d6f60154f15e3fe7638f2781f91f
580,138
def postprocess_for_cse(expr, optimizations): """ Postprocess an expression after common subexpression elimination to return the expression to canonical sympy form. Parameters ---------- expr : sympy expression The target expression to transform. optimizations : list of (callable, calla...
f80acee2822f8dc252d56347131d7cac565fbe78
580,141
def knots2ms(knots: float) -> float: """ Convert knots to meters per second. :param float knots: knots :return: speed in m/s :rtype: float """ if not isinstance(knots, (float, int)): return 0 return knots * 0.5144447324
b6c39606cb37cc72fe30d4ae5cabf34c76a7845e
580,142
def _param_station_data(ds, param, date): """ Return station measurements including station x, y and z coordinates for one or more given parameter(s) and a specified date. Parameters ---------- ds : xr.Dataset Dataset containing the station measurements (i.e. the model.meteo var...
0f616e9f416990cba1fc61a0c44b5fead15f691b
580,145
def annotate_graph(g, annots): """ Add node annotations to graph from annots nodes without a value recieve None type. :param g: networkx graph :type: networkx.Graph :param annots: dictionary with node annotations :type: dictionary :returns g: graph with node annotations """ la...
1b89f1826efa1ae6cb310577039cca4a7d017d25
580,149
def bubble_sort(arr: list) -> list: """ Sort a list to non-decreasing order using bubble sort :param arr: list :return: sorted list """ n = len(arr) for i in range(n-1): for j in range(n-1-i): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] r...
26fef2af7fd423169a0490a02b05cd0556716c0c
580,150
def select_residues(frame, residue_name): """Get indices for residues based on a name.""" index = [] for i, residue in enumerate(frame['residuname']): if residue == residue_name: index.append(i) return index
37248144b599602ce54f84f351cf7118e1871b38
580,155
def b_string_to_bytes(b_str: str) -> bytes: """ converts a string containing a bytes literal (ex: 'b"something"') to bytes. """ return b_str[2:-1].encode()
ad95a19396a5210b1801613dd6c560b4f29880be
580,156
def stringify_options(config): """Convert config dict to params for gsevol, like: opt=val;opt2=val2 """ opts = [] for opt, value in config.items(): opts.append("%s=%s" % (opt, value)) return ";".join(opts)
664ecbbd48ca868bff5f2632954cad0916be3346
580,159
from typing import Sequence from typing import Tuple def _extend_nc(spatial_slice: Sequence[slice]) -> Tuple[slice, ...]: """Extend a spatial slice ([D,] H, W) to also include the non-spatial (N, C) dims.""" # Slice everything in N and C dims (equivalent to [:, :] in direct notation) nonspatial_slice = [s...
4110d19eb6d297584e8eed76b0f2cf1ec561e63f
580,160
def get_min_x_y_coord(city): """ Returns min x- and y-coordinates as tuple, found within city object. Requires position parameter (shapely point) on every node! Parameters ---------- city : object City object of pycity_calc Returns ------- tuple_min : tuple (of floats) ...
c5009b20fd65f494ad9eb6578767761f69bb9428
580,161
def get_headers(context_data) -> list: """ Arrange the headers by importance - 'name' and 'id' will appear first Args: context_data: list or dict containing the context data Returns: headers arrange by importance """ if isinstance(context_data, dict): context_data = [context_da...
a466d6c10070c4d2e7296a79f1e514d45d37901d
580,162
def one_item_list(request): """ Fixture that yields one item lists. """ return request.param
e0b4f0c2987d8a2d9becb2a29daf0dd6b66d8f87
580,168
def make_pairs_by_mask(mask): """Given a 1d `mask` of size (n), generate a 2d tensor `out_mask` of size (n, n) such that `out_mask[i, j] = mask[i] and mask[j]`. Args: mask (BoolTensor): 1d tensor of size n. Returns: out_mask (BoolTensor): 2d tensor of size (n, n) where n is the dim of ...
8a37c5b77d9187987caee2681922e7866b57d0c3
580,172
def check_image_type(image, type): """Check if image 'type' property matches passed-in type. If image has no 'type' property' return True, as we cannot be sure what type of image it is. """ return (image.properties.get('type', type) == type)
ae598129a520ab9028fbcf2f9fc73b862974ec6f
580,174
def get_survival_probability(init_rate, block_num, total_blocks): """Get survival probability based on block number and initial rate.""" return init_rate * float(block_num) / total_blocks
927974db12e787275a628cbea9a6e0ba600abb7d
580,177
def is_odd(nr): """Confirms that a number is odd Args: nr (float): the number Returns: bool: True if the number is odd, False otherwise """ if nr % 2 == 0: return False else: return True
5ca2f0d69f9472a3810c956cfce91dcb6ccb315a
580,179
from typing import Tuple def zone_to_seat(zone: str) -> Tuple[int, int]: """convert the zone code into a seat number given by (row, col)""" replacements = [("F", "0"), ("B", "1"), ("L", "0"), ("R", "1")] for old, new in replacements: zone = zone.replace(old, new) return int(zone[:7], base=2),...
353ccf3d1bdfcc3c0bc7327bbffd73d36425841d
580,184
def isatty(stream): """Check if a stream is a tty. Not all file-like objects implement the `isatty` method. """ fn = getattr(stream, 'isatty', None) if fn is None: return False return fn()
3498d6694a602c95efb2e2268c424e5333f38c9d
580,188
def getVarType(line) -> str: """ Gets the type from a given string and returns it as str """ l = line.strip().split(' ') if l[0].startswith("@"): if l[0].startswith("@var"): return l[1].strip() else: return "META" elif l[0].startswith("--"): return "ROOT"...
d36bfbcb54707c041c1a77101fce9f28d0a3aaa3
580,189
def get_query(path: str = "../data/my_food.txt") -> str: """ Used to get a comma-separated string of ingredients from a file to use as a query for Spoonacular's API (assuming defaults in this script are used). The type of data used here can vary depending on which Spoonacular endpoint the user wishes to...
d5acbd589b49eff5cce58b03899654b4b5104e8c
580,191
import re def is_256b_hex_str(value): """ Checks if a given value is a 32-byte hex encoded string. Args: value(:mod:`str`): the value to be checked. Returns: :obj:`bool`: Whether or not the value matches the format. """ return isinstance(value, str) and re.match(r"^[0-9A-Fa-f...
34f8d8d0aa72f620d48f717131b57cf6d82b4866
580,193
from typing import List import torch def get_gpus_for_rank(world_size: int) -> List[List[int]]: """This will return a list, each element of which contains a list of GPUs to be used by the respective process. Examples (results are shown for a machine with 2 GPUs): >>> get_gpus_for_rank(2) # [[0]...
6fb375a26e72ff3197140f8b153c806c892cc8eb
580,194
def scopes_to_string(scopes): """Converts scope value to a string suitable for sending to OAuth 2.0 authorization servers. Args: scopes (Sequence[str]): The sequence of scopes to convert. Returns: str: The scopes formatted as a single string. """ return ' '.join(scopes)
52ce2b601fb02d41c87f9eee8ec4aa65949fd462
580,206
def logged_in(request): """Jinja2 filter that checks if the current user is logged in.""" return request.current_user is not None
458b6b48d63891c2988252ef5d8b8b0706fbd627
580,209
def max_number(number: int) -> int: """Returns number starting from the largest item. Args: number (int): input number Examples: >>> assert max_number(132) == 321 """ return int("".join(sorted(tuple(str(number)), reverse=True)))
2da3c9fb139d971cc794733112a2340675631e9e
580,211
def list_in_string(char_list: list[str], text: str): """Returns true if all input characters are in the given text""" return all(c in text for c in char_list)
3122dda55978e9486554aaf9df88f21b7a0b1f71
580,215
import re def remove_tracebacks(body: str): """Removes python tracebacks from the string.""" regex = re.compile( r''' # A line that says "Traceback (...):" ^Traceback[^\n]*:\n # Followed by lines that begin with whitespace. ((\s.*)?\n)*''', re.MULTILINE | re.VERBOSE) retu...
7ed302c5c98e767c6604c9eeb82d476ed2417358
580,216
def contains_all(string, matches): """ Determine if a string contains all of the given values. """ return all([m in string for m in matches])
4d38b0d7210b8f8a34622fc1bb641d10dd079e4e
580,218
import re def make_url_tags(line: str) -> str: """Find URLs in string and replace them with <a> tags.""" return re.sub( r""" ( (?:http://|https://|ftp://|mailto:|news:|irc:) [^\s<>()"]*? (?:\([^\s<>()"]*?\)[^\s<>()"]*?)*) ((?:...
bb5030a1c9915a42e1b84c52524760eb9278be9d
580,222
from typing import Mapping from typing import Optional from typing import Callable from typing import Tuple from typing import Any from typing import Iterable from typing import Hashable def mapping_repr( mapping: Mapping, prefix: str = "{", template: str = "{key}: {value}", separator: str = ", ", ...
9a59c1b80cc8b89e87965ac26043c265081eda02
580,224
def calculate_overlap(info): """Returns the overlap length of the base and the check sequences.""" overlap = 0 base_start = info['base']['start'] base_end = info['base']['end'] check_start = info['check']['start'] check_end = info['check']['end'] # Calculate the overlap based on the relativ...
d0148d912cb474c0b67379a83fab2ebe2a7c0449
580,225
def _interval_contains_close(interval, val, rtol=1e-10): """ Check, inclusively, whether an interval includes a given value, with the interval expanded by a small tolerance to admit floating point errors. Parameters ---------- interval : (float, float) The endpoints of the interval. ...
a9a7588da4e62ddf1ac9db0e971879cbdff3d6bf
580,227
def get_repeated_command(command: str): """ Functionality: Repeats a given string. Out of precaution, " " are put around the string to make sure the text always has at least some context. Maybe this is a bit too much, but for the time being, this is how it is. Parame...
53f37984426202fb2e8b4b4c453762f6700d2323
580,231
import math def to_dms(value, absolute=False): """ Split a float value into DMS (degree, minute, second) parts :param value - Float value to split :param absolute - Obtain the absolute value :return tuple containing DMS values """ invert = not absolute and value < 0 value = abs(value)...
94bc5137ab8b864421c3d9d7fb3883259426211b
580,234
def ndwi_mcfeeters(b3, b8): """ Normalized Difference Water Index (McFeeters, 1996). .. math:: NDWI = (b3 - b8)/(b3 + b8) :param b3: Green. :type b3: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns NDWI: Index value .. Tip:: McFeeters, S....
93e0180ae7973fbb53646dc84de51ba866b4f424
580,247
def get_year(file, type = 'Sales'): """ Arguments: file: filename type: 'Sales' or 'Ann' (see below) Get year a particular file corresponds to Will throw error if not an annual file if type = 'Sales': the last half of the filename is the year. Use type = 'Sales' if in Retail ...
e7e30050b2add426bdc136ee7881b8544eeeea37
580,248
def num_parameters(network): """ returns the number of "parameter"s in a network """ vws = network.relative_network().find_vws_in_subtree(tags=["parameter"]) return sum(vw.value.size for vw in vws)
92ad7bdf210400590f124b0f41b3e0e478b073d8
580,253
def get_code ( x, code_out, code_in ): """Convert from one coding to another :Parameters: *x* input to be coded *code_out* desired code of the output *code_in* code of the input :Example: >>> code_out = [-1,1] >>> code_in = [0,1] >>>...
daa63d5234c2cd4b8dba18ec1b8a66df0810967f
580,256
def apply_transparency(color, alpha): """Apply transparency level to given color in RGB format.""" return (color & 0xFFFFFF00) | (alpha)
0aafdc7ede3024a015ddf6576e30987be259cf62
580,265
from typing import Sequence from typing import Any def format_array(array: Sequence[Any], fmt: str) -> str: """Convert `array` to string with format `fmt` for each entry.""" return "[" + ", ".join(fmt.format(elem) for elem in array) + "]"
579bcb1c863df7806f673e927086756f9333bcf1
580,266
def hw(target): """ Returns the Hamming Weight of the input target. """ return bin(target).count("1")
bbef94d4c9acd9c6ffebf09ae76e6f45352af55c
580,268
import math def temporary_magnitude_quantity_reverse(C, J, n): """ Returns the temporary magnitude quantity :math:`t`. for reverse *CIECAM02* implementation. Parameters ---------- C : numeric *Chroma* correlate :math:`C`. J : numeric *Lightness* correlate :math:`J`. n ...
c83034b95580dedd2dd39e62f89eea7185125c12
580,270
def remove_file_from_tree(tree, file_path): """Remove a file from a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of a file to remove from a tree. Returns: The provided tree, but with the item matching the s...
7c22a7af4838fdb2a4c17916797c95829a1ae3bb
580,274
from pathlib import Path from click.testing import CliRunner def runner_with_args_and_paths(tmp_path: Path): """ wrap up some things used for click testing """ runner = CliRunner() workdir = tmp_path / "work" output = tmp_path / "output" args = ["--workdir", str(workdir), "--output", str(outpu...
8ca08f08cc2a81ec97dcb12e06e2154317377619
580,276
def _get_or_create_subgenre_node(subgenre_name, taxonomy_graph, main_genre_node): """ Return the node for the subgenre if it exists, otherwise create a new node and make it a child of the given main genre node. """ if subgenre_name in taxonomy_graph: subgenre_node = taxonomy_graph.get_node(s...
823c806e3bb832d93e8f7b94e192d4317565f526
580,280
def _get_column_nums_from_args(columns): """Turn column inputs from user into list of simple numbers. Inputs can be: - individual number: 1 - range: 1-3 - comma separated list: 1,2,3,4-6 """ nums = [] for c in columns: for p in c.split(','): p = p.strip() ...
dfba0ac16bba1a3ae1fd59261670318964220ab4
580,282
def calculate_health(bunch_percentage, gap_percentage, on_time_percentage): """ Calculates an average of 3 main statistics, returns a float (does not use coverage since that is already dependent on on-time and bunches) Arguments: bunch_percentage (float): the bunched percentage score ...
4dc9a9f4a9de614ba1165b07e42434834e118e2e
580,285
import struct def read_plain_int32(file_obj, count): """Read `count` 32-bit ints using the plain encoding.""" length = 4 * count data = file_obj.read(length) if len(data) != length: raise EOFError("Expected {} bytes but got {} bytes".format(length, len(data))) res = struct.unpack("<{}i".fo...
b7edb9114d27cead7af05430287cf8cdd928e78a
580,288
def apply_single_mapping(strings, mapping): """Apply letter mapping to a list of strings.""" new_strings = [] for str in strings: curr_str = '' for l in str: curr_str += mapping.get(l, l) new_strings.append(curr_str) return new_strings
83bb8546470c06c356d66f56e29f2ef42fa6c2e5
580,289
import base64 def _auth_header(username, password): """return the value part of an Authorization: header for basic auth with the specified username and password""" return b"Basic " + base64.b64encode(username + b":" + password)
83ce29513993bea0185b209a6cb6b4d9beb9ee3a
580,291
def is_tile(*tiles): """Return a predicate function for `find()` that will find all coordinates containing one of `tiles`.""" tiles = set(tiles) def predicate(tile_map, coord): tile = tile_map[coord] return (tile in tiles) return predicate
a8372a2ee8fa3c3b23dc246365330ea32adbdea8
580,297
import copy def filter_comments(tree): """Filter comment nodes from parsed configurations.""" def traverse(tree): """Generator dropping comment nodes""" for entry in tree: key, values = entry if isinstance(key, list): new = copy.deepcopy(entry) ...
2766d91b189019e844883a6e09093267342e833d
580,298
from typing import List import random def choose_seq_indices( input_seqs: int, proportion: float = 1.0, max_records: int = 10000) -> List[int]: """Generate a list seq indices. Args: input_seq (int): number of input_sequences proportion (float): proportion of seqs to extract ...
abc47c52361a02481e55e81f093052e5e5465f29
580,302
def molecule_cartesian_coordinates_mapping( molecule, symmop ): """ Maps the coordinates of pymatgen ``Molecule`` according to a ``SymmOp`` symmetry operation. Args: molecule (``Structure``): The pymatgen ``Molecule``. symmop (``SymmOp``): The pymatgen symmetry operation object. ...
f4bff9ccdaf3156f49eac60aa923c264c686b8e2
580,304
def _to_swarming_dimensions(dims): """Converts dimensions from buildbucket format to swarming format.""" return [ {'key': key, 'value': value} for key, value in (s.split(':', 1) for s in dims) ]
711c09d786cd6728fd46f81a5253090925cedfc2
580,305
def type_name(type_: type) -> str: """Convert a type object to a string in a consistent manner. :param type_: the type object to convert :return: a string with the type name """ type_qualname = type_.__qualname__ type_module = type_.__module__ if type_module not in ("__main__", "builtins"):...
2e1a5626ec7e4c11e57cb9e80d4916ecc9c6c7e5
580,309
import torch def cam2pix(cam_pts: torch.Tensor, intrinsics: torch.Tensor) -> torch.Tensor: """ Convert points in camera coordinate to pixel coordinates :param cam_pts: Points in camera coordinates, (N,3). :param intrinsics: Vamera intrinsics, (3,3). :return: Pixel coordinate (u,v) cooresponding t...
0ebc361488a7f4f5da85ddc904a972970cbd2df7
580,310
from typing import Dict from typing import Union from typing import Tuple from typing import Optional from typing import Callable from typing import Any def get_nested_dict_value_by_path(nest_dict: Dict, path: Union[Tuple, str], cast: Optional[Callab...
8011fcd5f452d72d342f096621b6bb11218ebeae
580,312
def skipUrl(url): """Check if a given url needs to be skipped by default e.g. mailto: or tel: urls or in-page links""" url = url.strip() if url.startswith("tel:") or url.startswith("mailto:") or url.startswith("#"): return True return False
2fabcbe7851322fa83ec6618aa3dd7b7892a6eea
580,314
def reshape_to_n_steps(raw_mat, num_steps): """ Reshapes provided data from (positions * step, bin) to (positions, step * bin). Use this to restructure data back to its original form after parallel computing Parameters -------------- raw_mat : 2D numpy array Data organized as (positions...
c7e5246dc171e5edf1ae44d4df4174f6d0509456
580,315
def reverse(value): """Reverse int/float values.""" reversed_str = str(value)[::-1] if type(value) == int: return int(reversed_str) elif type(value) == float: return float(reversed_str) else: raise ValueError(f'Reverse does not support type {type(value)}')
0805d4a0a465c60cb6d947e88e9b4c8fdc019c82
580,322
async def websocket_lovelace_config(hass, connection, msg, config): """Send Lovelace UI config over WebSocket configuration.""" return await config.async_load(msg["force"])
a09b92334c93d7c4603a566939a643dcffcaba57
580,327
def find_mean(arr: list) -> float: """Finds the average of a given list""" return sum(arr) / len(arr) if len(arr) > 0 else 0
876d1c60adf05c3f88bec057f537b756c63c57cf
580,328
def get_url_entry_by_submit_type(submit_type, given_url, sample): """ Args: submit_type (int) : SubmitType argument (can be one of those: 0,1,2,3) given_url (str) : a url if SubmitType arg is 2, None otherwise. sample (str) : a url (if SubmitType is 1 or 3 ) or a file ent...
9048d51db95c9ed1a9a4df137a7e585ccaf392ac
580,329
def execute_path(path,controller,speed=1.0,smoothing=None,activeDofs=None): """Sends an untimed trajectory on a controller. Arguments: - path: a list of milestones - controller: a SimRobotController - smoothing: any smoothing applied to the path. Valid values are: * None: starts / stops at each milestone, mo...
a29a012610d67cfdb03f209d429f304580b4c241
580,331
def get_job_name(table_name: str, incremental_load: bool) -> str: """Creates the job name for the beam pipeline. Pipelines with the same name cannot run simultaneously. Args: table_name: a dataset.table name like 'base.scan_echo' incremental_load: boolean. whether the job is incremental. Returns: ...
37509b2165c597426e8264ad7cb3f0ccc0dc020f
580,332
def translate_severity(severity): """ Translate from Jask insight severity to Demisto severity """ if severity <= 4: return severity return 4
3ccc974c0c412f68db99f3bf753b957de19a8848
580,338
def transpose (tickets): """Returns the transpose of `tickets`, i.e. a grouping of fields for all `tickets`. """ return zip(*tickets)
eadf2faa5ea146317c88a81e2b80549b016a9be0
580,342
def add_txt_n_char(txt: str,char: str, length:int ) -> str: """Create a new string with char of length bookending txt.""" a = f'{char*length}' return f'{a}{txt}{a}'
365619adb79b4ffb41116aac864bf1402d71b8cf
580,343
import re def ensure_tensor_name_has_port(node_name): """Makes sure that a tensor name has :0 if no explicit port exists.""" m = re.search(r"(.*):\d+$", node_name) if m: name_with_port = node_name else: name_with_port = node_name + ":0" return name_with_port
b27d36c1dfcf84510bbd6e8ace4352cc8734b07f
580,344
def valid_filename(filename): """Check if filename is for a CSV file with no folder names.""" return not "/" in filename and filename.endswith(".csv")
c42832a8e9e624c78a0cba668b4700cfbba61910
580,345
def contains(item, elements): """Returns True if the item is contained in the list elements""" for element in elements: if item.equals(element): return True return False
af798aca9c89e17c016629b6ca8b98e2f6f98640
580,346
def str_clean(input: str, **kwargs) -> str: """ Cleans and encodes string for template replacemnt Keyword Arguments: replace_dual (bool, optional): Replace ``::`` with ``.`` Default ``True`` """ _replace_dual = bool(kwargs.get('replace_dual', True)) result = input if _replace_dual: ...
ecfe87ce1d272b2c05fec6515382e247484e2372
580,347
import requests from bs4 import BeautifulSoup def get_first_paragraphs(url): """ Request link `url` (str) and return the first paragraph or so, limited to the hard-coded number of characters. """ # Hard-coded: max_chars = 500 # Get wikipedia article: response = requests.get(url) ...
19d428d5e79062d04691d60f4ca986431c35f792
580,351