content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import logging def _get_logger(logger_name: str = "default_logger") -> logging.Logger: """Get logger for a given name. Args: logger_name (str, optional): Name of the logger (to retrieve). Defaults to "default_logger" Returns: logging.Logger: Logger object """ return l...
995f97465b5be002772287fb95ed6511bc8aeaa2
621,448
def round_temp(temperature): """Round a temperature to the resolution of the thermostat. RadioThermostats can handle 0.5 degree temps so the input temperature is rounded to that value and returned. """ return round(temperature * 2.0) / 2.0
33875e05b8d9cab4f54b2d9012a6cf54124a7976
621,460
def numéroPlusGrande(tas): """ numéroPlusGrand(tas) donne l'indice dans la liste d'entiers tas du plus grand élément. Si la liste est vide, le résultat est -1 par convention. On suppose les entiers positifs ou nuls. """ # Si le tas est vide, on rend la valeur -1 if tas == []: return(-1) # On trouve ...
9807978935e4c80fa3de43b03f4c921538d16535
621,462
def create_intervals(interval_length: int, n_intervals: int): """ Creates the intervals for observations. :param interval_length: Length of the one interval in seconds. :param n_intervals: Number of intervals. :return: List of intervals. """ return list(range(0, (interval_length * n_interval...
72edfdfd87765f9c8fbc1444b86ca183d8534b03
621,466
def strip_flags(flags): """ Remove leading and trailing spaces from the list of flags. :param flags: The list of flags which should be stripped. :type flags: list[str] :rtype: list[str] :return: The list of flags with leading and trailing spaces removed. """ return [flag.strip() for fla...
86dcd6c346ec618542d251dc0576c1e3acb3725e
621,469
def hexStrToInt(inputstr): """ Converts a string with hex bytes to a numeric value Arguments: inputstr - A string representing the bytes to convert. Example : 41414141 Return: the numeric value """ valtoreturn = 0 try: valtoreturn = int(inputstr,16) except: valtoreturn = 0 return valtoreturn
33a54c1212b75caa961c667b4ca25c6d888517e5
621,470
def rgb2lab(R_G_B): """Convert RGB colorspace to Lab Adapted from http://www.easyrgb.com/index.php?X=MATH. """ R, G, B = R_G_B # Convert RGB to XYZ var_R = ( R / 255.0 ) # R from 0 to 255 var_G = ( G / 255.0 ) # G from 0 to 255 var_B = ( B / 255.0 ) ...
aa1c2befa547e358c46ab7533709ad41ccd0f1a2
621,472
def convert_bytes(tot_bytes): """Convert bytes to human-readable GB, MB, KB. Parameters ---------- tot_bytes : int Total number of bytes. Returns ------- [GB, MB, KB, rem] : list Bytes divided into Giga, Mega, Kilo bytes. """ GB, rem = divmod(tot_bytes, 1024 * 1024 ...
4e2726c45fccfde62b53b842d3e30cb28fef19b1
621,474
def log_index(caplog, loggerpart, level, msg, after=0): """Find a log in line in the captured log, return the index of the first occurrence :param after: only consider records after the given index""" close = [] for i, (logger_name, log_level, message) in enumerate(caplog.record_tuples[after:]): ...
67e6e17c0ab89f7edce7322c3c4a030845a8cfd3
621,480
def low_left_digit(in_txt): """ Return the digit in the lower left corner for the board 'in_txt' given as a 81 length string. """ return(in_txt[9*8 + 0])
6d6fb7fb33d2ac14f10064e33ef3e776a4608cc4
621,490
from typing import Iterable def loadtest_base_name(scenario_name: str, uniquifiers: Iterable[str]) -> str: """Constructs and returns the base name for a LoadTest resource.""" elements = scenario_name.split('_') elements.extend(uniquifiers) return '-'.join(elements)
3af1237b839c5022214e4ee640e43cec5f591fd1
621,492
def _subs(value): """Return a list of subclass strings. The strings represent the ldap objectclass plus any subclasses that inherit from it. Fakeldap doesn't know about the ldap object structure, so subclasses need to be defined manually in the dictionary below. """ subs = {'groupOfNames': ['k...
443168aa2fac4f5919f42b3d83d420058a9894fe
621,496
import torch def _get_entropy(p): """ Compute entropy of the input prob vector p Inputs: p -- torch variable, a list of prob vectors Outputs: entropy -- the average entropy of all the vectors """ log_p = torch.log(p) return torch.mean(- p * log_p)
1401477802969ae9a2e804e41f39e59d5ae8e485
621,497
import json def get_json_columns(json_file_or_dict, check_row_count=1): """Determines the names of columns in a JSON file Args: json_file_or_dict (str or dict): The file name of the JSON file, or a dict check_row_count (int, optional): The number of rows to use to get columns Returns: ...
f1a11fe8c071c05c76f05898dd543b4344f96c09
621,501
import re def get_error_num(function): """ Extract first number from function name and return string with it. Leading zeroes will be truncated. """ match_obj = re.search(r"\d+", function.__name__) if match_obj is None: return "0" result = match_obj.group(0).lstrip("0") if resu...
67f0fb54e2b7bc260b1f26e2f15f1ea101f2168b
621,502
import base64 def _base64encode_dict(dict_): """ Base64-encode all `bytes`-items in this `dict_` and recursively in all sub-dicts. :param dict dict_: dict, potentially containing bytes objects :returns: dict with bytes-objects base64-encoded """ def _encoded(val): if isinstance(val, by...
93b769463bc379144f9d68dd5ee6e4ff15289f26
621,504
from typing import Dict from typing import Any def txt_to_dict(txt_val: str) -> Dict[str, Any]: """ Return dict from string of "key:val; key2:val2" pairs. Parameters ---------- txt_val : str The key/value string (items separated by ";", key/value separated by ":") Returns ...
aacff590c0c0e4adcfbf0fd923e4f0e8f3c4f96b
621,505
def has_key(dictionary, key) -> bool: """Dictionary contain the key.""" return key in dictionary.keys()
a71063972d88d533a6aa16349ef0522a615fa443
621,506
def separateUnit(string): """ Separates the unit and number in given string e.g. '1 em' will return (float(1), 'em') """ # create an array of valid numbers (and '.') nums = ['.'] + [str(x) for x in range(10)] num_str = str() unit_str = str() # find first char in string that i...
ceab4bfc607c70714a5bc0459747a087eefec344
621,509
def dict_has_key(target_dict, key): """ Judge if target_dict has target key """ return key in target_dict
5433ff9adb36a6c90be0f92b64e25d42e8e0fc1c
621,510
def duration_str(s): """ s: number of seconds Return a human-readable string. Example: 100 => "1m40s", 10000 => "2h46m" """ if s is None: return None m = int(s // 60) if m == 0: return "%.1fs" % s s -= m * 60 h = int(m // 60) if h == 0: return "%dm%d...
18c8ce1f4c9f8f4ac854b87319b68509bdfd193e
621,511
def read_file(path): """Returns file content as string.""" file_handler = open(path, 'r') content = file_handler.read() file_handler.close() return content
b723d1a7e4f6a51d4bd1451c228f2317193643d4
621,513
def diff(list1, list2): """ Difference between unique elements of lists :type list1: list :param list1: first list :type list2: list :param list2: second list """ c = set(list1).union(set(list2)) d = set(list1).intersection(set(list2)) return list(c - d)
b2218d1d1dc7794bd697032f6752992ff84b307f
621,514
def manage_met(met_input): """Manage metadata.""" final = [] with open(met_input, 'r') as metadata: for i in metadata: i = i.strip().split('\t') result = [j.strip() for j in i] final.append(result) return(final)
538805ef739d8c133bd1d2078e7e2151dbf3bd91
621,518
def get_release_status(release): """ :param release: helm release metadata :return: status name of release """ return release['info']['status']
f4722b0353893d8940a7166b7f85ce8d5e8e3700
621,522
def fix_constants(constants): """Given a dict of constant parameters this function returns a fixer function that updates the json to include these constants""" def fix_const_updater(json): json.update(constants) return json return fix_const_updater
73eabb149537b8744bf060a3d4c4b64a794c981a
621,532
def rect_to_bounding_box(rect): """ Method for converting the dlib's rect object to standard --coordinates of (x1, y1) and (x2, y2) :param rect: :return tuple: (x1, y1, x2, y2) """ x = rect.left() y = rect.top() w = rect.right() - x h = rect.bottom() - y return x, y, w, h
f7e954af041e379d4e056437814f39d5ede3a35e
621,534
def make_create_payload(**kwargs): """Create payload for upload/check-upload operations.""" # Remove empty arguments for k, v in kwargs.items(): if not v: del kwargs[k] payload = {} payload.update(kwargs) return payload
56787734860084f40edaf93fdbd7299975cfb284
621,537
def tokenize(records): """Create a token mapping from objects to integers. Parameters ---------- records : array_like of iterables. Collection of nested arrays. Returns ------- enum_map : dict Enumeration map of objects (any hashable) to tokens (int). """ unique_ite...
3b64bedc5de575c97f32c717d4b56db9e284f680
621,538
def get_controller_object(controller): """ Get the object associated with a controller, or None if there's no object, which is usually a group. """ controller_objects = controller.controllerObject.listConnections(s=True, d=False) # controller_objects = pm.ls(cmds.listConnections(unicode(controlle...
b57d7d9218c53a3424132d91cfe217af498b1426
621,540
def convert_dict_keys(func, in_dict): """Apply a conversion function to all keys in a dict. Parameters ---------- func : callable The function to apply. Takes a str and returns a str. in_dict : dict The dictionary to convert. If some value in this dict is itself a dict, it a...
70ff6ac34d760df1a5e70df4f49c2a5358999585
621,542
def overlap(response1, response2): """Any overlap between two responses?""" if response1.protein == response2.protein: coord2 = response2.coords for i in response1.coords: if i in coord2: return True return False
a7654b14aa98cb0fbf777adf37bc44871ede30ff
621,543
def parse_bro_metadata(filename, meta_separator): """Parses Bro metadata. This function parses Bro metadata that is encoded in the filename. The parsed metadata can include any of the following, in order: File source (e.g. HTTP, SMTP, SMB) Connection UID File UID Originator ...
b8576e2bb9f2435a71d2339b9d2809f4aeae2bbd
621,549
def in_range(value, rng): """ Check if value(s) are in the range of list[0], list[1] """ return (rng[0] <= value).all() and (value <= rng[1]).all()
686b208e5388d56e6f9a6d77003f5f8800496d67
621,551
def front(inlist): """ Pop from a list or tuple, otherwise return untouched. Examples -------- >>> front([1, 0]) 1 >>> front("/path/somewhere") '/path/somewhere' """ if isinstance(inlist, (list, tuple)): return inlist[0] return inlist
011c21b9dd3974b69162c9e93602e96d1b285b3e
621,553
def build_flags(flags): """Convert `flags` to a string of flag fields.""" return "\n".join([" flag: '" + flag + "'" for flag in flags])
fdd8e6d2caee31ebe9956cf6248e9ef85e6cec6e
621,557
def centers(array): """ Centers corresponding to bin edges (assuming regular linear intervals). """ return array[0: -1] + (0.5 * (array[1] - array[0]))
082ba946cc6a6c90b8e385342c99c2cdccb454d6
621,558
def apache_client_convert(client_dn, client_ca=None): """ Convert Apache style client certs. Convert from the Apache comma delimited style to the more usual slash delimited style. Args: client_dn (str): The client DN client_ca (str): [Optional] The client CA Returns: t...
40eb9d75fed646f7fadfce20571fd7f5792bd73f
621,562
def _build_shift_table(grammar, item_sets, item_set_transitions): """ Returns a list of maps from terminal symbols to shift actions. A shift action is simply an index into the item_set array. """ shifts = [] for transitions in item_set_transitions: shifts.append( { ...
aec2de0f9fd65a3e47eca5601e738ae18be35ee1
621,563
def query_tw_username(username): """ES query by Twitter's author.username Args: username (str) Returns: ES query (JSON) """ return { "query": { "bool": { "filter": [ {"term": {"doctype": "tweets2"}}, {"mat...
390fa38c43601323a92b7cfe74f0c17052d51754
621,564
from typing import List def worst_of_five(errors: List[float]) -> bool: """Returns true when the last error is the worst of five last ones.""" if len(errors) > 3 and (errors[-1] > max(errors[-5:-1])): return True return False
7828994933218f5eb037c92541dfbf021ad5db22
621,566
import math def correct_csmf_accuracy(uncorrected): """Correct Cause-Specific Mortality Fraction accuracy for chance Chance corrected metrics are derived from the general equation: .. math:: K_j = \\frac{P(observed)_j - P(expected)_j}{1 - P(expected)_j} where K\ :sub:`j` is the corrected s...
8a887fd6d8774b68466fbb041f8518fc4eb075a7
621,567
def eval_acer(results, is_print=False): """ :param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score """ ind_n = (results[:, 1] == 0) ind_p = (results[:, 1] == 1) fp = (results[ind_n, 0] == 1).sum() fn = (results[ind_p, 0] == 0).sum() ...
28e8a4cd15bb27efd2e52053c3759ebd14e3080d
621,569
import codecs def read_dataset(inpath): """ Reads a generic dataset with rows separated by tabs into a list. Args: inpath (str): Path to dataset. Returns: list: List of line contents as tuples. """ with codecs.open(inpath, 'rb', 'utf-8') as infile: return [tuple(line.strip().split('\t')) for line in inf...
9b93e50cfad94ca5f52f80ae2389ded16d5ea20b
621,574
import time def dtime(t0): """time since t0.""" return round(time.perf_counter() - t0, 2)
5bf458ed277f2fa48c6b751397659e0216654d15
621,582
def alpha_to_num(char): """Takes a single character and converts it to a number where A=1""" translator = { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9, "J": 10, "K": 11, "L": 12, "M": 13, "N": 14, "O": 15, "P": 16, "Q": 17, "R": 18, "S"...
d9f0c02b7e5d155c21b992304a006832a5e872ff
621,584
def compute_U(Sigma_sfr, Sigma_g): """ Ionizaton parameter as a function of star formation and gas surface densities. reference: Eq. 38 Ferrara et al. 2019 inputs: Sigma_sfr in Msun/yr/kpc^2 Sigma_g in Msun/kpc^2 """ out= (1.7e+14)*(Sigma_sfr/(Sigma_g*Sigma_g)) return ou...
164761c824f22fede47d03c3e5cc2f673715c103
621,586
import inspect def get_function_name(count: int = 0) -> str: """ Return the name of the function calling this function, i.e., the name of the function calling `get_function_name()`. """ ptr = inspect.currentframe() # count=0 corresponds to the calling function, so we need to add an extra #...
faf295d6c9b5a520ff0a06ff21fdfa8542b2a070
621,588
import random def rand_nonce(diff): """ Returns a random int in [0, 2**diff) """ return random.randint(0,2**diff-1)
6bab357d4183e429e02919753681593c3a2dca26
621,589
def decode(index, idxs, end= "\n", sep= ""): """-> str decodes `idxs : seq int` according to `index : PointedIndex`. stops at `end` and joins the results with `sep`. """ end = index(end) tgt = [] for idx in idxs: if idx == end: break tgt.append(index[idx]) return sep.j...
6d14f0a989db4e6315b61460761bf0ffc39643cc
621,590
def convert_py_to_cpp_namespace(python_namespace: str) -> str: """Convert a Python namespace name to a C++ namespace. Parameters ---------- python_namespace : `str` A string describing a Python namespace. For example, ``'lsst.example'``. Returns ------- cpp_namespace : `str...
d45f54db237ecb4888a2701fe02b6eda254a4dee
621,591
def h_bubble(heigth_layer, epsi_vapor): """ Calculates the heigth of bubble layer. Parameters ---------- epsi_vapor : float The vapor content of bubble layer, [dimensionless] heigth_layer : float The heigth ligth layer of the liquid, [m] Returns ------- h_bubble : fl...
f713bd71553fce50461359fd5946113e26927937
621,593
import configparser def to_dict(cfg: configparser.ConfigParser) -> dict: """Converts ConfigParser object into dictionary""" return {s.lower(): dict(cfg[s]) for s in cfg.sections()}
45833955bcfb32c6b0cadc9ad6027686da300d1a
621,597
import re def rm_quotation_marks(sent): """ Remove single quotes used as quotation marks (e.g. some 'phrase in quotes') Remove double quotes used as quotation marks (e.g. some "phrase in quotes" or ``phrase in quotes'') """ sent = re.sub(r"\s'([\w\s]+[\w])'\s", r' \1 ', sent) return re.sub(r'[...
0977773e9b9b72af9566ca3c31d3c30f9800e165
621,600
def _TaskPathToId(path): """Transforms the pathname in YAML to an id for a task. Args: path: Path name. Returns: id of the task. """ return '<joiner>'.join(path)
3eb350717250e316cfff402812033cc467270d38
621,602
import base64 def img_to_base64(path): """Converts an img to a base64 encoded string.""" with open(path, 'rb') as f: return base64.b64encode(f.read()).decode()
6d0a948cb8350a0e8c91cb774878a6f1028c9fef
621,603
def select_from_list(tabstop, values): """Completes a partially-completed `tabstop` to one of predefined `values`.""" if tabstop: values = [value[len(tabstop):] for value in values if value.startswith(tabstop)] if len(values) == 1: return values[0] return "[" + " | ".join(values) + "]"
19653b29bd216b6fa35576207453dc854c8282ed
621,604
import uuid def createUUID(prefix='uid'): """Create uuid4 specific UUID which uses pseudo random generators. Further, uuid is prefixed using 3 letter acronym to visually differentiate among them Some prefix used when generating UUIDs are: ant - annotation img - image lbl - label / cat - category train ...
01f861dd2d59988c8fead8c618850e86e7f2e233
621,606
def get_positive_label(values): """ Returns the label of the positive examples. :param values: the labels :type values: collections.Iterable[float] :return: the label of the positive example :rtype: Optional[float] """ for value in values: if value > 0.0: return valu...
b89ef9bb33164d204fbf8932a80c28beb17ec346
621,611
def get_config_name(arduino): """Return config filename for arduino.""" config_name = str(arduino.vid) config_name += str(arduino.pid) config_name += str(arduino.serial_number) config_name += ".yaml" return config_name
b62cfead2d5fc1129a4c522cbbf5ae056182c2ae
621,613
def completion_score_flag( df, photo_bit_binary="mhm_PhotoBitBinary", has_genus="mhm_HasGenus", sub_completeness="mhm_SubCompletenessScore", completeness="mhm_CumulativeCompletenessScore", inplace=False, ): """ Adds the following completness score flags: - `SubCompletenessScore`: The...
089752f71981c599410b80212012e46907e374a0
621,615
from typing import Dict def _dictify(data, keys, val) -> Dict: """ Helper function to generate nested dictionary from list of keys and value. Calls itself recursively. Arguments: data (dict): dictionary to add value to with keys keys (list): list of keys to traverse along tree an...
333c95927b5ec9fe9132299ed5c8f9be9e9cecaa
621,617
def signal_1D(mu, i, key, n): """ Generate signal power consumption S values for all messages mu. Parameters: mu -- list of bool, size n x 2^n i -- integer in [0,n-1] key -- list of bool, length n n -- integer Return: S -- list of integers, length 2^n """ S = [] # For each message mu for j in rang...
0c2d2b4468066d6767ca9f7aaa25d929a862dd42
621,619
def string_safe_list(obj): """ Turn an (iterable) object into a list. If it is a string or not iterable, put the whole object into a list of length 1. :param obj: :return list: """ if isinstance(obj, str) or not hasattr(obj, "__iter__"): return [obj] else: return list(ob...
0688a5a9392c7bf07d1903fdedcd686317a87967
621,620
def plot_bar(data, **kwargs): """ Plot bar chart.""" ax = data.plot(kind='barh', **kwargs) return ax
51c8f6e39e9fdbd85541b117e8c03291bb7db08f
621,621
def _can_condition_be_resolved(base_conditions, extending_condition): """Determine whether an extending condition can be resolved.""" return all( condition_name in base_conditions for condition_name in extending_condition.extended_conditions )
3111fef3c202002cb12ab6bcade5a64b24dff12a
621,623
def quadratic_bezier_point(p0,p1,p2,t) : """Returns the bezier point returned with p0, p1, and p2 as reference points at fraction t along curve. Reference point arguments are length 2 numpy arrays.""" return (1-t)**2*p0 + 2*(1-t)*t*p1 + t**2*p2
b7b19934f56e6cb1bbaa898a32876098dc9c3c41
621,625
def arrow_out(value): """Convert an Arrow object to timestamp. :param Arrow value: The Arrow time or ``None``. :returns int: The timestamp, or ``None`` if the input is ``None``. """ return value.timestamp if value else None
67fe51f921d7373618003be1721a0cfd194d4a72
621,626
def remove_ssml_tags(parm_text:str) -> str: """Remove the SSML tags from parm text. The tags are surrounded by <chevrons>.""" output_text = '' inside_chevrons = False for c in parm_text: if c == '<': inside_chevrons = True elif c == '>': inside_chevrons = False ...
f0428f94f9dcb159b27b79cb02a8ed31a6ceb086
621,630
def t_scat(t_G, f): """ Scattering timescale in seconds at f in MHz. t_G is the timescale at 1GHz, in seconds. """ return t_G*((f/1000.)**(-4))
9e37c67000b1cca38935975f3e5735e7729e085a
621,631
def tokenise(text): """Character based tokeniser.""" return list(text)
3be218ade79a00e648acf538d0523cd10f3089ad
621,632
import csv def _read_benchmark_numbers(benchmark_filepath): """Reads benchmark numbers from file. Args: benchmark_filepath: string, file path to benchmark result. Returns: A list of benchmark names and a list of corresponding performance number (in ns). """ with open(benchmark_filepath) as c...
3ca77a17a3db9fb63d8b6f73d1c896b76f7723f3
621,633
import unittest def make_suite(tc_class, config, root_tmpdir, ports_sock): """Compose test suite based on test class names.""" testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(tc_class) suite = unittest.TestSuite() for name in testnames: suite.addTest(tc_class(nam...
2c15747faf4aaf88801941b70540459b4f98761b
621,634
import io import csv def roaming_channel_csv() -> io.StringIO: """ Generates a placeholder RoamingChannel.csv """ header = [ "No.", "Receive Frequency", "Transmit Frequency", "Color Code", "Slot", "Name", ] sio = io.StringIO() writer = csv....
404496ad2e8dbddf1def0e1259d580b6c82c86e4
621,635
def find_neighbors(pindex, tri): """ Adapted from @user2535797 at https://stackoverflow.com/questions/12374781/how-to-find-all-neighbors-of-a-given-point-\ in-a-delaunay-triangulation-using-sci Parameters ---------- pindex: integer a index of a single point tri: ...
63dd75ba53a7144e0988ba02d719da20eb41c4ca
621,636
def dup_quo_ground(f, c, K): """ Quotient by a constant in ``K[x]``. **Examples** >>> from sympy.polys.domains import ZZ, QQ >>> from sympy.polys.densearith import dup_quo_ground >>> f = ZZ.map([3, 0, 2]) >>> g = QQ.map([3, 0, 2]) >>> dup_quo_ground(f, ZZ(2), ZZ) [1, 0, 1] >...
f272e4789ac37ced50b93d1600aa43b814543849
621,641
import requests from bs4 import BeautifulSoup def extract_communication_text(communication_url): """Pull the raw text of a SOTU communication (message or address).""" # open the communication page communication_request = requests.get(communication_url) # read the html for the communication page communicat...
f6b0beafcd9b6add3e283243fba7b7aefc8a7c1c
621,642
from typing import List def get_header_col(board: List[List[str]]) -> List[str]: """ Get the column header. (Note: this list should only contain alphabet.) Parameters ---------- board: List[List[str]] 2D array containing all the game detail, including column he...
aa07bbc9197984ec5b1020044c45aace9565618c
621,643
async def get_home(): """[Get Home ] Returns: JSON Response with a small introductory message """ return {"msg": "Home Microservice"}
3f0b9ae768e1182e590f8adbe6a8965565eada6e
621,644
def assert_ops_in_graph(expected_ops, graph): """Assert all expected operations are found. Args: expected_ops: `dict<string, string>` of op name to op type. graph: Graph to check. Returns: `dict<string, node>` of node name to node. Raises: ValueError: If the expected ops are not present in th...
abd5ac66f391168f636bdc10c24695d0b638d16a
621,645
def read_stripped_lines(filename): """Return a list of stripped lines from a file""" with open(filename) as fobj: return [line.strip() for line in fobj.readlines()]
968ddf8f4c091dc59a7e3b965f96c09383fb41ec
621,649
def is_hex(s): """Return whether s is a hex string.""" try: int(s, 16) except (TypeError, ValueError): return False return True
2bf4e431cfc5a2d8fc9e2a30850546202063e67c
621,650
def flat_set_from_df(df, col, condition=None): """Flatten Series from DataFrame which contains lists and return as set, optionally after filtering the DataFrame. """ if condition is not None: df = df[condition] lists = df[col].tolist() return set([item for sublist in lists for item in su...
035b8d7ab5698752c880b078380558a7fa0c6645
621,652
from typing import Tuple def get_axis_collision_times( distance_entry: float, distance_exit: float, v: float ) -> Tuple[float, float]: """ Gets the entry and exit times for a collision in 1 dimension. Parameters: distance_entry: float - Entry distance of first object to other. di...
263516eb7300e8268471b5eb55ba21fa6202066a
621,655
import click def format_boolean(value): """ Format boolean with color """ if type(value) == bool: if value: return click.style(str(value), fg='green') else: return click.style(str(value), fg='red') return value
ef55b36e078d2ea74ab89453bbd4dfac88a808aa
621,656
def line_XY_intersection(point, direction): """ Finds intersection (x,y) between XY plane and a line. point: some point on the line (e.g. camera position) direction: some vector pointing along the line Assumes numpy arrays. """ r = point[2]/direction[2] xy = point[0:2] - r*direction[0:...
bb225d2e72f0237f7f573de1895a155e79ead975
621,658
def split_repo_name(repository): """Take a string of the form user/repo, and return the tuple (user, repo). If the string does not contain the username, then just return None for the user.""" nameparts = repository.split('/', 1) if len(nameparts) == 1: return (None, nameparts[0]) else: ...
3740b80c2658315a27498b05832b120a937e053b
621,659
import csv def dict_from_tsvfile(filename): """open a tab separated two column file, return it as a str->str dict""" d = {} with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter='\t') for row in reader: d[row[0]] = row[1] return d
cece7b5a06cee4bf5c8082f56d2f1e235d021497
621,660
def celsius_to_fahrenheit(celsius): """ convert celsius to fahrenheit """ fahrenheit = (celsius * (9.0/5.0)) + 32.0 return fahrenheit
6a2b0b4c2a15459a92241345ae66d14b548b9a38
621,662
from typing import Dict from typing import Any def get_test_data() -> Dict[str, Any]: """ Auxiliary method to return test data args. :return: Test data. """ return { "root": { "branch1": {"number": 23, "string": "value"}, "branch2": {"object": object(), "boolean": ...
78b162e8f6b2b1b8f82e73f55bf0bc5f3425e829
621,664
def transObj(object, disp): """ Translate an object """ return (object[0]+disp,object[1])
0deddfb85e8241a48efa232a2041ba06af65c25f
621,668
def by_type(blocks, slist=None): """Sort blocks into layout, internal volume, data or unknown Arguments: Obj:blocks -- List of block objects. List:slist -- (optional) List of block indexes. Returns: List:layout -- List of block indexes of blocks containing the volume t...
dfe773699d3a606518b7e9128ceb4f60db9cc898
621,671
def dashes(count): """ Return the specified number of dashes as a string """ return "".join(("-" for _ in range(0, count)))
3be3a43284b6a88497432985fe858038e4229d17
621,677
def min_sample_rate(st, min_sps=20.0): """ Discard records if the sample rate doers not exceed minimum. Args: st (StationStream): Stream of data. min_sps (float): Minimum samples per second. Returns: StationStream: Stream checked for sample rate criteria...
4eae6fe43d04be82e345ee2ee9db218ace8cc32e
621,678
def column(data, key): """ get specific column Args: data (list(dict)): data object returned by csv.DictReader key (str): name of the column (header in first row) Returns: list(float): column data """ column_data = [] for row in data: column_data.append(float(row[key])) return colu...
f86ec7af049c354c3bd57132ac45500fc042e1be
621,681
def _validate_record_owner(signer_public_key, record): """Validates that the public key of the signer is the latest (i.e. current) owner of the record """ latest_owner = max(record.owners, key=lambda obj: obj.timestamp).agent_id return latest_owner == signer_public_key
dd21fa40d05b5f020b0c3eee302a8a9d627717f7
621,683
def _CalcLutOffsets(lods, isalpha): """ Compute the offset into the lookup tables by LOD level. Return an array of offsets indexed by LOD. Also return (appended to the end of the result) the lookuop table size. The result differs depending on whether this is the alpha or brick LUT. The highe...
4dbb59e2e85b668eab0ec10ff1081f431d5bf7a2
621,684
def find_max(nums, left, right): """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True ...
484133577b3e6681410ea7c11a30a19754a6586d
621,685
def sum_array(a): """ Returns the sum of the numbers. :param a: an array of integers. :return: the sum of the array. """ return sum(a)
9faf64c29a423364202cda0370756bddd6a594aa
621,687
def bitflags(*sequential, **named): """ Enum helper to generate bit-flag values usage: ENUM_TYPE = bitflags(VALUE, VALUE2, VALUE3) or: EnumType = bitflags(VALUE1, VALUE2, VALUE3=0x0ff) The result will be VALUE = 0x1, VALUE2 = 0x2, VALUE3 = 0x4, etc. """ values = [] base = 1 for _ ...
3304093b2a0496f82f0e523f4c29fd1f41350579
621,688