content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def beginsField(line):
"""
Does the given (stripped) line begin an epytext or ReST field?
"""
if line.startswith("@"):
return True
sphinxwords = """
param params return type rtype summary var ivar cvar raises raise except
exception
""".split()
for word in sphinxwords:
... | 5500fe3a165ac743f9a371fb120c7119e23eb54c | 690,595 |
def is_pair(part):
"""
>>> is_pair([4])
False
>>> is_pair([4, 4])
True
>>> is_pair([6, 9])
False
"""
if len(part) != 2:
return False
return part[0] == part[1] | d8bfbc8713250cb6d2c56cf2fa6e4b83c97619e0 | 690,596 |
import ast
def extract_attribute(module_name, attribute_name):
"""Extract metatdata property from a module"""
with open('%s/__init__.py' % module_name) as input_file:
for line in input_file:
if line.startswith(attribute_name):
return ast.literal_eval(line.split('=')[1].stri... | 0d766ff44d4df1cc867c54e210ada3cdf3882293 | 690,597 |
from threading import local
def make_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value."""
class TLSProperty(object):
def __init__(self):
self.local = local()
def __get__(self, instance, cls):
if not instance:
... | b923a72a63908affc637e31208714100b0093ff2 | 690,598 |
import math
def distance(point):
"""
What comes in: An rg.Point.
What goes out: The distance that the rg.Point is from (0, 0).
Side effects: None.
Example:
If the argument is rg.Point(3, 4) this function returns 5.
"""
# This code has an error, on purpose. Do NOT fix it.
x... | 7f3c98fc9ac7a15a78908f27ecea822259cc922b | 690,599 |
def dread(infile, cols):
"""
reads in specimen, tr, dec, inc int into data[]. position of
tr, dec, inc, int determined by cols[]
"""
data = []
f = open(infile, "r")
for line in f.readlines():
tmp = line.split()
rec = (tmp[0], float(tmp[cols[0]]), float(tmp[cols[1]]), float... | 5912f7f0873cfa2c11c66f588dcd10cfc21427fb | 690,600 |
def _transform_session_persistence(persistence):
"""Transforms session persistence object
:param persistence: the session persistence object
:returns: dictionary of transformed session persistence values
"""
return {
'type': persistence.type,
'cookie_name': persistence.cookie_name
... | b703cf02099c42df24cf110e3a96693adabca5d7 | 690,601 |
def backslashedp(c):
"""
BACKSLASHEDP char
BACKSLASHED? char
"""
## outputs TRUE if the input character was originally entered into
## Logo with a backslash (\) before it or within vertical bars (|)
## to prevent its usual special syntactic meaning, FALSE
## otherwise. (Outputs TRUE onl... | bfb59c9165046cc1f5d46e815c29b5a68bada246 | 690,602 |
def default_PSO_params(params):
"""
This is to set the default PSO parameters. Note by default constriction will be applied over inertia weighting.
To prevent this, specify the wdamp parameter that isn't 1.
Will display info by default
Early stopping is disabled by default
"""
if 'maxit' n... | 032b706b67c35a9c612dbf8da464fa39c89dfd08 | 690,603 |
import logging
def checkAndUpdateAlerts(dbManager, camera, timestamp, driveFileIDs):
"""Check if alert has been recently sent out for given camera
Args:
dbManager (DbManager):
camera (str): camera name
timestamp (int):
driveFileIDs (list): List of Google drive IDs for the uplo... | 3f9549fdec6be4167ab9c1ad1398b3168fb7d138 | 690,604 |
def byte_notation(size: int, acc=2, ntn=0):
"""Decimal Notation: take an integer, converts it to a string with the
requested decimal accuracy, and appends either single (default), double,
or full word character notation.
- Args:
- size (int): the size to convert
- acc (int, optional): n... | 614bdfd883f0d875abe22e05186d2073380497b3 | 690,605 |
import copy
def _DeepCopySomeKeys(in_dict, keys):
"""Performs a partial deep-copy on |in_dict|, only copying the keys in |keys|.
Arguments:
in_dict: The dictionary to copy.
keys: The keys to be copied. If a key is in this list and doesn't exist in
|in_dict| this is not an error.
Returns:
Th... | 2d759603ad7cf1ada5741333be138f57957677f6 | 690,606 |
def is_seq_list(list_or_dict):
"""Checks to "seq" key is list or dictionary. If one seq is in the prefix-list, seq is a dictionary, if multiple seq,
seq will be list of dictionaries. Convert to list if dictionary"""
if isinstance(list_or_dict, list):
make_list = list_or_dict
else:
make_... | eb4ad947e2df2f8610002f02ddaf5d39d3b2329c | 690,607 |
import re
def str_to_unicode_emoji(s):
"""
Converts 'U+FE0E' to u'\U0000FE0E'
"""
return re.sub(r'U\+([0-9a-fA-F]+)', lambda m: chr(int(m.group(1), 16)), s).replace(' ', '') | f8a862374d1a77e73b4ee61d3dabefe3206d43f1 | 690,609 |
def prandtl(cp=None, mu=None, k=None, nu=None, alpha=None):
"""
Calculate the dimensionless Prandtl number for a fluid or gas.
.. math:: Pr = \\frac{c_p \\mu}{k} = \\frac{\\nu}{\\alpha}
Parameters
----------
cp : float
Specific heat [J/(kg⋅K)]
mu : float
Dynamic viscosity [... | 62a9ce6b458373d93c9cb4df4ccb705968e4a8b6 | 690,610 |
def sentence_selection(sentences):
"""
select sentences that are not only space and have more than two tokens
"""
return [
sent.strip()
for sent in sentences
if (sent or not sent.isspace()) and len(sent.split()) > 2
] | 0e6ec6082c39a2e2728b5813ecd463b7f2731b65 | 690,611 |
def check_consistency(header1,
header2):
"""
Return true if all critical fields of *header1* equal those of
*header2*.
"""
return (header1.Station_Name == header2.Station_Name and
header1.IAGA_CODE == header2.IAGA_CODE and
header1.Geodetic_Latitude == he... | 7166f8acc10a5401364fc987a6b1b5b1e381a793 | 690,612 |
def is_feature_component_start(line):
"""Checks if a line starts with '/', ignoring whitespace."""
return line.lstrip().startswith("/") | f9ce6e88987f86e0b2116252e0aaa9fd449de567 | 690,613 |
def header(img, author, report_date, report_time, report_tz, title) -> str:
"""Creates reports header
Parameters
----------
img : str
Image for customizable report
author : str
Name of author responsible by report
report_date : str
Date when report is run
report_time... | 484176e93ff7dcfc70e3c2adc54874a3a650d57c | 690,615 |
import re
def text_split(text):
""" Split a string of text.
"""
text_list = re.split('; |, | |\n+',text)
return [word for word in text_list if word] | 3917ffc2a0ea896b668d7db7e3e0fe72a768959c | 690,616 |
import copy
def flattened(header):
"""
This function ...
:param header:
:return:
"""
flat_header = copy.deepcopy(header)
flat_header["NAXIS"] = 2
if "NAXIS3" in flat_header: del flat_header["NAXIS3"]
for key in flat_header:
if "PLANE" in key: del flat_header[key]
ret... | 82eceaf1557b91534c9e8286019b95fac294333f | 690,617 |
def render_terms_text():
"""
Inclusion tag for terms of service.
Context::
Template::
terms_text.html
"""
return {} | 569018b2523c448f1c1948e319ff00f1acc9ebb8 | 690,618 |
import requests
def handle_response(r, http_method, custom_err):
"""
Handles the HTTP response and returns the JSON
Parameters
----------
r: requests module's response
http_method: string
"GET", "POST", "PUT", etc.
custom_err: string
the custom error message if any
... | e22799a1e841263f74dc22adda76d1897f7fe725 | 690,619 |
from typing import OrderedDict
def _Net_blobs(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
blobs indexed by name
"""
return OrderedDict([(bl.name, bl) for bl in self._blobs]) | 6c68e91a10fb9eda6c0be9ef03ffdd08823131d8 | 690,620 |
def is_cg_developed(properties):
"""Check if a colorgroup is fully developed."""
# check validity of colorgroup
assert len(set([c.color for c in properties])) == 1
return all([c.has_hotel for c in properties]) | 9ef92a7695b9deb73d2fdd78dc13df44b70599a1 | 690,622 |
def _matrix_to_vector(X):
"""
Returns a vector from flattening a matrix.
"""
u = X.reshape((1, -1)).ravel()
return u | 500290449bc0bac48b6ca6b7f59bf2f0d39bd216 | 690,623 |
def _prepare_agent_cmd(
ip_address: str,
machine_id: str,
cluster: str,
qnames: str,
workers_n=1,
):
"""
It will run nb agent command.
Name is not provided, so the agent will choose their name.
"""
cmd = f"nb agent -i {ip_address} -C {cluster} -q {qnames} -w {workers_n} -m {mach... | 17b2270ed850716e3f8cb74113a431c353f9163a | 690,624 |
def pad_guid_bytes(raw_bytes: bytes) -> bytes:
"""Pads a sequence of raw bytes to make them the required size of a UUID.
Note that if you're using an int as your source for instantiating a UUID,
you should not use this function. Just use UUID(your_int_here).
"""
if not (0 < len(raw_bytes) <= 16):
... | b1cf8f50a041ac63be1c208388b904f774e437f3 | 690,626 |
def file_info_equal(file_info_1, file_info_2):
"""Return true if the two file-infos indicate the file hasn't changed."""
# Negative matches are never equal to each other: a file not
# existing is not equal to another file not existing.
if (None, None, None) in (file_info_1, file_info_2):
return ... | 0cc17448dba034d65521c86a0f6d7c70b98cf02c | 690,627 |
import re
def sort_strings_by_regex_list(sl,rl):
"""Example:
sl = ["aaa.0.1.shared","aaa.0.01.shared","aaa.0.03.shared"]
rl = [r"0.01",r"0.03",r"0.1"]
print sort_strings_by_regex_list(sl,[re.escape(r) for r in rl])
>>> ["aaa.0.01.shared","aaa.0.03.shared","aaa.0.1.shared"]
"""
def rx_... | d40de7144012fac4c3d73286ddd4eb8b7f40a5b6 | 690,628 |
def es_get_class_defs(cls_def, cls_name):
"""
Reads through the class defs and gets the related es class
defintions
Args:
-----
class_defs: RdfDataset of class definitions
"""
rtn_dict = {key: value for key, value in cls_def.items() \
if key.startswith("kds_es")}
... | 994813b878bef8c18862f94dd59631c629c14be5 | 690,629 |
def status_new_data_body(new_title: list, new_video: list) -> str:
"""Get the text body for updating status line data
Wrapped for short-circuit if no new data, and due to the complexity of
latter operations (a bit of a jumble).
@param new_title List of new (changed) video titles
@param new_video L... | ce3a307dba2180fb1d7cf1460f3cf7a1a6c9c017 | 690,630 |
import random
def generateIndices(n_blocks, N, D):
"""
generates indices for block matrix computation.
Checked.
Input:
n_blocks: number of blocks to use.
N: number of samples.
D: number of genes.
Output:
y_indices_to_use[i][j] is the indices of block j in sample i.
"""
y_indices_to_use = []
idxs = list(ra... | 8850db07af5811846cd80f6225b2a56b71284dc2 | 690,631 |
def get_target_name(prefix='', rconn=None):
"""Return wanted Telescope named target.
On failure, or no name returns empty string"""
if rconn is None:
return ''
try:
target_name = rconn.get(prefix+'target_name').decode('utf-8')
except:
return ''
return target_name | 6da7399e69f53ed37c3db29e7274eec29f2be83d | 690,632 |
import sys
import os
import fnmatch
def _get_standard_modules():
""" Return list of module names in the Python standard library. """
# Find library directories.
if sys.platform == 'win32': #pragma no cover
lib_dir = os.path.join(sys.prefix, 'Lib')
obj_dir = os.path.join(sys.prefix, 'DLLs'... | 968ca6360c57af6a584a4c7791eb06f53e18473d | 690,633 |
import argparse
def parseArgs():
"""
Well, parse the arguments passed in the command line :)
"""
parser = argparse.ArgumentParser(description="Does a bunch of draining checks")
parser.add_argument('-t', '--twiki', action='store_true', default=False,
help='Use it to get an o... | e245fdeee29da2c254515180c7b28c074edd9db8 | 690,634 |
import re
def quotemeta(text):
"""Quote letters with special meanings in pychart so that <text> will display
as-is when passed to canvas.show().
>>> font.quotemeta("foo/bar")
"foo//bar"
"""
text = re.sub(r'/', '//', text)
text = re.sub(r'\\{', '/{', text)
text = re.sub(r'\\}', '/}', text)
re... | 706a5b9ed9ee83b1330b7e8052372036ad6c651c | 690,635 |
def write_doc(file_name):
"""Write a converted document.
Parameters
----------
file_name : str
The converted document.
Returns
-------
out_doc : file
A file object that allows writing of document.
"""
return open(file_name, "wb") | 6f5ca1ed612bee3135adb262ee2ffd2511a8b4b0 | 690,636 |
def compute_delays(SOA):
""" calculate the delay time for color/word input
positive SOA => color is presented earlier, v.v.
Parameters
----------
SOA : int
stimulus onset asynchrony == color onset - word onset
Returns
-------
int,int
the delay time for color/word input,... | 3c048633501e75f0a46dc99d225819c9d0750a74 | 690,637 |
def selection_criteria_harris(l1, l2, k = 0.04):
"""
Si se quiere obtener los puntos Harris de una imagen utilizando el operador
Harris, es necesario seguir un criterio. En este caso se hará uso de los
autovalores de M (l1, l2) y de la constante k.
El criterio es: l1*l2 - k * (l1+l2)^2
"""
... | 2a4d4f4c08f7ec572c2ab7d6dac63fa3bdc99b47 | 690,638 |
import binascii
import struct
def fw_int_to_hex(*args):
"""Pack integers into hex string.
Use little-endian and unsigned int format.
"""
return binascii.hexlify(
struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8') | 059e328e725a0fc5b9630d71b3162f1ddfa7c0a4 | 690,639 |
import torch
def VDraw(x):
""" Generate a Gaussian distribution with the given mean(128-d) and
std(128-d).
"""
return torch.distributions.Normal(x[:, :128], x[:, 128:]).sample() | e85f25795a28acd15dc46a4aadd54e631a26bd7e | 690,640 |
import glob
import os
def get_cache_file_list(path):
"""
This function counts the number of json files under a given directory.
To save an system call the path is given as the argument
If the passed path is not a valid directory then the result is undefined
:return: int, as the number of... | 621851317f371a92d67d80e6a710bc029461d7c5 | 690,641 |
import math
def dist(p,q):
"""
Helper function to compute the "distance" of two
2D points.
"""
return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2) | d15da20e31627aef4fb589fcbc6bae25adf7c32d | 690,644 |
from typing import Dict
def sra_id_to_app_input(sra_id: str) -> Dict:
"""Generate input from app for sra_fastq_importer
Set split files to false so we no merging is needed
Args:
sra_id:
Returns:
dictionary containing
"""
return {"accession": sra_id, "split_files": False} | bf1ca62df98932a05cb6fce476a361273f86c35e | 690,645 |
def div(num1, num2):
"""
Divide two numbers
"""
return num1 / num2 | 2d39f276196d913f6393335e5fbbdf5998a37a89 | 690,646 |
from datetime import datetime
def to_excel_ts(ts):
"""
Converts a datetime timestamp into Excel format date time
"""
EPOCH = datetime(1899, 12, 30)
delta = ts - EPOCH
return float(delta.days) + (float(delta.seconds) / 86400) | 7fa466aafa75254d468d4969c4c4c666abc09aaa | 690,647 |
def get_content_id(item):
"""Extract content id or uri."""
if item.item_class == "object.item.audioItem.musicTrack":
return item.get_uri()
return item.item_id | d4041481995ecea12aaaf6e0d60d82e4f31e8e1c | 690,648 |
import re
def get_declarations(code, qualifier=""):
""" Extract declarations of type:
qualifier type name[,name,...];
"""
if not len(code):
return []
variables = []
if isinstance(qualifier, list):
qualifier = "(" + "|".join([str(q) for q in qualifier]) + ")"
if qua... | c79cddaad4ba7d21c2ddf6061ddeae8b43688a93 | 690,649 |
def getkey(dict_, key, default=None):
"""Return dict_.get(key, default)
"""
return dict_.get(key, default) | fd874b56862e5d6094ea26b6dc30bc34c22ea496 | 690,650 |
import sys
import itertools
import gzip
def split_fastq_file_pbat(num_chunks, input_files, output_prefix):
"""
This function mimics the unix split utility.
"""
def reverse_complement(dna):
complement = {"A":"T","C":"G","G":"C","T":"A","N":"N"}
return("".join([complement[base] for base... | f46740b6e7fe4c821deeffb1d9cbaa615555121b | 690,651 |
from datetime import datetime
def _to_collected_format(date):
"""Convert input date format from '%Y%-m-%d' to '%Y%m%d'"""
return str(datetime.strptime(date, "%Y-%m-%d").strftime("%Y%m%d")) | ec9dd77f6ff58d26e3059b595f32c78ff0996c36 | 690,652 |
def _unpersist_broadcasted_np_array(broadcast):
"""
Unpersist a single pyspark.Broadcast variable or a list of them.
:param broadcast: A single pyspark.Broadcast or list of them.
"""
if isinstance(broadcast, list):
[b.unpersist() for b in broadcast]
else:
broadcast.unpersist()
... | dbd43e27db1bad87a8b86f1e9e24a40ad4bfa558 | 690,653 |
from typing import Callable
from typing import Any
def is_callback(func: Callable[..., Any]) -> bool:
"""Check if function is safe to be called in the event loop."""
return getattr(func, "_mass_callback", False) is True | 0620699de8e4df5faeff52d524d327b4f4f4f6b8 | 690,654 |
def _to_str(s):
"""Downgrades a unicode instance to str. Pass str through as-is."""
if isinstance(s, str):
return s
# This is technically incorrect, especially on Windows. In theory
# sys.getfilesystemencoding() should be used to use the right 'ANSI code
# page' on Windows, but that causes other problems,... | 6df44a8c56bdadf767e11d5d784c83fe0bd842cc | 690,655 |
def Intersect(list1,list2):
"""
This function takes two lists and returns a list of items common to both
lists.
"""
ReturnList = []
for x in list1:
if x in list2: ReturnList.append(x)
return ReturnList | f190ae7723b7cccfbd144b6df500ce8cf8e2ead2 | 690,657 |
import math
def euler_problem_9(n=1000):
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
as... | a4db0c09619d977027a45972abf092ec28062e7e | 690,658 |
import itertools
def _get_inputs(values):
""" Generate the list of all possible ordered subsets of values. """
power_set = set(
[
tuple(set(prod))
for prod in itertools.product(values, repeat=len(values))
]
)
power_perms = [itertools.permutations(comb) for comb... | 5150d08954f9867a5d7c1fca3bb4384f4e89ff59 | 690,659 |
import re
def next_look_say(current_value):
"""
Given a numeric string, find it's 'look-and-say' value to determine the
next value in the sequence.
"""
# Split into groups of same consecutive digits
r = '(1+|2+|3+|4+|5+|6+|7+|8+|9+|0+)'
matches = re.findall(r, current_value)
return ''.... | 338ad3c563799bc163044441a608da1491c34a0a | 690,660 |
def set_union(sets):
"""Non variadic version of set.union.
"""
return set.union(*sets) | eda2b95f985e9f9fc9efa193de34008e376b1173 | 690,661 |
def solve_nu(H):
"""
求解 μ
:param H: 一系列H
:return:
"""
N = [H[i] / (H[i] + H[i + 1]) for i in range(len(H) - 1)]
for i in range(len(N)):
print('μ{} = {}'.format(i + 1, N[i]))
return N | 8b2b25cfce53c57cf5a12df024800973c3306d95 | 690,662 |
def set_tags(config, tags):
""" set gloabal tags setting in config """
config['tags'] = tags
return True | c0c946337d6f1a9511db694ed9192e192c4658ec | 690,663 |
import warnings
def _validate_repo_id_deprecation(repo_id, name, organization):
"""Returns (name, organization) from the input."""
if not (repo_id or name):
raise ValueError(
"No name provided. Please pass `repo_id` with a valid repository name."
)
if repo_id and (name or orga... | 89653f85b4a29a02e32ce9f3b7c3a33d6bc75ff6 | 690,664 |
import importlib
def resolve_python_path(path):
"""
Turns a python path like module.name.here:ClassName.SubClass into an object
"""
# Get the module
module_path, local_path = path.split(':', 1)
thing = importlib.import_module(module_path)
# Traverse the local sections
local_bits = loca... | 768fa4c5b260fe1bf66dd20a8c96f36e4fb0fefe | 690,665 |
from typing import Dict
def get_reversed_enumerated_from_dict(enumerated_dict: Dict[int, int]) -> Dict[int, int]:
"""
Get inverse of enumerated dictionary.
:param enumerated_dict:
:return:
"""
reversed_map = {}
for index_sorted, true_index in enumerated_dict.items():
reversed_map[t... | a0fbed023fae12e3d92e1aa5f6fa2327e05a44d0 | 690,666 |
def maxThreats(a):
""" left_threads stores threads in left-top-to-right-bottom direction
right_threads stores threads in right-top-to-left-bottom direction"""
left_threads, right_threads = dict(), dict()
max_threads, threads = 0, [0] * len(a)
for row, col in enumerate(a):
col -= 1 # def... | c2e91ccfd59f4b49716487e637d52a916ca02123 | 690,667 |
def subsitute_env_vars( line, env ):
""" Substitutes environment variables in the command line.
E.g. dir %EPOCROOT% -> dir T:\
The command line does not seem to do this automatically when launched
via subprocess.
"""
for key, value in env.items():
line = line.replace( "%%%s%%" ... | 6dc8725d6ddbdcf0a7f59cfe18839210975fdd09 | 690,668 |
import torch
def validation(model, validationloader, criterion, device):
"""
During training, we will look at the performance of our Network with regards to the Validation Set.
Inputs:
- model: The model that is currently being trained.
- validationloader: A dataloader object represen... | f54ee6b4fdcd3144127d28eeedbb5b27ee8ba161 | 690,669 |
import argparse
def generate_parser():
"""Generate an argument parser."""
description = "%(prog)s -- Find a quality score for a HiC dataset"
parser = argparse.ArgumentParser(description=description)
parser.add_argument(dest="input1", type=str, action='store', help="First quasar file name")
parser.... | 2731d15a4b9589f784b7734d3f74850c6cc1b7a0 | 690,670 |
def cut_below() -> str:
"""Return a "cut after this line" line."""
return "\n.--Cut after this line --.\n" | 54e8098b1c27f7c7282049e21fe965f3305cdae0 | 690,671 |
import requests
import json
def get_poc_info(poc):
"""Retrieves ARIN point of contact information.
Args:
poc: The URL for the ARIN PoC information.
Returns:
A list containing point of contact information. The list contains the
name of the contact, the ARIN company name, the addre... | 7ac8a546e18e15293d1c959ee0647acde01cc77c | 690,672 |
def effect_on_response(codes, effect, result):
"""
Returns the specified effect if the resulting HTTP response code is
in ``codes``.
Useful for invalidating auth caches if an HTTP response is an auth-related
error.
:param tuple codes: integer HTTP codes
:param effect: An Effect to perform ... | 329f81c0880768010d19cf5905e34b524b5825b9 | 690,673 |
def format_markdown(content, params):
"""Format content with config parameters.
Arguments:
content {str} -- Unformatted content
Returns:
{str} -- Formatted content
"""
try:
fmt = content.format(**params)
except KeyError:
fmt = content
return fmt | d009a3217ee1e5efdf1ee48d44b0456080595e93 | 690,674 |
def snake_to_camel(s: str):
"""
Convert a snake_cased_name to a camelCasedName
:param s: the snake_cased_name
:return: camelCasedName
"""
components = s.split("_")
return components[0] + "".join(y.title() for y in components[1:]) | 10ec9951a9b63835a8161a8aa8666f1873348a6e | 690,675 |
import subprocess
import time
def wait_for_compose(name, architecture=None, labcontroller=None, timeout=7200, wait_step=600):
"""
:param name: Compose ID
:type name: str
:param architecture: Architecture like x86_64 or aarch64. If not provided, any available architecture is sufficient.
:type archi... | 95cb9c06fbbc5d5ad74be4328202f1b97176864b | 690,676 |
from typing import AbstractSet
def add_to_set(set_: AbstractSet[str] | None, new: str) -> set[str]:
"""Add an entry to a set (or create it if doesn't exist).
Args:
set_: The (optional) set to add an element to.
new: The string to add to the set.
"""
return set(set_).union([new]) if se... | ec1f6e3ca51bc11ff0996a1aab00e84e2c23228e | 690,677 |
def get_clean_bool_option(a_string):
""" This function removes the 'YES\n' or 'NO\n' from the end of the
option so that it can be set differently later on.
This function returns a revised option almost ready for CLI usage.
"""
option, _ = (a_string).split('=')
option = "-D{}".format(option)
... | bbfb240659c1c7804c5777a29092cdac67eb3cd5 | 690,678 |
def weight_l1_loss(pred_loc, label_loc, loss_weight):
"""
:param pred_loc: [b, 4k, h, w]
:param label_loc: [b, 4k, h, w]
:param loss_weight: [b, k, h, w]
:return: loc loss value
"""
b, _, sh, sw = pred_loc.size()
pred_loc = pred_loc.view(b, 4, -1, sh, sw)
diff = (pred_loc - label_lo... | 20736d8bf69f42e8bc41fc442e7bb79d4864ee13 | 690,679 |
def read_phase_results(stable_phases,calculation_results) :
"""
read_phase_results
# input
compostable_phasesnents: list of strings,
calculation_results: TC_python calcualgtion result object
# output
volume_fractions_temp: list of floats, volume fractions of ... | bd456ffe616521d7a4e2ebd4f9878243423840a7 | 690,680 |
import subprocess
def call(cmd, **kwargs):
"""Calls the given shell command. Output will be displayed. Returns the
status code."""
kwargs['shell'] = True
return subprocess.call(cmd, **kwargs) | b1109402b2a7e9b274a909d824b90f0928a16ca2 | 690,681 |
def _transform_record (record):
"""Transform a record from a list of fields to a dict.
Doesn't handle nested records.
"""
if isinstance(record, list):
# value can only be missing if it was an empty sequence of tokens,
# which should have become a list, which we should transform into a dict
... | fbdbb2e15e6e5781ccd93588bdb50f4df936155b | 690,682 |
import os
def get_path(name):
"""helper"""
basedir = os.path.dirname(__file__)
return "%s/../data/wepp/%s" % (basedir, name) | 50d3e69c6f75c51a8d14ce47037e9c25ecd37c8c | 690,683 |
def make_orderer():
"""
Create helper functions for sorting and comparing objects
"""
order = {}
def orderer(obj):
order[obj.__name__] = len(order)
return obj
def comparator(obj_a, obj_b):
return [1, -1][order[obj_a] < order[obj_b]]
return orderer, comparator | 7933b4f8d5d733e141c03bff4d6c45318e73e118 | 690,684 |
def extrapolDiff(f, x, h):
"""return Ableitung der Funktion f an Stelle x
nach '1/3h *( 8*(f(x + h/4)-f(x - h/4)) - (f(x + h/2) - f(x - h/2)))'
"""
return 1/(3*h) * (8*(f(x+h/4) - f(x-h/4)) - (f(x+h/2) - f(x-h/2))) | f3e9c1cc58a7aa8d3f9767bfd34ff3938b8a2edc | 690,685 |
import torch
def invert_convert_to_box_list(x: torch.Tensor, original_width: int, original_height: int) -> torch.Tensor:
""" takes input of shape: (*, width x height, ch)
and return shape: (*, ch, width, height)
"""
assert x.shape[-2] == original_width * original_height
return x.transpose(dim0... | 4f98f955bb6373bf358108fdf237aa109afae436 | 690,686 |
def merge_geometry(catchment, splitCatchment, upstreamBasin):
"""Attempt at merging geometries"""
print('merging geometries...')
d = 0.00045
# d2 = 0.00015 # distance
cf = 1.3 # cofactor
splitCatchment = splitCatchment.simplify(d)
diff = catchment.difference(splitCatchment).buffer(-d).bu... | d57b1baec73a2fe24b52059f2dc231bebf0decb7 | 690,687 |
def load_ndarray(arr):
""" Load a numpy array """
# Nothing to be done!
return arr | 03db490e1541e8f4e6d6d26d9825d37bca34dd92 | 690,688 |
import re
def convert_crfpp_output(crfpp_output):
"""
Convert CRF++ command line output.
This function takes the command line output of CRF++ and splits it into
one [gold_label, pred_label] list per word per sentence.
Parameters
----------
crfpp_output : str
Command line output o... | dbb23736516755706a3910fea86a2cfdf76771e0 | 690,689 |
def create_word_inds_dicts(words_counted,
specials=None,
min_occurences=0):
""" creates lookup dicts from word to index and back.
returns the lookup dicts and an array of words that were not used,
due to rare occurence.
"""
missing_words ... | 769d16257b4f979444a347079392ca632b5f05c1 | 690,691 |
import math
def normalize_values_in_dict(dictionary, factor=None, inplace=True):
""" Normalize the values in a dictionary using the given factor.
For each element in the dictionary, applies ``value/factor``.
Parameters
----------
dictionary: dict
Dictionary to normalize.
factor: float... | 109d30d3661cae45c6a4983bd7cc66ff0dcfbdf3 | 690,692 |
def get_lines(filepath):
"""
"""
lines = []
with open(filepath, 'r') as f:
for i, l in enumerate(f.readlines()):
l = l.strip()
lines.append(l)
return lines | ffbe3d183fdfb6c29d2a4251abb4df849afe5dbe | 690,693 |
def getDezenas(resultado):
"""
Gera o texto das dezenas para ser falado com o resultado
:param resultado: dict
:return string
"""
concurso = str(resultado['numero'])
return 'O resultado da Loteria Federal no dia '+resultado['dataApuracao']+' foi: 1º Prêmio: '+resultado['listaDezenas'][0][4:]... | 243b226d0f63ae1e280c9f605c14df70805c9f09 | 690,694 |
def flatten_results(results, comparison_records, print_warning=False):
"""Flattens and extract a deep structure of results based on a list of
comparisons desired."""
# process the request comparisons into chunks
comparisons = [x.split('.') for x in comparison_records]
# store a nested tree structu... | b5250500b39a00e0feb124baf76fcbf2b0e3a66e | 690,695 |
import json
def load_times(filename="cvt_add_times.json"):
"""Loads the results from the given file."""
with open(filename, "r") as file:
data = json.load(file)
return data["n_bins"], data["brute_force_t"], data["kd_tree_t"] | 1fc27348ed2028a6ebdcb13b488d98614a28c83f | 690,696 |
def is_even_or_odd(number: int) -> str:
"""Number `odd` or `even`."""
return "even" if number % 2 == 0 else "odd" | 1c8bf9985b96e2fed44585f6a68eca5ede93c0bc | 690,697 |
def add_leading_zero(number: int, digit_num: int = 2) -> str:
"""add_leading_zero function
Args:
number (int): number that you want to add leading zero
digit_num (int): number of digits that you want fill up to. Defaults to 2.
Returns:
str: number that has the leading zero
Exa... | 8db9bbb762e33510de896c09917b0d832e81f7de | 690,698 |
def create_repr_string(o):
"""
Args:
o (object): any core object
Returns:
str: repr string based on internal attributes
"""
# Filter peripheral unimportant attribute names:
params = [
attr for attr in dir(o) if not attr.startswith('__') # Data-model dunder methods
... | e9740af38647347933ede49328d6dfaf139cb01a | 690,700 |
import re
def _find_streams(text):
"""Finds data streams in text, returns a list of strings containing
the stream contents"""
re_stream = re.compile(r"<< /Length \d+ >>\n(stream.*?endstream)", re.DOTALL)
streams = []
for m in re_stream.finditer(text):
streams.append(text[m.start(1):m.end(1... | 37f011276d4ca2eeeb03927910b2d494519cd17e | 690,701 |
import torch
def _create_1d_regression_dataset(n: int = 100, seed: int = 0) -> torch.Tensor:
"""Creates a simple 1-D dataset of a noisy linear function.
:param n: The number of datapoints to generate, defaults to 100
:param seed: Random number generator seed, defaults to 0
:return: A tensor that cont... | 1534c7a968dfb3663c1f4d953e3088225af54b5f | 690,702 |
def decrease_parameter_closer_to_value(old_value, target_value, coverage):
"""
Simple but commonly used calculation for interventions. Acts to decrement from the original or baseline value
closer to the target or intervention value according to the coverage of the intervention being implemented.
Args:
... | 4f22c90fae1c69801ff4c89c1ed34ca1362dc92f | 690,703 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.