content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def multiproduct(seq=(), start=1): """ Return the product of a sequence of factors with multiplicities, times the value of the parameter ``start``. The input may be a sequence of (factor, exponent) pairs or a dict of such pairs. >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4 279936...
b1f40f1251e521e773f29355161f7c8b5c804b29
632,899
def make_comment(content: str) -> str: """Return a consistently formatted comment from the given `content` string. All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single space between the hash sign and the content. If `content` didn't start with a hash sign, one is provided. ...
1c83a1180493de6eca6c100d2e4d661a5e10e48f
632,900
def get_alphabet(number): """ Helper function to figure out alphabet of a particular number Remember: * ASCII for lower case 'a' = 97 * chr(num) returns ASCII character for a number e.g. chr(65) ==> 'A' """ return chr(number + 96)
dac98249de4b819d317922a0d390f1d84c3f338f
632,901
def make_doc1_url(court_id, pacer_doc_id, skip_attachment_page): """Make a doc1 URL. If skip_attachment_page is True, we replace the fourth digit with a 1 instead of a zero, which bypasses the attachment page. """ if skip_attachment_page and pacer_doc_id[3] == '0': # If the fourth digit is ...
ed1d37573632dfdafc3cd43255223e9e4fa474c6
632,903
import inspect from typing import Dict from typing import List def parse_method_signature( signature: inspect.Signature, param_dict: Dict[str, str] ) -> List[List[str]]: """Combines Signature with the contents of a param_dict to create rows for a parameter table. Args: signature: the output from ...
91e333a6ac37e938fdadadb7d47f312d3c43edb3
632,907
def part_one(password_list): """Count the number of passwords that meet their accompanying criteria. In this case, a password must have a specified character occur between a minimum and maximum number of times. :param password_list: A list of tuples from parse_input :return: int """ valid_p...
864c41e786512f64a21d5522c7db5e6168366d9e
632,908
def create_stack( cfn_client, template_path, stack_name, params={}, capabilities=[], timeout=300, interval=30, ): """ Creates a cloudformation stack from a cloudformation template """ with open(template_path) as file: body = file.read() stack_params = [ ...
80608a4a04e70701bbc5c1628a4300b69aec7486
632,909
import random import string def letter(random=random, *args, **kwargs): """ Return a letter! >>> mock_random.seed(0) >>> letter(random=mock_random) 'a' >>> letter(random=mock_random) 'b' >>> letter(random=mock_random, capitalize=True) 'C' """ return random.choice(string.a...
22ffff88c32d34b1fb5afcb6bc87ed8ac1be9c9a
632,910
def get_list_as_str(list_to_convert): """Convert list into comma separated string, with each element enclosed in single quotes""" return ", ".join(["'{}'".format(list_item) for list_item in list_to_convert])
040ef0887e19a134c3ade513a880870cc4d50c5c
632,912
def flatten(children, sidx, lidx): """ Helper function used in Visitor to flatten and filter lists of lists """ ret = [children[sidx]] rest = children[lidx] if not isinstance(rest, list): rest = [rest] ret.extend(list(filter(bool, rest))) return ret
cafeeeca2c7d3b08cd68547814415b8024e6be08
632,914
from typing import Union from typing import NoReturn def _get_file_str(file: int) -> Union[str, NoReturn]: """Convert a given integer to a file letter on a chessboard.""" file_dict = { # Used for int to str lookup for files 0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h' } return file_dict[...
6c057a780792b26551825be72aa1553a2b80497d
632,915
def vars_to_dic(vars): """ Converts list of tf variables to a dictionary where the var names are the keys Args: vars: list of variables Returns: dic """ return dict((var.name.split(":")[0], i) for i, var in enumerate(vars))
0b74ac80c7d1b0018a7e5f1fe21596ef19fae2be
632,917
def all_routes(cities, i=0): """Return all possible routes, where cities[i:] have been permuted. Args: cities (list of string): The cities that make up each route. i (int, optional): The starting index of the subarray of cities to be permuted. Returns: list...
28a2616f1696f554f703eef7a3a059637a3b03b4
632,918
def _strip_h5(value: str) -> str: """ remove trailing .h5, if present """ if value.endswith(".h5"): value = value[:-3] return value
163d4b9f5d05ae0165cfb7d3b1e0fdbc7b3ca2a6
632,919
import torch def invariant_loss(x, y, symmetry): """ Finds permutation invariant loss, for fixed set of allowed permutations. Computes picking minimal loss under all permutations. Uses L2 loss. :param x: Input of shape (..., d) :param y: Output of shape (..., d) :param symmetry: Symmetry ...
7cbcbb2ba49757d940bbaf5bc9f5668c00a74b9d
632,920
def unique_edge_sizes(H): """A function that returns the unique edge sizes. Parameters ---------- H : Hypergraph object The hypergraph of interest Returns ------- list() The unique edge sizes """ return list({len(H.edges.members(edge)) for edge in H.edges})
cfa1bcca6f2e55f9986e1f81a23ab9d7c94fb464
632,925
def is_valid_str(s: str) -> bool: """ Check if the input string is not empty. :param s: Input string. :return: True if the string is not empty. """ if s is None: return False if not isinstance(s, str): return False if len(s) <= 0: return False return True
01dc8056d9e152cab4261a47c108b50853340f6e
632,926
def sem_to_minor(version): """ Returns a minor release part of the semantic version @param version: semantic version in format x.x.x @return: minor release in format x.x """ return ".".join(version.split(".")[:2])
da3399c4eae24cd3344035de7223766e266b4822
632,927
def _grid_location_equals(xarr,grid_location=None): """Return True when the xarr grid_location attribute is grid_location Parameters ---------- xarr : xarray.DataArray xarray dataarray which attributes should be tested. grid_location : str string describing the grid location : eg 'u'...
f5d849e5553ce61ecf2af3c60288c852a838ed8b
632,931
import logging def makeRecord(self, name, level, fn, lno, msg, args, exc_info, # noqa: N802 func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = logging.LogRecord(name, level, fn, lno, msg, args, e...
7ec82058a3b4efd2d8db0a4c070fcab1695ba80b
632,932
def set_chain(base, key_chain, value): """Sets a value in a chain of nested dictionaries. """ if base is None: base = {} cur = base n = len(key_chain) for i, key in enumerate(key_chain): if i + 1 < n: if key not in cur: cur[key] = {} cur = ...
420e279c963524af2895055783b59167569a9951
632,933
def multiply_sequences(seq1: list, seq2: list): """ A function to multiply two sequences and return the result seq1: A list of integers seq2: A list of integers returns: seq1 * seq2 as a list """ if len(seq1) == len(seq2): return [x * y for x, y in zip(seq1, seq2)] elif len(seq1)...
6106cd1585f101cb9c2507bb03b705043096bc5b
632,934
def reprojection(gdf, tgt_crs): """Reproject in given the GeoDataFrame. Args: gdf (geopandas.GeoDataFrame): GeoDataFrame of reprojection target. tgt_crs (int): EPSG code of target crs. Returns: geopandas.GeoDataFrame: Reprojected GeoDataFrame. """ gdf = gdf.to_crs(tgt_crs) ...
f84f465d3272e5f87e5ea1d9232ba63ee15b6cba
632,935
import torch def fix_K_camera(K, img_size=137): """Fix camera projection matrix. This changes a camera projection matrix that maps to [0, img_size] x [0, img_size] to one that maps to [-1, 1] x [-1, 1]. Args: K (np.ndarray): Camera projection matrix. img_size (float): Size of im...
96993d3625fb4f2952327b695e9f7e971473d23b
632,941
def get_bit(n: int, i: int) -> int: """ Description: Récupère le i-ème bit de n. Paramètres: n: {int} -- Le nombre à traiter i: {int} -- L'index du bit à récupérer Retourne: {int} -- 0 ou 1 Exemple: >>> get_bit(2, 0) 0 >>> get_bit(2, 1...
a51e3205757201a3dcaf5b8b234f48e9fc4741d9
632,945
import socket def unbracket_ipv6(address): """Remove a bracket around addresses if it is valid IPv6 Return it unchanged if it is a hostname or IPv4 address. """ if '[' in address and ']' in address: s = address[address.find("[") + 1:address.find("]")] try: socket.inet_pton...
bb8b902f89fbcbb8088fb264287ac18295ad4df0
632,948
import re def extract_version_changelog(changelog, version): """Extract the changelog for a particular version from the entire changelog.""" escaped_version = re.escape(version) pattern = rf"""(?m:^)# Data Hub API {escaped_version} \([0-9-]+\) (?P<content>.*?) (# Data Hub API|$)""" match = re.search...
b59990e6095014a7ea7b4f1ed09eb06f4141e0f4
632,951
def _create_indice(chip): """Account for missing indices (Duo and PrixPowr) and create them. Even if these indices do not actually exist, we still need one for relational data purposes. """ if not chip['game'] == 'bn4': # Nothing to do here. return chip['indice'] indice = ...
8c07ec1022a47ab59a80cc359715fedb320eb170
632,952
import math def get_dxy(region: tuple): """ Get the grid spacing size that will be used to open a grd file Note: h5py will crash when opening grd with less than 2^14 gridpoints, so keep dx and dy small enough relative to domain Parameters ---------- region : (min lon, max lon, min lat, ma...
ad89aa3975803fb5e50dd213d2a53d260437a98b
632,953
def extractDatSignerParts(dat, method="igo"): """ Parses and returns did index keystr from signer field value of dat as tuple (did, index, keystr) raises ValueError if fails parsing """ # get signer key from read data. assumes that resource is valid try: did, index = dat["signer"].rs...
7cf1e4f2e49f1d5d752ec377955d479e7d52820d
632,958
from pathlib import Path def get_name(path): """Gets the name of the dynophore trajectory without the .pml extension Args: path (str): File path to the dynophore trajectory Returns: str: dynophore_pml """ file = Path(path).stem return file
bef9912cc39702070d160839a9abd102c709deea
632,959
import torch def select_embs(embs, pred_cands, M): """Select the embeddings for the predicted indices. Args: embs: embedding tensor (M x K x H) pred_cands: indices into the K candidates to select (M) M: M Returns: selected embedding (M x H) """ return embs[torch.arange(M)...
9ac40cb87652bf1662be212845bfc4291ad99004
632,960
def get_uid_warning(uid: str) -> str: """ Returns the templated message for the warning of existing `UID`, while creating a `Student` """ uid_href = f"/students/{uid}/#:~:text={uid}" msg = f"Student with UID <a class=\"alert-link text-secondary font-weight-medium text-decoration-none\"\ ...
a701b6d42ca78e93121903251d5887155fb73835
632,963
def cdf_TPL(x, a, beta, b): """ Cumulative function for truncated power law. pdf(x) = (beta-1)/(a*(1-c^(beta-1))) * (a/x)^beta for a <= x <= b """ F = (1-(a/x)**(beta-1))/(1-(a/b)**(beta-1)) return F
15b735608b5cdb9f72843e4cbe1405c6b26c78c6
632,964
def remove_special_chars(text: str): """ Removes the special characters. :param text: text to be modified :return: modified data """ filtered = text.strip().replace('\'', '').replace('"', '').replace('”', '')\ .replace('–', '').replace('“', '').replace('!', '.').replace(...
d31ada108615416191a2b6e8307d775c119c600e
632,970
from typing import Dict import json def error_response(text: str = '', status_code: int = 400, content_type: str = 'text/html; charset=utf-8') -> Dict: """ Creates an error response with parameterizable values. :param text: Optional explanatory error text :type text: str :param status_code: Respo...
226285e5897c13c40d01ba36bd8d668218979845
632,982
def get_severity_detail(severity_detail): """ Retrieve details of severity related fields. :param severity_detail: severity details from response :return: severity detail :rtype: dict """ return { 'Combined': severity_detail.get('combined', ''), 'Overridden': severity_detail...
6b6f144815689070667cbf5beec2ea670b422360
632,984
def dirstats(path): """Get stats for the specified directory. Parameters ---------- path : Path Directory to calculate stats of. Returns ------- num_files : int Number of files under the directory (recursive). total_size : int Total size in bytes of all files un...
480ca90ed0d705c046a1fa53e4a4f868cb0bcd88
632,987
from typing import Dict def to_affiliations_list(dict_: Dict): """Convert affiliation dict into a list. :param dict_: affiliation dict. :return: affiliation list. """ l_ = [] for k, v in dict_.items(): v["members"] = list(v["members"]) v["members"].sort() if "count" i...
6c377cb3c682ee2bd5d304bb3321c005029afe43
632,988
def get_lawyer_id(obj): """ Returns string representing an lawyer object. Returns obj.organization if it exists, else returns concatenated obj.name_first + '|' + obj.name_last """ if obj.organization: return obj.organization try: return obj.name_first + '|' + obj.name_last ex...
32c55b001cf06e3b22e889ff079ccbcb834a27d5
632,989
def rosenbrock(x): """Rosenbrock test fitness function""" n = len(x) if n < 2: raise ValueError('dimension must be greater than one') return -sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(n-1))
3ffa6019c597bf6215015a8a0de444bfa17b410b
632,992
def model_name_to_rest(name): """Gets a name of a :mod:`atomx.models` and transforms it in the resource name for the atomx api. E.g.:: >>> assert model_name_to_rest('ConversionPixels') == 'conversion-pixels' >>> assert model_name_to_rest('OperatingSystem') == 'operating-system' >>> ...
95e54361caf0d5a5a537cc80e146dcf63bebc242
632,993
def geometricSeries(*, u_1: int, r: int, n: int) -> int: """Compute geometric series up to 'n', given initial value 'u_1' and common ratio 'r'.""" return (u_1 * n) if r == 1 else (u_1 * (u_1 ** n - 1) / (r - 1))
3739e460a61bc7bf2bd3d089176bd482a7f095e6
632,995
def _audience_condition_deserializer(obj_dict): """ Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match. """ return [ ...
e875cb939340bba1f83174a9f06bd862ce78d89b
632,996
def _use_ssl(addr): """Decide if SSL should be used for the given server address.""" if isinstance(addr, str): return addr.endswith(':993') return len(addr) == 2 and addr[1] == 993
3b3fc9fc73f5740678822ea27df04359421bf294
632,997
def sbr(data, weights): """Stolen Base Runs (SBR) SBR = runSB * SB + runCS * CS :param data: DataFrame or Series of player, team, or league totals :param weights: DataFrame or Series of linear weights :returns: Series of SBR values """ return weights["lw_sb"] * data["sb"] + weights["lw_cs"]...
f577dfa2955802a7cb7177f06f508d7902cbc60d
633,003
import json def already_run(db, configuration): """Checks whether the given configuration is already present in the database""" configuration = configuration.copy() configuration['threads'] = configuration.get('threads', 1) configuration['params']['threads'] = configuration.get('threads', 1) confi...
632deee051e789ed0cdb418ff23ff683db101522
633,004
def does_entry_exist(conn, tweet_id): """ Check weather entry with exact tweet_id already exists :param conn: DB connection :param tweet_id: tweet_id to check :return: True if story already in db, else False """ cur = conn.cursor() cur.execute("SELECT * FROM tweets WHERE tweet_id=?", (tweet_...
e14af8997cdf69df5b02f67baa90904e76316c6f
633,006
import re def check_list_name(name): """checks that list_name begins with an alphanumeric character Parameters ---------- name: string name of the new listing. Return ------ bool True if listing name conforms to requirements """ return re.search(r'^\w+', name) ...
4ce46453b6a0afa233569b171923a31e0ac3cacd
633,009
def total_norm(tensors, norm_type=2): """ Computes total norm of the tensors as if concatenated into 1 vector. """ if norm_type == float('inf'): return max(t.abs().max() for t in tensors) return sum(t.norm(norm_type) ** norm_type for t in tensors) ** (1. / norm_type)
a5f7c4a8687a1f8e33dc507bd0428de34d278b27
633,010
import re def charges_clean_up(charges): """ Returns cleaned charges. Charges are typically separated by newlines and can often be in all caps, which we want to avoid.""" charges = charges.split("\n") charges = [charge.capitalize() for charge in charges] charges = "; ".join(charges) # we want...
7d3e65f12bc488f40af9d4421f3d0c58e01ce9cd
633,013
def make_ordinal(number): """ Coverts an integer to an ordinal string :param number: integer to convert :return: ordinal string """ number = int(number) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(number % 10, 4)] if 11 <= (number % 100) <= 13: suffix = 'th' return str(numbe...
a022254ac0d7820f10688618314400eabe7dd758
633,016
def _get_displayed_page_numbers(current, final): """ This utility function determines a list of page numbers to display. This gives us a nice contextually relevant set of page numbers. For example: current=14, final=16 -> [1, None, 13, 14, 15, 16] This implementation gives one page to each side ...
2c37f9a3de18b3aed22fe0e2cca84aeed4ce327b
633,017
def OP_start(counter_state): """Our start state initializes counter_state.count = 0""" counter_state.count = 0 operator = "counter" return(operator, counter_state)
0a261f9984ebfb3f732074212a278b8d96110790
633,018
def get_train_test_data(all_fc_data, train_subs, test_subs, behav_data, behav): """ Extracts requested FC and behavioral data for a list of train_subs and test_subs """ train_vcts = all_fc_data.loc[train_subs, :] test_vcts = all_fc_data.loc[test_subs, :] train_behav = behav_data.loc[train_subs...
33a7288ae262bb7591f16b82f7a42cc628c671b5
633,021
import uuid def _get_uuids(cnt): """ Return things like this 75659c39-eaea-47b7-ba26-92e9ff183e6c """ uuids = set() while len(uuids) < cnt: uuids.add(str(uuid.uuid4())) return uuids
a1efa3020ddf125c401a7f55ba6014a1e4f257d5
633,022
def exp_smooth(new_n, new_s, new_m, old_n, old_s, old_m, a = 0.05): """ This function takes in new and old smoothed values for mean, sd and sample size and returns an exponentially smoothed mean, sd and sample size. """ smooth_n = a*new_n + (1-a)*old_n smooth_s = a*new_s + (1-a)*old_s sm...
08c8c8c5aee12e530cd5152d8e5558fabcb68058
633,023
def istoken(docgraph, node_id, namespace=None): """returns true, iff the given node ID belongs to a token node. Parameters ---------- node_id : str the node to be checked namespace : str or None If a namespace is given, only look for tokens in the given namespace. Otherwise,...
79f4c553ae2918b4295dd443c2bc6e0866b040e7
633,029
def convert_meV_to_GHz(w): """ Convert an energy from unit meV to unit GHz. Parameters ---------- w : float / array The energy in the old unit. Returns ------- w_new_unit : float / array The energy in the new unit. """ # 1 meV = 1.0/4.1357e-3 GHz w_GHz = w /...
c75ad5d1112fb36ac8df7b36545d4ccebebfc7b8
633,030
def exactly_one(iterable): """Obtain exactly one item from the iterable or raise an exception.""" i = iter(iterable) try: item = next(i) except StopIteration: raise ValueError("Too few items. Expected exactly one.") try: next(i) except StopIteration: return item ...
e51b3ac7cbd1d01718263618ff6f629a9830ec60
633,033
def generate_final_vocabulary(reserved_tokens, char_tokens, curr_tokens): """Generates final vocab given reserved, single-character, and current tokens. Args: reserved_tokens: list of strings (tokens) that must be included in vocab char_tokens: set of single-character strings curr_tokens: stri...
2996958639465aa756864ac88583c77ac313bf69
633,035
def _strip_markup_line(line, sigil): """Strip sigil and whitespace from a line of markup""" return line.lstrip(sigil).rstrip()
86daa55bbd2d3cddeed6a14930dab705af57705b
633,040
def is_prim_rou(modulus: int, degree: int, val: int) -> bool: """ Test whether input x is a primitive 2d^th root of unity in the integers modulo q. Does not require q and d to be NTT-friendly pair. :param modulus: Input modulus :type modulus: int :param degree: Input degree :type degree: in...
b2d23ad6c580de460bf6e3d59e2c053ffd538892
633,042
def ordinal( value ): """ Converts zero or a *postive* integer (or their string representations) to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... '1st' '2nd' '3rd' '4th' '5th' '6th' '7th' '8th' '9th' '10th' '11th' '12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ...
f87c29be42e048df117ee7e8641f6e8188ba9bd4
633,043
def _clean_netloc(netloc): """Remove trailing '.' and ':' and tolower. >>> _clean_netloc('eXample.coM:') 'example.com' """ try: return netloc.rstrip('.:').lower() except: return netloc.rstrip('.:').decode('utf-8').lower().encode('utf-8')
d8b00244282a65a933460c6be4a7a9a728df8790
633,047
def load_kitti_odom_intrinsics(file_name, new_h, new_w): """Load kitti odometry data intrinscis Args: file_name (str): txt file path Returns: intrinsics (dict): each element contains [cx, cy, fx, fy] """ raw_img_h = 370.0 raw_img_w = 1226.0 intrinsics = {} with open...
bd959fda5bf81bbfd414f77ce9f79bb27fd9c211
633,055
def build_titles_list(title, args): """Build a list of titles from the 'title' option and arguments. Args: title: NoneType or unicode Title given to options.title args: list Leftover arguments on the command line, presumably extra titles. Returns: List of strings or [None]. """ # If args is non...
5428e56a3a42b5307b7593b21af9a050852aec2a
633,056
def norm(s: str) -> str: """Normalize a string for dictionary lookup.""" return s.lower().replace(" ", "").replace("-", "").replace(".", "")
9c04c2ebc3e3bb28fa4ba569ecffa5b407abf5a4
633,058
def dig_pow(n, p): """ Some numbers have funny properties. For example: 89 --> 8¹ + 9² = 89 * 1 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we w...
75ce21dd0dac71a414cfe992dd83f96e38dc8dbb
633,060
def _get_boundary_date_string(date_sr, boundary, date_format='%Y-%m-%d'): """ Returns the first or last date of the series date_sr based on the value passed in boundary. date_sr: Series consisting of date boundary: Allowed values are 'first' or 'last' date_format: Format to be used for co...
93ac0f29259e92411d9cd3f21a546394bf2924c6
633,064
def detach_nic(fco_api, server_uuid, nic_uuid): """ Detach NIC from server :param fco_api: FCO API object :param server_uuid: Server UUID :param nic_uuid: NIC UUID :return: Job-compatible object """ return fco_api.detachNic(serverUUID=server_uuid, networkInt...
e48ee62e0f215db014e90b7d9178299330146778
633,068
import torch def get_rays_shapenet(hwf, poses): """ shapenet camera intrinsics are defined by H, W and focal. this function can handle multiple camera poses at a time. Args: hwf (3,): H, W, focal poses (N, 4, 4): pose for N number of images Returns: rays_o (N, H, W...
2e3c25b819753e8e482da49bb33c4d4247a0284a
633,071
import torch def get_random_index(x: torch.Tensor) -> torch.Tensor: """Given a tensor it compute random indices between 0 and the number of the first dimension :param x: Tensor used to get the number of rows """ batch_size = x.size()[0] index = torch.randperm(batch_size) return index
088b5498f9fbf85802af19e72d23ca519f7e15d3
633,074
def instance_attributes(inst): """Given an instance, lists the name of all public non-callable members. Attributes: inst (obj): The instance of the object. """ return [n for n in dir(inst) if not n.startswith('_') and not callable(getattr(inst, n))]
1daa5e34800276c314e9cc1dc8bcf2da2ba0a02f
633,076
def calc_shield_power(block_count, active=False): """ Calculate the power usage of Shield Rechargers Given the number of Shield Rechargers, this function will calculate how much power they draw in 'e/sec'. It will calculate both inactive (shields full) and active (shields charging) power consumption b...
60df874717b7d8e2e2dfc07b534f24025220e2b3
633,077
def type_to_class_string(type): """ Takes a ROS msg type and turns it into a Python module and class name. E.g >>> type_to_class_string("geometry_msgs/Pose") geometry_msgs.msg._Pose.Pose :Args: | type (str): The ROS message type to return class string :Returns: | str: A py...
bcfbaa72c4709c735112977d413430acf3f90fdb
633,078
def dfs(reactions, chemical, seen): """DFS to traverse all reaction requirements for chemical.""" seen.add(chemical) if chemical == 'ORE': return [] order = [] _, needed_chemicals = reactions[chemical] for next_chemical, _ in needed_chemicals.items(): if next_chemical not in seen...
e9d5720d05fa5a1677d2e02758c26a13422a96ac
633,079
def get_survey_local_time_dayofweek(dt): """Get day of week when survey was taken.""" try: weekday = dt.weekday() weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return weekdays[weekday] except: return None
4ee97430f9ef3b87783985a574fbe74dab617f28
633,080
def sort_links(links): """Sorts endpoint links alphabetically by their href""" return sorted(links, key=lambda link: link["href"])
e20ac056cb341f1d8600b4c642812c7446d672a5
633,081
def convertBytes(nbytes): """Convert a size in bytes to a string.""" if nbytes >= 1e9: return '{:.1f} GB'.format(nbytes / 1e9) elif nbytes >= 1e6: return '{:.1f} MB'.format(nbytes / 1e6) elif nbytes >= 1e3: return '{:.1f} KB'.format(nbytes / 1e3) else: return '{:.1f} ...
34308e7bbdc4a6cb3753715ba9a0320d3979b27f
633,082
from six import string_types import logging def log_level(level): """ Attempt to convert the given argument into a log level. Log levels are represented as integers, where higher values are more severe. If the given level is already an integer, it is simply returned. If the given level is a s...
53d0bc6057d50a8ad1ea2779114b33a586d91d33
633,084
def insert_instr(qobj, exp_index, item, pos): """Insert a QasmQobjInstruction into a QobjExperiment. Args: qobj (Qobj): a Qobj object exp_index (int): The index of the experiment in the qobj. instruction(QasmQobjInstruction): instruction to insert. pos (int): the position to ins...
e26d4fe3b32ebdd890ce2b1bd99f86ce8686d063
633,086
def __points_to_dict(points): """transform list of [x, y] into a dict() where {x: y}""" return {p[0]: p[1] for p in points}
83c7445e1c4c2c034f609f19da0d9638b3d9dbf3
633,087
import hashlib def CalculateSha256Checksum(filename): """Calculate the sha256 checksum for filename.""" sha = hashlib.sha256() with open(filename, 'rb') as f: data = f.read(65536) while len(data) > 0: sha.update(data) data = f.read(65536) return sha.hexdigest()
f3f353cb05c74e6b78285153a29a86eb56c87a58
633,092
def escapeBelString(belstring): """Escape double quotes in BEL string""" return belstring.replace('"', '\\"')
ef2efa04cd356dd17d44f1a2f0b9f518d7c13170
633,093
def first_and_last(sequence): """Returns the first and last elements of a sequence""" return sequence[0], sequence[-1]
6aae9364559f3f9b892f9aa66c1e9e368997fb65
633,094
from collections import Counter def gen_idx_byclass(labels): """ Neatly organize indices of labeled samples by their classes. Parameters ---------- labels : list Note that labels should be a simple Python list instead of a tensor. Returns ------- idx_byclass : dictionary {[cl...
c5969a62fc9f503df32fbbec8861cc34f9782a74
633,097
def multiplica(x, y=2.0): """Multiplica dos números, por defecto el primero por 2.""" return x * y
51d8243d80e90d97da284895f02b73884b67b341
633,099
def get_floor(directions): """ Get the floor for Santa. Parameters ---------- directions : str A string of parentheses representing directions. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. R...
f6ab8d6d2fb134a71a5a1a06db14073327a5eb58
633,100
def get_randaug(aug: str) -> str: """Returns a string representing the RandAugment op to use during preprocessing.""" l, m = { 'light0': (2, 0), 'light1': (2, 10), 'medium1': (2, 15), 'medium2': (2, 15), 'strong1': (2, 20), 'strong2': (2, 20), 'extreme1': (4, 15), 'ex...
5177e0a92b5ca5ba089647d1f12a916badffb0b8
633,102
import hashlib def compare_hash(file_a: str, file_b: str) -> bool: """Compute and compare the hashes of two files""" print("Comparing: ") print(" File_A: "+file_a) print(" File_B: "+file_b) file_a_hash = hashlib.sha256(open(file_a, 'rb').read()).digest() file_b_hash = hashlib.sha...
dad85b423ba59a823ccc656cf50e9c586deeb793
633,108
import re def expand_sharded_pattern(file_pattern: str) -> str: """Expand shards in the given pattern for filenames like base@shards. For example, '/path/to/basename@3' to expand to '/path/to/basename-00000-of-00003' '/path/to/basename-00001-of-00003' '/path/to/basename-00002-of-00003' Args: f...
d2f1b2638d26889b059e225d9e64c395242184a0
633,111
import math def _get_beta(steering_angle: float, wheel_base: float) -> float: """ Computes beta, the angle from rear axle to COG at instantaneous center of rotation :param [rad] steering_angle: steering angle of the car :param [m] wheel_base: distance between the axles :return: [rad] Value of beta...
16a8fbbe2b7f03e78dde168fafd914c7c4cc1d7f
633,112
def three_to_one_gates_and_measurement_bob(q1, q2, q3): """ Performs the gates and measurements for Bob's side of the 3->1 protocol :param q1: Bob's qubit from the first entangled pair :param q2: Bob's qubit from the second entangled pair :param q3: Bob's qubit from the third entangled pair :ret...
ae318c4ef196aeb1392aea05e2de9d25f45aa672
633,115
import smtplib def smtp_connection(c): """Create an SMTP connection from a Config object""" if c.smtp_ssl: klass = smtplib.SMTP_SSL else: klass = smtplib.SMTP conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout) if not c.smtp_ssl: conn.ehlo() conn.starttls...
db57f751cb25683222e6fd621ec02e7b05bc598e
633,117
def config_loader_mock_no_creds(config_key): """Return mocked config values.""" if config_key == "energy_recorder.api_url": return "http://pod-uri:8888" elif config_key == "energy_recorder.api_user": return "" elif config_key == "energy_recorder.api_password": return "" else:...
cba5bdef266ea267f35c195b66defd0fa557a512
633,120
from typing import Union from pathlib import Path def add_extension(file_path: Union[str, Path], extension: str) -> Union[str, Path]: """Adds the extension to the file path if it is not present. Parameters ---------- file_path : Union[str, Path] The path to the file. extension : str ...
f0a6c638701cd5ce34c387a3e6d445bcad4a2d1f
633,121
def compute_average_cosine_similarity(square_norm_of_sum, num_vectors): """Calculate the average cosine similarity between unit length vectors. Args: square_norm_of_sum: The squared norm of the sum of the normalized vectors. num_vectors: The number of vectors the sum was taken over. Returns: A float...
231f75f153da38cfbcd43fd4198a8734ab565b48
633,123
def ignoreStrReplace(line, cur, rep): """Wrapper for str.replace to ignore strings""" if '"' in line: #Split string at quotation marks lsplit = line.split('"') #Replace items contained within even partitions lsplit[::2] = [spl.replace(cur, rep) for spl in lsplit[::2]] #Re...
bbc2593354fdc9c748bd6fcadc81e48a30a5e55c
633,125
def encode(char, offset): """Shift any letters by a given offset. Ignore non-letter characters.""" if char < 97 or char > 122: return chr(char) char += offset if char > 122: char -= 26 return chr(char)
08432ec9a935dd600544710ee5d80edc7964a973
633,126