content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_slide_id(full_filename:str) -> str:
"""get slide id
Get slide id from the slideviewer full file name. The full_filename in
the slideview csv is of the format: year;HOBS_ID;slide_id.svs
for example: 2013;HobS13-283072057510;1435197.svs
Args:
full_filename (str): full filename o... | fd225d7803318e79659833f64d3069d3056ec698 | 639,101 |
from datetime import datetime
def timer(start_time=None):
"""Counting processing time
:parameter start_time: if None start to computing time, if not None compute total processing time
:type start_time: None, datetime
:return start datetime or print out total processing time
"""
# Get starting ... | 79e993abb2c87417035616ee29c7c084823fdc8e | 639,102 |
def sum_str(a, b):
"""Add two strings of ints and return string."""
if a == '' or a == ' ':
a = 0
if b == '' or b == ' ':
b = 0
return str(int(a) + int(b)) | bb8f4a6c34ef5c803b3dfe8b9a05fd5e84dba5cc | 639,108 |
def InitialILCInput(t, T, u0, uT):
"""
Conduct linear interpolation in the time domain for the torque and force
applied at the shoulder joints by the user of the PLLO, in order to
initialize the ILC algorithm.
Arguments
t: Time in [s].
T: Duration of ascension phase in [s].
... | 0b9c534d7d5ca429e312b07363d3e7599f77467e | 639,109 |
def unifymorphfeat(feats, percolatefeatures=None):
"""Get the sorted union of features for a sequence of feature vectors.
:param feats: a sequence of strings of comma/dot separated feature vectors.
:param percolatefeatures: if a set is given, select only these features;
by default all features are used.
>>> pri... | f9d628e56732f8567699f29b5810a0d7955bf1be | 639,110 |
def get_data_info(image_datasets):
"""
This function just returns information about our image datasets
Parameters:
- image_datasets: the image_datasets for the proejct
Returns:
- dataset_sizes: the size for each dataset
- class_names: the name for each class
... | d87ec367697599b0c7c1771016b50450d9a98415 | 639,111 |
def sanitizers_from_args(args):
"""Returns the sanitizers enabled by a given set of ldflags."""
sanitizers = set()
for arg in args:
if arg.startswith('-fsanitize='):
sanitizer_list = arg.partition('=')[2]
sanitizers |= set(sanitizer_list.split(','))
elif arg.startswit... | 2a45712d460eb46edff71883dbf724e60c034438 | 639,112 |
def join(seq, string="", func=None):
"""Create a list from sequence.
*string* is appended to each element but the last.
*func* is applied to every element before appending *string*.
"""
if func is None:
func = lambda x: x
return [func(x) + string for x in seq[:-1]] + [func(seq[-1])] | 4e0e2b500d88c3c81ebb028098244378065ce42d | 639,113 |
def pillar_tree_root_dir(integration_files_dir):
"""
Fixture which returns the salt pillar tree root directory path.
Creates the directory if it does not yet exist.
"""
dirname = integration_files_dir / "pillar-tree"
dirname.mkdir(exist_ok=True)
return dirname | d15f3c8e1871c470604d54d7fb0a344581323511 | 639,114 |
def _toIPv6AddrString(intIPv6AddrInteger):
"""Convert the IPv6 address integer to the IPv6 address string.
:param int intIPv6AddrInteger: IPv6 address integer.
:return: IPv6 address string that adopted the full represented.
:rtype: str
Example::
intIPv6AddrInteger R... | d61c180b4ea87e55129c253c339ad8a3adaaf268 | 639,116 |
def _get_cmd(*args):
"""Combines the non-interactive zypper command with arguments/subcommands"""
cmd = ['/usr/bin/zypper', '--quiet', '--non-interactive']
cmd.extend(args)
return cmd | a91e91c12d1ab3c7b7fcd3ae68db21544bfac1b0 | 639,118 |
from typing import Callable
def return_constant_value(value: float) -> Callable:
"""
For situations below in which we just need a function that returns a constant value.
Args:
value: The value that the function will return
Returns:
The function that returns the value, ignoring the ti... | 4449243d4ae1e688cd531f43622e1fa5c7b14eca | 639,122 |
def anyviolation(tickets, i, rule):
""" does the i'th field in any ticket violate the given rule? """
for ticket in tickets:
val = ticket.values[i]
if rule.anyok(val):
continue
return True
return False | 5fb17e20f560def1c6f9c14a4735b9a165ef5b4b | 639,123 |
def list_isos(cfg, distribution, isos):
"""generate a list with available ISOs"""
for release in cfg[distribution]['isos']:
for flavour in cfg[distribution]['iso_flavours']:
for architecture in cfg[distribution]['architectures']:
name = '-'.join((distribution, release, archit... | e14797d1bcda6d7a217c7235abde846d483e7cf8 | 639,125 |
def convert_macaddr(addr):
"""Convert mac address to unique format."""
return addr.replace(':', '').lower() | 020d90ccfa50287ae29f0bc2bedeb1d19da62c71 | 639,127 |
def ingest_configs(datacube_env_name):
""" Provides dictionary product_name => config file name
"""
return {
'ls5_nbar_albers': 'ls5_nbar_albers.yaml',
'ls5_pq_albers': 'ls5_pq_albers.yaml',
} | e61f6e8316cfe7cb8cf1768c465e9283530cc07b | 639,128 |
def storeUpdateResult(cache):
""" Store results
Update T0
Store temperaure results into a dataframe and
save it in the cache.
"""
timeStep = cache['ts']
TProfile = cache['TProfile']
T = cache['T']
cache['T0'] = T.copy()
TProfile[:,timeStep] = T.reshape(1,-1)
return cach... | 7272855fd553b5571a8451f779ddc0c60c8d8d67 | 639,129 |
from typing import Any
from typing import Optional
from typing import Dict
def default_target_fcn(actor: Any, instances: tuple, kwargs: Optional[Dict] = None):
"""
A target function that is executed in parallel given an actor pool. Its arguments must be an actor and a batch of
values to be processed by th... | 1ccfba2df2ac9f9f20e929557dadf880b634f044 | 639,131 |
import typing
def parse_tuple_string(argument: typing.Union[str, typing.Tuple, typing.List],
type_func=int) -> typing.Optional[typing.Tuple]:
""" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """
if argument is None:
return None
if isinstance(argument, str):
ret... | 45af8c412b00015c8fe434fe89ed802fe9dcedce | 639,132 |
def select_from_batch(advs, batch):
"""
Take a rollout-shaped list of lists and select the
indices from the mini-batch.
"""
indices = zip(batch['rollout_idxs'], batch['timestep_idxs'])
return [advs[x][y] for x, y in indices] | d0a20c1cd260f952e83c07d96a2747d9f42c36f8 | 639,147 |
def _before_underscore(s):
"""
:type s: str
:rtype: str
>>> _before_underscore('LC80880750762013254ASA00_IDF.xml')
'LC80880750762013254ASA00'
>>> _before_underscore('LC80880750762013254ASA00_MD5.txt')
'LC80880750762013254ASA00'
>>> _before_underscore('383.000.2013137232105971.ASA')
... | c3245b850381878d153543a1a45e6d42aa41da46 | 639,148 |
from datetime import datetime
from typing import List
def parse_text(now: datetime, key: str, group: List[str]) -> str:
"""
Handles the Text presentation
https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text
"""
# Era designator
if key == "G":
# no length impli... | 575862948d6442a73c8d270e4caed2c39ad50ddb | 639,150 |
def is_valid_uni(uni):
""" Validate the syntax of a uni string """
# UNIs are (2 or 3 letters) followed by (1 to 4 numbers)
# total length 3~7
if not isinstance(uni,str):
return False
if len(uni) < 3 or len(uni) > 7:
return False
if uni[:3].isalpha():
# 3 letters
return uni[3:].isnumeric()
elif uni[:2].... | 77df11c5a4fe857cd9e74a4dd13496244ee9a57f | 639,157 |
def _rear_right_tire_pressure_supported(data):
"""Determine if rear right tire pressure is supported."""
return data["status"]["tirePressure"]["rearRightTirePressurePsi"] is not None | dad0c415ae4ab11b7d2626741bfbf723b5893c22 | 639,161 |
def ChangeExtension(file_name, old_str, new_str):
"""
Change the 'extension' at the end a file or directory to a new type.
For example, change 'foo.pp' to 'foo.Data'
Do this by substituting the last occurance of 'old_str' in the file
name with 'new_str'. This is required because the file name may c... | f214c4f2109713b39681fd67d5984392d8fa3f47 | 639,164 |
def _build_bit_string_set(b_strings, dif_qubits, dif_values):
"""
Creates a new set of bit strings from b_strings, where the bits
in the indexes in dif_qubits match the values in dif_values.
Args:
b_strings: list of bit strings eg.: ['000', '011', ...,'101']
dif_qubits: list of integer... | 1b320e5e7fbe353951608c4aa7c3ecc84134da2c | 639,167 |
def _filter_subword(sentence, pattern_list):
"""
If the sentence contains any pattern in the pattern_list as a single word or phrase,
return true, else false
"""
word = False
sentence = sentence.replace('-', ' ')
sentence = sentence.replace('/', ' ')
sentence = sentence.replace('_', ' '... | 240db283d67a66d3089f7ea4a64160b0a903ae3d | 639,169 |
def split(iterable, f):
"""Split an iterable ``I`` into two iterables ``I1`` and ``I2`` of the
same type as ``I``. ``I1`` contains all elements ``e`` in ``I`` for
which ``f(e)`` returns True; ``I2`` is the complement of ``I1``."""
i1 = type(iterable)(i for i in iterable if f(i))
i2 = type(iterable)(... | 48234a60f3befdec86bac45a1189b0b3412529bd | 639,170 |
def logEq(a, b):
"""Returns 1 if the logical value of a equals the logical value of b, 0 otherwise"""
return (not a) == (not b) | 3abbc64ce6ff29864f9bc08a0971febcd4c8dfff | 639,172 |
import hashlib
def md5(string):
"""
Calculates a MD% sum of the provided string
:param string: The string to calculate teh MD% sum
:returns: MD% sum of the provided string
"""
return hashlib.md5(string.encode('utf-8')).hexdigest() | b8414267094e0f8ccd7275d69fb5bf0ffbd648fa | 639,176 |
def cloud_mask_ls8(image):
"""
Function to mask clouds based on the pixel_qa band of Landsat 8 SR data
:param {ee.Image} image input Landsat 8 SR image
:return {ee.Image} cloudmasked Landsat 8 image
"""
# Bits 3 and 5 are cloud shadow and cloud, respectively.
cloudShadowBitMask = (1 << 3)
... | d3284468d8acf2c00d5d5061333a1990f7c6b8e9 | 639,181 |
def solve(grades):
"""
Return grades rounded up to nearest 5 if above 38, otherwise, do not round
the score.
"""
rounded_grades = []
for grade in grades:
if grade >= 38:
rounded = ((grade + 5) / 5) * 5
if rounded - grade < 3:
grade = rounded
... | 42012d042ec6e997abb419f5cbcac78b607ca0b0 | 639,182 |
def put(a, ind, v, mode='raise'):
"""
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
... | 8e4e915f49f3159a890f8a79306ca80e2e57006f | 639,189 |
import json
def jinja_resilient_substitute(value, json_str):
"""jinja custom filter to replace values based on a lookup dictionary
Args:
value ([str]): [original value]
json_str ([str]): [string encoded json lookup values]
Returns:
[str]: [replacement value or original value if n... | d8b2e566d36c91d47fcce7b839fe801de5b73e91 | 639,190 |
import io
def ReadSymbolTable(path, skip_epsilon=False):
"""Read a bijective symbol table in OpenFst text format."""
symbol2label = {}
label2symbol = {}
with io.open(path, mode='rt', encoding='utf-8') as reader:
for line in reader:
line = line.rstrip('\n')
fields = line.split()
assert le... | f77d3971fc9663dd94c19c5ad5f92e73db5b26aa | 639,195 |
import gzip
def build_geneinfo(bed):
"""
Loads bed file into a dictionary with the key being the name and a string being the value
Input:
BED -- a bed file to load
Return:
A dictionary with the key being the name position of the bed file and the values being the
ordered bed... | 2cfc4ef90c62db9dd10b9f0a1bd8e7a13df7bacb | 639,196 |
import sqlite3
def table_drop(cursor, table_name):
"""
Delete a table
Returns:
``True`` if table was removed, ``False`` else
"""
sql_command = f"DROP TABLE '{table_name}';"
try:
cursor.execute(sql_command).fetchall()
except sqlite3.OperationalError:
return False
... | 88a4e9eb5c54d4e27564ba02c4c81bb23b003646 | 639,199 |
def std_value(x: float, m_x: float, s_x: float) -> float:
"""
This function computes standardized values of a sequence value
given its mean and standard deviation.
"""
return (x - m_x) / s_x | 5802d7da10813c07c67fa34c93bb54569ab02e37 | 639,200 |
def add(v1, v2):
"""
Returns the addition of a two 2-D vectors.
"""
return (v1[0] + v2[0], v1[1] + v2[1]) | 40ddea20e33efec8a3f1cdb41964a404247deed5 | 639,208 |
from typing import Dict
def format_selector_movements(info:Dict[str,str])->str:
"""Callback to parse the accounts/cards into a string format """
return f"{info['name']} - {info.get('currency','')}" | 7e7bfa98b2af7ae59f8d785f3ad1db9c701e4b09 | 639,212 |
def is_anagram(s1, s2):
""" Figures out if the two strings are anagrams.
Complexity: O(n)
Args:
s1: str
s2: str
Returns:
boolean, True if s1 is an anagram of s2.
"""
letters = {}
for c in s1:
if c in letters:
letters[c] += 1
else:
... | b46d02dad00f480bd7feaaf286e61538b8b5f4d1 | 639,217 |
def set_and_true(key, _dict):
"""Is key in dict and value True?
Args:
key (str): Key to lookup in dictionary.
_dict (dict): The dictionary.
Returns:
bool: Is key in dict and value True?
"""
return key in _dict and _dict[key] is True | ceb88511d0c09c6805c5b1c9ba173e687aa752ce | 639,218 |
def tf_trans(T):
""" Return translation vector from 4x4 homogeneous transform """
assert T.shape == (4, 4)
return T[0:3, 3] | 3661bb6fe3c16cf3e144b5b471f527dadf8f2335 | 639,220 |
def develop(envelope):
"""
Remove the envelope from a message.
:param envelope: PokerTHMessage object that envelops a message
:return: PokerTH message from the envelope
"""
msg = [v for _, v in envelope.ListFields() if v != envelope.messageType]
assert len(msg) == 1
assert msg[0].IsInit... | 0398b6f61ff2e36dec38f56833a90110041d45a2 | 639,225 |
def get_age_schedule_table(schedules):
"""
Generate a table of initial ages, schedule number,
period number, and current age.
"""
age_schedules = {}
for i in range(0, 200, 10):
age_schedules[i] = {}
for a, schedule in enumerate(schedules):
age = i
sch... | aea6d744068b82442c79c6e97fb0ebe1aee0263a | 639,231 |
def schema_contest() -> str:
"""Schema for contest document"""
return """
_id 5f70c6f3430508338f95ddab
winner
slateType 1
gameCount 13
siteSlateId 39913
start 2020-09-27T17:00:00.000Z
sport 1
prizePool 4275000
maxEntriesPerUser 150
... | 9b29a8472895d389cbcb590c711596fd029f7328 | 639,234 |
def format_kit_descriptor(name, version, iteration):
"""
Returns a properly formatted kit 'descriptor' string in the format
<name>-<version>-<iteration>
"""
return '{0}-{1}-{2}'.format(name, version, iteration) | 87fa82769648edf0c587b15bace329b63bcc5f8d | 639,236 |
def richclub(graph, fraction=0.1, highest=True, scores=None, indices_only=False):
# from http://igraph.wikidot.com/python-recipes#toc6
"""Extracts the "rich club" of the given graph, i.e. the subgraph spanned
between vertices having the top X% of some score.
Scores are given by the vertex degrees by de... | ebbab04068709858fc3b88d2517e648a6a979c57 | 639,237 |
def chain_length(n, chains):
""" Return the chain length of a number n.
If the chain length of n isn't stored yet, then calculate it according
to the collatz sequence rules recursively and store it for future
reference. Also store all the chain lengths for numbers that are found
duri... | efc213c8b5916be775e969f07309bce7a667914a | 639,238 |
def calc_ertelPV(n2, bx, rel_vorticity, g=9.8,f=-1e-4):
"""
As in Thomas et al., 2013; Thompson et al., 2016
The assumption is made that flow is in geostrophic balance
PV can be used as a diagnostic to indicate the suscepptibility of a flow to instability e.g., Hoskins, 1974; Thomas et al., 2008
Wh... | 60a4b43d9290f1dbab15621a9384ff567975e16c | 639,239 |
def extractFolders(folders):
"""
convert a string of folders to a list of tuples (db , schema, node)
:param folders: a string containing folders db-schema-node seperated by ,
:return: a list of tuples (db , schema, node)
"""
output = []
folderList = folders.split('-')
for folder in fol... | b5ba5e2ce3fcbc33e51fea06d2019c36b65aaece | 639,240 |
def pdf_norm_from_kernel(
kernel_val: float,
**kwargs):
"""
Just use the pdf_max value passed, usually originating from the distance
function.
"""
return kernel_val | 0f70c8656ae80461bed86f6c3f52dff5b3fe3c6b | 639,245 |
def batch_binary_confusion_matrix(pred, target):
"""
Compute the binary confusion matrix for batch of prediction, target.
----------
INPUT
|---- pred (torch.tensor) the binary prediction with shape (B x *).
|---- target (torch.tensor) the binary ground truth with shape (B x *).
OUTPU... | 20b24f0c91a37cf8e9447df21885d235cd8eac92 | 639,246 |
def _to_value_seq(values):
"""
:param values: Either a single numeric value or a sequence of numeric values
:return: A sequence, possibly of length one, of all the values in ``values``
"""
try:
val = float(values)
return [val,]
except (ValueError, TypeError):
return valu... | cc571692d3c11429cc6b2a3591556a24af5d3396 | 639,248 |
import yaml
def load_yaml_config_file(path):
""" Returns the parsed structure from a yaml config file.
:param path: Path where the yaml file is located.
:return: The yaml configuration represented by the yaml file.
"""
result = None
with open(path, 'r') as steam:
result = yaml.safe_lo... | bad2844af34d57c1660d71b4d9ec43c145770390 | 639,249 |
def usage(cmd='', err=''):
""" Prints the Usage() statement for the program """
m = '%s\n' %err
m += ' Default usage is to scan latest Task Branch (TB) on SalesForce.\n'
m += ' '
m += ' walkSF -c walk -s4.1 \n (walk sForce and enforce approval workflow)'
m += ' or\n'
m +=... | 595123fbc1c920b4f0d7099adddbe549f71abd95 | 639,250 |
from typing import Tuple
def split_tab_pair(x: str) -> Tuple[str, str]:
"""Split a pair of elements by a tab."""
a, b = x.strip().split('\t')
return a, b | dc16ee922c857e12eb7af646790811bff990b025 | 639,251 |
def center_data(x, dim=-1):
"""
Center x along the dimension dim.
:param x: torch.Tensor
:param dim: int, dim for centering
:return: torch.Tensor, centered x
"""
return x - x.mean(dim=dim, keepdim=True) | 66293bb4db508d75e9709c6e50dad3b6ad7fa01b | 639,254 |
async def get_text(page, b, norm=True):
"""Get the inner text of an element"""
text = await page.evaluate('(element) => element.textContent', b)
if norm:
text = text.lower().strip()
return text | 30df718406b91a44e5e5d666259564e81d7e0909 | 639,256 |
import random
def shuffle_list(arg):
"""
Return a shuffled copy of a list
"""
tmp = arg[:]
random.shuffle(tmp)
return tmp | d80de9f925332b857eacf42bc5edb4056555184f | 639,259 |
import textwrap
def cleantext(text: str) -> str:
"""
Clean a text string.
:param text: The input text
:type text: str
:return: The cleaned text
:rtype: str
"""
return " ".join(textwrap.dedent(text).strip().split("\n")) | 7eb6a4f32c9268fae0f016fc50faa5c21901572e | 639,261 |
def slurp(filename):
"""
Return the contents of filename as a string.
>>> 'public domain' in slurp('LICENSE.txt')
True
"""
with open(filename) as file:
return file.read() | 5c62513119984dac80cded916085a58994dc4d8d | 639,263 |
def format_date(str_date):
""" Prepare string to be used by datetime.strptime using format "%Y-%m-%dT%H:%M:%S%z"
:param str_date e.g. 2014-04-17T19:14:29+08:00:
:return e.g. 2014-04-17T19:14:29+0800:
"""
str_length = len(str_date)
return str_date[:-6] + str_date[str_length-6:str_length-3] + str_... | 5bb027d87b6fdcde0e24373e01ad37545c59bba2 | 639,264 |
from typing import Dict
def recover_info_from_exception(err: Exception) -> Dict:
"""
Retrives the information added to an exception by
:func:`add_info_to_exception`.
"""
if len(err.args) < 1:
return {}
info = err.args[-1]
if not isinstance(info, dict):
return {}
return ... | e172111ae364b9999c5c62f9bb549737584919a5 | 639,265 |
def string_index(neg_idx, string):
"""Solution to exercise R-1.8.
Python allows negative integers to be used as indices into a sequence,
such as a string. If string s has length n, and expression s[k] is used for
index −n ≤ k < 0, what is the equivalent index j ≥ 0 such that s[j]
references the sam... | 30e69a395e2b49e9edf15e68e7a4b663299a4956 | 639,268 |
def padding_mask(seq_k, seq_q):
"""For masking out the padding part of the keys sequence.
Args:
seq_k: Keys tensor, with shape [B, L_k]
seq_q: Query tensor, with shape [B, L_q]
Returns:
A masking tensor, with shape [B, L_1, L_k]
"""
len_q = seq_q.size(1)
# `PAD` is 0
pad_mask = seq_k.eq(0)
... | 22f84e5b2e7b0ef31c0aa36771f50de110a1fa9d | 639,269 |
def attempt_actions_for_machine(machine_action_definition, machine, context, actions):
"""Check the given actions for a machine and determine which action was successfully taken.
For the given list of actions, the corresponding function from the given machine_action_definition will be called
with the machi... | af3abe7a1a7c25f5ac54ab8659d9a111551c6ef5 | 639,272 |
def getSimData(opsimDb, sqlconstraint, dbcols, stackers=None, groupBy='default', tableName=None):
"""Query an opsim database for the needed data columns and run any required stackers.
Parameters
----------
opsimDb : `rubin_sim.maf.db.OpsimDatabase`
sqlconstraint : `str`
SQL constraint to ap... | 87798597fdc36902ea4b638be534efde60b37f77 | 639,273 |
def ribbon(dimensions):
"""Return total ribbon needed for box of size dimensions
The total ribbon is equal to twice the lengths of the shortest two
dimensions plus the product of all three dimensions.
"""
s1, s2, s3 = sorted(dimensions)
return (2 * s1) + (2 * s2) + (s1 * s2 * s3) | 71b5fd29e4e080090a280b3852184271f552220c | 639,279 |
def DeleteVersion(client, messages, version):
"""Deletes a version by its name."""
delete_ver_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesVersionsDeleteRequest(
name=version)
return client.projects_locations_repositories_packages_versions.Delete(
delete_ver_req) | f08dd41708021b06b29f92db745242d026b56188 | 639,281 |
def get_gradient_index(val, min_val, max_val, steps):
"""
Returns the index in gradient given p-value, minimum value, maximum value
and number of steps in gradient.
>>> get_gradient_index(0.002, 0.001, 0.0029, 10)
5
>>> get_gradient_index(0.0011, 0.001, 0.0029, 10)
0
>>> get_gradien... | 998f4190abe2e43b6f01c3595425c5fd8349aff8 | 639,283 |
def getPredictedLabels(model, features):
"""Run inference on trained model to get predicted class labels."""
return model.predict(features) | d01b7457e6f3aa3af94a0621995363fa1a9b96e9 | 639,284 |
def evaluate_guess(guess: str, mystery: str):
"""Get the partition label for the mystery word given the guess.
There are 3^n different partitions, where n is the number of characters in
guess or mystery.
Args:
guess: word being guessed
mystery: candidate for mystery word
Returns:
... | b6a9ef35b6a776f9954bb2971c37677c68fd49e2 | 639,287 |
def c_is_fun(text):
"""
Return desired string for /c/<text> route, replace _ with space
"""
return "C {}".format(text.replace("_", " ")) | fd3c49eff9a4c111f4424cc779531b89214b8234 | 639,289 |
def error_on_blank(_value, _error):
"""Raises an error if blank"""
if _value not in [None, '']:
return _value
else:
raise Exception(_error) | 69a96364de6062c3f3fcfac8285bb8421cf822a1 | 639,291 |
import six
def is_listlike(x):
"""
>>> is_listlike("foo")
False
>>> is_listlike(5)
False
>>> is_listlike(b"foo")
False
>>> is_listlike([b"foo"])
True
>>> is_listlike((b"foo",))
True
>>> is_listlike({})
True
>>> is_listlike(set())
True
>>> is_listlike((x ... | c6473bdd56ec71619a7c5455bdbeb7c35e7dc213 | 639,293 |
def _integer_surround(number):
"""Return the 2 closest integers to number, smaller integer first."""
if number > 0:
return int(number), int(number) + 1
else:
return int(number) - 1, int(number) | a309930e3d7992008c08085a1ea121480de1396e | 639,294 |
def get_initial_domains_by_genome_assembly(genome_assembly):
"""Get a list of defaults HiGlass data ranges for a file.
Args:
genome_assembly(string): Description of the genome assembly.
Returns:
A dict with these keys:
initialXDomain(list): Contains 2 numbers. The HiGlass display wil... | 6140d80f417e166942ac376d4383acda5d746937 | 639,297 |
def _is_ingredient_heading_1(line):
"""Returns True for the first heading line of ingredients section."""
return line.strip().lower() == 'amount measure ingredient -- preparation method' | 81c9a552087b20c6138e303ff833a96d1d01c3fc | 639,298 |
def date_marker(date, today):
"""Return a one-character date marker."""
if date == today:
return '*'
if date == today.tomorrow():
return '+'
if date == today.tomorrow(-1):
return '-'
return ' ' | dd1e5bb4392522ebf82ab28bf76ebe3140e11085 | 639,299 |
def find_cl_max_length(codelist):
"""
find and return the length of the longest term in the codelist
:param codelist: codelist of terms
:return: integer length of the longest codelist item
"""
max_length = 0
for term in codelist.split(", "):
if len(term) > max_length:
max... | 820fbf7a1b3ac80679d3f1e4937e960c1bdbd77d | 639,300 |
import inspect
def derive_top_level_package_name(package_level=0, stack_level=1):
"""Return top level package name.
Args:
package_level (int): How many package levels down the caller
is. 0 indicates this function is being called from the top
level package, 1 indicates that it'... | e9ff1119cd02f01c355aef1e68fae55db7fbbba0 | 639,304 |
import torch
def size_to_str(torch_size):
"""Convert a pytorch Size object to a string"""
assert isinstance(torch_size, torch.Size) or isinstance(torch_size, tuple) or isinstance(torch_size, list)
return '('+(', ').join(['%d' % v for v in torch_size])+')' | ffad3362dd32953fb78521e10262591d486049fb | 639,305 |
import mpmath
def pdf(x):
"""
Probability density function (PDF) of the raised cosine distribution.
The PDF of the raised cosine distribution is
f(x) = (1 + cos(x))/(2*pi)
on the interval (-pi, pi) and zero elsewhere.
"""
with mpmath.extradps(5):
x = mpmath.mpf(x)
if... | 765d86f3baab3adf4370fe386aaf776e80694a5d | 639,310 |
from typing import Optional
import dataclasses
def field(description: str, *args, metadata: Optional[dict] = None, **kwargs):
"""
Creates an instance of :py:func:`dataclasses.field`. The first argument,
``description`` is the description of the field, and will be set as the
``"description"`` key in th... | 151a6c5a171facbfc2ed7da8da179cd30d7db248 | 639,312 |
def rgb(red, green, blue):
"""
Return the string HTML representation of the color
in 'rgb(red, blue, green)' format.
:param red: 0 <= int <= 255
:param green: 0 <= int <= 255
:param blue: 0 <= int <= 255
:return: str
"""
assert isinstance(red, int)
assert 0 <= red < 256
... | dc10e8b3cd63a79380130397d5e4b064b7acb157 | 639,313 |
def has_next_page(content: str) -> bool:
"""Check whether a Flaticon search page has another page
Args:
content (str): Contents of the current Flaticon search page
Returns:
bool: Whether a next page exists
"""
return "<span>Next page</span>" in content | 8dc75963346e876da8c92eec9a476b95f45a866e | 639,317 |
def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines) | a83e4ad25fedf3292b2678785cc9bb417ebe1452 | 639,319 |
import math
def geo_bounds(xmin, ymin, xmax, ymax):
"""
Project web mercator bounds to geographic.
Parameters
----------
xmin: float
ymin: float
xmax: float
ymax: float
Returns
-------
[xmin, ymin, xmax, ymax] in geographic coordinates
"""
merc_max = 20037508.342... | ed44c70d01e310294823884d88fcfc37d240a3dd | 639,322 |
def get_variation(type_variation, list_detections, str_detections):
"""Gets a specific variation list of detections"""
return list_detections[str_detections.index(type_variation)] | fb2d79ff79bfd7246617f16d1e10ef38d4c4218b | 639,323 |
import re
def text_normalization(text):
"""
Normalize text
Remove & Replace unnessary characters
Parameter argument:
text: a string (e.g. '.... *** New York N.Y is a city...')
Return:
text: a string (New York N.Y is a city.)
"""
text = re.sub(u'\u201e|\u201c', u'', text)
text ... | e4aa05e4f81f3c625ee4334f52bf4672c3ac912b | 639,330 |
def fortfloat(text: str) -> float:
"""Convert Fortran-style float to python float."""
text = text.strip()
if text.endswith("d"):
text = text[:-1]
text.replace("d", "e")
try:
return float(text)
except ValueError:
if len(text) > 1 and "-" in text[1:]:
text = f"{... | 0af8820985ae44d07e04135783a0bc1e1c271d75 | 639,332 |
from typing import Counter
def build_worddict(data, num_words=None):
"""
Build a dictionary associating words from a set of premises and
hypotheses to unique integer indices.
Args:
data: A dictionary containing the premises and hypotheses for which
a worddict must be built. The di... | a7dd855a9cfda93df88f1593236d0ccc3a4917b4 | 639,334 |
def b64pad(data):
"""
Pad base64 data with '=' so that it's length is a multiple of 4.
"""
missing = len(data) % 4
if missing:
data += b'=' * (4 - missing)
return data | 76e0cb9954011511009d5508ed837ef5614660fa | 639,337 |
def _tpi_name(scale, smth_factor):
"""Return name for the array in output of the tpi function"""
add = f"_SMTHFACT{smth_factor:.3g}" if smth_factor else ""
return f"TPI_{scale}M{add}" | 4ef4734c747983a7340da2835e602aff4b23b55c | 639,339 |
def GetDiskConfig(dataproc, boot_disk_type, boot_disk_size, num_local_ssds,
local_ssd_interface):
"""Get dataproc cluster disk configuration.
Args:
dataproc: Dataproc object that contains client, messages, and resources
boot_disk_type: Type of the boot disk
boot_disk_size: Size of the... | 9a7254992900d9e325eac2eba21bfb5bbfa7d680 | 639,347 |
def _get_port_to_string(iface):
"""Simple helper which allows to get string representation for interface.
Args:
iface(list): Which IXIA interface to use for packet sending (list in format [chassis_id, card_id, port_id])
Returns:
str: string in format "chassis_id/card_id/port_id"
"""
... | 3d1da011c2bc63657020043f7a0aca1e14e5f276 | 639,350 |
def __ask_int(message):
"""
Asks User for an Integer Value
Args:
message = str - Input from Console
"""
value = ''
while not isinstance(value, int):
value = input(message)
try:
value = int(value)
return value
except:
print("The... | d88c1d1f9794b6ac653d95899d6d9472e9276718 | 639,353 |
def default_matching(name: str, target_version: int) -> str:
"""Default matching method
"""
return name | d6fbaca343c3ef7899a56363dace550a1a60f6cf | 639,355 |
from typing import Tuple
def extended_euclidian_gcd(left: int, right: int) -> Tuple[int, int, int]:
"""Solve left * x + right * y = gcd(left, right) and return r, x, y."""
new_x, new_y, new_r = 0, 1, right
old_x, old_y, old_r = 1, 0, left
while new_r != 0:
quotient = old_r // new_r
old... | 4d4244f87f518bee8e57f866a2ec6eca7b2bc262 | 639,358 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.