content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_degree_of(links: list, node_i: int) -> int: """ computes the degree of each node and maps the node id to its degree :param links: a list of tuples with [(src, dst), ...] :param node_i: index i of node :return: degree of node i """ deg_i = sum(1 if node_i == i else 0 for i, _ in link...
940f5942430d62091afd6ecdf668faa48621f017
643,111
def vector_dot(v1,v2): """ Calculate vector dot product of two vectors. Parameters ---------- v1,v2 : ndarray The arrays to calculate the product from. The vectors are represented by the last axis. Returns ------- product : float or ndarray Scalar produc...
3f51c17f2aad5ebc1c788534177bf3fe89fd7a04
643,113
def make_video_path(task_path, itr): """ Generate a video name based on a task name and iteration number :param task_path: the name of the task :param itr: the iteration number """ return "{}_tune_iter{}.mp4".format(task_path.replace("_center", ""), itr)
ff245ad4890863fd6cfec600071f8b10e4330e63
643,115
def get_label_name(node, dialogue_list): """ Takes a node and returns the name for its label """ for dialogue in dialogue_list: if dialogue["Id"] == node["Parent"]: label_name = "{}_{}".format(dialogue["DisplayName"], node["Id"]) return label_name
0971de9fac5861785edc97625ae9d331449403a3
643,117
def add_numbers(number1: int, number2: int) -> int: """Add two numbers together. Args: number1 (int): The first number. number2 (int): The second number. Returns: int: The sum of number1 + number2. Examples: >>> add_numbers(10, 5) 15 """ return number1 ...
52fc2bee6059e677d3d105e6ab9abe0720680b0d
643,118
def cent_from_year(year): """ takes an integer and returns the matching century """ if year == 0: return 1 elif year < 0: return -(year - 1) // -100 else: return (year - 1) // 100 + 1
cfa372d9b21b7d6b56bfbd73be4518f485f1b8ce
643,123
def y_fitted_line(m_val, b_val, vec_x): """ This function returns the fitted baseline constructed by coeffecient m and b and x values. ---------- Parameters ---------- x : list Output of the split vector function. x value of the input. m : int/float inclination of the bas...
03913131167279428e48a60cef3a8c9035916f5b
643,126
def dissolve_footer(soup): """ Remove the BNN footer, generated date, build, etc. This is included with all OOTP pages. """ # Dissolve the BNN footer trs = soup.body.table.find_all('tr') last_tr = trs[-1] last_tr.decompose() # Dissolve the generated date and build tbls = soup.bo...
922e0c835ef1e6bd8e7924e449f8d61e6613e94e
643,127
def _compile_module(s, name='<string>'): """ Compiles a string representing a python module (file or code) and returns the resulting global objects as a dictionary mapping name->val. @param name: Optional name for better error message handling. """ gen_module = {} code = compile(s, name...
3b3ea8a428617adead44bec55b5f1638328e0148
643,128
def siqs_build_matrix_opt(M): """Convert the given matrix M of 0s and 1s into a list of numbers m that correspond to the columns of the matrix. The j-th number encodes the j-th column of matrix M in binary: The i-th bit of m[i] is equal to M[i][j]. """ m = len(M[0]) cols_binary = [""] * m ...
faac80e9d645e829f198b167ef8ee9c4cfa2df0a
643,129
def binary_to_int(binary: str) -> int: """Convert a binary string to an integer Args: binary (str): Binary string Returns: int: Integer value of binary string """ return int(binary, 2)
aa7d694facc18c3872d345c5c06dcd6ad3b51105
643,130
def is_timerange(item: str) -> bool: """Returns True if the item is a TAF to-from time range""" return ( len(item) == 9 and item[4] == "/" and item[:4].isdigit() and item[5:].isdigit() )
28961d8699574b1fca24dc0961a281f92d12aac3
643,132
def ensure_arg(args, arg, param=None): """Make sure the arg is present in the list of args. If arg is not present, adds the arg and the optional param. If present and param != None, sets the parameter following the arg to param. :param list args: strings representing an argument list. :param string arg: arg...
c65bec4c3352a2d7e197bd3c0f75d09b9b796722
643,137
def ns_split(term): """ Take apart an ElementTree namespaced name, returning the namespace and a localpart. """ (ns, local) = term.split("}") assert ns[0] == "{" ns = ns[1:] return ns, local
ffadd295bb2bce5f2d39c6e8acdedfeb34682ba3
643,139
import requests def get_request(url, headers): """ Method which makes a GET request to specified url :param url: url :param headers: headers :return: get response """ return requests.get(url, headers=headers)
d1b4c346d2382840de2197b0cc78e473bccbbbbf
643,141
import hashlib def genId(filename): """ Generates an identifier suitable for ingestion Based off of the Watson Discovery Tooling method of generating IDs """ return hashlib.md5(filename).hexdigest()
ca645809ba94f7d9d4e81a87f2ca8e643114a5ed
643,143
def validate_key_value_pairs(string): """ Validates key-value pairs in the following format: a=b;c=d """ result = None if string: kv_list = [x for x in string.split(';') if '=' in x] # key-value pairs result = dict(x.split('=', 1) for x in kv_list) return result
81713ae08bc096168843384aa79563f4737d4c41
643,144
from typing import Union from typing import Tuple def _to_tuple(value: Union[Tuple[float, float], float]) -> Tuple[float, float]: """Convert value to a tuple if it is not already a tuple. Args: value: input value Returns: value if value is a tuple, else (value, value) """ if isin...
1efad46b6ade7ab07aa5bf09fb18c6588d619246
643,147
def walkable(grid_array: list) -> list: """Get a list of all the coordinates that are walkable Args: grid_array (list): map of the terrain Returns: list: all coordinates that are walkable """ walkable = [] for i, row in enumerate(grid_array): for j, cell in enumerate(ro...
848f2f3eec16086e235d4ea9e2181c8c7ba31375
643,153
import re def _sanitized_conf(parser): """Formats parser config, redacting database url password.""" out = parser.format_values() return re.sub(r'(?<=:)\w+(?=@)', '<redacted>', out)
580640d160c88ecaf9a5bc9df741df1d9056ae5c
643,157
def image(img): """Function to obtain image from tensor""" img = img / 2 + 0.5 # unnormalize return img.numpy()
bb53dde61db4b3af81e2e123ed9c6c2dd87fabaf
643,158
def total_consumption(consumption: float, area: float) -> float: """Get the total consumption of a building in a year. It's function of the energy consumption and total area. Args: consumption (float): The consumption of the building in kWh/m².year. area (float): The total area of the buil...
33ff23a3fff2a095c0800db5a36550f74047c418
643,160
def OffsetList(inputList, offset): """ Return a list equal to the input list with all entries equal to the corresponding entries in the input list plus the supplied offset """ outputList = [] for entry in inputList: outputList.append(entry + offset) return outputList
66b1633791d3ca6ef91006e8cbca88a6dbe9db99
643,162
import re def set_filename_version(filename, version_number, pattern): """Write the given version number in the given (in filename) file, after the given pattern. E.g.: set_filename_version('setup.py', '1.0.0', 'version') Extracted from Flask source, see: - file: flask/scripts/make-r...
c2cd57e38809a4ff25ee8fcd4d722eadbb95ec9f
643,164
def create_end_repeat(nstep, iline, protocol, inrepeat): """ Given a line from a file with format: add to the protocol an [# : End repeat nstep steps :] line Parameters ----------- nstep : int Number of steps in a loop iline : int Counter for protocol lines protocol : ...
cb058834d0be6a147e1800a61a4381e837177f8e
643,165
import math def columnate(strings, separator=", ", chars=80): """ render a list of strings as a in a bunch of columns Positional arguments: strings - the strings to columnate Keyword arguments; separator - the separation between the columns chars - the maximum with of a row """ col_w...
eb205ba26b90c55d21502a3ffc758986b3ee54e8
643,166
def _before(node): """ Returns the set of all nodes that are before the given node. """ try: pos = node.treeposition() tree = node.root() except AttributeError: return [] return [tree[x] for x in tree.treepositions() if x[: len(pos)] < pos[: len(x)]]
63c0fef768c3ade922a834fba24c3797d5d0e932
643,167
def calculate_immediate_dominators(nodes, _dom, _sdom): """ Determine immediate dominators from dominators and strict dominators. """ _idom = {} for node in nodes: if _sdom[node]: for x in _sdom[node]: if _dom[x] == _sdom[node]: # This must be th...
51775461134dc07993462c903c3d6a23b26199da
643,170
from typing import List def simulate_day(school: List[int]) -> List[int]: """Simulates a school of fish for one day and returns the school.""" return [*school[1:7], school[0] + school[7], school[8], school[0]]
126f430920474d54651bf7a19a18006f66792ff1
643,171
def chromedriver_path_of(system_name) -> str: """Gets system name and returns a string path :param string system_name: should be "Windows", "Linux" or "Darwin". System name can be obtained from "platform" module and "system" function """ if system_name == 'Windows': return "./chromedriver....
6fd114dc105e14de6abb7ecf6cc9e40cdc03d751
643,172
def mscb(t): """ Find the index of the most significant change bit, the bit that will change when t is incremented aka the power of 2 boundary we are at >>> mscb(0) 0 >>> mscb(1) 1 >>> mscb(7) 3 >>> mscb(8) 0 """ return (t^(t+1)).bit_length()-1
aedcd5501a83d872053582608552e841535e027b
643,176
from typing import List import re def get_terms(tickers: List[str]) -> List[str]: """Map tickers to bond terms, e.g. Brazil 5Y -> 5Y""" return re.findall(r"\d+[MYmy]", "|".join(tickers))
9ba1a9d348282a6202002c187346c7b95da4504a
643,185
def format_percent(n, baseline): """Format a ratio as a percentage (showing two decimal places). Returns a string. Accepts baseline zero and returns '??' or '--'. """ if baseline == 0: if n == 0: return "--" else: return "??" return "%.2f%%" % (100 * n ...
274c3dce2f88ec9fa5f0d4ea41890a8dfd7d79cb
643,186
def _gendesc(infiles): """ Generate a desc entity value. Examples -------- >>> _gendesc("f") 'coeff' >>> _gendesc(list("ab")) ['coeff0', 'coeff1'] """ if isinstance(infiles, (str, bytes)): infiles = [infiles] if len(infiles) == 1: return "coeff" retur...
81645b805f4d8e7a0ba110be53c30fdb4c7ac0c5
643,187
def _get_arguments(*args): """Helper function which prepares input data for custom myrange2 and myrange3 functions. It makes sure that at least one but no more than three integers were supplied. Returns tuple of three integers, where the last number is never zero. Can raise TypeError or ValueError exce...
234efb67c7b6c7aa879dd5f85f77f99e8abf1a3a
643,188
def has_empty_domains(csp) : """Returns True if the problem has one or more empty domains, otherwise False""" variables = csp.variables for var in variables: if len(csp.get_domain(var)) == 0: return True return False
a3506b1ffd73c1a26dcaa9fcd2428e8e1bc83875
643,196
def github_paginate(session, url): """Combines return from GitHub pagination :param session: requests client instance :param url: start url to get the data from. See https://developer.github.com/v3/#pagination """ result = [] while url: r = session.get(url) result.extend(r....
6c951f0dadc3d6b8c0bae7ada61bbd46e085d544
643,200
import csv def get_stats(csv_path): """Parse aligned results csv file to get results. Args: csv_path: str, aligned result path, e.g., xx_corresp.txt Returns: stat_dict, dict, keys: true positive (TP), deletion (D), insertion (I), substitution (S), error rate (ER), ground truth numbe...
f453d5af9a8f77a9767ccbb1f78ee21d4122844c
643,202
import re def scrape_eps(soup, sngl=False): """Scrapes all episode names and numbers from a specified HTML page, in the form of a specified :class:`bs4.BeautifulSoup` object. :param soup: A :class:`bs4.BeautifulSoup` object containing the HTML of the Wikipedia page to be scraped. :para...
a9dcbe7e409ba36615048fd3d73dd8636a6c12b9
643,203
def read_file(filename): """ Return the contents of a file as a string. """ with open(filename) as f: str = f.read() return str
1adf083bf2d54c9ed07e7afa81ff746bc36b4303
643,204
def get_strand_color(is_rev): """ Get color for forward and reverse reads :param is_rev: True if read is reversed :return: """ if is_rev == 240.0: return 1 else: return 0
b306eefe724ad35b7738240ec04e9fb4b12e1b57
643,211
import math def define_cutoff(max_freq, passing_freq, high_pass): """ # Define Cutoff Value Args: max_freq (int): the max frequency allowed passing_freq (int): the cutoff value high_pass (bool): if is a high pass filter Returns: float: the cutoff value to subtitute wc ...
ad87b730e2659fcd75b6d014249012a89978d62d
643,216
import types def is_object_module(obj): """ Test if the argument is a module object. :param obj: Object :type obj: any :rtype: boolean """ return isinstance(obj, types.ModuleType)
b9dc22543b19be02f0cd2ac396370affcd0e3aeb
643,223
def registrar(registry, name="entry"): """ Creates and returns a register function that can be used as a decorator for registering functions into the given registry dictionary. :param registry: Dictionary to add entry registrations to. :param name: Name to give to each entry. "entry" is used by def...
9ca990c262133d26659fb92823f0b12b867424db
643,229
from datetime import datetime def make_datetime_pretty_md(DateTime: datetime): """pretty print DateTime for use in Markdown Args: DateTime (datetime): DateTime to pretty print, format: 2020-09-05 17:30:00 Returns: str: pretty printed DateTime, in markdown syntax """ return DateT...
5e337258554af5f8d0678ab0d4ba384753a9e906
643,233
def string_to_array(string): """Convert a string to array, even if empty.""" if string == "": return [""] return string.split()
c601c7966fc11477e32dbd5ccbd12fb0e212ebc0
643,235
def senhas_nao_iguais(senha, senha2): """Verifica se as senhas digitadas não são iguais""" return senha != senha2
6e6391749da3c2e2bc84cf52e56e0e81efaed777
643,242
def quote_stripped(value: str) -> str: """ Strip out a single level of single (') or double (") quotes. """ single, double = "'", '"' if (value.startswith(single) and value.endswith(single)) or\ (value.startswith(double) and value.endswith(double)): return value[1:-1] return value
b7016bc484948d053635795b8617b962535b46c6
643,243
import six def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (six.text_type, six.binary_type)): ...
37cb0d03e17603b4a3461476d4f20b12383de14c
643,252
def code_block(text, language=""): """Return a code block. If a language is specified a fenced code block is produced, otherwise the block is indented by four spaces. Keyword arguments: language -- Specifies the language to fence the code in (default blank). >>> code_block("This is a simple c...
3f530bf9027340b46d4724020f2285c5e74813f7
643,255
def le16_bytes_to_list(bstr): """Convert 16bit little-endian bytes to list""" i = iter(bstr) return [lb + 256*next(i) for lb in i]
32aaa6830bb917ff0e3d5a1aa24f96fbecff55e6
643,257
def get_displacement_vector(molecule, start_atom, end_atom): """ Get the displacement vector between `start_atom` and `end_atom`. """ position1, position2 = ( molecule.get_atomic_positions((start_atom, end_atom)) ) return position2 - position1
a15e6dfcc701660979889d004b12d188fc629664
643,261
from typing import Dict def is_directory_entry(entry: Dict) -> bool: """Return if given entry is for directory.""" return "directory" == entry["type"]
948ca602171be307e132a370e33ec77767d110de
643,263
import six def FuzzyBool(value): """Returns value as a boolean with special handling for false-like strings.""" if (isinstance(value, six.string_types) and value.strip().lower() in ('false', 'no', '0')): return False return bool(value)
ee29b901e8acbfc8249dc26f744a3768a39861e9
643,265
def _get_saml_user_data_property(request, prop_slug): """ Shortcut for getting samlUserData properties generated by python3-saml. These can sometimes manifest as lists or strings. :param request: HttpRequest :param prop_slug: string (property slug) :return: string or None """ value = req...
28cf482cfe2c71e5afebd8fae96c0b9b6739b120
643,266
def rect_from_sides(left, top, right, bottom): """Returns list of points of a rectangle defined by it's `left`, `top`, `right`, and `bottom` coordinates, ordered counter-clockwise.""" return [ (left, bottom), (right, bottom), (right, top ), (left, top ), ]
083676ce815b97afe16cd53ffedb75212f3f03c1
643,271
def img2windows(img, h_split, w_split): """Convert input tensor into split stripes Args: img: tensor, image tensor with shape [B, C, H, W] h_split: int, splits width in height direction w_split: int, splits width in width direction Returns: out: tensor, splitted image ""...
1580c818bf4ba2d0a13d0c039f4d4028dc113061
643,273
def tcl_findprd_prepcuref(center, tail, noprefix=False, key2mode=False): """ Prepare candidate PRD. :param center: PRD-center-tail. :type center: str :param tail: PRD-center-tail. :type tail: int :param noprefix: Whether to skip adding "PRD-" prefix. Default is False. :type noprefix: ...
af19ccf44a5ef9eb8492ce9a44a4775703e5841b
643,275
from typing import List from typing import Callable import inspect def find_scrapers(module) -> List[Callable]: """ Build a list of 'scraper' functions contained in a module. These consist of every function public function (i.e., does not begin with_) that is defined, but not imported, in the module ...
7f6c3ebdf41f16a5998b4cba679b895b05d491da
643,276
def has_numbers(string): """Returns true if there are digits in the string""" return any(char.isdigit() for char in string)
27d741316aac6c0d0125cd35028bf589febea9a8
643,279
def is_melceplogf0_evaluator(evaluator_keys): """Are these evaluator keys from MelCepLogF0 evaluator?""" return (len(evaluator_keys) == 2 and evaluator_keys[0] == 'max_mel_cep_distortion' and evaluator_keys[1] == 'max_log_f0_error')
253ae0bd5b71b536466f58414a3040f6ea6aade5
643,282
from warnings import warn def _deprecated_getitem_method(name, attrs): """Create a deprecated ``__getitem__`` method that tells users to use getattr instead. Parameters ---------- name : str The name of the object in the warning message. attrs : iterable[str] The set of allowe...
d6521c46120ce8bcbde62b1e73735e0218773ba8
643,283
def _to_utf8_string(s): """Encodes the input csv line as a utf-8 string when applicable.""" return s if isinstance(s, bytes) else s.encode('utf-8')
af7eeae024a48df61f56851e2fe78596b70b5fac
643,284
import click def show(obj): """Display the content of the configuration file.""" if obj.temporary: click.secho("This is a temporary config file. Please create a " "proper config file using `quickci config create`.", fg="red") click.echo(obj.show()) retur...
e4c0ca97a17577c493809d95a0c6736e37073bb4
643,285
from typing import Iterable from typing import Any def contains_class_type(l: Iterable, cls: Any) -> bool: """Return if the given list contains a class with the given type""" for e in l: if isinstance(e, cls): return True return False
e74d14f2365ddbbc9153048af6977220be4db4f8
643,286
def extract_uuidlist_from_record(uuid_string_list): """Extract uuid from Service UUID List """ start = 1 end = len(uuid_string_list) - 1 uuid_length = 36 uuidlist = [] while start < end: uuid = uuid_string_list[start:(start + uuid_length)] start += uuid_length + 1 uui...
f6f4acdbdbfdf9aac909669d7ea3ad8492bed685
643,289
def get_exchange_trading_pair(table_name): """Function to get exchange and trading_pair bc coinbase_pro has an extra '_' """ # for coinbase_pro if len(table_name.split('_')) == 4: exchange = table_name.split('_')[0] + '_' + table_name.split('_')[1] trading_pair = table_name.split('_')[2] + ...
d6516142e4c987c087e4cba278f356f003575020
643,290
def parse_did(did): """Takes a did and returns the run number, dtype, hash""" scope, name = did.split(':') number = int(scope.split('_')[1]) dtype, h = name.split('-') return number, dtype, h
de7e9727877f968e2a7ce5b37146b229f6b04663
643,292
def standard2natural(mu, sigma): """ Converts standard parameterisation of a 1-D Gaussian to natural parameterisation. :param mu: The mean, (*, D). :param sigma: The standard deviation, (*, D). :return: np1, np2, (*, D), (*, D). """ assert mu.shape[-1] == sigma.shape[-1], "mu (*, D), sig...
c80158dc0122579e55ead6bcd83cf5a411dd214b
643,296
def collapse_axes(xlab, ylab): """Return X/Y labels for unique X positions""" _xlab, _ylab, pos = [xlab[0]], [ylab[0]], [0] for i in range(1, len(xlab)): if xlab[i] != xlab[i-1]: _xlab.append(xlab[i]) _ylab.append(ylab[i]) pos.append(i) return _xlab, _ylab, po...
4bf4ae99b8addaa0ea4973446e81f1d5701c4889
643,305
def check_filters_enabled(params): """ Check if filters are enabled """ tab = params.tab filters = tab.get('filters', None) if tab is None: return False if not filters or not filters.get('items', None) or not filters.get('conjunction', None): return False return True
fcd86f63e3bf6a182eeabb3d2986feb98bd0b9b6
643,308
def get_percentile_values(cycle_time_dataframe, percentiles): """ Get percentile values for cycle times from cycle time data frame. """ return tuple([cycle_time_dataframe.Cycle_time.quantile(p/100.0) for p in percentiles])
b6eb5b30562959984f327b9b8616f3c3abb1cae9
643,309
def compare_bits(mem_entry, mem_idx, test_bit): """Compare a memory entry to the expected bit value for that entry""" valid_entry = True for bit_idx, bit in enumerate(reversed(mem_entry)): valid_entry = False assert int(bit) == test_bit, ( "Incorrect bit @ index {} of mem entry #...
4afa92b95331f6134aac63833da8fb3aade93f8c
643,312
def hitTest( a, b ): """Circular collision test. Assumes x, y, and radius members on both objects.""" r = a.radius + b.radius x = abs( a.x - b.x ) y = abs( a.y - b.y ) if x <= r and y <= r and x*x + y*y <= r*r: return 1 return 0
98285d71f6ab73501cff7a3d4cd56891b00e25bc
643,314
def validateCPE(cpe): """ Returns None if CPE text is valid, validation error string otherwise. """ if not cpe.startswith("cpe:"): return 'CPE must start with "cpe:"' return None
8f7beaf75b2cff6e8a2efb0456e872bf968807fe
643,315
def bold(text: str): """Return bolded text""" return f"**{text}**"
56adc60296db01de3bd63b0b5383cc3ed4dc90be
643,316
import re def _compose_comment(remote: str, sha: str, git_log: str) -> str: """Composes a comment describing the original (triggering) commit. Arguments: remote {str} -- a link to the remote git repo sha {str} -- the hash of the commit git_log {str} -- the git log for the commit ...
d6aac13cbf23db2b5ea94e0b6cfe9600f1900283
643,319
def CountWordOccurences(wordArray): """Returns a dictionary containing each word in the array and how often it occurs""" dict = {} for word in wordArray: # If the dictionary does not contain the word, add it to the dictionary with 1 occurence if not word in dict: dict[word] = 1 ...
7b964dd16a3826043f7730df642f51b0cdbcdadd
643,320
def add_one(x: int): """Add one to `x` Args: x: an integer """ return x + 1
878d5e795ac45e67b471cbfce6d215c55f44f69f
643,322
def discard_empty_elements(soup, exempt=()): """Remove HTML elements that have no/whitespace-only content""" for tag in soup.find_all(): if len(tag.get_text(strip=True)) == 0 and tag.name not in exempt: tag.extract() return soup
8c50b0bf611a66327631f5fe044a6b52464f14d3
643,324
from typing import Tuple def get_color_for_figure(n_vertices: int) -> Tuple[int, int, int]: """Returns an RBG color tuple depending on the number of vertices.""" if n_vertices == 3: return (200, 0, 0) elif n_vertices == 4: return (0, 200, 0) elif n_vertices >= 10: return (0, ...
d917f8d357f3fd4be2902a970d4224695f3a7dcf
643,325
import math def dist(p0, p1): """ Calculates the distance between two xy coordinates, each each coordinated supplied by a tupel""" return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
87f1ce3e1062d1d365bab27066e9d4271e4a251d
643,326
def get_ages(df, sex): """Returns the ages of men or women, whom Embarked from section C. Parameters: df(pyspark.sql.DataFrame): based on the titanic.csv module sex(str): for our dataset, it is a binary classification of 'male' or 'female' Returns: List[float] """ ...
93d49fc11845b8dc560c7235e441eb7b101d19d1
643,327
def pb_dict(message): """Create dict representation of a protobuf message""" return dict([(field.name, value) for field, value in message.ListFields()])
6c2d592b44436244ff2d5a508222eace151a3a75
643,333
def get_resource_bar(avail, total, text='', long=False): """Create a long/short progress bar with text overlaid. Formatting handled in css.""" if long: long_str = ' class=long' else: long_str = '' bar = (f'<div class="progress" data-text="{text}">' f'<progress{long_str} max="...
c0c1c492a05c96aca31367825f91441f3a1f600b
643,336
def dongers(l, b, i): """ヽ༼ຈل͜ຈ༽ノ""" b.l_say(dongers.__doc__, i) return True
4da1f390eedd827b35d09e891359c03958cc4db4
643,337
def to_camel_case(text, split=" "): """ Converts text to camel case, e.g. ("the camel is huge" => "theCamelIsHuge") Args: text (string): Text to be camel-cased split (char): Char to split text into """ camel_case_text = text splitter = text.split(split) if splitter: c...
6fc02f75ec86a246c1fed1425b3050304184f7e3
643,340
def read_input(path: str): """ Read game board file from path. Return list of str. """ lines = [] with open(path, 'r', encoding='utf-8') as file: for line in file: lines.append(line.strip()) return lines
5ea07d7a4e150296c0dda74cf38bea2b476cde11
643,341
import torch def check_random_state(seed, device=torch.device("cuda")): """Turn seed into a torch.Generator instance Parameters ---------- seed : None | int | instance of torch.Generator If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a n...
ffd35e2e588be3e49094720b2bea892229f6db45
643,343
def swedish_translator(firstname, lastname): """Check if 'firstname lastname' is a Swedish translator.""" swedish_translators = [ "Linnea Åshede" ] name = firstname + " " + lastname if name in swedish_translators: return True return False
c23cb86f3f3d434c37fd20a680309244889536d5
643,344
from pathlib import Path def get_stock_root(path: Path) -> Path: """ Traverse from given path up till root of the system to figure out the root of the stock repo. A stock repo must be hangar repo, a git repo and must have a head.stock file. The head.stock file has the information required for stockroo...
86a80f300a79b7e7e7e9b3f1714127e1f23efa88
643,345
from pathlib import Path import shutil def pwhich(command: str) -> Path: """Path to given command. shutil.which only returns a string. :returns: Path to command :rtype: pathlib.Path """ path_str = shutil.which(command) assert path_str, f"{command} not found" return Path(path_str)
a926850cab35bace6c2187933438c44001d01eeb
643,347
def removeprefix(text, prefix): """Removes a prefix from a string. If the string starts with the prefix string, return string[len(prefix):]. Otherwise, returns the original string. This function has been added in Python3.9 as the builtin `str.removeprefix`, but is defined here to support previous v...
a3a2cff3cd6b16626760ff332f4a702e20b7fffb
643,348
def _get_class_name(property_repr: str) -> str: """ Extract the class name from the property representation. :param property_repr: The representation :type property_repr: str :return: The class name :rtype: str """ return property_repr[: property_repr.index("(")]
1d99a452288c0d6909692cfb535d614989ba8540
643,350
def fixed_crops(X, crop_shape, crop_type): """ Take center or corner crops of images. Inputs: - X: Input data, of shape (N, C, H, W) - crop_shape: Tuple of integers (HH, WW) giving the size to which each image will be cropped. - crop_type: One of the following strings, giving the type of crop to co...
af35228a6e61e62920a60df7b3fd5431b047ff38
643,351
def mp0(en): """Return the 0th order energy.""" return en.sum()
64d16e66e58e421c829b093a89c6faeea7026690
643,352
def strip_numbers(text): """Strip numbers from text.""" return ''.join(filter(lambda u: not u.isdigit(), text))
1a2bb26577dbf67c7a47435043af0eea4859d926
643,355
def create_minio_dispatcher_node(name): """ Args: name(str): Name of the minio node Returns: dict: A dictionnary with the minio node configuration """ return { "endpoint_url": "http://{:s}:9000/".format(name), "aws_access_key_id": "playcloud", "aws_secret_acce...
df313dfa7152944332551dd70aab4b0a0e36ff56
643,358
def r_to_depth(x, interval): """Computes rainfall depth (mm) from rainfall intensity (mm/h) Parameters ---------- x : float, float or array of float rainfall intensity in mm/h interval : number time interval (s) the values of `x` represent Returns ------- output...
6472b75518c4ac9fa709d0efb9d2690cfabdca3f
643,362
def RunLintOverAllFiles(linter, filenames): """Runs linter over the contents of all files. Args: lint: subclass of BaseLint, implementing RunOnFile() filenames: list of all files whose contents will be linted Returns: A list of tuples with format [(filename, line number, msg), ...] with any viol...
b810322ad99185c06431336688f8e522ae72f8fc
643,365