content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_holiday(_date):
"""Является ли заданная дата выходным днём"""
return _date.weekday() == 5 or _date.weekday() == 6 | 6ec73da0254d3e1f851cc2d7493f8982c555f793 | 674,314 |
def my_route_tester(ctx):
""" return (true|fals) + arbitray nuber of paramteres that will be passed to handler"""
if 'function/' in ctx.request.path:
return True, 'value 1', 'val two'
return False | fd06e04300968d588334f365cf1d61602197a0b0 | 674,315 |
def divide(dataset, target_column):
"""
Divides the dataset in X and y.
This function is called inside prepare_data function (see below) in order to prepare data.
:param dataset:
:param target_column:
:return: X and y
"""
X = dataset.drop(columns=[target_column])
y = dataset[target_... | ba12b8e4c037f6181b3b2fa4f0201a3e15be4abd | 674,316 |
def extract_post_story(div_id_story):
"""
Extracts the post text contents, strips line breaks and whitespaces.
"""
before_keyword = "SHARE /"
post_story = div_id_story.get_text().strip().replace('\n', ' ').replace('\r', '')
return post_story[:post_story.find(before_keyword)] | 995347c56165f4fb701ab18499ef05bf2744e1b1 | 674,317 |
def mean(x):
"""Return the mean of an array across the first dimension."""
return x.mean(axis=0) | c45f1fc16e71e5284eb47369ccc0603321a927ce | 674,318 |
def check_i(i):
""" simply skips the urls without a comic or that the comic isn't an image """
if i == 404:
"""
this one took me a while to figure out
turns out he skipped 404 for 'obvious reasons'
"""
return False
if i == 1350 or i == 1608 or i == 2198:
print... | fc7cef131730107e9f529dd90a4b1924c58064f7 | 674,319 |
def get_n4j_param_str(self, parameters):
"""Returns a string properly formatted for neo4j parameter-based
searching
Parameters
----------
parameters (dict of str -> int|str): parameter mappings to
convert to string suitable for Cypher querying
Returns
-------
<unnamed> (str): forma... | 0fc4082e1f139686174f077e5221c80efa0fce71 | 674,320 |
def cli(ctx, family_name="", nuke=False):
"""Adds an entry in the featureprop table in a chado database for each family a gene belongs to (for use in https://github.com/legumeinfo/lis_context_viewer/).
Output:
None
"""
return ctx.gi.phylogeny.gene_families(family_name=family_name, nuke=nuke) | a302410b98f2249b2b63b63042e22dc2b30409cd | 674,321 |
from typing import List
from typing import Set
def _extract_target_labels(targets_in_order: List[dict], target_name: str) -> Set[str]:
"""Collect a set of all the board names from the inherits field in each target in the hierarchy.
Args:
targets_in_order: list of targets in order of inheritance, star... | f47dcd90427efd70b0ac965ea017852db68381e4 | 674,322 |
def svm_predict(classifier, test_data):
"""
Predict the labels of the given test data with the given classifier pipeline.
:param sklearn.pipeline.Pipeline classifier: The classifier pipeline with which the labels of the given test data should be predicted
:param pandas.core.series.Series test_data:... | 61b21073bce9ef1bff931b558331a591a780e409 | 674,323 |
def get_py3_string_type(h_node):
""" Helper function to return the python string type for items in a list.
Notes:
Py3 string handling is a bit funky and doesn't play too nicely with HDF5.
We needed to add metadata to say if the strings in a list started off as
bytes, string, etc. This h... | 3869a2a08438a8250435f18730daa15af441e189 | 674,324 |
def PLR_analysis(PLR):
"""
Analysis PLR(Positive likelihood ratio) with interpretation table.
:param PLR: positive likelihood ratio
:type PLR : float
:return: interpretation result as str
"""
try:
if PLR == "None":
return "None"
if PLR < 1:
return "N... | 0742a315cc8bbe6d8fcc05ac875e9469cd850b51 | 674,325 |
def contfractbeta(
a: float, b: float, x: float, ITMAX: int = 5000, EPS: float = 1.0e-7
) -> float:
"""Continued fraction form of the incomplete Beta function.
Code translated from: Numerical Recipes in C.
Example kindly taken from blog:
https://malishoaib.wordpress.com/2014/04/15/the-beautiful-be... | cfe30b64ae14717dc007866a8d3634a5ce1e1042 | 674,326 |
def readMetadata(lines):
"""
Read metadata tags and values from a TNTP file, returning a dictionary whose
keys are the tags (strings between the <> characters) and corresponding values.
The last metadata line (reading <END OF METADATA>) is stored with a value giving
the line number this tag was found in.... | e4a93539ccb203b350d17c33fd0daa4cb9afbac9 | 674,327 |
def xyxy2xywh(bbox_xyxy):
"""Transform the bbox format from x1y1x2y2 to xywh.
Args:
bbox_xyxy (np.ndarray): Bounding boxes (with scores), shaped (n, 4) or
(n, 5). (left, top, right, bottom, [score])
Returns:
np.ndarray: Bounding boxes (with scores),
shaped (n, 4) or (... | 708cdbed5d2cd77290b41744915788c3f0163045 | 674,328 |
def extracthypos(synset, limit=999):
"""Given a synset object, return a set with all synsets
underneath it in the PWN structure (including the original)."""
l = limit-1
result = []
result.append(synset)
if synset.hyponyms() and l > 0:
for each in synset.hyponyms():
x = extra... | e1696a937891eb1ae8a39e683bf71c18124c2984 | 674,329 |
def decimal_to_percent(value, decimal_place=2):
"""
Format a decimal to percentage with two decimal
:param value: the value to be formatted
:param decimal_place default decimal place, default to 2
:return: a string in percentage format, 20.50% etc
"""
format_str = '{:.' + str(2) + '%}'
r... | c2d777d608458151b3b9752897305dab79498778 | 674,330 |
def sec2hms(seconds):
"""
Convert seconds into a string with hours, minutes and seconds.
Parameters:
* seconds : float
Time in seconds
Returns:
* time : str
String in the format ``'%dh %dm %2.5fs'``
Example::
>>> print sec2hms(62.2)
0h 1m 2.20000s
... | 6dea7e13567660c2c4dd8f2d0d0ef78f2a4e994c | 674,331 |
import random
import string
def create_secret_key():
"""
Creates a random string of letters and numbers
"""
return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(30)) | 2598232a27af3f0458f1bb308698eb22bd3a3223 | 674,332 |
def get_HTML(file):
"""
Retrieves the source code from a specified saved html file
args:
file: The Specified html to retrieve the source code from
"""
f = open(file, 'r')
lines = f.readlines()
f.close()
return "".join(lines) | 0b0f555b840715bd19804047793a2f6c168e3da5 | 674,334 |
import fsspec
def map_tgt(tgt, connection_string):
"""Uses fsspec to creating mapped object from target connection string"""
tgt_map = fsspec.get_mapper(tgt, connection_string=connection_string)
return tgt_map | a5b4a8bb39ea69b3f9340c06266e0fa8a9b42dee | 674,336 |
import torch
def compute_brier_score(y_pred, y_true):
"""Brier score implementation follows
https://papers.nips.cc/paper/7219-simple-and-scalable-predictive-uncertainty-estimation-using-deep-ensembles.pdf.
The lower the Brier score is for a set of predictions, the better the predictions are calibrated.""... | 0cafeccc2422499cce6aeb148a407a29f4fdd0f8 | 674,337 |
def ring_idxs(gra_rings):
""" Get idxs for rings
"""
_ring_idxs = tuple()
for ring in gra_rings:
idxs = tuple(ring[0].keys())
if idxs:
_ring_idxs += (idxs,)
return _ring_idxs | 3bf7c8d368a49e825828dae538e0533fd8e61977 | 674,338 |
def total_passed(parsed_list, passing_grade):
"""
This function finds the total number of individuals that scored over or
equal to the passing grade.
:param parsed_list: the parsed list of the grades
:return: the total number of people graded
"""
passing_grades_list = (
[item for it... | 7028a63a542f4ae4f2e0e15cb690ab9a9b07d7cb | 674,340 |
def unpad(s: str) -> str:
"""Unpad string.
:param s: string to be unpadded
:type s: str
:return: unpadded string
:rtype: str
"""
return s[0: -ord(s[-1])] | 0014c999c7df2ccd71980593f10c97012a092312 | 674,341 |
from typing import Sequence
def waste(groups) -> Sequence[int]:
"""Calculate amount of unused registers in this grouping."""
return [sum(b - a for a, b in zip(g[:-1], g[1:])) for g in groups] | 7254122ef78c2e18a269d5ca1d79824abc387e72 | 674,342 |
def color_blend(a, b):
"""
Performs a Screen blend on RGB color tuples, a and b
"""
return (255 - (((255 - a[0]) * (255 - b[0])) >> 8),
255 - (((255 - a[1]) * (255 - b[1])) >> 8),
255 - (((255 - a[2]) * (255 - b[2])) >> 8)) | dbfed8d7697736879aab6ffa107d7f4f7927be4b | 674,344 |
import socket
def is_valid_ip(address):
"""
Summary: This function validates if provided string is a valid IP address.
"""
try:
socket.inet_aton(address)
return True
except Exception:
return False | fa743f212aefa48b0b8c2b709da7b8fc3cf54152 | 674,345 |
def get_creds_file_contents():
""" Reads the lines of the credential file. """
with open(f"./swito-google-creds.json", "r") as file:
lines = file.readlines()
return lines | b279bb5269e3e0cda9d8804f87adb3286880e628 | 674,346 |
import colorsys
def ncolors(levels):
"""Generate len(levels) colors with darker-to-lighter variants
for each color
Args:
levels(list): List with one element per required color. Element
indicates number of variants for that color
Returns:
List of lists with variants for ea... | 1eb9c569c1548eb349bfe3d6d35cbb8e5b71b8fb | 674,347 |
def nul() -> None:
"""
RIEN DU TOUT.
:return: RIEN.
:rtype: None
"""
return None | 875ddec9919c03dc31ae5c72bea6330eece3412c | 674,348 |
import os
import logging
def makeRecord(self, name, level, filename, lineno, msg, args, excInfo, func=None, extra=None, sinfo=None):
"""
A factory method which can be overridden in subclasses to create
specialized LogRecords.
"""
if extra is not None:
filename, lineno = extra
name ... | f23f3e676ee08d746c034f9edbbd796f4c05fc9e | 674,349 |
def clean_xl_data(data):
"""
appscript returns empty cells as ''. So we replace those with None to be in line with pywin32
"""
return [[None if c == '' else c for c in row] for row in data] | 78103c39f48555e9999854ab68213c433a010a20 | 674,350 |
def compileStatus(lOutput, iWarning, iCritical, sFilesystem):
"""
compiles OK/WARNING/CRITICAL/UNKNOWN status
gets:
lOutput : list of dicts for each Disk
iWarning : warning threshold
iCritical : critical threshold
sFilesystem: filesystem which to compare iWarning and iCritical agains... | db3e64785b447833167de2fa83cc67505b7adfbe | 674,351 |
import uuid
def post_async_device_request(cloud, path, device_id, headers):
"""
Sends POST async request to device
https://www.pelion.com/docs/device-management/current/service-api-references/device-management-connect.html#createAsyncRequest
:param cloud: Cloud object
:param path: Device resource ... | ebac75ee074bd9f9b1a7d9a32b12031fe8b53152 | 674,352 |
import argparse
def create_parser(description, prog=None, prefix=""):
"""
Configures a command-line parser with parameters for redis.
:param description: the description that the parser outputs on the help screen
:type description: str
:param prog: the program name, when using entry_points, None ... | d425b269e9f18099ea367958368762aa6a828e05 | 674,354 |
def has_reverse_domain_perm(user_level, obj, ctnr, action):
"""
Permissions for reverse domains
Ctnrs have reverse domains
"""
if not obj in ctnr.reverse_domains.all():
return False
return {
'cyder_admin': True,
'ctnr_admin': True,
'user': True,
'guest': ... | bc105fef6f0b83831460ac3ede7b3354d8b4ff30 | 674,355 |
def map_nested(function, data_struct, dict_only=False):
"""Apply a function recursivelly to each element of a nested data struct."""
# Could add support for more exotic data_struct, like OrderedDict
if isinstance(data_struct, dict):
return {
k: map_nested(function, v, dict_only) for k, v in data_stru... | 9514b24479a8dacf1c4947f49dc2cf371f34b049 | 674,356 |
def get_entities_filter(search_entities):
"""Forms filter dictionary for search_entities
Args:
search_entities (string): entities in search text
Returns:
dict: ES filter query
"""
return {
"nested": {
"path": "data.entities",
"filter":{
"bool":{
"should": [
{
"terms":... | 406f92124c95219a5c4c5e698bffe0e8f2f2a83e | 674,357 |
import torch
def try_gpu():
"""If GPU is available, return torch.device as cuda:0; else return torch.device as cpu."""
if torch.cuda.is_available():
device = torch.device('cuda:0')
else:
device = torch.device('cpu')
return device | 717656388e5499a840095b2f783adaf06c7e5890 | 674,358 |
from typing import Dict
def prepare_headers(token: str) -> Dict:
"""Prepare headers for client."""
if token:
return {"Authorization": f"token {token}"}
return {} | c44e99b62109e7f64e0e08daa544776c13b35907 | 674,359 |
def monkeypatch(name, new_value):
"""Replace name with new_value.
:return: A callable which will restore the original value.
"""
location, attribute = name.rsplit('.', 1)
# Import, swallowing all errors as any element of location may be
# a class or some such thing.
try:
__import__(... | bf04801efc825c658f520a063fc554b21154d5c5 | 674,360 |
import math
def rect(r, theta):
"""
theta in degrees
returns tuple; (float, float); (x,y)
"""
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
return x, y | cc3b1384be3c24b4a515a3c5c61cc5167bc3f6c1 | 674,362 |
import os
import glob
def get_tensorrt_op_path():
"""Get TensorRT plugins library path."""
wildcard = os.path.join(
os.path.abspath(os.path.dirname(os.path.dirname(__file__))),
'_ext_trt.*.so')
paths = glob.glob(wildcard)
lib_path = paths[0] if len(paths) > 0 else ''
return lib_pa... | c030a11cc8d3fea96f14643f05f84e4c7c4dbc2c | 674,363 |
def task_update() -> dict:
"""Update existing message catalogs from a *.pot file."""
return {
"actions": [
"pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l en",
"pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l ru",
],
... | b430472f4fd837c17866c52a91b1e16564cafd2e | 674,365 |
import sys
def get_argv_opt(shortname=None, longname=None, is_bool=False):
"""
Simple and naive helper to get option from command line.
Returns None on any error.
"""
assert shortname or longname
if shortname:
assert shortname.startswith('-')
try:
x = sys.argv.index... | 4dabe68620181d0748bf64157c68c35be037cf41 | 674,366 |
def _bootstrap_class(obj, severe, warn):
"""
gets a bootstrap class for an object comparing to thresholds.
assumes bigger is worse and default is good.
"""
if obj > severe:
return "label label-important"
elif obj > warn:
return "label label-warning"
else:
return "labe... | cda68f10b8cd323989e13724900194b13f067d17 | 674,367 |
import pytz
def datetime_to_string_stix(dttm):
"""Given a datetime instance, produce the string representation
with millisecond precision"""
# 1. Convert to timezone-aware
# 2. Convert to UTC
# 3. Format in ISO format with millisecond precision,
# except for objects defined with higher p... | 66bc4c7668afe24eec0fc03afddae93401de5301 | 674,369 |
from typing import Sequence
from typing import Mapping
def deepmap(f, m):
"""Apply functions to the leaves of a dictionary or list, depending type of the leaf value.
Example: deepmap({torch.Tensor: lambda t: t.detach()}, x)."""
for cls in f:
if isinstance(m, cls):
return f[cls](m)
... | defdc7da616d6f8bbbb8c1d059ce8200f90f5681 | 674,370 |
def _json_force_object(v):
"""Force a non-dictionary object to be a JSON dict object"""
if not isinstance(v, dict):
v = {'payload': v}
return v | bf6f86c92b05e0859723296b3cc58cd32863637c | 674,372 |
def get_threecommas_blacklist(logger, api):
"""Get the pair blacklist from 3Commas."""
newblacklist = list()
error, data = api.request(
entity="bots",
action="pairs_black_list",
)
if data:
logger.info(
"Fetched 3Commas pairs blacklist OK (%s pairs)" % len(data["p... | 082991d1913a6aa1318e60caee762f050d86418d | 674,373 |
import os
def get_path_for(view):
"""
Returns the path of the current file in view.
Returns / if no path is found
"""
if view.file_name():
return os.path.dirname(view.file_name())
if view.window().project_file_name():
return os.path.dirname(view.window().project_file_name())
... | 126a65389cbe2bc66cce5be365ecdf24048d6103 | 674,374 |
def out_degree_centrality(G):
"""Compute the out-degree centrality for nodes.
The out-degree centrality for a node v is the fraction of nodes its
outgoing edges are connected to.
Parameters
----------
G : graph
A NetworkX graph
Returns
-------
nodes : dictionary
Di... | 0ea94bb13a3ab72736e65730fc5783ea41679d52 | 674,375 |
import torch
def get_proj_layer(fairseq_pretrained_model_path):
"""
Get projection layer's weights and biases of wav2vec 2.0 pre-trained model
"""
w2v = torch.load(fairseq_pretrained_model_path)
return w2v["model"]["w2v_encoder.proj.weight"], w2v["model"]["w2v_encoder.proj.bias"] | a1a9d83db18fd8e28d8ab75bf1390f8d36e87ecf | 674,376 |
def erbs2hz(erbs):
"""
Convert values in Equivalent rectangle bandwidth (ERBs) to
values in Hertz (Hz)
Parameters from [1]
Args:
erbs (float): real number in ERBs
Returns:
hz (float): real number in Hertz
References:
[1] Camacho, A., & Harris, J. G. (2008). A sawt... | 9919ecdf4979e1dc28d2de2c87ff8246ec106fb2 | 674,378 |
import os
def is_exists_and_locked(filepath):
"""Checks if a file is locked by opening it in append mode.
If no exception thrown, then the file is not locked.
"""
if not os.path.exists(filepath):
return False
file_object = None
try:
file_object = open(filepath, 'a')
if... | a3115c976f5e52ce997d52b64306d633a27f2d0c | 674,379 |
import unittest
def get_test_suite():
"""
Prepare a test-suite callable with:
python setup.py test
"""
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests', pattern='test_*.py')
return test_suite | e691e79cbb1f7be9d51d6679996ab462a45b99ef | 674,381 |
def split_df_by_regions(df):
"""
Split the dataframe based on TotalUS, regions and sub-regions
"""
df_US = df[df.region == 'TotalUS']
regions = ['West', 'Midsouth', 'Northeast', 'SouthCentral', 'Southeast']
df_regions = df[df.region.apply(lambda x: x in regions and x != 'TotalUS')]
df_subreg... | 7a74315a8e5bf9dba8e156df4d8bf0e370b6be0c | 674,382 |
def ends_with_hashtag(text):
"""
Determines whether the text ends with a hashtag
:param text: The text to analyze
:return: 0 - 1 if there is not or is a hastag as the last word
"""
return int(text.split(' ')[-1][0] == '#') | 580bd764ce0bd87b0983870a5782e5552c67e802 | 674,385 |
def x(P):
"""
Return :class:`P.x` or :class:`P[0]`.
Args:
P (:class:`list`): ``secp256k1`` point
Returns:
:class:`int`: x
"""
return P[0] | ce33378476e550610e3240872bc8ab810bd19b31 | 674,386 |
def is_week_day(the_date):
""" Decides if the given date is a weekday.
Args:
the_date: Date object. The date to decide.
Returns:
Boolean. Whether the given date is a weekday.
"""
return the_date.isoweekday() in [1, 2, 3, 4, 5] | ddc3f7735062beb0b7cd4509a317dcc8d3acc439 | 674,387 |
def path_in_book(path):
"""
A filter function that checks if a given path is part of the book.
"""
if ".ipynb_checkpoints" in str(path):
return False
if "README.md" in str(path):
return False
return True | ba2be7b47ce6ad6581d26411149db3b0cd3b1e3d | 674,388 |
def entra_com_valor(val=0, msg='Digite um valor: '):
"""val => Valor avaliar msg => mensagem exibir"""
val = None
while val == None:
try:
val = int(input(msg))
except:
print(' - Não entendi')
pass
else:
return val | 9197076300a6bfb70f4321a22c330a370f4c8410 | 674,389 |
def remove_dash(text):
"""
Variable name can't have - in javascript
"""
text = str(text)
return text.replace('-', '') | d8e995fc94c69ab4ff5ebaef267542c4714f7014 | 674,390 |
def soil_heat_flux_by_nightday_period(rn, isday=True):
"""
:param rn: Net radiation at crop surface
:param isday: variable to say if is day period or night period
:return: Shorten period heat flux [MJ m-2 15min]
"""
if isday:
soil_heat_flux = 0.1 * rn
else:
soil_heat_flux = ... | f4a751c218537efbc1b55f3955213ad82cccea2a | 674,391 |
from typing import List
import posixpath
def format_path(base: str, components: List[str]) -> str:
"""
Formats a base and http components with the HTTP protocol and the expected port.
"""
url = "http://{}:8000/".format(base)
for component in components:
url = posixpath.join(url, component... | 7b55147db9dbdf0f87cd428a319c5cd3aa7276fe | 674,392 |
def FV(pv:float, r:float, n:float, m = 1):
"""
FV(): A function to calculate Future Value.
:param pv: Present Value
:type pv: float
:param r: Rate of Interest/Discount Rate (in decimals eg: 0.05 for 5%)
:type r: float
:param n: Number of Years
:type n: float
:param m: Frequency of Interest Calculatio... | ae0ad0fc37edd19983dc0ab44f1e238bc763084c | 674,394 |
import os
def path_modification_time(path: str, allow_nonexistent: bool = False) -> float:
"""Return the modification time of a path (file or directory).
If allow_nonexistent is True and the path does not exist, we return 0.0 to
guarantee that any file/dir later created at the path has a later
modifi... | bc47d53e482c8e833f1e665de7dfb7fcadf93069 | 674,395 |
def __equivalent_lists(list1, list2):
"""Return True if list1 and list2 contain the same items."""
if len(list1) != len(list2):
return False
for item in list1:
if item not in list2:
return False
for item in list2:
if item not in list1:
return False
... | f9ef5b643ed0ba4b6bddd3a6394af9a22ed118ee | 674,396 |
from typing import List
import math
def check_root(string: str) -> str:
"""
A function which takes numbers separated by commas
in string format and returns the number which is a
perfect square and the square root of that number.
If string contains other characters than number or
it has more o... | fb31b1cf3b9dc83d1cafec22dde273b16f9cc218 | 674,397 |
def get_dictvalue_from_xpath(full_dict, path_string):
""" get a value in a dict given a path's string """
key_value = full_dict
for i in path_string.split('/')[1:] :
key_value = key_value[i]
return key_value | fd3b0a38cc346eba2bcdb3355bc039a2a6fb82da | 674,398 |
def is_camel_case(st: str) -> bool:
"""Takes a string and returns True if the string is camel case or similar"""
return st != st.lower() and st != st.upper() and "_" not in st | cb9098ab513b560c194e08efac8790fffe4629a8 | 674,399 |
import re
def extract_nterm_mods(seq):
"""
Extract nterminal mods, e.g. acA.
Args:
seq: str, peptide sequence
Returns:
ar-like, list of modifications
"""
# matches all nterminal mods, e.g. glD or acA
nterm_pattern = re.compile(r'^([a-z]+)([A-Z])')
mods = []
# test... | 956215c420e78215206e207c1b1fe3dae1cd8eb8 | 674,400 |
def cubic_bezier(p0, p1, p2, p3, t):
""" evaluate cubic bezier curve from p0 to p3 at fraction t for control points p1 and p2 """
return p0 * (1 - t)**3 + 3 * p1 * t*(1 - t)**2 + 3 * p2 * t**2*(1 - t) + p3 * t**3 | ab308bc593e4674a8b3d4c2779c936286bf28f99 | 674,401 |
import requests
import json
def connect_to_api(_id: str):
"""
Connect to Call of Duty API.
:param _id: A matchID str.
:type _id: str
:return: A Json of lobby data related to specified matchID.
:rtype: Json
:example: *None*
:note: Connect to Cod API to receive lobby information.
... | 3916b1674b252af4e77a6a9581e34479af9651ae | 674,402 |
import os
import json
def get_worker(name, logger):
"""
Returns information dictionary about a worker given its name.
"""
path = os.path.join("workers", name, "worker.json")
if os.path.exists(name):
path = name
dirpath = os.path.dirname(path)
if not os.path.exists(path):
... | d22f5b271bbcd2880dc8dbb0994e68fb457b37cc | 674,403 |
def get_variable_shape(innersize, ngbs, nh):
"""
innersize sets the interior domain size
innersize = [nz, ny, nx]
ngbs is the neighbours dictionary
return:
size = the extended domain size (with halo)
domainindices = (k0, k1, j0, j1, i0, i1),
the list of start and last... | 416dc2bd703d540938617925e00221f427814b55 | 674,404 |
def filter_results(results, filters, exact_match) -> list[dict]:
"""
Returns a list of results that match the given filter criteria.
When exact_match = true, we only include results that exactly match
the filters (ie. the filters are an exact subset of the result).
When exact-match = false,
we ... | 7120c4239ba830a4624bebc033389158e17e4d30 | 674,405 |
def display_reversed_string():
"""
087
Ask the user to type in a word and then display it backwards on separate lines. For
instance, if they type in “Hello” it should display as shown below:
"""
word = input("Enter a word: ")[::-1] # Reverse the string
for char in word:
print(char)
... | f7c2951742e963f85b88626030e0a91d40e1868e | 674,406 |
def pack(fmt, *args): # known case of _struct.pack
""" Return string containing values v1, v2, ... packed according to fmt. """
return "" | cbad58831faa12563a85482a3ca8bedea830ae6c | 674,407 |
from typing import Optional
import os
def _default_token() -> Optional[str]:
"""Handle the token provided as env variable."""
return os.environ.get('HASS_TOKEN', os.environ.get('HASSIO_TOKEN', None)) | cb51536728a21e5c9fd9391c58dad534002ce32d | 674,408 |
def dict_chainget(obj, *chain):
""" Get the value from dictionary 'obj' one-by one in chain """
if not chain:
return obj
if not isinstance(obj, dict):
return None
if chain[0] not in obj:
return None
return dict_chainget(obj[chain[0]], *chain[1:]) | cf335934465685e841c8592c4e206e25cd2a41ca | 674,409 |
def fact(n):
"""Finding factorial iteratively"""
if n == 1 or n == 0:
return 1
result = 1
for i in range(n, 1, -1):
result = result * i
return result | 0ecbf67c679266c3b8d61f96bb84df48b7b0cbfe | 674,410 |
def SignDotNetManifest(env, target, unsigned_manifest):
"""Signs a .NET manifest.
Args:
env: The environment.
target: Name of signed manifest.
unsigned_manifest: Unsigned manifest.
Returns:
Output node list from env.Command().
"""
sign_manifest_cmd = ('@mage -Sign $SOURCE -ToFile $TARGET -Ti... | 44cc1e8be57fc1f1bac32885cdb852edc392574d | 674,411 |
import argparse
def argsparsefraction(txt):
"""
Validate the txt argument as value between 0.0 and 1.0.
:param txt: argument is a float string between 0.0 and 1.0.
:return: float
"""
msg = "Value shoud be a float between 0.0 and 1.0"
try:
value = float(txt)
if value < 0 o... | bc7819161855b4caaedf1394d573d0190c43beeb | 674,412 |
def calc_gene_lens(coords, prefix=False):
"""Calculate gene lengths by start and end coordinates.
Parameters
----------
coords : dict
Gene coordinates table.
prefix : bool
Prefix gene IDs with nucleotide IDs.
Returns
-------
dict of dict
Mapping of genes to leng... | 7eb54195f05d22c0240ef412fd69b93e1d46e140 | 674,413 |
def enc_gql(gql, *args):
"""from multiline to an interpolated line"""
joint_line = " ".join(map(lambda el: el.strip(), gql.splitlines()))
tupled_args = tuple(args)
enc_line = joint_line
if tupled_args:
enc_line = joint_line % tupled_args
return enc_line | 6bca7312540d6e2748a414424623fa65c20b4c5e | 674,414 |
def klucb(x, d, kl, upperbound, lowerbound=float('-inf'), precision=1e-6, max_iterations=50):
""" The generic KL-UCB index computation.
- x: value of the cum reward,
- d: upper bound on the divergence,
- kl: the KL divergence to be used (:func:`klBern`, :func:`klGauss`, etc),
- upperbound, lowerbou... | efc8a63dc0f5a738d68ae9824d7fb6a2b16c1074 | 674,415 |
import os
def get_config_home():
"""Returns the base directory for isrcsubmit's configuration files."""
if os.name == "nt":
default_location = os.environ.get("APPDATA")
else:
default_location = os.path.expanduser("~/.config")
xdg_config_home = os.environ.get("XDG_CONFIG_HOME", defaul... | 376d7884145a8c6830a92617397463eff131ee08 | 674,416 |
import torch
def int_to_one_hot(class_labels, nb_classes, device, soft_target=1.):
""" Convert tensor containing a batch of class indexes (int) to a tensor
containing one hot vectors."""
one_hot_tensor = torch.zeros((class_labels.shape[0], nb_classes),
device=device)
f... | ef0360cd41e34b78b158e015a02d3d8490069e51 | 674,417 |
import itertools
def pairwise(iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ..."""
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b) | bca8a95860bf42b5f6e2f9e1f49fff172ab56e4c | 674,418 |
def read_file(path: str) -> str: # pragma: nocover
"""
This function simply reads contents of the file. It's moved out to a function
purely to simplify testing process.
Args:
path: File to read.
Returns:
content(str): Content of given file.
"""
return open(path).read() | 743db60ee698baa67166c21dc514e93ccb0de912 | 674,419 |
def my_repr(line):
""" Given a latin1 line, output valid C++ string.
if the character is < 0x20 or > 0x7e, output in hex format.
if the character is ', " or ?, output \', \", or \?.
"""
r = ""
for c in line:
o = ord(c)
if ((o< 0x20) or (o > 0x7e)):
r += "\\x{0:02x}"... | bc2b032b6bcfb6aa3bc641f084f86957158dfb5d | 674,420 |
def text_to_list(element, delimiter='|'):
"""
Receives a text and a delimiter
Return a list of elements by the delimiter
"""
return element.split(delimiter) | 3638da81e7c952e8821bd843498e19b877c1d9aa | 674,421 |
def living_expenses(after_tax_income):
"""
Returns the yearly living expenses, which is 5% of the after tax income.
:param after_tax_income: The yearly income after income tax.
:return: The living expenses.
"""
return after_tax_income * 0.05 | a2c5b7c306cf8db8f11fc5f88282fd62e675c9ab | 674,422 |
def register_tokens():
"""Should fixture generated tokens be registered with raiden (default: True)
"""
return True | 891d298457c80033d20bf9001ca5631068bd21aa | 674,423 |
def comma_separated(xs):
"""Convert each value in the sequence xs to a string, and separate them
with commas.
>>> comma_separated(['spam', 5, False])
'spam, 5, False'
>>> comma_separated([5])
'5'
>>> comma_separated([])
''
"""
return ', '.join([str(x) for x in xs]) | da46d93d9f1b545f1d592da3ba51698e4ae96d5f | 674,424 |
def dummy_category(create_category):
"""Create a mocked dummy category."""
return create_category(title='dummy') | 02846f429da808394af2aebbb1cb07a8d008956c | 674,425 |
def is_list_like(arg):
"""Returns True if object is list-like, False otherwise"""
return (hasattr(arg, '__iter__') and
not isinstance(arg, str)) | 9897b3859fa618c74c548b1d8ffa94796bbe2b5d | 674,426 |
import time
def calc_future(time_future, kwdargs):
"""
Work out the rollover time based on the specified time.
"""
# Get future time
(yr, mo, day, hr, min, sec, wday, yday, isdst) = time.localtime(
time_future)
# override select values
d = { 'yr': yr, 'mo': mo, 'day': day, 'hr': h... | 46757ee9b3f3824c1be06106cadc43f5571629d5 | 674,427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.