content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def convert_ip(ip_str: str) -> float: """Convert innings pitched from the string representation to the float :param ip_str: String representation of innings pitched :returns: Float representation of innings pitched """ temp = ip_str.split(".") return int(temp[0]) + int(temp[1]) * (1 / 3)
f118332b64eda55b23ce2ffef989e96326ba401e
667,741
import logging def get_logger(args): """Creates the logger based on the provided arguments""" logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(args.log_level) return logger
a39e7a96eceaf7d47413f996d90bb066df92232a
667,747
def _parse_leaf_node_line(line): """ Return the leaf value given the string representation of a leaf node. """ return float(line.split('=')[1])
dd6054c8c3b23a7d7fc02c97388be97a58c49be0
667,749
import posixpath def api_path_join(*paths): """ Join API-style paths. """ return posixpath.join(*paths).strip('/')
1034198db585049e23d7a074acb26f44c72d5d12
667,754
def SIR_model(y, t, betta, gamma): """ Tradiional SIR model. :param y: :param t: :param betta: :param gamma: :return: """ S,I,R = y dS_dt = -betta*S*I dI_dt = betta*S*I - gamma*I dR_dt = gamma*I return ([dS_dt, dI_dt, dR_dt])
623cb64b9c9c22ed5930bdc1fe2435178ec883d2
667,759
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of the knot over the input knot vector using binary search. Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller. The NURBS Book states that the knot span index always starts from zero, i.e. for...
6050e7c09f290caa54bb6fb2f75082824c0faa85
667,760
def _autotuple(a): """Automatically convert the supplied iterable to a scalar or tuple as appropriate.""" if not hasattr(a, "__iter__"): return a if len(a) == 1: return a[0] return tuple(a)
1e8be83634e4d026b70a5f590c75765d8bafa4ba
667,762
def _loadfile(filename): """Returns a list of lines from `filename`""" with open(filename, 'r') as fd: lines = filter(lambda x: x, map(lambda x: x.strip(), fd.readlines())) return lines
ef11795224030a95b00ff67e021875a6d321c44c
667,764
def ternary(condition, first_opernad, second_operand): """Same as `first_operand if condition else second_operand`""" return first_opernad if condition else second_operand
3d5210fbaa6fa0de0ffd4318328b2c10122254ba
667,765
import pathlib def git_path(repo_root, tail=None): """Returns a Path to the .git directory in repo_root with tail appended (if present) or None if repo_root is not set. """ path = None if repo_root: path = pathlib.Path(repo_root) / ".git" if tail is not None: path = pat...
6335deadff7613657ea3dcd7e5019bf863aba67d
667,766
def read_labels(file_name): """ Read list of labels from file like this: label1 label2 label3 ... """ labels_tmp = [] try: with open(file_name, 'r') as f: labels_tmp = f.readlines() labels_tmp = [(i.rstrip(), 0) for i in labels_tmp] ...
247807c6a7a5e452b7bdb8a3874aabc889ef1ec9
667,768
def bare_spectrum(sweep, subsys, which=-1, **kwargs): """ Plots energy spectrum of bare system `subsys` for given ParameterSweep `sweep`. Parameters ---------- sweep: ParameterSweep subsys: QuantumSystem which: int or list(int), optional default: -1, signals to plot all wavefunction...
a441f5e838092aff6b7328c25d18357570d59c35
667,769
import torch def accuracy(outputs, labels): """ Calculate model accuracy * :param outputs(torch.tensor): Pytorch weights tensor * :param labels(list(str)): List of known labels :return (torch.tensor): Prediction accuracy """ _, preds = torch.max(outputs, dim=1) return torch.te...
737c5d82d0cec4955a47cfb879e6f1e0048f3408
667,770
def attn(card, mode=None, files=None, seconds=None, payload=None, start=None): """Configure interrupt detection between a host and Notecard. Args: card (Notecard): The current Notecard object. mode (string): The attn mode to set. files (array): A collection of notefiles to watch. ...
0f5313f56dfb91f407bdd5b428baf0890ebb9597
667,773
def first_alpha(s): """ Returns the length of the shortest substring of the input that contains an alpha character. """ for i, c in enumerate(s): if c.isalpha(): return i + 1 raise Exception("No alpha characters in string: {}".format(s))
7cccb3a5721323f8084731a587c6718bbe2dd368
667,774
def vswr_to_gama(vswr): """Calculate Gama (Reflection Coefficient) from VSWR""" gama = (vswr-1)/(vswr+1) return gama
cf3416b7dab6856606b764226ea359386dcafb80
667,777
def lerp(a, b, pos) -> float: """### Basic linear interpolation. This method returns a value between the given `a`->`b` values.\n When `pos=0` the return value will be `a`.\n When `pos=1` the turn value will be the value of `b`. `pos=0.5` would be\ half-way between `a` and `b`. """ lerp...
52039693bd702d4b41c219ac4667ebc2832b407e
667,779
def __get_codeclimate_severity(cpio_severity: str) -> str: """Get Code Climate severity, from CppCheck severity string CodeQuality: info, minor, major, critical, blocker """ map_severity_to_severity = { "high": "critical", "medium" : "major", "low" : "minor" } return map...
07b86d9a696eaf486dce4051a12c046a8087c85d
667,780
def change_parameter_unit( parameter_dict: dict, multiplier: float ) -> dict: """ Currently only used to adapt the latency parameters from the earlier functions according to whether they are needed as by year rather than by day. Could be more generally applicable. Args: parameter_dict:...
e3138e7c017e967f94f2c23b7c1937ee1a78a2d6
667,785
def is_in(elements, value): """ Determines if a value is in a list. It also handles degenerate cases when instead of a list, elements is True, False or None """ if not elements: return False elif elements is True: return True else: return value in elements
7d1c44966bd7eeaa8c4919d3d835ed13c6466ce7
667,787
def parse_endpoint(endpoint): """ Parse endpoint into (blueprint, endpoint). blueprint can be :const:`None` """ if '.' in endpoint: return endpoint.split('.', 1) return None, endpoint
ad1960367d1cd768641fd46dc4a8ef8886340d5e
667,791
def dict_swap(d): """ Swap dictionary keys and values. :type d: dict """ done = {} for k, v in d.items(): done[v] = k return done
4c050534fc0d3b4e5d6fcbf45ea51b43ae70cfb4
667,792
import copy def merge_dict(bot, top): """Helper function for merging dict fields over another dict. Merge top dict onto bot dict, so that the returned new dict has the updated top vals.""" new = copy.deepcopy(bot) for k, v in top.items(): new[k] = v return new
e52acd0bf1864cf8adb47b8ce85179fb74c25269
667,796
def get_gene_capacity(genes_df, database, col='GeneID'): """Get gene capcaity from the stored metadata""" capacity = (database.groupby('geneid').capacity.mean() .to_frame(name='GeneCapacity')) genes_df = genes_df.merge(capacity, how='left', left_on='GeneID', right_index=True) return gene...
f2091adedea143e46df3a6c18822bdbbc8e27f7f
667,798
import json def get_model_id_list(redis): """ Get the list of model ids """ ids = redis.get("m:ids") or "{}" return json.loads(ids)
65ef7d7884b0d93d4ce84f3fdb37feaae642d537
667,801
import random def get_random_string(characters, length=8): """ Returns a string of the requested length consisting of random combinations of the given sequence of string characters. """ return ''.join(random.choice(characters) for _ in range(length))
f0df5cc9b40f331ddead3cb05930b9dd4066101f
667,804
def graph_list_to_features(graphs): """Get a TFRecord feature dictionary from a list of graphs. The features from each graph is prepended with a prefix and all added to the final dictionary at the same level. Parameters ---------- graphs : [Graph] Returns ------- features : dict (...
97728caa1e5aedbb9e404b39fb6174361dd2b0cd
667,805
def mkdir_cmd(path): """Return mkdir command""" return " ".join(["/bin/mkdir", "-p", path])
7172eaab58c15541394fa3f3a67d21cdb9d5e04a
667,806
def transform_region_to_coordinates(x_coord, y_coord, prefix_len, image_bit_level=10): """Transforms (x,y)-bit region into a square for a final level. This method converts a leaf on some level `prefix_le...
7ac371e69279e45ee11d6cd97a289f0d530d9960
667,809
from typing import Optional def join_address_and_port(address: Optional[str], port: int) -> str: """ Join address and port using format "{address}:{port}". :param address: The address. If not given, "localhost" is used. :param port: The port number. :return: Joined address and port. """ r...
3243875396292d2b6528f5475f43055f7515f973
667,810
def merge_st(S1, S2): """Merge two sorted Python Lists S1 and S2 into properly sized list S""" i = j = 0 S = S1+S2 while i+j < len(S): if j == len(S2) or (i < len(S1) and S1[i] < S2[j]): S[i+j] = S1[i] i = i+1 else: S[i+j] = S2[j] j = j+1 ...
5d8f202d30af988971c6e797313f2d82bd08c285
667,815
def deny(blacklist): """ Decorates a handler to filter out a blacklist of commands. The decorated handler will not be called if message.command is in the blacklist: @deny(['A', 'B']) def handle_everything_except_a_and_b(client, message): pass Single-item blacklists may...
bd195f9345487f14129d27f487b8708c6b7ffc6c
667,817
import re def sanatize_text(text): """ Replace non alphanumeric characters in text with '_' Parameters ---------- text : str text to sanatize Returns ------- text the sanatized text """ if text is None: return text return re.sub('[^a-zA-Z0-9]', '_', text...
1158929bc909fbc0791ea2057d01f8750ba7c822
667,820
def first_key(d): """get the first key of a dict""" return list(d.keys())[0]
e8e6dd99872e02fb6c563a91607cc0393db19549
667,823
def n_coeffs_from_ell_max(ell_max): """Returns the number of coefficients for an SWSFT with max degree ell_max.""" return (ell_max + 1)**2
2c173b7f0c2365ddde5136fa3d3984468e0339bf
667,831
def declare_temp(var_type, var_name): """Create a declaration of the form (declare (temporary) <var_type> <var_name) """ return [['declare', ['temporary'], var_type, var_name]]
0df399f269e8f5372fea81b60cd5ed008ba1d806
667,832
def _iteritems(d): """Like d.iteritems, but accepts any collections.Mapping.""" return d.iteritems() if hasattr(d, "iteritems") else d.items()
06a4cd4a0817b37f19cf89604112b3f9f9af26c4
667,834
def file_session_to_import_file(file_session): """Get the import file of its session.""" return file_session.file
05fc886ec02e15743b58c22758ccbd33e65e3937
667,835
def get_project_id_from_service_account_email(service_account_email: str) -> str: """ Get GCP project id from service_account_email >>> get_project_id_from_service_account_email('cromwell-test@tob-wgs.iam.gserviceaccount.com') 'tob-wgs' """ # quick and dirty return service_account_email.spl...
8761823c940b447813e1e476c6aad2588fd95b79
667,837
def _filter_slabs(provisional, max_size): """ Filters the repeat slabs from the list of all the zero dipole slabs. Creates lists of large and repeat slabs if any are present for the warnings Args: provisional (`list`): All zero dipole slabs generated with SlabGenerator max_size (`int...
4993bc6d89e0d09840c30ce54119cc54e9ca42f2
667,839
import curses def resolve_capability(term, attr): """ Resolve a raw terminal capability using :func:`tigetstr`. :arg Terminal term: :class:`~.Terminal` instance. :arg str attr: terminal capability name. :returns: string of the given terminal capability named by ``attr``, which may be empty...
763f75987fde643382fb89a06cd0d7f7225183fc
667,840
def prettify_format(format): """ Return the date format in a more human readable form. """ f = format.replate('%Y', 'yyyy') f = f.replace('%m', 'mm') f = f.replace('%d', 'dd') return f
190f9beb7b05f888f2ea58c7ae83a768dff04525
667,841
import copy def merge_left_with_defaults(defaults, loaded_config): """ Merge two configurations, with one of them overriding the other. Args: defaults (dict): A configuration of defaults loaded_config (dict): A configuration, as loaded from disk. Returns (dict): A merged confi...
630db012b0705e7c0ab12c9cd4e7df07b3ab56f0
667,842
def get_version_name(lang: str, major: int, minor: int, patch: int): """Return the package name associated with the lang ``name`` and version (``major``, ``minor``, ``patch``)""" return f"{lang}_{major}_{minor}_{patch}"
62a07e3d66a10acb398687a0ba76d9e09d7407bf
667,845
def _environment_intersection(run, caseversion): """Intersection of run/caseversion environment IDs.""" run_env_ids = set( run.environments.values_list("id", flat=True)) case_env_ids = set( caseversion.environments.values_list("id", flat=True)) return run_env_ids.intersection(case_env_id...
ee6f5c302667532820af0b1e89cfdeaa2c825cf1
667,851
import tempfile def wrap_in_tempfile(data): """Return SpooledTemporaryFile with given data as content, ready to read eg. as a subprocess input. """ wrapped = tempfile.SpooledTemporaryFile() wrapped.write(data) wrapped.flush() wrapped.seek(0) return wrapped
803df030888ab379cca12aae904e76451c1dc739
667,853
def number_of_internal_nodes(tree): """Return the number of internal nodes of tree.""" if tree.is_empty(): return 0 elif tree.left_child().is_empty() and tree.right_child().is_empty(): return 0 else: return 1\ + number_of_internal_nodes(tree.left_child())\ ...
5ec45205cfa41cde8146b47d51bb198cc2dd6bb0
667,855
import random def generate_gender() -> bool: """Returns a random gender. True is male and False is female. Returns: bool: A gender represented by a bool. """ return bool(random.getrandbits(1))
2012bb100ad7f63125c95a552f9b0671d2658df3
667,856
def compute_optimum(groups, elements): """Compute the number of elements per group and the remainder. :param elements: total number of elements :param groups: total number of groups """ return elements // groups, elements % groups
cf973952358d5ccb940b149a8bb5717302009b4a
667,857
import math import random def create_spiral_galaxy(system_count=100, spirals=2): """ Creates a spiral galaxy with given spirals (arms) and system count. The galaxy is unlinked and just creates the galaxy shape """ sep = 2*math.pi/spirals spiral_list = [] for x in range(spirals): ...
c64507d5819d285f019b6093d19aee9c74458c04
667,864
def valid_filename_from_query(query): """ Generates a filename from a query. This just gets the descriptor string from the query and replaces any spaces with hyphens. (At the time of writing, descriptors can't contain spaces, but in the future they will be able to.) """ return query.dnode.t...
84bcb62a73a13f10aafea59772d2186013e2fe0b
667,865
import re def trim_offset(name): """_trim_offset(name: str) -> str Remove address offset from name. Example: some_function+0x42beef -> some_function """ return re.sub(r'\+0x[0-9a-fA-F]+$', '', name)
9151d13dca9c7888dd0dd8bcc3d042a37043cd15
667,866
import random def choose_false_edges(non_edges, K): """ Randomly choose a fixed number of non-existing edges :param non_edges: Edges that are not in the graph :param K: Fixed number of edges to choose :return: A list of K false edges """ indexes = random.sample(range(1, len(non_edges)), K)...
9b77228ac29a9d9f28f52af8c4352526171de0f9
667,870
def caption() -> str: """Caption to be displayed at the end. Returns: str: Message for the users. """ return 'Thank you for using crypto-candlesticks\ Consider supporting your developers\ ETH: 0x06Acb31587a96808158BdEd07e53668d8ce94cFE\ '
0a8f70ea04899208d2d714225e23d9d8c6ac4194
667,872
import math def get_approx_flame_length(head_fire_intensity: float): """ Returns an approximation of flame length (in meters). Formula used is a field-use approximation of L = (I / 300)^(1/2), where L is flame length in m and I is Fire Intensity in kW/m """ return math.sqrt(head_fire_intensity / 3...
5728ba488c8535ea27df31526b9e67fd9d01c6aa
667,874
def indicator_function_ei(X_i, M, X_nk_n): """Returns 1 if M is smaller or equal than X_nk_n and if X_nk_n is smaller than X_i, and 0 otherwise.""" return 1*(M <= X_nk_n < X_i)
35312d20272289de6c6deaeb6c1398066e75773a
667,875
def remove_http_https_prefix(endpoint): """remove http:// or https:// prefix if presented in endpoint""" endpoint = endpoint.replace("https://", "") endpoint = endpoint.replace("http://", "") return endpoint
3ec56da4eae83fa7637fee2fe08b47d61513b30e
667,876
def timedelta_as_string(td): """Formatted 'HH:MM:SS' representation of a timedelta object""" hours, remainder = divmod(td.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) return "{:02d}:{:02d}:{:02d}".format(*map(int, (hours, minutes, seconds)))
80fc9d59a74869c32b841cbebedd8878d2fe22f9
667,877
import pathlib def remove_name_prefix(path: pathlib.Path, prefix: str) -> pathlib.Path: """Remove prefix from path name. Does nothing if prefix is not part of path name. Args: path: File system path to edit. prefix: String prefix to remove from path name. Returns: Path witho...
2b505dc4694d9677c3f22a0d237a86c2486c2d7a
667,879
from typing import Any def is_multi_agg_with_relabel(**kwargs: Any) -> bool: """ Check whether the kwargs pass to .agg look like multi-agg with relabling. Parameters ---------- **kwargs : dict Returns ------- bool Examples -------- >>> is_multi_agg_with_relabel(a='max') ...
ab692e293de43d2d1d9c45235b9be819f790db14
667,882
def IsInTargetRange( target, error_ref, warning_percentage, error_percentage, value): """Test if a value falls into warning or error range around a target. Args: target: The target value. error_ref: The error reference as the base for warning/error percentage. warning_percentage: The percentage of ...
edcb405bd409d543005e95907faa1eaa0a1304a9
667,892
def SplitStringAtSeparator(string,sep): """ split string at commas :param str string: string :param str sep: separator character :return: strlst(lst) - list of splited strings """ #return filter(lambda s: len(s) > 0, string.split(sep)) strlst=[]; items=string.split(sep) for s in...
2c5358d7c0e3374a7ffd198beb3352709b6401e6
667,894
import random def random_color() -> str: """Generate a random hex string.""" return "".join("{0:02x}".format(random.randrange(1 << 8)) for _ in range(3))
e9cbcb187c7a044f8953c400be92277c8b4e7764
667,895
def get_row_values(model, keys): """Get the values needed to fill a row in the table Parameters ---------- model : `dmsky.Model` Model that we are getting the data from keys : list Names of the properties we are reading Returns ------- vals : dict A dict...
aaa2d8298999f9a2c75a038e65563ec91c6fe299
667,896
def _str_to_list(s): """Converts a comma separated string to a list""" _list = s.split(",") return list(map(lambda i: i.lstrip(), _list))
c977685188bd84a35a08ff6d193659cc9d5135dc
667,902
def seed_generator(generator, logger, seed=0): """Set seed for Dataloader generators. DataLoader will reseed workers the "Randomness in multi-process data loading" algorithm. Use `generator` to preserve reproducibility. For more information, see https://pytorch.org/docs/stable/notes/randomness.html. ...
887a968f6a0b76e6bdbc8a11bc1f61416f8af76f
667,905
def __check_epsilon_productions(cnf_variables, cnf_productions, cfg_productions): """ Check whether all reachable epsilon productions from Context Free Grammar are present in Chomsky Normal Form productions. """ cfg_epsilon_productions = set( filter( lambda prod: prod.head in cn...
200fd0a1d9fc828a8c8c05336dbafa1c38f81c83
667,906
def bytes_to_readable_str(num_bytes, include_b=False): """Generate a human-readable string representing number of bytes. The units B, kB, MB and GB are used. Args: num_bytes: (`int` or None) Number of bytes. include_b: (`bool`) Include the letter B at the end of the unit. Returns: (`str`) A strin...
04ca844a745f192fd06f4346cac38e1ba410305e
667,912
def issue_to_dict(issue): """ Convert an issue to a dictionary suitable for outputting to csv """ issue_data = {} issue_data['id'] = issue.id issue_data['title'] = issue.title issue_data['description'] = issue.description issue_data['due_date'] = issue.due_date issue_data['labels'] =...
3ae05441a873a54c04588684f45581d2d7d17b04
667,915
def filterLargeClusters(clusters, input_size, cluster_fraction_thresh): """ Remove big clusters which have more points than a given fraction of total points in the input data. Arguments: clusters: [list] a python list containing found clusters in the reachability diagram plot (optional) - ...
d929a6e38e8297deb0912c7b2cc7f079858a7bc0
667,921
import requests def search_qms(keyword, limit=10, list_only=True, add_prefix=True): """Search for QMS tile providers from Quick Map Services. Args: keyword (str): The keyword to search for. limit (int, optional): The maximum number of results to return. Defaults to 10. list_only (bool...
ced370effbef75ea90c1f08e9d76df41cef1be56
667,922
import re def validate_language_code(language_code): """ Checks whether the language code given follows the ISO format, e.g "en" :param language_code: the string being checked :type language_code: str :returns: whether the code is valid :rtype: bool """ return re.match('[a-z]{2}', la...
688ff2699eb0373296b384a23e49678421951a72
667,923
import math def to_time(seconds): """Convert a number of seconds into human readable compact string.""" prefix = '' if seconds < 0: prefix = '-' seconds *= -1 minutes = math.floor(seconds / 60) seconds -= minutes * 60 hours = math.floor(minutes / 60) minutes -= hours * 60 days = math.floor(hou...
d09c9557799e700302197e565fad87ef43583ba0
667,924
def task_docs() -> dict: """Build sphinx document.""" return { 'actions': ['sphinx-build -q -W -j 4 -b html docs docs/_build/html'], }
d88637dc31ea19944b8582026d7ed5d00d2d3996
667,925
def _infection_indicator( health_states, infected_state_index): """Returns a binary vector that indicates whether individuals are infected.""" return [int(state == infected_state_index) for state in health_states]
cbdb63aba8caa843e81655602284b14403b28507
667,928
def productOfAdjacents(i, n, number): """Returns the product of n adjacent digits starting at i""" """Takes in the number as a string""" product = 1 for i in range (i, i+n): product *= int(number[i]) return product
2744e285bf7770be742b592eb0d5a47d21230f44
667,932
def filter_stops(stop_info): """ Filter for only type 0 stops, ie load/unload""" new_stop_info = {} for stop in stop_info: if stop_info[stop]["location_type"] == "0": new_stop_info[stop] = stop_info[stop] return new_stop_info
d23c1f857ef41268b453aa17d905b391a1fc1f91
667,936
def tokens_to_ops(token_dict): """returns a list of ops from a {tokenId:token_obj} dict""" outops = [] for t in token_dict.values(): outops.append(t.as_op()) return outops
cf130b145198a74725b7219417e28b05a13aa721
667,942
def table_exists(table_name, connection, schema=None): """Returns `True` if a table exists in a database. Parameters ---------- table_name : str The name of the table. connection : .PeeweeDatabaseConnection The Peewee database connection to use. schema : str The schema i...
0c4434796042b788963e9c7f9ea52438aabc9b28
667,944
def format_test_id(test_id) -> str: """Format numeric to 0-padded string""" return f"{test_id:0>5}"
91d6acefdda63300a32c832320662d9b5403d9fd
667,948
def _format_column_name(raw_column_name, year=None): """Formats a raw column name to remove: spaces, year and character with accents. Args: raw_column_name (str): a column name year: the year tu remove Returns: (str) The formatted column name. """ raw_column_name = ('_'...
f826a5fdef59f69a67129a3efe3812150f99d578
667,949
from typing import List def get_interval_in_s(interval: List[str]) -> List[int]: """Converts an interval in string form (e.g. [1:10, 2:30] in seconds, e.g. [70, 150] seconds""" return [int(sec.split(":")[0]) * 60 + int(sec.split(":")[1]) for sec in interval]
18e21da1cdf3bd13f91550283040f9bcfbd14cb5
667,952
def qualifier(entry): """ Get the qualifer for this entry. """ return entry["Qualifier"][0]
ec15b37a6f08a6317af422630ab87fbe7fb06427
667,953
def get_info_dic(s): """ Parse the string from the VCF INFO column and return it as a dictionary. """ info_tuples = [t.split('=') for t in s.split(';')] info_tuples = [t for t in info_tuples if len(t) == 2] tags = [t for t in info_tuples if len(t) != 2] # try: d = {k: v for (k, v) in ...
b05e0a2859a5289ae46a2dd0f191360324cd8fa0
667,954
def get_strings(soup, tag): """Get all the string children from an html tag.""" tags = soup.find_all(tag) strings = [s.string for s in tags if s.string] return strings
205da9aa8214cef5fdf4d97c084b6bf0c7756554
667,956
def require_methods(*method_args): """Class decorator to require methods on a subclass. Example usage ------------ @require_methods('m1', 'm2') class C(object): 'This class cannot be instantiated unless the subclass defines m1() and m2().' def __init__(self): pass ...
e822d633c66af5e4ce7ec6eda397ffa456a58aba
667,960
def get_val_string(input): """ String for a value, formatted for CSycles """ val = "" if input.type == 'VALUE': val = "{0: .3f}f".format(input.default_value) elif input.type in ('RGBA', 'VECTOR'): val = "new float4({0: .3f}f, {1: .3f}f, {2: .3f}f)".format( input.defau...
5559ba4862b60503a40de5c0dd934595223e8198
667,961
def fmt_addr(addr): """ Format a Bluetooth hardware address as a hex string. Args: addr (bytes): raw Bluetooth address in dongle format. Returns: str. Address in xx:xx:xx:xx:xx:xx format. """ return ':'.join(reversed(['{:02x}'.format(v) for v in bytearray(addr)]))
06433ed5fc270bcf28b999e00c9de5e4159d7398
667,966
def _new_block_definition(block_name): """ This will return a new block definition with the given block name :param block_name: Name of the block to define :return: str """ return """ myData = attributes "%s" version:1 ( -- Define the act...
51de9a007e6f84d9ce84663421523c3198ef72e9
667,967
from typing import List from pathlib import Path def install_requires() -> List[str]: """ Populate install_requires from requirements.txt """ requirements_txt = Path(__file__).parent.joinpath("requirements.txt").read_text() return [requirement for requirement in requirements_txt.split("\n")]
e6845d00a53b0f9bffa2d83066be7b542c92de0d
667,968
def _parse_control_depends(fields): """ Parse the package names of the 'Depends:' directive in a debian control file. References: https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-controlsyntax https://www.debian.org/doc/debian-policy/ch-relationships.html#declaring-relations...
10148a8573d03d626ba7c35d706ce7ebdf88f05f
667,970
def get_ipsec_udp_key_config( self, ) -> dict: """Get IPSEC UDP key material configuration, seed lifetime, max activation wait time, and whether to persist seed on appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - ikeless ...
b972d689c0cdd88e369f2c637d85515c473e9f45
667,972
def decode_pass(boarding_pass : str) -> tuple[int, int, int]: """Get the row, column and seat id from a boarding pass""" row = int(boarding_pass[:7].replace("F", "0").replace("B", "1"), 2) column = int(boarding_pass[7:].replace("L", "0").replace("R", "1"), 2) return row, column, row * 8 + column
7b88b36f4e3c810c08121de5141cb8cd06cf4564
667,974
def _has_version(name): """Check whether a package identifier has a version component.""" return name.rpartition("-")[2].replace(".", "").isdigit()
e18e3aec0a4fa0944723ed704de6cd6b0d1c2ed3
667,980
def is_comment(line): """check whether a line is a comment""" return line.strip().startswith("#")
ea8be8d15e8e120702a597d410acc414a1cb2590
667,981
def merge_bindings(program, node, bindings): """Create a combined Variable for a list of bindings. Args: program: A cfg.Program instance. node: The current CFG node. bindings: A list of cfg.Bindings. Returns: A cfg.Variable. """ v = program.NewVariable() for b in bindings: v.PasteBindin...
8443d40defc8f5950f886809bf616a4137dd6c6d
667,985
async def heartbeat(): """ Example heartbeat function for proxies and load balancers to check """ return { 'status': 'ok' }
7087322f2bc4b1bc03888a9b7191504ae62dde98
667,987
def ct_mimetype(content_type): """Return the mimetype part of a content type.""" return (content_type or '').split(';')[0].strip()
1e6fd5d841c38b76c6197a46a138593003c29486
667,989
def correct_description(description): """Given an description, return a version with any typos pedantically corrected.""" for old, new in ( ('- ', ' - '), (' -', ' - '), (' -', ' -'), ('- ', '- '), ): description = description.replace(old, new) r...
cf5086f0c56ca92de7d29302388aca7d4ea7858f
667,990
def dunder_partition(key): """Splits a dunderkey into 2 parts The first part is everything before the final double underscore The second part is after the final double underscore >>> dunder_partition('a__b__c') >>> ('a__b', 'c') """ parts = key.rsplit('__', 1) return tuple(parts)...
afd33d6e03de982bb7b71b0e7817fc5f1ae7207f
667,993