content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def log_loss(
predictions: ArrayLike,
targets: ArrayLike,
) -> ArrayLike:
"""Calculates the log loss of predictions wrt targets.
Args:
predictions: a vector of probabilities of arbitrary shape.
targets: a vector of probabilities of shape compatible with predictions.
Returns:
a vector of same... | 9,100 |
def GetAccessTokenOrDie(options):
"""Generates a fresh access token using credentials passed into the script.
Args:
options: Flag values passed into the script.
Returns:
A fresh access token.
Raises:
ValueError: response JSON could not be parsed, or has no access_token.
"""
... | 9,101 |
def test_races2000():
"""Test module races2000.py by downloading
races2000.csv and testing shape of
extracted data has 77 rows and 5 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = races2000(test_path)
try:
assert x_train.shape == (77, 5)
except:
shutil.rmtree(test_path)
rai... | 9,102 |
def remove_whitespace(tokens):
"""Remove any top-level whitespace and comments in a token list."""
return tuple(
token for token in tokens
if token.type not in ('whitespace', 'comment')) | 9,103 |
def _closefile(fpath, modnames):
"""
An api to remove dependencies from code by "closing" them.
CommandLine:
xdoctest -m ~/code/netharn/netharn/export/closer.py _closefile
xdoctest -m netharn.export.closer _closefile --fpath=~/code/boltons/tests/test_cmdutils.py --modnames=ubelt,
Examp... | 9,104 |
def update(args):
"""
For LdaCgsMulti
"""
(docs, doc_indices, mtrand_state, dtype) = args
start, stop = docs[0][0], docs[-1][1]
global Ktype
if _K.value < 2 ** 8:
Ktype = np.uint8
elif _K.value < 2 ** 16:
Ktype = np.uint16
else:
raise NotImplementedError("Inv... | 9,105 |
def GetPackages(manifest, conf, cache_dir, interactive=False):
"""
Make sure that the packages exist. If they don't, then
attempt to download them. If interactive, use lots of
dialog messages.
"""
conf.SetPackageDir(cache_dir)
try:
manifest.RunValidationProgram(cache_dir, kind=Mani... | 9,106 |
def warn(string: str) -> str:
"""Add warn colour codes to string
Args:
string (str): Input string
Returns:
str: Warn string
"""
return "\033[93m" + string + "\033[0m" | 9,107 |
def test_get_latest_certification_period_no_threshold():
""" Tests the get_latest_certification_period function to make sure it returns Nones if there's no prior period """
results = get_latest_certification_period()
assert results['quarter'] is None
assert results['year'] is None | 9,108 |
def normalized_mean_square_error(logits, labels, axis = [0,1,2,3]):
"""
logits : [batch_size, w, h, num_classes]
labels : [batch_size, w, h, 1]
"""
with tf.name_scope("normalized_mean_square_error"):
nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(logits, labels), axis=[1,2,3]))
... | 9,109 |
def load_glove_data():
"""
Loads Stanford's dictionary of word embeddings created by using corpus of
Twitter posts. Word embeddings are vectors of 200 components.
OUTPUT:
dictionary containing tweet word embeddings
"""
glove_path = path.join('..', 'data', 'glove', 'glove.twitter.27B.200d... | 9,110 |
def assertIsNotSubdomainOf(testCase, descendant, ancestor):
"""
Assert that C{descendant} *is not* a subdomain of C{ancestor}.
@type testCase: L{unittest.SynchronousTestCase}
@param testCase: The test case on which to run the assertions.
@type descendant: C{str}
@param descendant: The subdomai... | 9,111 |
def test_string_in_filter(query):
"""
Test in filter on a string field.
"""
Pet.objects.create(name="Brutus", age=12)
Pet.objects.create(name="Mimi", age=3)
Pet.objects.create(name="Jojo, the rabbit", age=3)
schema = Schema(query=query)
query = """
query {
pets (name_In: ["... | 9,112 |
def get_partition_to_num_rows(
namespace, tablename, partition_column, partition_column_values
):
"""
Helper function to get total num_rows in hive for given
partition_column_values.
"""
partitions = {
"{0}={1}".format(partition_column, partition_column_value)
for partition_colum... | 9,113 |
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = initialize_game()
card_title = "Welcome"
speech_output = "Hello! I am Cookoo. Let's play a game. " \
"Are you ready to play?"
... | 9,114 |
def kl_divergence_with_logits(logits_a, logits_b):
"""
Compute the per-element KL-divergence of a batch.
Args:
logits_a: tensor, model outputs of input a
logits_b: tensor, model outputs of input b
Returns:
Tensor of per-element KL-divergence of model outputs a and b
"""... | 9,115 |
def load_labels(abs_path):
"""
loads relative path file as dictionary
Args:
abs_path: absolute path
Returns dictionary of mappings
"""
label_tsv = open(abs_path, encoding="utf-8")
labels = list(csv.reader(label_tsv, delimiter="\t"))
return labels | 9,116 |
def cut_tree_balanced(linkage_matrix_Z, max_cluster_size, verbose=False):
"""This function performs a balanced cut tree of a SciPy linkage matrix built using any linkage method
(e.g. 'ward'). It builds upon the SciPy and Numpy libraries.
The function looks recursively along the hierarchical ... | 9,117 |
def len_smaller(length: int) -> Callable:
"""Measures if the length of a sequence is smaller than a given length.
>>> len_smaller(2)([0, 1, 2])
False
"""
def len_smaller(seq):
return count(seq) < length
return len_smaller | 9,118 |
def e_2e_fun(theta, e_init=e_1f):
"""
Electron energy after Compton scattering, (using energy e_1f)
:param theta: angle for scattered photon
:param e_init: initial photon energy
:return:
"""
return e_init / (((m_e * c ** 2) / e_init) * (1 / (1 - np.cos(theta))) + 1) | 9,119 |
def tag_images_for_google_drive(
input_files: AbstractSet[Path],
database: Optional[Path],
extra_tags: Optional[Set[str]],
tag_file: Optional[Path] = None,
from_files: bool = False,
from_db: bool = False,
force: bool = False,
dry: bool = False,
ver... | 9,120 |
def xml_reader(filename):
"""
A method using iterparse as above would be preferable, since we just want to
collect the first few tags. Unfortunately, so far iterparse does not work
with html (aka broken xml).
"""
name = os.path.basename(filename)
with open(filename, "rb") as file_h:
... | 9,121 |
def exercise_10():
"""
nucleic acids: RNA
"""
in_pdb_str = """\
HEADER RNA 26-MAR-97 1MIS
CRYST1 1.000 1.000 1.000 90.00 90.00 90.00 P 1 1
ORIGX1 1.000000 0.000000 0.000000 0.00000
ORIGX2 0.000000 1.000000 0.000000 0.0000... | 9,122 |
def interval_list_intersection(A: List[List], B: List[List], visualization: bool = True) -> List[List]:
"""
LeteCode 986: Interval List Intersections
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval li... | 9,123 |
def set_project_user_attribute_name(number: int, value: str) -> None:
"""
Args:
number (int): user attribute number
value (str): value
""" | 9,124 |
def test_amf_classifier_serialization():
"""Trains a AMFClassifier on iris, saves and loads it again. Check that
everything is the same between the original and loaded forest
"""
random_state = 42
n_estimators = 1
n_classes = 3
iris = datasets.load_iris()
X = iris.data
y = iris.targ... | 9,125 |
def get(environ: OsEnvironLike = None) -> str:
"""Get the application ID from the environment.
Args:
environ: Environment dictionary. Uses os.environ if `None`.
Returns:
Default application ID as a string.
We read from the environment APPLICATION_ID (deprecated) or else
GAE_APPLICATION.
"""
if... | 9,126 |
def tokenize_query(query):
""" Tokenize a query """
tokenized_query = tokenizer.tokenize(query)
stop_words = set(nltk.corpus.stopwords.words("english"))
tokenized_query = [
word for word in tokenized_query if word not in stop_words]
tokenized_query = [stemmer.stem(word) for word in tokenized... | 9,127 |
def redo(layer):
"""Redo any previously undone actions."""
layer.redo() | 9,128 |
def _add_run_common(parser):
"""Add common args for 'exp run' and 'exp resume'."""
# inherit arguments from `dvc repro`
add_repro_arguments(parser)
parser.add_argument(
"-n",
"--name",
default=None,
help=(
"Human-readable experiment name. If not specified, a n... | 9,129 |
def rewrite_return(func):
"""Rewrite ret ops to assign to a variable instead, which is returned"""
ret_normalization.run(func)
[ret] = findallops(func, 'ret')
[value] = ret.args
ret.delete()
return value | 9,130 |
def get_loss_fn(loss_factor=1.0):
"""Gets a loss function for squad task."""
def _loss_fn(labels, model_outputs):
start_positions = labels['start_positions']
end_positions = labels['end_positions']
start_logits, end_logits = model_outputs
return squad_loss_fn(
start_positions,
end_p... | 9,131 |
async def run_command(*args):
"""
https://asyncio.readthedocs.io/en/latest/subprocess.html
"""
# Create subprocess
process = await asyncio.create_subprocess_exec(
*args,
# stdout must a pipe to be accessible as process.stdout
stdout=asyncio.subprocess.PIPE)
# Wait for the... | 9,132 |
def replace_config(conf_file_path, src_key, new_value):
"""Update the config file by a given dict."""
with open(conf_file_path, "a+") as fp:
content = json.load(fp)
content[src_key].update(new_value)
fp.truncate(0)
fp.write(json.dumps(content, indent=4)) | 9,133 |
def runcmd(ctx, cmdargs):
"""Execute the given command"""
utils.run_solver(cmdargs) | 9,134 |
def get_variants_in_region(db, chrom, start, stop):
"""
Variants that overlap a region
Unclear if this will include CNVs
"""
xstart = get_xpos(chrom, start)
xstop = get_xpos(chrom, stop)
variants = list(db.variants.find({ 'xpos': {'$lte': xstop, '$gte': xstart}
}, projection={'_id': Fals... | 9,135 |
def get_business(bearer_token, business_id):
"""Query the Business API by a business ID.
Args:
business_id (str): The ID of the business to query.
Returns:
dict: The JSON response from the request.
"""
business_path = BUSINESS_PATH + business_id
#4
return request(API_HOST, b... | 9,136 |
def AlexNet_modified(input_shape=None, regularize_weight=0.0001):
"""
Alexnet convolution layers with added batch-normalization and regularization
:param input_shape:
:param regularize_weight:
:return:
"""
from keras.layers import Conv2D, Input, MaxPooling2D, ZeroPadding2D
from keras.l... | 9,137 |
def main():
""" Make all images in current directory. """
for tex_file in iglob('./*.tex'):
jobname = tex_file.split('/')[-1][:-4]
os.system(f'pdflatex --shell-escape {jobname}')
for ext in ['aux', 'log', 'pdf']:
os.system(f'rm {jobname}.{ext}') | 9,138 |
def readblock(fileObj):
"""
parse the block of data like below
ORDINATE ERROR ABSCISSA
2.930E-06 1.8D-07 5.00E+02 X.
8.066E-06 4.8D-07 6.80E+02 .X.
1.468E-05 8.3D-07 9.24E+02 ..X.
2.204E-05 1.2D-06 1.26E+03 ... | 9,139 |
def test_config_override() -> None:
"""Test config can be overriden."""
bot = Phial(
"test-token",
config={
"prefix": "/",
"registerHelpCommand": False,
"baseHelpText": "All commands:",
"autoReconnect": False,
"loopDelay": 0.5,
... | 9,140 |
def test_get_svl_data_number_multi_row(test_conn):
""" Tests that get_svl_data raises an SvlNumberValueError when the query
returns multiple values.
"""
svl_plot = {
"type": "number",
"data": "bigfoot",
"value": {"field": "number"},
}
with pytest.raises(SvlNumberValueErr... | 9,141 |
def as_scalar(scalar):
"""Check and return the input if it is a scalar.
If it is not scalar, raise a ValueError.
Parameters
----------
scalar : Any
the object to check
Returns
-------
float
the scalar if x is a scalar
"""
if isinstance(scalar, np.ndarray):
... | 9,142 |
def evaluate_dnf( # pylint: disable=too-many-arguments,too-many-locals
num_objects: int,
num_vars: int,
nullary: np.ndarray,
unary: np.ndarray,
binary: np.ndarray,
and_kernel: np.ndarray,
or_kernel: np.ndarray,
target_arity: int,
) -> np.ndarray:
"""Evaluate given batch of interpret... | 9,143 |
def black_color_func(word, font_size, position, orientation,
random_state=None, **kwargs):
"""Make word cloud black and white."""
return("hsl(0,100%, 1%)") | 9,144 |
def setup(hass, config):
""" Setup history hooks. """
hass.http.register_path(
'GET',
re.compile(
r'/api/history/entity/(?P<entity_id>[a-zA-Z\._0-9]+)/'
r'recent_states'),
_api_last_5_states)
hass.http.register_path('GET', URL_HISTORY_PERIOD, _api_history_per... | 9,145 |
def test_rsun_missing():
"""Tests output if 'rsun' is missing"""
euvi_no_rsun = Map(fitspath)
euvi_no_rsun.meta['rsun'] = None
assert euvi_no_rsun.rsun_obs.value == sun.solar_semidiameter_angular_size(euvi.date).to('arcsec').value | 9,146 |
def shuffle_file(filename):
"""Shuffle lines in file.
"""
sp = filename.split('/')
shuffled_filename = '/'.join(sp[:-1] + ['shuffled_{}'.format(sp[-1])])
logger.info(shuffled_filename)
os.system('shuf {} > {}'.format(filename, shuffled_filename))
return shuffled_filename | 9,147 |
def fitallseq(digitslist, list):
"""if there is repeating digits, itertools.permutations() is still usable
if fail, still print some print, if i >= threshold, served as start point for new searching """
for p in itertools.permutations(digitslist):
#print "".join(pw)
i=0
pw=""... | 9,148 |
def adduser(args):
"""Add or update a user to the database: <username> <password> [[role] [role] ...]"""
try:
username, password = args[0:2]
except (IndexError, ValueError), exc:
print >> sys.stderr, "you must include at least a username and password: %s" % exc
usage()
try:
... | 9,149 |
def register_celery(app: Flask):
"""Load the celery config from the app instance."""
CELERY.conf.update(app.config.get("CELERY", {}))
CELERY.flask_app = app # set flask_app attribute used by FlaskTask
app.logger.info(
f"Celery settings:\n{CELERY.conf.humanize(with_defaults=False, censored=True)... | 9,150 |
def test_issue_too_many(web3, issuer, issue_script_owner, customer):
"""Issue over allowance."""
with pytest.raises(TransactionFailed):
issuer.functions.issue(customer, 3000).transact({"from": issue_script_owner}) | 9,151 |
def check_linear_dependence(matrix: np.ndarray) -> bool:
"""
Functions checks by Cauchy-Schwartz inqeuality whether two matrices are linear dependent or not.
:param matrix: 2x2 matrix to be processed.
:return: Boolean.
"""
for i in range(matrix.shape[0]):
for j in range(matrix.shape[0]):... | 9,152 |
def cors_400(details: str = None) -> cors_response:
"""
Return 400 - Bad Request
"""
errors = Model400BadRequestErrors()
errors.details = details
error_object = Model400BadRequest([errors])
return cors_response(
req=request,
status_code=400,
body=json.dumps(delete_non... | 9,153 |
def detect_label_column(column_names):
""" Detect the label column - which we display as the label for a joined column.
If a table has two columns, one of which is ID, then label_column is the other one.
"""
if (column_names and len(column_names) == 2 and "id" in column_names):
return [c fo... | 9,154 |
def get_date():
"""
get the date
"""
date = subprocess.check_output(["date"])
date = date.decode("utf-8")
date = re.search(r"\w{3} \d{1,2} \w{3} \d{4}", date)
date = date.group(0)
return date | 9,155 |
def sorted_files(pattern):
"""Return files matching glob pattern, *effectively* sorted by date
"""
return sort_files(glob.glob(pattern)) | 9,156 |
def random_float_tensor(seed, size, a=22695477, c=1, m=2 ** 32, requires_grad=False):
""" Generates random tensors given a seed and size
https://en.wikipedia.org/wiki/Linear_congruential_generator
X_{n + 1} = (a * X_n + c) % m
Using Borland C/C++ values
The tensor will have values between [0,1)
... | 9,157 |
def test_isel_xarray_func(hind_ds_initialized_1d, reconstruction_ds_1d):
"""Test whether applying isel to the objects works."""
hindcast = HindcastEnsemble(hind_ds_initialized_1d)
hindcast = hindcast.add_observations(reconstruction_ds_1d)
hindcast = hindcast.isel(lead=0, init=slice(0, 3)).isel(time=slic... | 9,158 |
def derivable_rng(spec, *, legacy=False):
"""
Get a derivable RNG, for use cases where the code needs to be able to reproducibly derive
sub-RNGs for different keys, such as user IDs.
Args:
spec:
Any value supported by the `seed` parameter of :func:`seedbank.numpy_rng`, in addition
... | 9,159 |
def main() -> None:
"""Function to start the whole application."""
configure_logger()
log: Logger = getLogger(__name__)
log.info("Attempting to start application")
app = get_flask_application()
app.run(
host=app.config["PIPWATCH_API_HOST"],
port=app.config["PIPWATCH_API_PORT"]
... | 9,160 |
def gsort_vcf(f, out_file, genome_file='mitylib/reference/b37d5.genome', remove_unsorted_vcf=False):
"""
use gsort to sort the records in a VCF file according to a .genome file.
:param f: the path to an unsorted vcf.gz file
:param out_file: the path to a resulting sorted vcf.gz file
:param genome_f... | 9,161 |
def table(custom_headings, col_headings_formatted, rows, spec):
"""
Create a LaTeX table
Parameters
----------
custom_headings : None, dict
optional dictionary of custom table headings
col_headings_formatted : list
formatted column headings
rows : list of lists of cell-str... | 9,162 |
def send_async_email(msg, html, text, attach=None, send_independently=True, ctype="other"):
"""
发送email
:param subject:
:param recipients:数组
:param text:
:param html:
:param attach:(<filename>,<content_type>)
:param send_independently:如果为True, 独立给recipients中的每个地址发送信息,
否则,一次发送... | 9,163 |
def readCommand( argv ):
"""
Processes the command used to run pacman from the command line.
"""
from optparse import OptionParser
usageStr = """
USAGE: python pacman.py <options>
EXAMPLES: (1) python pacman.py
- starts an interactive game
(2) pytho... | 9,164 |
def skipIfNoDB(test):
"""Decorate a test to skip if DB ``session`` is ``None``."""
@wraps(test)
def wrapper(self, db, *args, **kwargs):
if db.session is None:
pytest.skip('Skip because no DB.')
else:
return test(self, db, *args, **kwargs)
return wrapper | 9,165 |
def rboxes2quads_numpy(rboxes):
"""
:param rboxes: ndarray, shape = (*, h, w, 5=(4=(t,r,b,l) + 1=angle))
Note that angle is between [-pi/4, pi/4)
:return: quads: ndarray, shape = (*, h, w, 8=(x1, y1,... clockwise order from top-left))
"""
# dists, shape = (*, h, w, 4=(t,r,b,l))
# angles,... | 9,166 |
def _async_register_services(
hass: HomeAssistant,
coordinator: NZBGetDataUpdateCoordinator,
) -> None:
"""Register integration-level services."""
def pause(call: ServiceCall) -> None:
"""Service call to pause downloads in NZBGet."""
coordinator.nzbget.pausedownload()
def resume(ca... | 9,167 |
def cleanup(f):
"""
Remove dir if exists
:param f: Dir to remove
:type f: str
"""
if os.path.exists(f):
shutil.rmtree(f) | 9,168 |
def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection],
resolved_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]:
"""
Represent function arguments and frame values in the error message on contract breach.
:param condition: condit... | 9,169 |
def human_permissions(permissions, short=False):
"""Get permissions in readable form.
"""
try:
permissions = int(permissions)
except ValueError:
return None
if permissions > sum(PERMISSIONS.values()) or permissions < min(
PERMISSIONS.values()
):
return ""
... | 9,170 |
def predict():
"""
Prediction end point
Post a JSON holding the features and expect a prediction
Returns
-------
JSON
The field `predictions` will hold a list of 0 and 1's corresponding
to the predictions.
"""
logger.info('Starting prediction')
json_ = request.get_j... | 9,171 |
def run_program(program, cmdargs, stdin_f, stdout_f, stderr_f,
run=True, cmd_prepend="", run_from_cmd=True,
**kwargs):
"""Runs `program` with `cmdargs` using `subprocess.call`.
:param str stdin_f: File from which to take standard input
:param str stdout_f: File in which to pu... | 9,172 |
def test_invalid_login(test_client, init_database):
"""
GIVEN a Flask application
WHEN the '/login' page is posted to with invalid credentials (POST)
THEN check an error message is returned to the user
"""
response = test_client.post('/login',
data=dict(email='ber... | 9,173 |
def second_step_red(x: np.array, y: np.array, z: np.array,
px: np.array, py: np.array, pz: np.array,
Fx: np.array, Fy: np.array, Fz: np.array,
z_start: float, z_stop: float) -> (np.array, np.array, np.array,
... | 9,174 |
def drop_tabu_points(xf, tabulist, tabulistsize, tabustrategy):
"""Drop a point from the tabu search list."""
if len(tabulist) < tabulistsize:
return tabulist
if tabustrategy == 'oldest':
tabulist.pop(0)
else:
distance = np.sqrt(np.sum((tabulist - xf)**2, axis=1))
index ... | 9,175 |
def get_atom_feature_dims(list_acquired_feature_names):
""" tbd
"""
return list(map(len, [CompoundKit.atom_vocab_dict[name] for name in list_acquired_feature_names])) | 9,176 |
def parse_selector(selector):
"""Parses a block of selectors like div .name #tag to class=.name, selector=div and id=#tag.
Returns (selector, id, class[]) """
m_class, m_id, m_selector, m_attr = [], None, None, {}
if selector is not None and type(selector) == str:
selector_labels = selector.spli... | 9,177 |
def is_batch_enabled(release_id):
"""
Check whether batching is enabled for a release.
"""
details = get_release_details_by_id(release_id)
return details['data']['attributes']['enable_batching'] | 9,178 |
def create(tiles):
"""Handler."""
with futures.ThreadPoolExecutor(max_workers=8) as executor:
responses = executor.map(worker, tiles)
with contextlib.ExitStack() as stack:
sources = [
stack.enter_context(rasterio.open(tile)) for tile in responses if tile
]
dest, ... | 9,179 |
def write_rxn_rates(path, lang, specs, reacs, fwd_rxn_mapping):
"""Write reaction rate subroutine.
Includes conditionals for reversible reactions.
Parameters
----------
path : str
Path to build directory for file.
lang : {'c', 'cuda', 'fortran', 'matlab'}
Programming language.
... | 9,180 |
def executeMouseEvent(flags, x, y, data=0):
"""
Mouse events generated with this rapper for L{winUser.mouse_event}
will be ignored by NVDA.
Consult https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-mouse_event
for detailed parameter documentation.
@param flags: Controls various aspects... | 9,181 |
def _rfftn_empty_aligned(shape, axes, dtype, order='C', n=None):
"""Patched version of :func:`sporco.fft.rfftn_empty_aligned`.
"""
ashp = list(shape)
raxis = axes[-1]
ashp[raxis] = ashp[raxis] // 2 + 1
cdtype = _complex_dtype(dtype)
return cp.empty(ashp, cdtype, order) | 9,182 |
def createErrLog(contents, path="."):
"""Writes an errors.log file with the formatting characters removed.
Args:
contents (str): The stuff to write to the log file.
path (str): Path to write errors.log (by default CWD).
Returns:
Nothing.
"""
fd = open(path + "/errors.log",... | 9,183 |
def get_test_config():
"""
Returns a basic FedexConfig to test with.
"""
# Test server (Enter your credentials here)
return FedexConfig(key='xxxxxxxxxxxxxxxxx',
password='xxxxxxxxxxxxxxxxxxxxxxxxx',
account_number='xxxxxxxxx',
mete... | 9,184 |
def write_data(movies, user, data_format='json'):
"""
"""
assert movies, 'no data to write'
date = datetime.now().strftime('%Y%m%d')
movies_clean = itertools.chain.from_iterable((json.loads(el) for el in movies))
movies_clean = tuple(movies_clean)
if data_format == 'all':
file_format... | 9,185 |
def download_file_insecure(url, target, cookies=None):
"""
Use Python to download the file, even though it cannot authenticate the
connection.
"""
if cookies:
raise NotImplementedError
src = dst = None
try:
src = urlopen(url)
# Read/write all in one block, so we don't... | 9,186 |
def get_genotypes(
single_end: list,
paired_end: list,
metadata: str,
bam_dir: str,
intermediate_dir: str,
reference_genome_path: str,
mapping_quality: int,
blacklist_path: str,
snps_path: str,
processes: int,
memory: int,
skip_preprocessing: bool = False,
write_bam: ... | 9,187 |
def async_handle_google_actions(hass, cloud, payload):
"""Handle an incoming IoT message for Google Actions."""
result = yield from ga.async_handle_message(
hass, cloud.gactions_config, payload)
return result | 9,188 |
def get_picture_landmarks(filepath, predictor, logs=True):
"""
Do the doc!
"""
if logs:
print("Processing file: {}".format(filepath))
frame = cv2.imread(filepath)
lm = FLandmarks()
lm.extract_points(frame, predictor)
return lm
if logs:
print('\n') | 9,189 |
def query_master(h5in, query, idfile='sami_query.lis',
verbose=True, returnID=True, overwrite=True):
""" Read a SAMI master table and perform a query """
"""
The query should be passed either as a string argument or as an ascii file
containing such a string. Adding '@list' functional... | 9,190 |
def conflict(next_x: int, s: tuple) -> bool:
"""Return a boolean that defines the conflict condition of the next queen's position"""
next_i = len(s)
for i in range(next_i):
if abs(s[i] - next_x) in (0, next_i - i):
return True
else:
return False | 9,191 |
async def main_page():
"""Main page. Just for example."""
return APIResponse(message="ok") | 9,192 |
def split_to_sublists(initial_list:list, n:int, strict:bool=True) -> List[list]:
"""Takes a list and splits it into sublists of size n
Parameters
----------
initial_list : list
The initial list to split into sublists
n : int
The size of each sublist
strict: bool
Whethe... | 9,193 |
def get_matched_files(dirPath=".", regex=None):
"""Get the abspath of the files whose name matches a regex
Only files will be returned, and directories are excluded.
Args:
dirPath (str): the directory to search
regex (regex): the regular expression to match the filename
Returns:
... | 9,194 |
def get_sha1(req_path: Path) -> str:
""" For larger files sha1 algorithm is significantly faster than sha256 """
return get_hash(req_path, sha1) | 9,195 |
def upload_attachment(page_id, file, comment, confluence_api_url, username, password, raw = None):
"""
Upload an attachement
:param page_id: confluence page id
:param file: attachment file
:param comment: attachment comment
:return: boolean
"""
content_type = mimetypes.guess_type(file)... | 9,196 |
def test_run_and_track_job_failure(mocked_get_job_pods):
"""
Tests that a Failure phase in a pod triggers an exception in run_and_track_job
"""
client = MagicMock()
labels = {"l1": "label1"}
pod = pod_spec_from_dict("name_of_pod", dummy_pod_spec, labels=labels)
job = job_definition("my_job",... | 9,197 |
def _make_note(nl_transcript: str, tl_audio_file: str) -> Note:
"""
Creates an Anki note from a native langauge transcript and a target language audio file.
"""
return Note(model=_MODEL, fields=[f"[sound:{tl_audio_file}]", nl_transcript]) | 9,198 |
def bed2beddb_status(connection, **kwargs):
"""Searches for small bed files uploaded by user in certain types
Keyword arguments:
lab_title -- limit search with a lab i.e. Bing+Ren, UCSD
start_date -- limit search to files generated since a date formatted YYYY-MM-DD
run_time -- assume runs beyond run... | 9,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.