content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_signal_extract_clip_longer_sowhat(audio_file, tmpdir):
"""Expects a soundfile greater than 3.0 seconds in duration"""
start_time = 1.0
exp_duration = float(claudio.sox.soxi(audio_file, 'D')) - start_time
assert exp_duration > 0.0
output_file = os.path.join(
str(tmpdir), "test_sign... | 4,800 |
def conv_block(data, name, channels,
kernel_size=(3, 3), strides=(1, 1), padding=(1, 1),
epsilon=1e-5):
"""Helper function to construct conv-bn-relu"""
# convolution + bn + relu
conv = sym.conv2d(data=data, channels=channels,
kernel_size=kernel_size, strid... | 4,801 |
def var2fa(stream, gzipped=False):
"""convert variant calling's .var file to fasta"""
for line in stream:
if gzipped: line = line.decode()
if line[0]!='V': continue
line = line.strip().split('\t')
_1, chrom, start, end, _2, _3, ref, alt, queryname, q_start, q_end, strand = line
... | 4,802 |
def utzappos_tensor_dset(img_size, observed, binarized, drop_infreq,
cache_fn, *dset_args, transform=None, **dset_kwargs):
"""
Convert folder dataset to tensor dataset.
"""
cache_fn = UTZapposIDImageFolder.get_cache_name(cache_fn, img_size, observed, binarized, drop_infreq)
... | 4,803 |
def test_rdn_scenario1(rambank, chip, register, char):
"""Test instruction RDn"""
from random import randint
chip_test = Processor()
chip_base = Processor()
value = randint(0, 15)
address = encode_command_register(chip, register, 0,
'DATA_RAM_STATUS_CHAR'... | 4,804 |
def compare_versions(aStr, bStr):
"""
Assumes Debian version format:
[epoch:]upstream_version[-debian_revision]
Returns:
-1 : a < b
0 : a == b
1 : a > b
"""
# Compare using the version class
return cmp(Version(aStr), Version(bStr)) | 4,805 |
def repdirstruc(src, dst, credentials):
"""Replicate directory structure onto GCS bucket.
SRC is path to a local directory. Directories within will be replicated.
DST is gs://[bucket] and optional path to replicate SRC into.
If --credentials or -c is not explicitly given, checks the
GOOGLE_APPLICA... | 4,806 |
def alpha_034(code, end_date=None, fq="pre"):
"""
公式:
MEAN(CLOSE,12)/CLOSE
Inputs:
code: 股票池
end_date: 查询日期
Outputs:
因子的值
"""
end_date = to_date_str(end_date)
func_name = sys._getframe().f_code.co_name
return JQDataClient.instance().get_alpha_191(**locals(... | 4,807 |
def create_mean_median_plot(data, filename):
"""Create a plot of the mean and median of the features
Args:
data: pandas.DataFrame
Description of the features. Result of running the
pandas.DataFrame.describe method on the features
filename: str
... | 4,808 |
def unscale_parameter(value: numbers.Number,
petab_scale: str) -> numbers.Number:
"""Bring parameter from scale to linear scale.
:param value:
Value to scale
:param petab_scale:
Target scale of ``value``
:return:
``value`` on linear scale
"""
if pe... | 4,809 |
def save_answers(article_title, system_answers):
""" Create a file at output folder with article's name with name system_answers.txt in this form:
ArticleTitle Question Answer AnswersComment
ie. Zebra question name question's answer answer's comment
:para... | 4,810 |
def perturb(sentence, bertmodel, num):
"""Generate a list of similar sentences by BERT
Arguments:
sentence: Sentence which needs to be perturbed
bertModel: MLM model being used (BERT here)
num: Number of perturbations required for a word in a sentence
"""
# Tokenize the sentence
tokens = tokenizer.tokenize(s... | 4,811 |
async def test_disallowed_duplicated_auth_provider_config(hass):
"""Test loading insecure example auth provider is disallowed."""
core_config = {
"latitude": 60,
"longitude": 50,
"elevation": 25,
"name": "Huis",
CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_IMPERIAL,
"time_z... | 4,812 |
def test_base_data_object():
"""Test the base data object."""
obj = MockDataObject({
"attr1": "value1",
"attr2": "value2",
})
assert obj.attr1 == "value1"
assert obj.data == {"attr1": "value1"}
with pytest.raises(AttributeError):
obj.attr2
with pytest.raises(Attribut... | 4,813 |
def discovery_dispatch(task: TaskRequest) -> TaskResponse:
"""Runs appropriate discovery function based on protocol
Args:
task (TaskRequest): namedtuple
Returns:
TaskResponse[str, dict[str, str|int|bool|list]]
"""
task = TaskRequest(*task)
proto = constant.Proto(task.... | 4,814 |
def get_free_times(busy_times, begin_date, end_date):
"""
Gets a list of free times calculated from a list of busy times.
:param busy_times: is the list of busy times in ascending order.
:param begin_date: is the start of the selected time interval.
:param end_date: is the end of the selected time i... | 4,815 |
def upstream_has_data(valid):
"""Does data exist upstream to even attempt a download"""
utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
# NCEP should have at least 24 hours of data
return (utcnow - datetime.timedelta(hours=24)) < valid | 4,816 |
def encode_array(x, base=2, **kwds):
"""Encode array of integer-symbols.
Parameters
----------
x : (N, k) array_like
Array of integer symbols.
base : int
Encoding base.
**kwds :
Keyword arguments passed to :py:func:`numpy.ravel`.
Returns
-------
int
... | 4,817 |
def str_for_model(model: Model, formatting: str = "plain", include_params: bool = True) -> str:
"""Make a human-readable string representation of Model, listing all random variables
and their distributions, optionally including parameter values."""
all_rv = itertools.chain(model.unobserved_RVs, model.observ... | 4,818 |
def get_device(
raw_data: dict, control_data: dict, request: Callable
) -> Optional[
Union[
HomeSeerDimmableDevice,
HomeSeerFanDevice,
HomeSeerLockableDevice,
HomeSeerStatusDevice,
HomeSeerSwitchableDevice,
HomeSeerCoverDevice,
HomeSeerSetPointDevice
]... | 4,819 |
def wait():
"""
Gets the New Block work unit to send to clients
"""
return _event.get() | 4,820 |
def process(msd_id: str, counter: AtomicCounter) -> Optional[dict]:
"""
Processes the given MSD id and increments the counter. The
method will find and return the artist.
:param msd_id: the MSD id to process
:param counter: the counter to increment
:return: the dictionary containing the MSD id and the arti... | 4,821 |
def choose_run(D, var2align, run):
"""Get input for the alignment.
Do it by indicating a run to align to.
Args:
D (pd.DataFrame): DataFrame containing columns 'id', 'run', and ...
var2align (str): Name of the column to align.
run (whatever): The run to align to.
Returns:
... | 4,822 |
def test_div():
"""division of complexes, 64x"""
for s in numbers:
for t in numbers:
s / t | 4,823 |
def keyring(homedir, monkeypatch, scope='module'):
"""Default keyring, using the test profile"""
monkeypatch.setattr(os.path, "expanduser", lambda d: homedir)
kr = S3Keyring(profile_name='test')
kr.configure(ask=False)
return kr | 4,824 |
def stack(tensor_list, axis=0):
"""
This function is the same as torch.stack but handles both
numpy.ndarray and torch.Tensor
:param tensor_list:
:param axis:
:return:
"""
if isinstance(tensor_list[0], th.Tensor):
return th.stack(tensor_list, axis)
else:
return np.stac... | 4,825 |
def generate_svg(input_file, input_hocr, options):
"""
Generates page SVG with embedded raster image and text overlay.
"""
output_file_path = get_result_file_path(
input_file_path=str(input_file),
output_dir=options.sidecar_dir,
output_ext=options.sidecar_format
)
base64... | 4,826 |
def alias(alias):
"""Select a single alias."""
return {'alias': alias} | 4,827 |
def model_creator(config):
"""Constructor function for the model(s) to be optimized.
You will also need to provide a custom training
function to specify the optimization procedure for multiple models.
Args:
config (dict): Configuration dictionary passed into ``PyTorchTrainer``.
Returns:
... | 4,828 |
def ensure_r_vector(x):
"""Ensures that the input is rendered as a vector in R.
It is way more complicated to define an array in R than in Python because an array
in R cannot end with an comma.
Examples
--------
>>> ensure_r_vector("string")
"c('string')"
>>> ensure_r_vector(1)
'c(... | 4,829 |
def get_games():
"""Actually retrieves the games and adds them to the datastore"""
stats = utils.retrieve_stats()
total_games = 0
games = Games()
all_games = games.get_all('us')
current_stack = []
for game in all_games:
if game.type == 'game':
name = game.name.encode('ascii', 'ignore')
store_url = creat... | 4,830 |
def open_and_prepare_avatar(image_bytes: Optional[bytes]) -> Optional[Image.Image]:
"""Opens the image as bytes if they exist, otherwise opens the 404 error image. then circular crops and resizes it"""
if image_bytes is not None:
try:
with Image.open(BytesIO(image_bytes)) as im:
... | 4,831 |
def _load_env(
file=".env",
):
"""Load environment variables from dotenv files
Uses https://github.com/theskumar/python-dotenv
Parameters
----------
file
Path to the dotenv file
"""
if not XSH.env:
return
from dotenv import dotenv_values
vals = dotenv_values(f... | 4,832 |
def test_find_file_present():
"""Test if existing datafile is found.
Using the bird-size dataset which is included for regression testing.
We copy the raw_data directory to retriever_root_dir
which is the current working directory.
This enables the data to be in the DATA_SEARCH_PATHS.
"""
t... | 4,833 |
async def handler(client, _path):
"""
Immediate function called when WebSocket payload received
:param client: client that sent payload
:type client: websockets.WebSocketCommonProtocol
:type _path: str
"""
try:
async for message in client:
try:
payload = ... | 4,834 |
def is_GammaH(x):
"""
Return True if x is a congruence subgroup of type GammaH.
EXAMPLES::
sage: from sage.modular.arithgroup.all import is_GammaH
sage: is_GammaH(GammaH(13, [2]))
True
sage: is_GammaH(Gamma0(6))
True
sage: is_GammaH(Gamma1(6))
True
... | 4,835 |
def plot_images_overlap(imgs, title, order_axes, meta_title=None, savefig=False, show_plot=True,
cmaps=None, alphas=None, **kwargs):
""" Plot one or more images with overlap. """
cmaps = cmaps or ['gray'] + ['Reds']*len(imgs)
alphas = alphas or [1.0]*len(imgs)
defaults = {'figsi... | 4,836 |
def _run_with_interpreter_if_needed(fuzzer_path, args, max_time):
"""Execute the fuzzer script with an interpreter, or invoke it directly."""
interpreter = shell.get_interpreter(fuzzer_path)
if interpreter:
executable = interpreter
args.insert(0, fuzzer_path)
else:
executable = fuzzer_path
runner... | 4,837 |
def remove_vol(im_in, index_vol_user, todo):
"""
Remove specific volumes from 4D data.
:param im_in: [str] input image.
:param index_vol: [int] list of indices corresponding to volumes to remove
:param todo: {keep, remove} what to do
:return: 4d volume
"""
# get data
data = im_in.dat... | 4,838 |
def cost_logistic(p, x, y):
"""
Sum of absolute deviations of obs and logistic function L/(1+exp(-k(x-x0)))
Parameters
----------
p : iterable of floats
parameters (`len(p)=3`)
`p[0]` L - Maximum of logistic function
`p[1]` k - Steepness of logistic function
... | 4,839 |
def estimate_dt(time_array):
"""Automatically estimate timestep in a time_array
Args:
time_array ([list]): List or dataframe with time entries
Returns:
dt ([datetime.timedelta]): Timestep in dt.timedelta format
"""
if len(time_array) < 2:
# Assume arbitrary valu... | 4,840 |
def gen_uuid() -> str:
"""
获取uuid
:return: uuid
"""
return uu.uuid4().hex | 4,841 |
def make_signature(arg_names, member=False):
"""Make Signature object from argument name iterable or str."""
kind = inspect.Parameter.POSITIONAL_OR_KEYWORD
if isinstance(arg_names, str):
arg_names = map(str.strip, arg_name_list.split(','))
if member and arg_names and arg_names[0] != 'self':... | 4,842 |
def copy_images(source_list: list[str], source_path: str, destination_path: str):
""" Copy the images in the source_list from the source_path to the destination_path
:param source_list: The list with images
:param source_path: The current location of the images
:param destination_path: The location wh... | 4,843 |
def set_trace_platform(*args):
"""
set_trace_platform(platform)
Set platform name of current trace.
@param platform (C++: const char *)
"""
return _ida_dbg.set_trace_platform(*args) | 4,844 |
def leapfrog2(init, tspan, a, beta, omega, h):
"""
Integrate the damped oscillator with damping factor a using single step
Leapfrog for separable Hamiltonians.
"""
f = forcing(beta, omega)
return sym.leapfrog(init, tspan, h, lambda x, p, t: -x-a*p+f(t)) | 4,845 |
def delete(state='', datefilter='', key=''):
"""Delete raw state files from S3
Supports deleting:
1) A single file using 'key' argument
2) All files in cache using 'state' argument, or a
subset of cached files when 'datefilter' provided.
"""
if key:
state = key.lstrip('/'... | 4,846 |
def get_paths(config, action, dir_name):
"""
Returns 'from' and 'to' paths.
@param config: wrapsync configuration
@param action: 'push'/'pull'
@param dir_name: name of the directory to append to paths from the config
@return: dictionary containing 'from' and 'to' paths
"""
path_from = ''... | 4,847 |
def to_dense(arr):
"""
Convert a sparse array to a dense numpy array. If the
array is already a numpy array, just return it. If the
array passed in is a list, then we recursively apply this
method to its elements.
Parameters
-----------
arr : :obj:`numpy.ndarray`, :obj:`scipy.sparse... | 4,848 |
def output_results(results, way):
"""Helper method with most of the logic"""
tails = way(results)
heads = len(results) - tails
result = ", ".join([["Heads", "Tails"][flip] for flip in results])
return result + f"\n{heads} Heads; {tails} Tails" | 4,849 |
def guess_init(model, focal_length, j2d, init_pose):
"""Initialize the camera translation via triangle similarity, by using the torso
joints .
:param model: SMPL model
:param focal_length: camera focal length (kept fixed)
:param j2d: 14x2 array of CNN joints
:param init_pose: 72D vector o... | 4,850 |
def clean_containers(args):
"""
Delete non-running containers.
Images cannot be deleted if in use. Deleting dead containers allows
more images to be cleaned.
"""
for container in determine_containers_to_remove(args):
print "Removing container ID: {}, Name: {}, Image: {}".format(
... | 4,851 |
def write_package_to_disk(
package: GreatExpectationsContribPackageManifest, path: str
) -> None:
"""Serialize a GreatExpectationsContribPackageManifest instance into a JSON file.
Args:
package: The GreatExpectationsContribPackageManifest you wish to serialize.
path: The relative path to th... | 4,852 |
def adjust_learning_rate(optimizer, epoch, epoch_num):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // epoch_num))
print('| Learning Rate = %f' % lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 4,853 |
def TCnCom_Dump(*args):
"""
Dump(TCnComV const & CnComV, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
Desc: TStr const &
TCnCom_Dump(TCnComV const & CnComV)
Parameters:
CnComV: TCnComV const &
"""
return _snap.TCnCom_Dump(*args) | 4,854 |
def roughness_convert(reference, invert) :
"""
Open an image and modify it to acomodate for the way Mitsuba Renderer interprets roughness.
returns the reference for the image.
"""
# Conversion for Mitsuba : no value above .5, and if this is a glossinness map, do an inversion.
# I'm doing a linear inversion, it's ... | 4,855 |
def get_reparametrize_functions(
params, constraints, scaling_factor=None, scaling_offset=None
):
"""Construct functions to map between internal and external parameters.
All required information is partialed into the functions.
Args:
params (pandas.DataFrame): See :ref:`params`.
constr... | 4,856 |
def gaussNewton(P, model, target, targetLandmarks, sourceLandmarkInds, NN, jacobi = True, calcId = True):
"""
Energy function to be minimized for fitting.
"""
# Shape eigenvector coefficients
idCoef = P[: model.idEval.size]
expCoef = P[model.idEval.size: model.idEval.size + model.expEval.size]
... | 4,857 |
def arange(start, stop=None, step=1, dtype='int32'):
"""Creates a 1-D tensor containing a sequence of integers.
The function arguments use the same convention as
Theano's arange: if only one argument is provided,
it is in fact the "stop" argument.
"""
return T.arange(start, stop=stop, step=step,... | 4,858 |
def test_multiple_observation_sequences_1d_some_flat_with_single():
"""Multiple 1D (flat and non-flat) observation sequences with allow_single=True"""
X = [np.arange(2).reshape(-1, 1), np.arange(3)]
assert_all_equal(val.is_observation_sequences(X, allow_single=True), [
np.array([
[0],
... | 4,859 |
def create_attachable_access_entity_profile(infra, entity_profile, **args):
"""Create an attached entity profile. This provides a template to deploy hypervisor policies on a large set of leaf ports. This also provides the association of a Virtual Machine Management (VMM) domain and the physical network infrastructu... | 4,860 |
def test_destroy():
"""Test the destroy action"""
with patch(
"salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock()
) as connect:
with patch("salt.cloud.clouds.hetzner.wait_until", return_value=True) as wait:
with patch("salt.cloud.clouds.hetzner.show_instance") a... | 4,861 |
def test_merged_conecpts(processed_ids, dynamodb, is_test_env):
"""Create merged concepts and load to db."""
if is_test_env:
dynamodb.merge.create_merged_concepts(processed_ids) | 4,862 |
def update_scorboard(player1, player2, screen):
"""
updates the scoreboard to the new values
"""
# make the bar white to remove old points
WIDTH_OF_SCOREBOARD = 300
screen.fill(pygame.Color("white"), (0, 0, WIDTH_OF_SCOREBOARD, BORDER))
# we render the new points
textsurface = myfo... | 4,863 |
def warning(msg: str):
"""Utility function for print an warning message and also log it
Args:
msg (str): Warning message
"""
print(f'[Warning] {msg}')
logging.warning(msg) | 4,864 |
def tensor_projection_reader(
embedding_file_path: str,
label_file_path: str
) -> Tuple[np.ndarray, List[List[str]]]:
"""
Reads the embedding and labels stored at the given paths and returns an np.ndarray and list of labels
:param str embedding_file_path: Path to the embedding file
:par... | 4,865 |
def xml_to_dict(xmlobj, saveroot=True):
"""Parse the xml into a dictionary of attributes.
Args:
xmlobj: An ElementTree element or an xml string.
saveroot: Keep the xml element names (ugly format)
Returns:
An ElementDict object or ElementList for multiple objects
"""
if isins... | 4,866 |
def test_update_nonexistent_cve():
""" the cve record cannot be updated because it doesn't exist """
with open('./src/test/cve_tests/cve_record_fixtures/CVE-2009-0009_rejected.json') as json_file:
data = json.load(json_file)
res = requests.put(
f'{env.AWG_BASE_URL}{CVE_URL}/{reject_c... | 4,867 |
def test_success(database):
""" Tests success for when AssistanceType field is required and must be one of the allowed values:
'02', '03', '04', '05', '06', '07', '08', '09', '10', '11'
"""
det_award_1 = DetachedAwardFinancialAssistanceFactory(assistance_type='02', correction_delete_indicatr='')
... | 4,868 |
def conve_interaction(
h: torch.FloatTensor,
r: torch.FloatTensor,
t: torch.FloatTensor,
t_bias: torch.FloatTensor,
input_channels: int,
embedding_height: int,
embedding_width: int,
hr2d: nn.Module,
hr1d: nn.Module,
) -> torch.FloatTensor:
"""Evaluate the ConvE interaction functi... | 4,869 |
def index():
"""Show Homepage"""
return render_template("index.html") | 4,870 |
def wav_to_spectrogram(audio_path, save_path, spectrogram_dimensions=(64, 64), noverlap=16, cmap='gray_r'):
""" Creates a spectrogram of a wav file.
:param audio_path: path of wav file
:param save_path: path of spectrogram to save
:param spectrogram_dimensions: number of pixels the spectrogram should ... | 4,871 |
def add_path(G, data, one_way):
"""
Add a path to the graph.
Parameters
----------
G : networkx multidigraph
data : dict
the attributes of the path
one_way : bool
if this path is one-way or if it is bi-directional
Returns
-------
None
"""
# extract the ... | 4,872 |
def structure_standardization(smi: str) -> str:
"""
Standardization function to clean up smiles with RDKit. First, the input smiles is converted into a mol object.
Not-readable SMILES are written to the log file. The molecule size is checked by the number of atoms (non-hydrogen).
If the molecule has mor... | 4,873 |
def main() -> None:
"""
Entry point of this test project.
"""
ap.Stage(
background_color='#333',
stage_width=1000, stage_height=500)
sprite: ap.Sprite = ap.Sprite()
sprite.graphics.line_style(
color='#0af', thickness=10, dot_setting=ap.LineDotSetting(dot_size=3))... | 4,874 |
def upload(fname, space, parent_id):
"""Upload documentation for CMake module ``fname`` as child of page with
id ``parent_id``."""
pagename = path.splitext(path.basename(fname))[0]
rst = '\n'.join(extract(fname))
if not rst:
return
log.debug('=' * 79)
log.info('Uploading %s', pagenam... | 4,875 |
def with_input_dtype(policy, dtype):
"""Copies "infer" `policy`, adding `dtype` to it.
Policy must be "infer" or "infer_float32_vars" (i.e., has no compute dtype).
Returns a new policy with compute dtype `dtype`. The returned policy's
variable dtype is also `dtype` if `policy` is "infer", and is `float32` if
... | 4,876 |
def download_users_start(api: API, start_point: str, n: float = math.inf) -> None:
"""
This function downloads n Twitter users by using a friends-chain.
Since there isn't an API or a database with all Twitter users, we can't obtain a strict list
of all Twitter users, nor can we obtain a list of strictl... | 4,877 |
def decode_object_based(effects):
"""
Reads and decodes info about object-based layer effects.
"""
fp = io.BytesIO(effects)
version, descriptor_version = read_fmt("II", fp)
try:
descriptor = decode_descriptor(None, fp)
except UnknownOSType as e:
warnings.warn("Ignoring objec... | 4,878 |
def example_add(x: int, y: int):
"""
...
"""
return x + y | 4,879 |
def inverse(text: str, reset_style: Optional[bool] = True) -> str:
"""Returns text inverse-colored.
Args:
reset_style: Boolean that determines whether a reset character should
be appended to the end of the string.
"""
return set_mode("inverse", False) + text + (reset() if reset_sty... | 4,880 |
def make():
""" hook function for entrypoints
:return:
"""
return LocalFileSystem | 4,881 |
def nkp(directory):
"""
Args:
directory:
Returns:
"""
# TODO Seems to fail. Could be related to the fact that the symmetry
# tolerances are different.
input_dir = os.path.abspath(directory)
structure = Structure.from_file(os.path.join(input_dir, "POSCAR"))
# incar = Inca... | 4,882 |
def configure():
"""read configuration from command line options and config file values"""
opts = parse_options()
defaults = dict(v.split('=') for v in opts.S or [])
with open(opts.config_file) as config:
targets = read_config(config, defaults, opts.ignore_colon)
if opts.T:
return {o... | 4,883 |
def access_contact(the_config, the_browser, page_event_new) -> None:
"""I should access to the contact page."""
p_page = ContactPage(_driver=the_browser, _config=the_config['urls'], _contact=page_event_new.contact)
assert p_page.visit() is True
assert verify_contact(p_page) is True | 4,884 |
def proper_loadmat(file_path):
"""Loads using scipy.io.loadmat, and cleans some of the metadata"""
data = loadmat(file_path)
clean_data = {}
for key, value in data.items():
if not key.startswith("__"):
clean_data[key] = value.squeeze().tolist()
return clean_data | 4,885 |
def _get_time_total(responses: List[DsResponse]) -> List[str]:
"""Get formated total time metrics."""
metric_settings = {
"name": "time_total",
"type": "untyped",
"help": "Returns the total time in seconds (time taken to request, render and download).",
"func": lambda response: _... | 4,886 |
async def list_sessions(
cache: Redis = Depends(depends_redis),
) -> ListSessionsResponse:
"""Get all session keys"""
keylist = []
for key in await cache.keys(pattern=f"{IDPREFIX}*"):
if not isinstance(key, bytes):
raise TypeError(
"Found a key that is not stored as b... | 4,887 |
def install(comicrack):
"""
Installs this module. This must be called before any other method in this
module is called. You must take steps to GUARANTEE that this module's
uninstall() method is called once you have called this method.
Takes a single parameter, which is the ComicRack object th... | 4,888 |
async def update_listener(hass, entry):
"""Update listener."""
entry.data = entry.options
await hass.config_entries.async_forward_entry_unload(entry, PLATFORM)
hass.async_add_job(hass.config_entries.async_forward_entry_setup(entry, PLATFORM)) | 4,889 |
def square(x, out=None, where=True, **kwargs):
"""
Return the element-wise square of the input.
Args:
x (numpoly.ndpoly):
Input data.
out (Optional[numpy.ndarray]):
A location into which the result is stored. If provided, it must
have a shape that the inp... | 4,890 |
def evaluate_tuple(columns,mapper,condition):
"""
"""
if isinstance(condition, tuple):
return condition[0](columns,mapper,condition[1],condition[2])
else:
return condition(columns,mapper) | 4,891 |
def imread(path, is_grayscale=True):
"""
Read image using its path.
Default value is gray-scale, and image is read by YCbCr format as the paper said.
"""
if is_grayscale:
return scipy.misc.imread(path, flatten=True, mode='YCbCr').astype(np.float)
else:
return scipy.misc.imread(pa... | 4,892 |
def configparser(subparsers):
"""The config subparser setup."""
parser = subparsers.add_parser('config', help="Configuring the presets.")
parser.set_defaults(func=configuring)
parser.add_argument('-dp', '--default-preset', nargs='?', const=True,
help="Setup a default pattern. Pr... | 4,893 |
def get_priority_text(priority):
"""
Returns operation priority name by numeric value.
:param int priority: Priority numeric value.
:return: Operation priority name.
:rtype: str | None
"""
if priority == NSOperationQueuePriorityVeryLow:
return "VeryLow"
elif priority == NSOperat... | 4,894 |
def get_experiment_tag_for_image(image_specs, tag_by_experiment=True):
"""Returns the registry with the experiment tag for given image."""
tag = posixpath.join(experiment_utils.get_base_docker_tag(),
image_specs['tag'])
if tag_by_experiment:
tag += ':' + experiment_utils.get... | 4,895 |
def create_dummy_vars():
"""Dummy vars for restore to work when not using TPU codepath."""
var_names = set([v.name for v in tf.global_variables()])
if "losses_avg/problem_0/total_loss:0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name in... | 4,896 |
def call_pager():
"""
Convenient wrapper to call Pager class
"""
return _Pager() | 4,897 |
def sign_in(request, party_id, party_guest_id):
"""
Sign guest into party.
"""
if request.method != "POST":
return HttpResponse("Endpoint supports POST method only.", status=405)
try:
party = Party.objects.get(pk=party_id)
party_guest = PartyGuest.objects.get(pk=party_guest_... | 4,898 |
def mcoolqc_status(connection, **kwargs):
"""Searches for annotated bam files that do not have a qc object
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_ti... | 4,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.