content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def calculate_closest_pattern_dictionary(distances_dictionary): """ Calculates the closets pattern from a dictionary with the distances of a point to a dictionary :param distances_dictionary: a dictionary where each key is the index of a fis point and the value is the distance to that fix point ...
5a2e42ae8b85e129ff97bc19bb839423ed6a1355
568,589
def parseDeviceName(deviceName): """ Parse the device name, which is of the format card#. Parameters: deviceName -- DRM device name to parse """ return deviceName[4:]
3c51757dd56fa48ce586e826a1df345d917398d1
568,590
def _get(obj, name): """ Get the indexable value with given `name` from `obj`, which may be a `dict` (or subclass) or a non-dict that has a `__getitem__` method. """ try: # try to get value using dict's __getitem__ descriptor first return dict.__getitem__(obj, name) except TypeEr...
e3798c918387fb01f78c54e9af6cb197a8fe4643
568,594
def toy_problem_ident(identifier): """ This function makes it easier to call the toy problems, as they can now be identified by their full name, an abbreviation or a simple integer value. """ if identifier in ["shortest-path-1", "sp1", "0"]: return "shortest-path-1" if identifier in ["shortest-p...
c3d1367edce24a5b6897707f087e766bdcd0f2dd
568,598
def issubclass_safe(value, type_): """Determine if value is a subclass of type_ Will work even value is not a class """ try: return issubclass(value, type_) except (TypeError, AttributeError): # Cannot perform issubclass on some types return False
7c1e41954602a906cfc41cecf62b85ffd22bcd77
568,599
import click def validate_layers(ctx, param, value): """Validates that the input layers passed into CLI are correctly formatted.""" try: layers = [l for l in value.split(',')] convs = [(int(p),int(l)) for p,l in [layer.split("_") for layer in layers]] assert all(isinstance(l, int) and ...
95b79642fc9da47bef4d4030be6d48e233cbe3ec
568,608
import re def remove_whitespace(input_text: str, remove_duplicate_whitespace: bool = True) -> str: """ Removes leading, trailing, and (optionally) duplicated whitespace """ if remove_duplicate_whitespace: return ' '.join(re.split('\s+', input_text.strip(), flags=re.UNICODE)) return input_text.stri...
697c75e16cbe94214847bf4a1924fc9a9b47afa0
568,611
def compute_sea_level_pressure(barometric_pressure, altitude): """Compute sea level pressure (hPa) from barometric pressure (hPa) and altitude (m).""" return barometric_pressure * pow((1 - (altitude / 44307.69396)), -5.2553)
949c33511cf0d99988c67141d0bb750f340e9a35
568,612
import pickle def open_obs_sequence(obs_seq_file='params.pkl'): """opens existing obs sequence .pkl file and returns it""" with open(obs_seq_file, 'rb') as handle: obs_sequence =pickle.load(handle) return obs_sequence
9f23eec0e35f620ce7f435011b490c172c449abb
568,613
def compose_route(host, domain, port, path): """Builds a string representation of the route components. Args: host (str): the first dot-segment of the hostname domain (str): the remainder of the hostname after the first dot-segment port (int|str): port number if applicable. If it's a Fa...
b30ff51b32d55041120b5445ebfe65004b4203f0
568,619
import six from typing import Mapping def update_dict(old_dict, new_dict): """Updates old dictionary with data from a new one with respect to existing values. :param old_dict: :param new_dict: :return: updated dict :rtype: dict """ for key, val in six.iteritems(new_dict): if isins...
879647ca8754c3577bbea630f470ddda3f40b3e4
568,620
def get_func_id_match(func_id, d): """Find matching func_id, taking into account sync/async method pairs.""" for func_id_try in [func_id, func_id.replace("async", ""), func_id + "async"]: if func_id_try in d: return func_id_try
6786f149e9df78ba9ddfc48780a41ebd507e64d4
568,625
def calculate_single_gpa(score): """ Calculate gpa with a score. Use a lookup table to calculate a single gpa. Empty scores or scores not between 0 and 100 will be regarded as 0. """ lookup_table = [0.0] * 60 + [1.0] * 4 + [1.5] * 4 + [2.0] * 4 + \ [2.3] * 3 + [2.7] * 3 + [3.0] * 4 + [3...
65906bb2347a0d846638e720702be7197894ec50
568,626
from typing import List def calcular_ganador(tiempos: List[int]) -> int: """Calcula el ganador de la competencia :param tiempos: lista de tiempos :type tiempos: List[int] :return: ganador :rtype: int """ ganador = 0 for i, tiempo in enumerate(tiempos): if tiempo < tiempos[...
20f080a2470bd70e34c10e17dbdd5b56d5ab5a19
568,632
def req_remove(requirements, remove_str): """ remove any line from requirements containing remove_str :param requirements (list of strings): each string a package install requirement (e.g. 'flake8==3.7.9') :param remove_str (str): string pattern :return: updated list of requirements """ new_...
167d55644e12d1def4f0a3a1dc154659d40b09b8
568,633
def create_kickstart_file_for_redhat(kickstart_filepath, kickstart_file, server_data): """This function is to create custom kickstart file for Red Hat Enterprise Linux nodes Arguments: filepath {string} -- custom kickstart file path kickstart_file {string} -- base kickstart file pat...
f9adc7ab5fa31e4a7235cbfc02f4cfbbd42183d0
568,637
def _from_hass_brightness(brightness): """Convert Home Assistant brightness units to percentage.""" return brightness / 255
88cd48f70c661ff498bf9de59c35b2397063fee6
568,642
def aligned_maxdims(origin, dims, container_dims, alignment_x="left", alignment_y="top"): """ Determine the maximum dimensions of an object inside a container of fixed size. """ x, y = origin w, h = dims cw, ch = container_dims # This needs to take into account the alignment (X) maxwidth = min(cw - x, w) ...
4dbf5e62a4e482df94437257d2cbd925431d7f74
568,644
from pathlib import Path import json from typing import OrderedDict def read_json(filename): """ 读取json :param filename: 文件路径 :return: json.loads() """ # Path(),PurePath subclass that can make system calls. filename = Path(filename) """ ========= ================================...
2382e89af3f2ff13747ebca5e91ab6af3f2a0e10
568,646
from typing import Any def getConstantAttrs(obj: Any) -> tuple: """Get the constant attributes of an object. (Uppercase attrs)""" return tuple(a for a in dir(obj) if a.isupper())
804b704561b2529def0fc5e0a8de1db5225ea001
568,649
def HasCacheKeyPolicyArgsForUpdate(args): """Returns true if update request requires a CacheKeyPolicy message. Args: args: The arguments passed to the gcloud command. Returns: True if there are cache key policy related arguments which require adding a CacheKeyPolicy message in the update request. ...
1afc7de05af1b1900f69eb4e2e4607fcd50d9afc
568,650
import re def reloc(frame, column, pattern, flags=re.IGNORECASE, method="contains"): """ return rows of frame where the regex pattern is contained in column set method to "match" to just check beginnings of strings this is case-insensitive by default; adjust flags to modify that """ regex = re...
208c737a290ae6dcbc43532ead010c50ea20eda8
568,652
import torch def exponential_moving_average(tensor, window: int): """ Exponential moving average in a sliding window. Parameters ---------- tensor : (N,) torch.Tensor Input tensor. window : int Sliding window width. Returns ------- out : (N,) torch.Tensor ...
4959afa69e13f5da599d2018e52b42bdd6da8204
568,658
def nesting_level(x): """Calculate nesting level of a list of objects. To convert between sparse and dense representations of topological features, we need to determine the nesting level of an input list. The nesting level is defined as the maximum number of times we can recurse into the object whi...
28cc1d72855d159c4f1efcba01e2a05424864833
568,662
def always_iterable(obj, base_type=(str, bytes)): """If *obj* is iterable, return an iterator over its items:: >>> obj = (1, 2, 3) >>> list(always_iterable(obj)) [1, 2, 3] If *obj* is not iterable, return a one-item iterable containing *obj*:: >>> obj = 1 >>> list(alwa...
7c13cd97ea29c9d412dea19af40f158750b5f540
568,664
def calcMu(muRef,temp,tempRef): """ Calculate local dynamic viscosity using Sutherland's Law """ mu = muRef* ( (temp/tempRef)**(3/2) ) * ( (tempRef+110)/(temp+110) ) return mu
5bed9f4252ecf50deeab4cde1f6f0fc2095f45e6
568,668
def filter_attributes(resource_type): """Returns a list of attributes for a given resource type. :param str resource_type: type of resource whose list of attributes we want to extract. Valid values are 'adminTask', 'task', 'adminVApp', 'vApp' and 'adminCatalogItem', 'catalogItem'. :return:...
8fb484196c6d4aa7aabc1295797a4f853e7d0872
568,670
from typing import List import json def bbox_coco( file_path: str, ) -> List[dict]: """ Returns the labeled bounding boxes from a COCO annotation (*.json) file. :param file_path: path to a COCO annotation file :return: list of bounding box dictionary objects with keys "label", "x", "y...
c7562d7d6ba089b9779d47081e76ce629b3b9daa
568,671
import random def flip_random_character(s): """Returns s with a random bit flipped in a random position""" if s == "": return s pos = random.randint(0, len(s) - 1) c = s[pos] bit = 1 << random.randint(0, 6) new_c = chr(ord(c) ^ bit) # print("Flipping", bit, "in", repr(c) + ", givi...
4726feee8ab4780b17b68f450050ae6d8b1cb840
568,672
def boolparser(true_strings=['true', 't', 'yes', 'y', '1'], false_strings=['false', 'f', 'no', 'n', '0'], case_sensitive=False, strict=True): """ Return a function to parse strings as :class:`bool` objects using a given set of string representations for `True` ...
9d64d656503014801cb4bf2cc3fcf6e45acd8302
568,673
def colorHashToRgba( colorHash ): """ Converts the given HTML-style color hash (e.g., '#aabbcc') or HTML-with-alpha color hash (e.g. '#aabbccdd') to a quad-color (r, g, b, a) tuple and returns the result. Examples: >>> colorHashToRgba( '#ffffff' ) (1.0, 1.0, 1.0, 1.0) >>> colorHashToR...
467b37822b21db41f4d7b80799b806b84a675857
568,674
def get_capabilities() -> list[str]: """List the capabilities of the module.""" return ["help", "metadata", "analyze"]
fe9a51f6ae32c9e39ae83cd4131f9cb6b2e6a8af
568,675
import random def shuffle(seq): """Shuffle a list randomly using Knuth's algorithm. The method randomly shuffles a list by iterating over each position and exchanging the element with another random element. The original list is not maintained and will change. Args: seq: A list to shuffl...
a6a442a6148e97136b680e08bbc9890221a1fb51
568,676
def get_topdog_tactic(etype: str) -> str: """Return topdog defensive strategy""" return 'bullet_preferred'
c5c125d517d0463c66d984d146b3726d95494df1
568,678
def verify_board(board: list) -> bool: """Verifies the board in O(n^2) time complexity. Args: board (list): Current puzzle Returns: bool: True if valid, else false """ # Row/Column verification for i in range(9): row = [cell for cell in [board[col][i] for col in rang...
3bacd7a06efe438264aff2f0247d2c1ed9e2e9e3
568,679
def get_adj_quantity_feature(dataset): """ Return adj_quantity feature (combining min_order_quantity and quantity). """ return dataset[['min_order_quantity', 'quantity']].max(axis=1)
0b00e9b0c60bc3aa39dcfac9857481e47edb3122
568,682
def fib1(a,b,n): """Calculate the nth fibonacci number using the seeds a and b""" if n==1: return a elif n==2: return b else: return fib1(a,b,n-1)+fib1(a,b,n-2)
c720711e9c79302495d8fa7f3800766918153ff1
568,686
import shlex def extract_key_value(parameters): """Parses a list of strings, looking for key-value pairs pr. line separated by whitespace, into a dictionary. Spaces in keys and/or values are supported if quoted. Quotes in keys/values are not supported. Args: parameters (list of str) ...
c796ce0e90fba4db3e24fcbe9799a5ac4a89f1e2
568,687
from typing import Union def num_cvt(string: str) -> Union[int, float]: """ >>> num_cvt("2007") 2007 >>> num_cvt("3.14") 3.14 >>> num_cvt("1,234") 1234 """ try: return int(string) except ValueError: pass try: return float(string) except ValueErro...
d99019a5bbd5a6490adf85758c14b815a0c8a3b3
568,690
def is_set(cards): """ Return True if all cards all unique, False otherwise. """ return len(set(cards)) == len(cards)
faa2585b108d8b970cb01f2bc38b0757bdfd1079
568,692
import re def _parse_exception(e): """Parses an exception, returns its message.""" # Lazily import # MySQL matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e)) if matches: return matches.group(1) # PostgreSQL matches = re.search(r"^\(psycop...
00c1bd75f8f7e440d993b4c77439d5169b856c36
568,693
def get_domain_name(service_name: str) -> str: """ Returns the domain name given a service name. Params ------- service_name Name of the service Returns ------- Name of the domain. """ return service_name.split("_")[0]
0ec3042ea258b4e2d12aacdbf0e42dcb44d2420c
568,695
def pix2ang(val, pixel_scale): """Transform an angle from units of pixels into angular units.""" return val * pixel_scale
ae01b4ea1aa86949beabcad8cdab23fca644e1e8
568,698
def generate_dir2save(opt): """ Generate directory to save depending on the mode. Arguments: opt (argparse.ArgumentParser) : Command line arguments. Returns: dir2save (String) : Relative path to directory in which files are stored. """ dir2save = None if (opt.mode == 'train...
79aad4b7e9a949e95bd9f69f1d2cbcccc2c76964
568,699
def reject_hit(client, assignment_id, feedback): """Rejects a HIT assignment on MTurk Parameters ---------- client : MTurk.Client A boto3 client for MTurk assignment_id : string The ID of the assignment. The assignment must correspond to a HIT created by the Requester. feed...
bc1f742e47baee29cfdf556aed31b32dd43b7da2
568,701
def same_sign(nums): """ Returns True if all numbers in nums have the same sign; otherwise, returns False (including the case where at least one number is zero). @type nums: iterable @param nums: list of numbers to check @rtype: boolean @return: whether the numbers all have the same sign ...
f9895b7d97c6d314cc51ae49bb71938e6d78d3a2
568,705
def get_peer_values(field, db_object): """Retrieves the list of peers associated with the cluster.""" peers = [] for entry in getattr(db_object, 'peers', []): hosts = [] for ientry in getattr(entry, 'hosts', []): hosts.append(ientry.hostname) val = {'name': entry.name, ...
1716574f48e66875aa796015063f789a8cc90c08
568,709
import importlib def _load_experiment_name_from_config(config_path): """Extract the identifying experiment name from config.""" experiment_config = importlib.import_module(config_path) config = experiment_config.get_config() return config.name
047ef93c895d920b15996df27cc7155ba08a0e85
568,712
def dens_por(Rlog, Rmatrix=2650.0, Rfluid=1000.0): """ Calculate density porosity Usage: phi = dens_por(Rlog, Rmatrix=2650.0, Rfluid=1000.0) Inputs: Rlog = density log values (kg/m3) Rmatrix = density of mineral matrix (kg/m3) Rfluid = density of pore fillin...
7bbea071ca18091fe1cb6215699390ae2ca07852
568,714
def unhandled_intent_handler(handler_input): """Handler for all other unhandled requests.""" # type: (HandlerInput) -> Response lang = handler_input.attributes_manager.request_attributes["_"] speech = lang['UNHANDLED_MSG'] handler_input.response_builder.speak(speech).ask(speech) return handler_i...
fda14c1b0cc1fe25931f38331c447a078d907bed
568,716
def merge_dict(*args): """ Merges any number of dictionaries into a single dictionary. # Notes In Python 3.5+, you can just do this: ```python r = {**x, **y} ``` But if you want a single expression in Python 3.4 and below: ```python r = merge_dict(x, y) ``` """ result = {} ...
9211ad5c859609194199e02960af497373085eb5
568,717
def combine_tokens(tokens): """Helper function to combine tokens.""" return ''.join(tokens)
5828e12217d0e8015cdcd4417d6f5f369e5a6b0f
568,718
import hashlib def generate_hostid(host, project_id): """Generate an obfuscated host id representing the host. This is a hashed value so will not actually look like a hostname, and is hashed with data from the project_id. :param host: The name of the compute host. :param project_id: The UUID of ...
871cf75c6b83a1b3fa547b86e13b3656c2926c7b
568,720
def _get_component_repositories(config): """ Gets an initialized dictionary from the value in componentVersionMap. This structure is sent on every command by Ambari and should contain each service & component's desired repository. :config: the configuration dictionary :return: """ if "componentVersionMap...
c06591252dd5b7749b41128889113132979d7a4f
568,721
import copy def clean_names(names): """Clean factor names to remove formatting characters. Parameters ---------- names: list of str Names to be cleaned. Returns ------- list of str List of strings without formatting characters. """ new_names = co...
1a0bb74cedfd5b7b1e17e025370c00f9a2684507
568,723
import re def strip_p_tag(s: str, _re=re.compile(r"<p>(.*)</p>")): """ >>> strip_p_tag("<p> </p> </p>") ' </p> ' """ return _re.sub("\\1", s)
30ce9fd4d8ba2854fe39b79ed374841c3dae8286
568,724
def safe_unicode(arg, *args, **kwargs): """ Coerce argument to Unicode if it's not already. """ return arg if isinstance(arg, str) else str(arg, *args, **kwargs)
e8db7e18e6adb74587a052cc6b4e5b70f5656f53
568,725
def key_has_dot_or_dollar(d): """Helper function to recursively determine if any key in a dictionary contains a dot or a dollar sign. """ for k, v in d.items(): if ("." in k or k.startswith("$")) or ( isinstance(v, dict) and key_has_dot_or_dollar(v) ): return True
adb6cfa9d0a1a061e0da2bb67833356eb9168c31
568,727
def superuser_client(client, superuser): """Return logged in superuser client.""" client.force_login(superuser) return client
36290dc0a736e7423eaa41ce76d17f1175a76cd7
568,729
async def fetch(session, url): """Async function to fetch a single URL using the aio-http session.""" # The async keyword makes the function a coroutine async with session.get(url) as response: # Await suspends a coroutine on an awaitable object return await response.read()
ea0d5da4fdaa6d1618e48593d4f8d5699cc76fa1
568,730
def _shell_quote(string): """ Create a single-quoted string for a shell :param string: A unicode string to quote :return: A unicode string quoted for a shell """ return "'" + string.replace("'", "'\\''") + "'"
5e21e41638ee21ee02123c55af1db1f958f5ccd2
568,732
def show_size(s): """String that translates size in bytes to kB, Mb, etc.""" return '%d %.2f kB %.2f Mb %.2f Gb' % (s, s / 1024., s / (1024. * 1024.), s / (1024. * 1024. * 1024.))
74c6b65f44e93cb6a662a39393f76f32f6dca933
568,733
import torch def l2_loss(pred_traj, pred_traj_gt, loss_mask, random=0, mode='average'): """ Computes standard L2 norm loss between predicted and ground truth trajectories. This involves squaring the differences between coordinates, and summing over all length (pred_traj_len) :param pred_traj: Tensor o...
c3492e6a9df477bfad256ef2cf7f6fdd2de73b40
568,734
import pycocotools.mask as cocomask def segmentation_to_mask(polys, height, width): """ Convert polygons to binary masks. Args: polys: a list of nx2 float array. Each array contains many (x, y) coordinates. Returns: a binary matrix of (height, width) """ polys = [p.flatten()....
13f18044931f2811f2a35f0c5fe51baf8f2cc8e9
568,735
def getNames(tails): """ Returns a list of the names of all genes found in a tail file :param tails: nested list. Produced by tail parser from a .tails file :return: list of gene names """ names = [] for tail in tails: names.append (tail[2]) return list(set(names))
98d9021aed77bde895ea06a5af9b798062fd9221
568,736
def minimize_reference(reference): """ Takes a reference spikein dataset object and strips it down to a subset of its fields. """ reference_fields = ['accession', 'dbxrefs', 'description'] minimized_reference = {field:reference[field] for field in reference_fields if field in reference} return m...
035b3b2e3241501f0623870264cdef79f0cabece
568,738
def get_redirect_uris(cinfo): """ Used before there is a Conversation instance :param cinfo: Client Configuration Information :return: list of redirect_uris """ try: res = cinfo["registration_info"]["redirect_uris"] except KeyError: res = cinfo["registration_response"]["redir...
f6be84e383c478df7bbdb3687351a393c578b37d
568,739
def perimeter_node_count(shape): """Number of perimeter nodes. Number of nodes that are on the perimeter of a structured grid with dimensions, *shape*, and thus boundary nodes. Examples -------- >>> from landlab.utils.structured_grid import perimeter_node_count >>> perimeter_node_count((3,...
54b5a533683cb651b46ad5d696a4085807b3f0e0
568,745
from textwrap import dedent def fish_variable(variable_name: str, value: str): """Render the code to backup and set a variable in fish. :param variable_name: The name of the variable. :param value: The new value to set the variable to. :return: The code to backup and set the variable. """ ret...
70010dc8047c676e5ffb898acdbb9996b3f78fa9
568,747
import torch def reduce_mean(tensor, dim=None, keepdim=False, out=None): """ Returns the mean value of each row of the input tensor in the given dimension dim. Support multi-dim mean :param tensor: the input tensor :type tensor: torch.Tensor :param dim: the dimension to reduce :type dim:...
d4b26c331468906e1148f19715c8970f5fd37234
568,750
import math def get_grid_size(k: int) -> int: """ returns the grid size (total number of elements for a cgr of k length kmers :param: k int -- the value of k to be used :return: int -- the total number of elements in the grid """ return int(math.sqrt(4 ** k))
2a770d0be8093a16f7c795fb6b8dfeccd8c8e140
568,752
def is_macho(filename): """ Check that a file is in the Mach-O format. """ with open(filename, "rb") as fp: data = fp.read(2) fp.close() return data == '\xcf\xfa'
5ac43b1be13350c347aebd7a49d8f10b60cdd5b1
568,753
def linearSearch(myList, objetive, iter_lin=0): """ Searches in the list, the objetive number in a iteratively way. """ match = False for element in myList: iter_lin += 1 if element == objetive: match = True break return (match, iter_lin)
8e42a2f2da15cbe2b2d25bae6d84347c103fffd7
568,759
from typing import Optional from typing import Any import json def get_json_body(event) -> Optional[Any]: """Return the body as JSON object, if present; otherwise it will return None Args: event: the AWS Lambda event object Returns: a dictionary containing the deserialized JSON conte...
93941a82d213cfceb2268fd7d47306b3506ea3b6
568,760
def apim_nv_get(client, resource_group_name, service_name, named_value_id): """Shows details of a Named Value. """ return client.named_value.get(resource_group_name, service_name, named_value_id)
bd413438fafa8f4ae8133f44c66e8f7f9c1d84a5
568,763
def count_trees(tree_map, down, right): """Count number of trees encountered in tree_map, with down, right steps.""" column = 0 trees = 0 for index, row in enumerate(tree_map[::down]): if row[column] == '#': trees += 1 column = (column + right) % len(row) return trees
58b7098b08de25a418578a66ce6419d5f9cec6af
568,768
from typing import Counter import string def find_version_sep(s): """Given a pure version string, find the character (most often) separating version components""" i = 0 s_len = len(s) char_count = Counter() if s[i] in ['v', 'V', 'r', 'R']: i += 1 if s[i] == '/': i += 1 ...
18fc064bc027c681489b964695c67db25bb7f87d
568,782
def compute_length(stroke): """ Return the total length of a stroke (sum of the lengths of the geometries of the edges that make up the stroke). :param stroke: list of edges :type stroke: list of Edge objects """ # List of the geometries that make up the stroke list_geom = [edge.geo...
c19e54dbbc7c4a6cf7e2e614d031bab77572d5ac
568,783
def mu_chi_var_chi_max_to_alpha_beta_max(mu_chi, var_chi, amax): """ Convert between parameters for beta distribution """ mu_chi /= amax var_chi /= amax**2 alpha = (mu_chi**2 * (1 - mu_chi) - mu_chi * var_chi) / var_chi beta = (mu_chi * (1 - mu_chi)**2 - (1 - mu_chi) * var_chi) / var_chi ...
0f54ad7a188b3a5ccd82f40907e96ec070e8ce7c
568,788
def is_it_prime(number): """Check if a number is prime.""" number = abs(int(number)) # make sure n is a positive integer # simple tests if number < 2: return False if number == 2: # 2 is prime return True if not number & 1: # other even numbers aren't return False ...
628e0ca727d344f4a4cf6120c3ba4dc110b9da11
568,790
def _decode_index(packet): """Decode integer index value of response packet.""" return packet[6] - 1
11a35cc1ac0993382af51376a65d7cb345c602a3
568,792
async def redirect_index() -> str: """Redirect to documents. Returns: str: Redirects `/` url to `/docs` """ return "/docs"
a0be0512fc13a477b9bca5ff95c57fb00907b67e
568,794
def get_campaign_variation(campaign, variation_name): """Returns variation from given campaign and variation_name. Args: campaign (dict): The running campaign variation_name (string): Variation identifier Returns: dict: Variation corresponding to variation_name in respective campai...
6569631f77aeab00a89c160451bb403c696cbd37
568,796
def is_aware(value): """ Determines if a given datetime.datetime is aware. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo """ return value.tzinfo is not None and \ value.tzinfo.utcoffset(value) is not None
e45d1433a98601d75742ffeb8a22a8668bdfca9a
568,797
def merge_cms(cm1, cm2): """ Merge two confusion matrices. Parameters ---------- cm1 : dict Confusion matrix which has integer keys 0, ..., nb_classes - 1; an entry cm1[i][j] is the count how often class i was classified as class j. cm2 : dict Another confusion m...
8c9a58434b7bd301e7931ee67b255a5e15f50a51
568,798
def convert_mycity_coordinates_to_arcgis(mycity_request) -> dict: """ Gets coordinates from a MyCityRequestDataModel and converts them to dictionary required by GIS utilities :param mycity_request: MyCityRequstDataModel containing geolocation coordinates to convert :return dictionary: x, y ...
47874213a8ad170b95da32b88e72908de04a8ea7
568,802
def _is_pair(obj): """Helper to test if something is a pair (2-tuple).""" return isinstance(obj, tuple) and len(obj) == 2
7ce4a62c4b812b0d7a144aecf7e608dd48a893a8
568,805
def count(items): """count(items) -> dict of counts of each item Count the number of times each item appears in a list of data. """ c = {} for i in items: c[i] = c.get(i, 0) + 1 return c
3fe50e3787622f67cb5e17ec39ed89a2f2ef45b7
568,806
from typing import Dict from typing import Any import jinja2 def render_jinja(template: str, context: Dict[str, Any]) -> str: """Render the input jinja string using the context and return it.""" jinja_env = jinja2.Environment( loader=jinja2.FunctionLoader(load_func=lambda _: template), trim_bl...
a573925209c45389c4bff6b4189cfc14e99ddbe4
568,807
def elo(old, exp, score, k=32): """ Calculate the new Elo rating for a player :param old: The previous Elo rating :param exp: The expected score for this match :param score: The actual score for this match :param k: The k-factor for Elo (default: 32) """ return old + k * (score - exp)
1784e2f6cb8d6d55a1d2c3b7a0ec9662e5ee1912
568,809
import decimal import fractions def num2decimal(num): """Converts a number into a decimal.Decimal. The number may be an str in float, int or fraction format; a fraction.Fraction, a decimal.Decimal, an int or a float. """ if isinstance(num, decimal.Decimal): return num if isinstance(nu...
02036f0ccc330c8bfcad10e458f3782218051ac5
568,813
def need_search_path_refresh(sql): """Determines if the search_path should be refreshed by checking if the sql has 'set search_path'.""" return 'set search_path' in sql.lower()
29519c3bbd49df32c66ad23705f6b4545b80b0fc
568,815
def get_epsilon_rate(data) -> str: """ Computes the epsilon rate by taking the least common bit for each bit in all binary entries of the given data set. :param data: Array of binary numbers arranged as Strings. :return: Epsilon rate as a string of binary values. """ _output = '' for elem ...
f5c2ce8e07e08c0a6673f6ea81948b68d7c5e36b
568,826
def _default_combiner(tokens): """Default token combiner which assumes each token is a line.""" return '\n'.join(tokens)
e919519ec127a37819059438196f33bb016be5e8
568,830
from pathlib import Path def create_output_folder(output_path: str) -> Path: """Creates a path to store output data if it does not exists. Args: path: the path from user in any format (relative, absolute, etc.) Returns: A path to store output data. """ path = Path(output_path) ...
0cbdb331f3257a20a926beb697ee4f6b9834657b
568,832
def convertweight(weight): """Convert a weight in a string to a float. >>> [convertweight(a) for a in ('0.5', '0x1.0000000000000p-1', '1/2')] [0.5, 0.5, 0.5]""" if '/' in weight: a, b = weight.split('/') return float(a) / float(b) elif weight.startswith('0x'): return float.fromhex(weight) return float(weig...
482bef2f22443fbe65d103a436b04b34ee7682ea
568,840
def append_cloud_repository_sources(function, context): """ Adds the source code from the cloud repository. """ repo = context.properties.get('sourceRepository', { 'url': context.properties.get('sourceRepositoryUrl') }) function['properties']['sourceRepository'] = repo name = function['nam...
aaad904aafa8ada34cacfe8336a05a971a71403a
568,842
def p(n, d): """ Helper to calculate the percentage of n / d, returning 0 if d == 0. """ if d == 0: return 0.0 return float(n) / d
2b009b7059af7e2897a9e4d92246f8c0c883e7e1
568,844
def chr_start_end(content_case): """Get chr, start, end continuous matrix slicing parameters Arguments: test (Node): reference to Node object runner (Runner): reference to Runner object Returns: (dict): filters for continuous subsetting """ test = content_case.test ...
e5c625060307787e5990e8e608b8114800f79c11
568,845
def electricity_cost_sek(dist, sekpkwh=.85, kmpkwh=100): """Gets cost of commute via ebike in Swedish Krona. Inputs: dist: distance in kilometers (numeric) sekpkwh: Swedish Krona (SEK) per kilowatt-hour (kWh). Obtained from electricity_price() function. kmpkwh: Kilometers (km) per kilowa...
0edc0c0c8e3d0bcf15d2a884fbe6c6fc3a9494a8
568,849