content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_list_duration_white_space_nistxml_sv_iv_list_duration_white_space_1_4(mode, save_output, output_format):
"""
Type list/duration is restricted by facet whiteSpace with value
collapse.
"""
assert_bindings(
schema="nistData/list/duration/Schema+Instance/NISTSchema-SV-IV-list-duration-w... | 55,600 |
def test_valueConstraintType_pattern_warn_if_not_valid_regex():
"""For valueConstraintType pattern, warns if valueConstraint not valid regex."""
sc = TAPStatementConstraint()
sc.propertyID = ":status"
sc.valueConstraintType = "pattern"
sc.valueConstraint="approved_(*"
sc._valueConstraintType_pat... | 55,601 |
def commnets(milestone):
"""Filtrira milestone tako da nadje samo broj komentara za svaki pojedinacni"""
comments = milestone.event_set.filter(event_kind="K")
size = comments.count()
return size | 55,602 |
def finish_login(request):
"""Complete OpenID Login Process"""
response = _finish_verification(request)
if not response:
# Verification failed, redirect to login page.
return redirect(request, 'mediagoblin.plugins.openid.login')
# Verification was successfull
query = OpenIDUserURL.... | 55,603 |
def check_tweet_emphasis(tweet):
"""
Performs check whether words in a tweet have 3 or
more repeating characters. If the word has 3 or
more repeating characters, word will be replaced
by one that matches the original word as close as
possible repeated twice, otherwise original word
is re... | 55,604 |
def buildList(pdList, matrix):
"""Takes a list of primary datasets (PDs) and the AlCaRecoMatrix (a dictinary) and returns a string with all the AlCaRecos for the selected PDs separated by the '+' character without duplicates."""
alCaRecoList = []
for pd in pdList:
alCaRecoList.extend(matrix[pd].spli... | 55,605 |
def add(config: Config, unique_id, first_name, last_name, email, section, username):
"""Adds a new student to the active course.
"""
new_student = {
"answered": {},
"bonus": 0,
"disallowed": [],
"email": email,
"first_name": first_name,
"hw": [],
"id":... | 55,606 |
def random_wish(rankings):
"""
Select a wish randomly with exponential decay
:param rankings: ordered [(pitch, role)]
:return: i the index of the chosen wish in the rankings
"""
cum_weights = exp_cum(len(rankings))
total = cum_weights[-1]
hi = len(cum_weights) - 1
return bisect_right... | 55,607 |
def serialize_to_database(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, date):
return str(obj.isoformat())
if isinstance(obj, (DateRange, DateTimeRange)):
return f"[{obj.lower}, {obj.upper}]"
return obj | 55,608 |
def _flatten_dict_into_array(dictionary, dtype=np.float32):
"""
Flatten the given dictionary into an array of scalars, and return the beginning index of each sequence of values.
Parameters
----------
dictionary : dict
Some dictionary containing scalars or array of scalars as each of its key... | 55,609 |
def DecoderBlock(d_model, d_ff, n_heads,
dropout, mode, ff_activation):
"""Returns a list of layers that implements a Transformer decoder block.
The input is an activation tensor.
Args:
d_model (int): depth of embedding.
d_ff (int): depth of feed-forward layer.
n_... | 55,610 |
def test_sealevel():
"""Test sealevel conditions"""
sealevel = Atmosphere(0)
# Geopotential and geometric height are equal
assert sealevel.H == sealevel.h == 0
# Table 1
assert sealevel.temperature == 288.15
assert sealevel.temperature_in_celsius == 15
assert sealevel.pressure == 1.01... | 55,611 |
def fit_network(graph: nx.DiGraph,
client: Client,
target_modularities: Union[List[float], np.ndarray],
graphs_per_modularity: int,
energy_kwargs: Dict[str, Any],
cooling_kwargs: Dict[str, Any],
annealing_kwargs: Dict[str, A... | 55,612 |
def print_enumerated_list(items, fh=None):
"""Print a list, enumerating each item."""
if not fh:
fh = sys.stdout
i = 1
for item in items:
print >> fh, "%8d. %s" % (i, item)
i += 1 | 55,613 |
def get_gradient(pixels,processing = 'normalize'):
"""returns the gradient of an image, and does basic preprocessing"""
horgradient = ndimage.sobel(pixels, axis = 1)
vergradient = ndimage.sobel(pixels, axis = 0)
gradient = np.array((vergradient,horgradient))
if processing == 'normalize':
"... | 55,614 |
def test_get_python_versions():
"""Test basic behavior of function get_versions_for_pypi_package."""
package_versions = get_versions_for_pypi_package("numpy")
assert package_versions is not None
# good old version 1.3.0 should be reported
assert "1.3.0" in package_versions
package_versions = g... | 55,615 |
def register_languages():
"""Register all supported languages to ensure compatibility."""
#for language in set(SUPPORTED_LANGUAGES) - {"en"}:
# language_stemmer = partial(nltk_stemmer, get_language_stemmer(language))
# Pipeline.register_function(language_stemmer, "stemmer-{}".format(language)) | 55,616 |
def finder_target(skicall):
"""Reads ident and sets target_name into call_data"""
storedtarget = target_from_store(skicall)
if not storedtarget:
# no ident data
raise FailPage("Target data unavailable")
if storedtarget.target_name != 'none':
skicall.call_data['target_name'] = ... | 55,617 |
def get_roommates():
"""Endpoint to get all rooms for the given search conditions."""
LOGGER.info(' Inside /api/getRoommates')
roommates_list = userscontroller.get_all_roommates("")
return roommates_list | 55,618 |
def log_mean_temp_diff(T_A_one, T_A_two, T_B_one, T_B_two):
"""
Calculate the logarithmic mean temperature difference (LMTD) of two fluid
streams `one` and `two` of a heat exchanger with two ends `A` and `B`.
Parameters:
-----------
T_A_one : float, int, np.array
Fluid temperature of st... | 55,619 |
def trade_from_coinbase(raw_trade: Dict[str, Any]) -> Optional[Trade]:
"""Turns a coinbase transaction into a rotkehlchen Trade.
https://developers.coinbase.com/api/v2?python#buys
If the coinbase transaction is not a trade related transaction returns None
Throws:
- UnknownAsset due to Asset in... | 55,620 |
def has_image_extension(uri) -> bool:
"""Check that file has image extension.
Args:
uri (Union[str, pathlib.Path]): the resource to load the file from
Returns:
bool: True if file has image extension, False otherwise
"""
_, ext = os.path.splitext(uri)
return ext.lower() in {".bm... | 55,621 |
def test_activate_tokens(client: citric.Client, survey_id: int):
"""Test whether the participants table gets activated."""
client.activate_survey(survey_id)
with pytest.raises(LimeSurveyStatusError, match="No survey participants table"):
client.list_participants(survey_id)
client.activate_toke... | 55,622 |
def infected():
"""
Real Name: b'Infected'
Original Eqn: b'INTEG ( Infection Rate-recovery rate, 1)'
Units: b'Person'
Limits: (None, None)
Type: component
b''
"""
return _integ_infected() | 55,623 |
def get_dataproc_cluster(cluster_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDataprocClusterResult:
"""
Get information about a Yandex Data Proc cluster. For more information, see [the officia... | 55,624 |
def GetNumberPreAmpGains(LR: ctypes, error: Error=default) -> tuple:
"""
Returns tuple(MsgError type, number)
"""
if not error['status']:
n = ctypes.c_int32(0)
number= ctypes.pointer(n)
executed = LR.GetNumberPreAmpGains(number)
return errorcodehandler(executed), number.... | 55,625 |
def write_file(self):
"""write file to disk with a random name (to compare)"""
self.is_private = 1
file_path = get_files_path(is_private=self.is_private)
if os.path.sep in self.file_name:
frappe.throw(_('File name cannot have {0}').format(os.path.sep))
# create directory (if not exists)
frappe.create_folder(f... | 55,626 |
def ele2json(data: list) -> List[str]:
"""把元素为dict类型的list数据,转为,元素为json字符串的list数据
Args:
data: list类型的数据,元素为dict类型
Returns:
转换后的list数据
"""
return [dict2json(item) for item in data] | 55,627 |
def remove_small_components(mesh, min_volume=5e-05):
"""Removes all components with volume below the specified threshold."""
if mesh.is_empty:
return mesh
out = [m for m in mesh.split(only_watertight=False) if m.volume > min_volume]
if not out:
return mesh
return trimesh.util.concatenate(out) | 55,628 |
def is_retriable(exception):
"""Returns True if this exception is retriable."""
errs = list(range(500, 505)) + [429]
errs += [str(e) for e in errs]
if isinstance(exception, HttpError):
return exception.code in errs
# https://cloud.google.com/storage/docs/key-terms#immutability
if isinsta... | 55,629 |
def test_1_8_1_2_issue_file_isfile(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 1.8.1.2
Tests if /etc/issue file is a file
"""
assert host.file(ETC_ISSUE).is_file | 55,630 |
def var_to_struct(val, name, format='%s', do_trim=True, evaluate_full_value=True):
""" single variable or dictionary to Thrift struct representation """
debug_value = DebugValue()
try:
# This should be faster than isinstance (but we have to protect against not having a '__class__' attribute).
... | 55,631 |
def parse_styles(cssfiles):
"""
Parse CSS files.
This parse some CSS files and build a map of each attribute with these values.
It's very useful to inline some CSS propety to html objects.
:param cssfiles: A list of CSS files
:type cssfiles: list
:return: A map of C... | 55,632 |
def sgld_gradient_update(step_size_fn, seed):
"""Optix implementation of the SGLD optimizer"""
def init_fn(_):
return OptixSGLDState(count=jnp.zeros([], jnp.int32),
rng_key=jax.random.PRNGKey(seed))
def update_fn(updates, state, params=None):
del params
lr = step_size_fn(... | 55,633 |
def _get_ip_addr_num(file_path):
"""Get the next IPADDR index num to use for adding an ip addr to an
ifcfg file.
"""
num = ''
with open(file_path, 'r') as f:
data = f.read()
data = data.splitlines()
for line in data:
found = re.search(r'IPADDR(\d?)=', line)
if found:
... | 55,634 |
def subsample(X, subsample=1, seed=0):
"""Subsample a fraction of 1/subsample samples from the rows of X.
Parameters
----------
X : np.ndarray
Data array.
subsample : int
1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.
seed : int
Seed for sampling.... | 55,635 |
def cli(ctx, version):
""" Particle Cloud Framework """
if version:
ctx.command.print_version(ctx)
elif ctx.invoked_subcommand is None:
click.echo(ctx.command.get_help(ctx))
ctx.exit() | 55,636 |
def norm(collection: str, country_code: str, name: str, lang: str = DEFAULT_LANG) -> str:
"""Normalize the name with respect to a collection and country code.
>>> norm(CITY, 'RU', 'leningrad')
'Saint Petersburg'
>>> norm(CITY, 'RU', 'peterburg')
'Saint Petersburg'
>>> norm(CITY, 'RU', 'peterbur... | 55,637 |
def createFeatureDF(pairs, classes, knownDrugDisease, drugDFs, diseaseDFs):
"""Create the features dataframes.
:param pairs: Generated pairs
:param classes: Classes corresponding to the pairs
:param knownDrugDisease: Known drug-disease associations
:param drugDFs: Drug dataframes
:param disease... | 55,638 |
def getBigram(words, join_string):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of bigram, e.g., ['I_am', 'am_Denny']
I use _ as join_string for this example.
"""
assert type(words) == list
L = len(words)
if L > 1:
lst = []
for i in rang... | 55,639 |
def print_error(content):
"""Thread safe and unicode safe error printer."""
content = u"ERROR: {}\n".format(content)
if six.PY2:
sys.stderr.write(content.encode('utf-8'))
else:
sys.stderr.write(content) | 55,640 |
def run_guest():
""" A sample for quick deploy and start a virtual guest."""
global GUEST_USERID
global GUEST_PROFILE
global GUEST_VCPUS
global GUEST_MEMORY
global GUEST_ROOT_DISK_SIZE
global DISK_POOL
global IMAGE_PATH
global IMAGE_OS_VERSION
global GUEST_IP_ADDR
global GATE... | 55,641 |
def get_xqueue_callback_url_prefix(request):
"""
Calculates default prefix based on request, but allows override via settings
This is separated from get_module_for_descriptor so that it can be called
by the LMS before submitting background tasks to run. The xqueue callbacks
should go back to the L... | 55,642 |
def abi_extensions():
"""List with all the ABINIT extensions that are registered."""
return list(_EXT2VARS.keys())[:] | 55,643 |
def solve_network_flows(case_dom):
"""Find the volumetric flow and head loss for the piping network defined in
the case_dom structure by using the first method described in Chapter 6 of
Jeppson.
Args:
case_dom (dict): Pipe flow network object model
Raises:
ValueError: Network solut... | 55,644 |
def load_csvs():
"""Returns dataframe containing all CSV files from directory 'cache' and returns a list of the filepaths.
"""
path = 'cache'
csv_list = glob.glob(path + "/*.csv") # collect all filepaths
df = pd.concat((pd.read_csv(f, index_col=0) for f in csv_list)) # concatenate all files to one ... | 55,645 |
def entry_point():
"""Use the TfidfNNClassifier classifier.""" | 55,646 |
def merge_networks_from_tags(shape, props, fid, zoom):
"""
Take the network and ref tags from the feature and, if they both exist, add
them to the mz_networks list. This is to make handling of networks and refs
more consistent across elements.
"""
network = props.get('network')
ref = props.... | 55,647 |
def tabs(text: str) -> str:
"""Remove tabs.
If you want to replace tabs with a single space, use
`normalize.whitespace()` instead.
Args:
text (str): The text from which tabs will be removed.
Returns:
The stripped text.
"""
return resources.RE_TAB.sub("", text) | 55,648 |
def tobool(value):
"""Convert value to boolean or Not a Number if not possible"""
from numpy import nan
if value is None: value = nan
else: value = bool(value)
return value | 55,649 |
def load_synonyms(synonym_filepath=None):
"""Loads synonym dictionary. Returns as defaultdict(list)."""
with tf.gfile.Open(synonym_filepath) as f:
synonyms = json.load(f)
synonyms_ = collections.defaultdict(list)
synonyms_.update(synonyms)
return synonyms_ | 55,650 |
def test_get_crumb(client: TestClient):
"""Test case for get_crumb
"""
headers = {
"Authorization": "BasicZm9vOmJhcg==",
}
response = client.request(
"GET",
"/crumbIssuer/api/json",
headers=headers,
)
# uncomment below to assert the status code of the ... | 55,651 |
def get_table_code(sol, table_name, unused_options):
"""
Gets the table code of a given parameter. For example, the
DISPLACMENT(PLOT,POST)=ALL makes an OUGV1 table and stores the
displacement. This has an OP2 table code of 1, unless you're running a
modal solution, in which case it makes an OUGV1 ... | 55,652 |
def wfFormIndex(text, lang, lowercase = True, contract = True, stopWords = False):
"""Returns the Formality Score of a text.
This function returns a value based on the weight that each kind of word
(adjective, noun, pronoun, etc.) has within the text.
"""
diffWords = stats.wordClass(text,... | 55,653 |
def load_project_data():
"""
Load project data from downloaded pickle file
- returns: data dictionnary
"""
if os.path.exists("final_project_dataset.pkl"):
with open("final_project_dataset.pkl", "r") as data_file:
return pickle.load(data_file)
else:
with open("./d... | 55,654 |
def showtables(hcaturi, dbname='default', username='hdfs'):
"""
hcat.showtables
Args:
hcaturi (str): uri for webhcat host, eg hive.myorg.com:50111
dbname (Optional[str]): database name, defaults to 'default'
username (Optional[str]): user name defaults to hdfs
Returns:
list: list of available tab... | 55,655 |
def list_subcommands():
"""List all datalabframework subcommands
searches PATH for `datalabframework-name`
Returns a list of datalabframework's subcommand names, without the `datalabframework-` prefix.
Nested children (e.g. datalabframework-sub-subsub) are not included.
"""
subcommand_tuples =... | 55,656 |
def fourier_gaussian(input, sigma, n = -1, axis = -1, output = None):
"""Multi-dimensional Gaussian fourier filter.
The array is multiplied with the fourier transform of a Gaussian
kernel. If the parameter n is negative, then the input is assumed to be
the result of a complex fft. If n is larger or eq... | 55,657 |
def amplitude_kurtosis(data):
"""
(list) -> float
pass in an array or list and return the kurtosis value of data. Using Pearson's definition
>signal_skewness([3,7,8,9,1])
1.4904
"""
return stats.kurtosis(data, fisher=False) | 55,658 |
def mh_sample(
logtarget,
x0,
sigma=None,
discrete=None,
args=(),
n_burn=1000,
n_steps=1000,
tune_interval=100,
variable_names=None,
return_acceptance_rate=False,
):
"""
Parameters
----------
logtarget : function
The function to compute the log posterior. ... | 55,659 |
def load(data):
"""loads the given byte-string representation to an object"""
stream = StringIO(data)
return _load(stream) | 55,660 |
def drop_path(x, drop_prob: float = 0., training: bool = False):
"""
Obtained from: github.com:rwightman/pytorch-image-models
Drop paths (Stochastic Depth) per sample (when applied in main path
of residual blocks).
This is the same as the DropConnect impl I... | 55,661 |
def factorial(n=10):
"""Calculates factorials with log messages."""
i = 1
factorial = 1
while i < n:
logging.info('starting iteration {}'.format(i))
factorial *= i
logging.debug('new factorial: {}'.format(factorial))
i += 1
#logging.info('unhandled event: ' + str(... | 55,662 |
def get_db_object(db_name) -> object:
"""
:type db_name: object
:return: pymongo client object
"""
db_handle = db_cache.get_db_cache(db_name)
if not __is_empty(db_handle):
__logger.info("sending db object from cache!")
return db_handle
else:
__logger.info("inside g... | 55,663 |
def set_dryrun(value):
"""Set the dryrun mode on or off.
Args:
value (bool): Mode to be in.
"""
global _dryrun
if type(value) is not bool:
raise TypeError("Boolean required")
_dryrun = value | 55,664 |
def test_str_magic_method():
"""Should return the original word."""
LINES = (
"One morn before me were three figures seen,",
"And once more came they by:-alas! wherefore?",
)
for line in LINES:
assert(str(LineBuilder(line)) == line) | 55,665 |
async def quote_add(ctx, parsed):
"""Add a quote to the database."""
submitter = await get_participant(
parsed.args['submitter'] or parsed.invoker.name)
style = getattr(QuoteStyle, parsed.args['style'].title())
if parsed.args['date']:
date = read_datestamp(parsed.args['date'])
if... | 55,666 |
def test_value_network():
"""
Test if the CartPole value network is invariant
"""
network = BasisCartpoleNetworkWrapper(1, [64, 64])
layer = BasisCartpoleLayer(64, 1, out="invariant")
representations = get_cartpole_state_group_representations()
p_m2 = representations[1].detach().cpu().nump... | 55,667 |
def tokenize(obj, tokenizer, max_seq_len):
"""Recursively convert to tokens."""
if isinstance(obj, str):
toks = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)[:max_seq_len])
assert all(
[t < len(tokenizer.encoder) for t in toks]
) # all(toks < len(tokenizer.encoder)... | 55,668 |
def setup(*args, **kwargs):
"""decorator for distutils.core.setup - use as:
args_to_cb_dot_build = []
mysetup = cb.setup(*args_to_cb_build)
mysetup(args_to_distutils_setup)"""
def wrapped(*setupargs, **setupkwargs):
global final_prefix
# check if we're trying to install and haven't built yet?
... | 55,669 |
def manifest_to_file_list(manifest_fn):
"""
Open a manifest file and read it into a list.
Entries in the list are relative, i.e. no leading
slash.
manifest_fn -- the manifest file to read
"""
image_manifest_list = []
with open(manifest_fn) as image:
image_manifest_list = [x[1:] ... | 55,670 |
def perform_climatology_esp(
model_name, forecast_date, forecast_duration, workdir=None, **kwds
):
"""
This function takes the model setup and name as well as forecast data and duration and returns
an ESP forecast netcdf. The data comes from the climatology data and thus there is a mechanism
to get ... | 55,671 |
def get_source_directories(proj_path, project_name, module_name=None):
"""Return the source and test source directory from the pom (or one of the pom)
Arguments
-------------
- proj_path: the path for the project
"""
look_for = project_name if not module_name else module_name
if look_for i... | 55,672 |
def get_fp(list_of_smi):
""" Function to get fingerprint from a list of SMILES"""
fingerprints = []
mols = [Chem.MolFromSmiles(x) for x in list_of_smi]
# if rdkit can't compute the fingerprint on a SMILES
# we remove that SMILES
idx_to_remove = []
for idx,mol in enumerate(mols):
try:... | 55,673 |
def intersect (sequence_a, sequence_b):
"""Return true if the two sequences contain items in common
If sequence_a is a non-sequence then return false.
"""
try:
for item in sequence_a:
if item in sequence_b:
return 1
except TypeError:
return 0
return 0 | 55,674 |
def _config():
"""Wrap configuration so that module can be imported without
environment variables set.
"""
nightwatch_exclude = resource_filename('desitransfer',
'data/desi_nightwatch_transfer_exclude.txt')
engineering = os.path.realpath(os.path.join(os.env... | 55,675 |
def time_neighbourhoods ():
"""
Times the numpy implementation. To run use command-line:
python3 -m timeit -s 'from benchmark import time_neighbourhoods' 'time_neighbourhoods()'
"""
for _ in range(10000):
moore_neighbourhood (neighbourhood_data,
... | 55,676 |
def convert_surface():
"""
CLI for converting surface formats
"""
parser = CommonParser('surf', 'coords', 'struct', 'out',
description="""Convert a surface file (.white/.pial/.vtk/.surf.gii).
NB FreeSurfer files will have the c_ras offset automatically
applied dur... | 55,677 |
def compileOverlapData(uniA,uniB,sigA,sigB,chrList):
"""
Piles-up the overlap coverage data for the fisher exact test.
:param uniA: Interval Universe A
:param uniB: Interval Universe B
:param sigA: Interval Significant A
:param sigB: Interval Significant B
:param chrList: List of chromosome... | 55,678 |
async def test_not_change_status_in_lift(cli):
"""Тестирует невозможность переключения статуса актора внутри лифта"""
ws, = await auth_actors(cli, 'actor1')
await req(ws, 'actor_expect', {'floor': 10})
resp = await receive(ws)
assert resp['status'] == 'ok'
resp = await receive(ws)
assert ... | 55,679 |
def get_location_dictionary(deployment):
""" Construct location dictionary from ui deployment information.
"""
try:
have_location_dict = False
latitude = None
longitude = None
location = None
depth = None
orbitRadius = None
if 'depth' in deployment:
... | 55,680 |
def __insert_color(txt,s,c):
"""insert HTML span style into txt. The span will change the color of the
text located between s[0] and s[1]:
txt: txt to be modified
s: span of where to insert tag
c: color to set the span to"""
return txt[:s[0]]+'<span style="color: {0};">'.format(c)+\
t... | 55,681 |
def legacy_do_linear_gst(dataFilenameOrSet, targetModelFilenameOrObj,
prepStrsListOrFilename, effectStrsListOrFilename,
gaugeOptParams=None, advancedOptions=None, comm=None,
memLimit=None, output_pkl=None, verbosity=2):
"""
Perform Linea... | 55,682 |
def StopAddHeaders(builder, headers):
"""This method is deprecated. Please switch to AddHeaders."""
return AddHeaders(builder, headers) | 55,683 |
async def test_update_file_path(
hass,
mock_imap_no_email,
mock_osremove,
mock_osmakedir,
mock_listdir,
mock_update_time,
mock_copy_overlays,
mock_hash_file,
mock_getctime_today,
mock_copyfile,
caplog,
):
"""Test update_file_path service."""
entry = MockConfigEntry(
... | 55,684 |
def test_pype_get_arguments_name_empty():
"""Empty pype name throw."""
context = Context({'pype': {'name': None}})
with pytest.raises(KeyInContextHasNoValueError) as err_info:
pype.get_arguments(context)
assert str(err_info.value) == ("pypyr.steps.pype ['pype']['name'] exists "
... | 55,685 |
def select_dominoes(dominoes: List[str], order: int, num_players: int) -> str:
"""Randonly generate a set of dominoes for a player
- If the number of players is 3, each player gets 9 dominoes,
plus a 10th dominoe that is to be played first (all players will get it)
- If the number of players is 4, each ... | 55,686 |
def repeat_three_times(value):
"""
repeat_three_times
:param value:
:return:
"""
yield value
yield value
yield value | 55,687 |
def test_get_environment():
"""Test getting the environment property."""
from .test_environment_base import EnvironmentBase
assert_is_instance(x.environment, EnvironmentBase) | 55,688 |
def fspecial_average(hsize=3):
"""Smoothing filter"""
return np.ones((hsize, hsize))/hsize**2 | 55,689 |
async def getTwitchChannelUsers(cls:"PhaazebotTwitch", **search) -> Union[List[TwitchUserStats], int]:
"""
Get channel levels and stats.
Returns a list of TwitchUserStats().
Optional 'search' keywords:
---------------------------
* `user_id` - Optional[str] : (Default: None)
* `channel_id` - Optional[str] : (De... | 55,690 |
def normalize_times(times, events):
"""Given a list of times and event ids, normalize the times (i.e. calculate
the time since the start of each event).
:param times: list of times
:type times: list
:param events: list of event ids
:type events: list
:return: list of normalized times
:... | 55,691 |
def convocar_reunion_nueva (asistentes_reunion_nueva, motivo_reunion_nueva, fecha_reunion_nueva, hora_inicio_reunion_nueva, duracion_reunion_nueva, agenda):
"""
str, str, str --> dic
OBJ: convocar reunión nueva
"""
fecha_hora_reunion_nueva = (fecha_reunion_nueva, hora_inicio_reunion_nueva)
separ... | 55,692 |
def salted_hmac(key_salt, value, secret):
"""
Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret. A different key_salt should be passed in for every application of HMAC.
"""
assert secret, f"secret must be provided."
key_salt = bytes(key_salt, encoding="utf-8")
... | 55,693 |
def _opcode(name):
"""Return the opcode by name from the dis module."""
return dis.opmap[name] | 55,694 |
def write_posts_to_csv(
account: Optional[str] = None,
group: Union[str, int, None] = None,
filename: str = None,
encoding: str = None,
**kwargs,
):
"""Write posts from an account or group to a CSV file
Args:
account (str): Facebook account name e.g. "nike" or "nintendo"
gro... | 55,695 |
def validate_compare_input(message):
"""
validate input for function that compare two songs
:param message: message received by microservice
:type message: `dict`
:return: tuple with status and error message
:rtype: `tuple`
"""
input_schema = {
"type": "object",
"require... | 55,696 |
def bundle_project(
working_area: Union[str, Path],
spec: RuntimeSpec,
privkey=None,
stash=False,
current=False,
) -> ProjectBundleFile:
"""
It's in charge of bundle all the files needed to build a runtime.
This bundle could be uploaded to the server or used to build a local docker image... | 55,697 |
def _gcp_agent_singleton(**kwargs):
"""Manage singleton of agents to particular apis.
This treates the agent instances as singletons based on their configuration.
The reason for this is simply to reduce logging noise on the creation.
This is possible since agents are stateless.
Args:
kargs: [kwarg... | 55,698 |
def get_media_playlist_uris(master_playlist, target_qualities):
"""From a master playlist, extract URIs of media playlists of interest.
Returns {stream name: uri}.
Note this is not a general method for all HLS streams, and makes twitch-specific assumptions,
though we try to check and emit warnings if these assumpti... | 55,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.