content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_runs(client):
"""Get runs"""
return client.WorkflowExecutionService.ListRuns(
).response(timeout=0.5, fallback_result=[]).result | ae1975f039d180553c4279b424548ddd9471c006 | 634,362 |
def option_wrong_value_msg(name, value, value_range):
""" The provided value is not among the range of values that it should
be
"""
return ("'%s' is not a valid 'options.%s' value.\nPossible values are %s"
% (value, name, value_range)) | af86d90d573c3fab4ededdc2814032e57c5a3bbc | 634,363 |
import os
import sys
def parse_run_name():
"""
Returns the parts of the run name of the daemon.
The run name should be of the form: project-daemon
This is used to determine the config location/section name.
"""
command = os.path.split(sys.argv[0])[1]
parts = command.split('-')
if len... | 2e664808ea9b6be46f27aa6c1a1cf7624f026fe9 | 634,364 |
import itertools
def all_configs_of_filenames(benchmark_files):
"""
[(str, int)] -> setstr
"""
return set(("-".join([str(x) for x in ids])
for ids in itertools.product(*[range(fc[1]) for fc in benchmark_files]))) | b95b73b3d968885436561a3eddced008b08ce238 | 634,365 |
def get_mock_loss_function(mock_value):
"""
A loss function that just returns a hardcoded value. Used for testing only.
:param mock_value:
:return:
"""
def mock_loss(y_true, y_pred):
return mock_value
return mock_loss | 182562a6ccf06944ef56dcb25f52918dc65a171e | 634,366 |
def feature_dict_map(weights):
"""construct a dict with features from a weights dictionary
:param weights: dictionary mapping features to numeric weights
:return: dictionary from features to a (index, weight)
"""
if type(weights) is dict:
result = {k: (i, weights[k]) for i, k in enumerate(... | b85f0e413348fce32b76bd6df14e7156da6a4caa | 634,367 |
def unit_cost(*argv, **args):
"""
Unit cost for given parameter set
"""
return 0 | 34661b9a011d66d258856b0e25a59775466f1896 | 634,368 |
def average(l):
"""The average value of a list"""
if len(l) == 0:
return 0
return sum(l)/len(l) | a91df0126004f8dbe1e3e007eb9b0098ae7d75e1 | 634,369 |
import ast
def bit_or(*arguments):
"""
Bitwise OR function.
"""
return ast.BitOr(*arguments) | e4eed129d93e808880945494dde39ea1c1639d82 | 634,370 |
def letters_only(word:str, lower_case:bool = True):
"""
Return only letters of string input parameter
Parameters
----------
word : str
String from which letters are being returned
lower_case : bool
If set to True (default) return lower-case letters
Returns
-------
... | 915ab2e4422091c98cc54c7c53afba08e7958451 | 634,371 |
import numpy
def linear_down_samp_cdf(x,xmin=0,xmax=1):
"""
CDF of distribution p(x) \propto (xmax-x)
"""
return 1.-1./(xmax-xmin)**2 * numpy.power(xmax-x,2) | fe159722d90a870462fcb21bdf12d900f5eea376 | 634,372 |
def sanitize_corners(*corners):
"""Sanitize corner inputs to NDCube crop methods."""
corners = [list(corner) if isinstance(corner, (tuple, list)) else [corner]
for corner in corners]
n_coords = [len(corner) for corner in corners]
if len(set(n_coords)) != 1:
raise ValueError("All c... | 82b4a079f430511c508bfa974fb4a153920f7a23 | 634,375 |
import warnings
def add_middle_line(image, axis=0, thickness=1, value=1):
"""Add middle line on a given image.
Parameters
----------
image : np.ndarray
Input image which needs a middle line along one axis.
axis : int
Axis along which to create the middle line.
thickness : int
... | 756054cb14c1defe7adc2ab002660793b8a0da29 | 634,376 |
import inspect
import ctypes
def cdll_with_spec(lib_path, spec):
"""
Open a shared library using ctypes.CDLL and apply the given spec class'
type annotations to the argtypes and restype attributes of the shared
library's functions.
The spec is a stub class with type annotations for the argument a... | 56c42a9677e850f14b614e09fbbb061a4d482650 | 634,377 |
def remote_addr_from_request(request):
"""
Returns the correct remote address from the request object. If the
request was proxied, this correct information is in HTTP_X_FORWARDED_FOR
"""
if not request:
raise TypeError("No request passed to function")
if 'HTTP_X_FORWARDED_FOR' in request... | d14a36a9da635c525e7500686523d1659e9312c5 | 634,378 |
import numpy
def elc_no_saturation(img):
"""
Função que devolve o elc da imagem sem saturação
:param img: a imagem a utilizar
:return: O elc da imagem
"""
min_img = abs(float(numpy.min(img)))
max_img = abs(float(numpy.max(img)))
lower_threshhold = 0
higher_threshhold = 255
elc_... | 1f8cc19e250a8173d7e5d709fac96a225bb46d00 | 634,379 |
import os
def getIterNumber():
"""Opens the file where the counter is, reads it and lastly adds one to it"""
filepath = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(filepath, 'data/weatherData.dat'), 'r') as file:
num = file.read().strip()
with open(os.path.join(fi... | 2577399b6f0e3c62b543a5d3d1a05dfe9e5464ad | 634,380 |
def create_choice_attribute(creator_type, value, choice_entry):
"""Create an instance of a subclass of ChoiceAttributeMixin for the given value.
Parameters
----------
creator_type : type
``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value``
class-meth... | da49acfab180a7d0d21aa031424d0187d3e3eb16 | 634,381 |
def intervalcheckstrict(a,b,c):
"""
Returns whether a < b < c is True or False
"""
if a<b and b<c:
return True
else:
return False | 49643ae8a9218c3599a43da4f395670043e7eea7 | 634,382 |
import logging
def get_services(netbox_api, host_list):
"""
Get all services from netbox and find ssh service for each host
Args:
netbox_api: The NetBox API object that we created earlier.
host_list: A list of dictionaries, where each dictionary contains the information for a single
h... | 3cac5ad22efd3ced353a2272448d35254703b81b | 634,383 |
import sys
def download_info(episodes=None):
"""Interface to Download
:return: a tuple of integers
"""
if not episodes:
# Indirect download invoked.
episodes = input("Enter the episode numbers\ne.g. 45-47 will download episodes from 45 to 47(including)\n[q to quit]\n")
if episo... | b8d198e5fe6f77592d8143c3748d4da2f3671bb4 | 634,384 |
def generate500response(error: str) -> dict:
""" A function that generates a '500-Internal Server Error' message and returns it as a dict """
return {
"status": 500,
"message": "Internal Server Error",
"error": error
} | 781c0467067a08fcd015b8109c2e8d4927af3d7c | 634,385 |
def handler(event, context):
"""Retrieve JSON from server."""
# Business Logic Goes Here.
response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {"id": 1, "name": "Kaiser", "type": "dog", "sub-type": "bulldog", "status": "availa... | 9b9d2c6c4cfecfc2337c57f0d79bafe2fb272712 | 634,386 |
def reprEnum(e, typ):
""" this is a port of the nim runtime function `reprEnum` to python """
e = int(e)
n = typ["node"]
flags = int(typ["flags"])
# 1 << 6 is {ntfEnumHole}
if ((1 << 6) & flags) == 0:
o = e - int(n["sons"][0]["offset"])
if o >= 0 and 0 < int(n["len"]):
return n["sons"][o]["nam... | a4e38c89cd5afebee04fea41b37b90f6f26689b0 | 634,387 |
def is_valid_version_code(ver):
"""Checks that the given version code is valid."""
letters = ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
numbers = list(range(1990, 2050))
if ver is not None and len(ver) == 5 and int(ver[:4]) in numbers and \
ver[4] in letters:
return True
else:
F... | 0eacbef81b7565b88fa63fee9ca129f67be6af8d | 634,388 |
def update_aggregated_list(times, plot_labels, aggregated_times, mean_times, list_pos):
"""
Update the aggregated list so that it is plotted in the required way
Parameters
----------
times : int
The current iteration number
plot_labels : list
The x-axis labels to use for plottin... | f5fb616e4b91983b9dddc480a8018dc04301477c | 634,389 |
def add_integers(a: int, b: int):
"""Sum two integers
Args:
a (int):
b (int):
Returns:
int: sum of the integer inputs a and b
"""
return a + b | 3cdd1be6670a649b69f0eaa4a274ebd4029a6d64 | 634,390 |
def standardize_input(score):
"""
Converts the score input of either a str, int, or float into the desired
input for percentage_to_gpa.
I don't care about some being int and some being float, still works all the same.
>>> standardize_input('95%')
95.0
>>> standardize_input(95)
95
... | 39a375da82003a715cec3965e7ad8f213d51b3a0 | 634,391 |
import os
def add_user_information(config):
"""Adds username and user's home directory to config.
@params config <dict>:
Config dictionary containing metadata to run pipeline
@return config <dict>:
Updated config dictionary containing user information (username and home directory)
"""... | 563610b750a49d7e4d8e639e5909c25fcb040b9c | 634,392 |
def _get_yearly_logical_year(year, month, day):
# type: (int, int, int) -> int
"""Retrieves the logical year for a yearly frequency."""
return year | 28e7e5a9554bf3d572f976238a8d65553435fb22 | 634,393 |
def GetAttemptString(attempts):
"""
Creates the string used to display the current attempt.
"""
match attempts:
case 1:
return "1st"
case 2:
return "2nd"
case 3:
return "3rd"
case _:
return "{}th".format(attempts) | 9efa9da631de0eb9cb65fff53748f0fba51dd927 | 634,394 |
def enum(**named_values):
# type: (object) -> object
# type: (str) -> str
"""
:str:
"""
return type('Enum', (), named_values) | a044ce9971555542bb14de36d9a4a215d42b6137 | 634,395 |
from typing import Dict
def get_custom_state() -> Dict:
"""Holds the custom state
Returns:
Dict -- A dictionary like {"username": "", "password": ""} etc.
"""
return {"username": "", "password": ""} | f9ab8f442207a82c8f5a2bc02217c0a6825a7c71 | 634,396 |
def _describe_obj(obj):
"""
Prints the name of the object, and any qualifiers.
- if an item with count > 1, appends the count
"""
if obj.item and obj.item.count > 1:
return obj.name + ' (x' + str(obj.item.count) + ')'
else:
return obj.name | 4c63286304337d9384da638217d5970d6254fc88 | 634,397 |
import functools
def dirichlet(boundary_values_fn):
"""Wrapper for Dirichlet boundary conditions to be used in PDE solvers.
Example: the boundary value is 1 on both boundaries.
```python
def lower_boundary_fn(t, location_grid):
return 1
def upper_boundary_fn(t, location_grid):
return 0
solver ... | 099e96005ddac741b031ed28995f8becf02c0e4b | 634,398 |
def create_tags(ec2_client, ec2_instance_id, event_detail):
"""
Given an EC2 Instance ID, and event['detail'] from an ECS Container
Instance State Change, updates EC2 Instance tags with clusterArn &
containerInstanceArn
Returns the SDK response to the create_tags call.
"""
cluster_arn = ev... | eda636232ae3d37feeb1d290e76fb795a061189b | 634,399 |
async def async_setup(hass, config):
"""Initialize default configuration."""
return True | afdba009fe396ca5edf99b8db61b4d87b1a01eb7 | 634,400 |
def is_unique(str):
"""Implement an algorithm to determine if a string has all unique characters.
Args:
str - String to test whether its characters are all unique.
Returns:
bool - True if str contains all unique characters, False otherwise.
"""
s = set(str)
return True if len(st... | 09abb96cd05170eed50600f657157dbcc71a04a3 | 634,401 |
def human_readable(bytes):
"""
Return a human-readable representation of the provided number of bytes.
"""
for n, label in enumerate(['bytes', 'KiB', 'MiB', 'GiB', 'TiB']):
value = bytes / (1024 ** n)
if value < 1024:
return f'{round(value, 2)} {label}'
else:
... | e0e0c4e780b2384e622428d0f883b1d4435ae74e | 634,402 |
def zchk(target):
"""Check if the input is zero"""
if target == 0:
return target + 1
return target | 27e0dbef1f03419af770f044017c51d37047c051 | 634,403 |
def __neg__(self):
"""Computes the unary operator NEGATIVE on an image.
Parameters
----------
self : ee.Image
Operand.
Returns
-------
ee.Image
Unary operator NEGATIVE.
"""
return self.multiply(-1) | a7bf4ac79b26269a4620e4a991a214afc929eb22 | 634,404 |
import os
def check_args(parsed_args):
"""
Function to check for inherent contradictions within parsed arguments.
For example, epochs < 1
Intended to raise errors prior to backend initialisation.
Args
parsed_args: parser.parse_args()
Returns
parsed_args
"""
if parsed_ar... | fd25b9ae5fec893d62159620e09fc36f228b20b5 | 634,405 |
import re
def is_base64(text: str) -> bool:
"""Guess whether text is base64-encoded."""
return bool(
re.match(
r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$",
text.replace("\n", ""),
)
) | f3be6a0e77e84715317d7233523b01ff5de92ce5 | 634,407 |
import re
def _original_neurosynth_guess_space(text):
"""Take article text as input and return a guess about the image space."""
targets = [
"mni",
"talairach",
"afni",
"flirt",
"711-2",
"spm",
"brainvoyager",
"fsl",
]
n_targ = len(targe... | 37a35136ef809118374db0ce7c4531149cede334 | 634,408 |
import torch
def top_k_logits(logits, k, probs=False):
"""
Masks everything but the k top entries as -infinity (1e10).
Used to mask logits such that e^-infinity -> 0 won't contribute to the
sum of the denominator.
"""
if k == 0:
return logits
else:
values = torch.topk(logit... | 2e24f430629fb00baf0723c7f03147c19b484e67 | 634,409 |
def getCommands(args):
"""Split (if needed) and obtain the list of commands that were sent into Skelebot"""
commands = []
command = []
for arg in args:
if arg == "+":
commands.append(command)
command = []
else:
command.append(arg)
commands.append(... | 84387d61b982a569e8a45f635a3da308833a6bf0 | 634,410 |
import sys
def import_name(mod_name):
"""Import a module by module name.
@param mod_name: module name.
"""
try:
mod_obj_old = sys.modules[mod_name]
except KeyError:
mod_obj_old = None
if mod_obj_old is not None:
return mod_obj_old
__import__(mod_name)
mod_ob... | 63f771c2c87a27d0184d45074be6353ee3a64181 | 634,411 |
from numpy import matrix
def _matrix(a):
"""Wrapper around numpy.matrix that reshapes empty matrices to be 0x0
Parameters
----------
a: sequence passed to numpy.matrix
Returns
-------
am: result of numpy.matrix(a), except if a is empty, am will be 0x0.
numpy.matrix([]) has size 1x0;... | effc880ddc84ea15d0b43399e7ad24011778e95a | 634,412 |
def build_srcdict(gta, prop):
""" Build a dictionary that maps src to a property """
o = {}
for s in gta.roi.sources:
o[s.name] = s[prop]
return o | bcbd50e9917a9000b46a98c16287a183f4e00cd3 | 634,413 |
def list_data(datas):
"""
:param datas: 测试数据
:return:
"""
def wrapper(func):
setattr(func, "PARAMS", datas)
return func
return wrapper | 4d0c42867a15ccd4b6b61cdb09fb7991f0f80096 | 634,414 |
def getValues(currentValues, current, total):
"""
Return either the current values (for this horizon) or all computed results
Parameters
----------
currentValues : Boolean
True: return 'current', False: return 'total'
current : Pointer
Pointer to the current values
total : ... | ff067d3307a0d2d9849ff32de5954c3ff7b8a5ed | 634,415 |
def abs_squared(x):
"""Computes Re(x)^2 + Im(x)^2.
Args:
x: An complex ndarray.
"""
return x.real**2 + x.imag**2 | 2a332841def511fa8cabc6e46b742dc9bf19a7cd | 634,416 |
def _GetInsertTime(operation):
"""Finds the insertTime property and return its string form.
Args:
operation: A messages.Operation instance.
Returns:
The time the operation started in string form.
"""
properties = operation.metadata.additionalProperties
for prop in properties:
if prop.key == 'i... | 9b7294f0ff94b6c375012fbcbb62bd4ea7698f64 | 634,417 |
def processFrame(frame):
"""Simulate a left and right sensor output (from 0 to 1) given the input image."""
# The pixels are grey-scale values from 0-255 - white = 255, black = 0
# We want to turn the image into two values, one for the left "sensor" and one for the right.
# There are many possible ways ... | 35b3b302df17c151cfef2a942c1d81cb50baad94 | 634,418 |
from datetime import datetime
def unixts_to_dt_obj(unixts):
"""
Convert unix timestamp to naive datetime object in UTC time zone.
:param float/int/str unixts: unix timestamp
:returns: datetime object in UTC timezone
"""
if isinstance(unixts, str):
try:
unixts = int(unixts)... | 8e57c4e467ab2b5f8c388156752a02e03037d959 | 634,419 |
def used_cached_results(metadata):
"""
Modified from: https://github.com/broadinstitute/dsde-pipelines/blob/develop/scripts/calculate_cost.py
"""
return (
"callCaching" in metadata
and "hit" in metadata["callCaching"]
and metadata["callCaching"]["hit"]
) | 1ebf4c5f4d134001c1238cdc5ed4d4bb56618b54 | 634,420 |
def _mergeClasses(classDictionaries):
"""
Look for classes that have the exact same list
of members and flag them for removal.
This returns left classes, left rename map,
right classes and right rename map.
The classes have the standard class structure.
The rename maps have this structure:
... | 0a61e2465fcccf08ff8111b28728d93306071b9f | 634,421 |
def get_vortex_slices():
"""Return the vortex slices"""
return [0.1, 0.2, 0.5, 1.0, 2.0, 4.0, 6.0] | f1f91a1cfb79f0ffe8e93c115071c00fbb65434d | 634,422 |
def fread(filename):
"""Read file and close the file."""
with open(filename, 'r') as f:
return f.read() | c31f9d939b2f2650b9d8c45239302eaa88bda012 | 634,423 |
from bs4 import BeautifulSoup
import re
def parse_lxml_form(text):
""" Parse lxml form into a dictionary of name:value based on the 'input' tags in text"""
soup = BeautifulSoup(text, features="lxml")
form = {}
for inputtag in soup.find_all(re.compile("(INPUT|input)")):
name = inputtag.get("nam... | 6f7e89f096718984c0a74130e26b530cd58c8467 | 634,424 |
import subprocess
def get_mime_type(path):
"""Use a filemagic command to get the mime type of a file. Returned as a
tuple of category and subtype.
:param str path: The path to the file to examine.
:returns: category, subtype"""
ftype = subprocess.check_output(['file',
... | 21f24ca4ac04c4212cf1da31f5bfd17c040a5180 | 634,425 |
def is_prime(number: int) -> bool:
""" Returns true if a number is prime false if not"""
number = int(number)
if number > 1:
for i in range(2, number):
if (number % i) == 0:
return False
else:
return True
else:
return False | 67af775ca7fd86a70d6643955c8d30575f288daa | 634,426 |
import os
def file_path(filepath):
"""Check onboarding yaml file exists."""
if not os.path.isfile(filepath):
return "Gateway Deployment yaml File Path Not Found."
return filepath | 382a03a4e9a63bc6037760dc9dea149ad4b803cf | 634,427 |
def orbputx(orb, srcname, time, packet, nbytes):
"""Put a packet on an orb, returning the pktid of the output packet"""
return orb.putx(srcname, time, packet, nbytes) | e15a39566aefdefd703272d7478c647078f9b32f | 634,428 |
def multiply_2():
"""
According to PEP8, there has to be a docstring here to explain
the function, but it's pretty obvious.
"""
return 2 + 2 | 35dfe11658c629bb192bb40d7bb188554aafc715 | 634,429 |
import os
def symbol_to_path(symbol,base_dir="data"):
"""This function returns CSV file to ticker given symbol """
return os.path.join(base_dir,f"{symbol}.csv") | 7eda4e958617359c93bbc9ef201efe9fb2a18ec8 | 634,430 |
import re
def is_email(text):
"""
Parameters
----------
text: string
text to test
Returns
-------
boolean
whether the input text is an email
"""
return bool(re.match(r"^.+@(\[?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", text)) | d0cff7f60fd59feb69af57286bd134a088641f77 | 634,431 |
import platform
def getOSVersion():
"""Return OS version."""
return platform.mac_ver()[0] | 169fcd15f8f80756ec4c10299e49a3cecd629ec4 | 634,432 |
def make_slim_provenance_dict(model_type, slim_generation,
stage='late', spatial_dimensionality='', spatial_periodicity='',
separate_sexes=False, nucleotide_based=False):
"""
Returns a dictionary encoding provenance information for a SLiM tree sequence.
"""
document = {
"schema_v... | a1e1788dcb22ed2c593d8df7c604e165236a32f6 | 634,433 |
def MAX(src_column):
"""
Builtin maximum aggregator for groupby
Example: Get the maximum rating of each user.
>>> sf.groupby("user",
... {'rating_max':tc.aggregate.MAX('rating')})
"""
return ("__builtin__max__", [src_column]) | 59d030a07fafb6f254149d264b3a4feb9431ed28 | 634,434 |
def process_object_uris(url, extras):
"""Extract doi from /extras, and return a list of object uris including /url and doi if it exists.
"""
doi = []
for d in extras:
if d['key'] == "DOI" or d['key'] == "DOI:":
doi.append(d['value'])
if doi == []:
return [url]
else:
... | 526fac141b0a0814b4627281c9b46f3b38f1eea8 | 634,435 |
def get_species_to_transcript(tree):
"""
Get the {species: species@transcript_id} dictionary
"""
return {x.name.split("@")[0]: x.name for x in tree.get_terminals()} | 74b94bc391cf15cc000475f55f1c94ce9a52c2cd | 634,436 |
def builder_support(builder):
"""Return True when builder is supported. Supported builders output in
html format, but exclude `PickleHTMLBuilder` and `JSONHTMLBuilder`,
which run into issues when serializing blog objects."""
if hasattr(builder, 'builder'):
builder = builder.builder
not_sup... | 3194c89ec2b4b86bf67ce7cb0deaefe832024b88 | 634,437 |
import os
import logging
import tqdm
import requests
import zipfile
def maybeDownload(name="mot17det", src=None, target=os.path.join("/","tmp"),
uncompressed=True):
"""maybeDownload: Maybe download the MOT17Det dataset from the official datasets
to the local.
Args:
name ... | 7ba68252e4903c5f6107e56f5f8ad84f0778477a | 634,438 |
from typing import List
from typing import Dict
import copy
def get_object_camera_target(bullet_odicts: List[Dict], oidx: int):
"""Computes the position of the target for the camera to look at, for a
given object index.
Args:
bullet_odicts: A list of object dictionaries.
oidx: The object ... | 66075dc5447a45861612b710864c557cca6d2e42 | 634,440 |
def get_content_of_sliding_window(image, abs_center, width, height, count=0):
"""Returns a width x height window where abs_center is the center."""
y_bottom = image.shape[0] - height*count
y_top = y_bottom - height
if y_top < 0:
return None
x_left = abs_center - round(width/2)
x_right ... | 44d773f1cce8576682ba75c89bc210dd111ca75e | 634,441 |
def filter_by_threshold(line):
"""
Just a filter
"""
temp = float(str.split(line, ',')[2])
return temp > 50 | f064f0df2b310b3a2d0bb55d7798eace46350903 | 634,442 |
def early_stopping(cost, opt_cost, threshold, patience, count):
"""
early stopping
"""
if opt_cost - cost <= threshold:
count += 1
else:
count = 0
if count >= patience:
return True, count
return False, count | cd2f071c5ff5775248776e587db3d16fc42ef6a6 | 634,443 |
def ctop(width, height, zx_coord, zy_coord, zxoff, zyoff, zoom):
"""
Converts complex space coordinates to actual pixel coordinates
(zxoff, zyoff are always the complex offsets).
"""
x_coord = (zx_coord + zxoff) * zoom * width / 2 / (width / height)
y_coord = (zy_coord + zyoff) * zoom * height ... | 9b39dd13232b50725e59105d168d5e82f8c814c6 | 634,444 |
import os
def tests_root():
"""Return the root path to the stock cases"""
dir_name = os.path.dirname(os.path.abspath(__file__))
return os.path.normpath(os.path.join(dir_name, '..', '..', 'tests')) | 18b70240de5150c748272426a40d087cb320d1bd | 634,445 |
import re
def dont_document_data(config, fullname):
"""Check whether the given object should be documented
Parameters
----------
config: sphinx.Options
The configuration
fullname: str
The name of the object
Returns
-------
bool
Whether the data of `fullname` s... | dfe56e6cad36ecb978d2973efa0a313e4b75587e | 634,446 |
def _get_file_data(ifname, interface):
"""
Return data for (sub-)interfaces and routes
"""
label = interface['label']
ip4s = interface['ip4s']
ip6s = interface['ip6s']
gateway4 = interface['gateway4']
gateway6 = interface['gateway6']
ifnum = None
iface_data = "# Automaticall... | c8c28748bfce81b6aef8c3673fef33fca76ec1fd | 634,447 |
def email_ctx():
"""Email context fixture."""
return {
'user': 'User',
'content': 'This a content.',
'sender': 'sender',
} | d80323a2e910450c16101456ae8f5e37c04f51eb | 634,448 |
import torch
def _distance_matrix(x: torch.Tensor, eps_factor=1e2) -> torch.Tensor:
"""Naive dense distance matrix calculation.
Parameters
----------
x : torch.Tensor
Dense [n, d] tensor containing the node attributes/embeddings.
eps_factor : [type], optional
Factor to be multipli... | bafe4c182101bbf161745aba11de549412bbbbfa | 634,449 |
def box(text: str, lang: str = "") -> str:
"""Get the given text in a code block.
Parameters
----------
text : str
The text to be marked up.
lang : `str`, optional
The syntax highlighting language for the codeblock.
Returns
-------
str
The marked up text.
"""
... | fbea21841bd02ef627370c9d5541b01dce695492 | 634,450 |
import torch
def proj_onto_unit_sphere(vectors):
"""
input: vectors: [batchsize, num_projs, dim]
"""
return vectors / torch.sqrt(torch.sum(vectors ** 2, dim=2, keepdim=True)) | b72ad8158f627723aa37dad0e1922713eef1b475 | 634,451 |
import fcntl
import os
def set_blocking(fd, blocking=True):
"""
Set the given file-descriptor blocking or non-blocking.
Returns the original blocking status.
"""
old_flag = fcntl.fcntl(fd, fcntl.F_GETFL)
if blocking:
new_flag = old_flag & ~ os.O_NONBLOCK
else:
new_flag = o... | fae0a79331daa4d85219a1c071d0032d0a98b361 | 634,452 |
def set_true_for_empty_dict(d):
"""
Recursively set value of empty dicts from a dictionary.
For some of entity G Suite API return {} (blank dictionary) which indicates some actions on resource.
Eg. Here, new or upload indicates resource is newly created or uploaded on the server.
{
"new": {}, /... | a96a22ba7c725c13f4ce1b7210f755f9e8e603b9 | 634,453 |
def chooseCave():
"""
This function prompts the user to choose a number as to what cave to enter.
return: the number (String) input by the user (cave).
"""
cave = ''
#while cave != '1' and cave != '2':
# print('Which cave will you go into? (1 or 2)')
# cave = input()
#
#return ca... | df8664b6bf86eb5d79d0624594e913a6e360a09f | 634,454 |
def at_sort(arg):
""" %s \t\t\t -- sort list/string. """
return list(sorted(arg.value)) | b2cf521121ee1be6b3c1bd6e3581a6d098d5984f | 634,455 |
from io import StringIO
import sys
import traceback
def execute_code(code: str, code_input: str = "") -> str:
"""Executes Python code and collects its output"""
if not code_input.endswith("\n"):
code_input += "\n"
input_buffer = StringIO()
input_buffer.write(code_input)
input_buffer.seek(... | f004bf5163deafb5239975dfbe85ba898804bcfb | 634,457 |
def add_three(a):
"""Return a + 3.
"""
return a + 3 | b4cd93f76ef768578a9f81dfa9f17d163dac0a84 | 634,458 |
def get_line_msg(line):
"""Return message part of a line."""
return line.split()[2] | 7b0b98cf487b58ebe2da9ee2b422a54dab44f3e0 | 634,459 |
from pathlib import Path
def version():
""" Get the local package version. """
namespace = {}
path = Path("t5chem", "__version__.py")
exec(path.read_text(), namespace)
return namespace["__version__"] | 12522952b1557aaa865a487c0505cdef58872c27 | 634,460 |
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:ret... | 38a3ab5d6684174429d21474b9f5f7ee9bee86f9 | 634,461 |
def check_interval_intersection(t1a, t1b, t2a, t2b):
"""
Determine if the intervals (t1a, t1b) and (t2a, t12b) intersect.
"""
if min(t1a, t1b) < t2a and max(t1a, t1b) > t2a:
return True
elif min(t1a, t1b) < t2b and max(t1a, t1b) > t2b:
return True
elif min(t2a, t2b) < t1b and max... | b6ed55eea625fbcc9e4787338d83cedc274c0f3a | 634,462 |
def get_topic_name(test_run_name):
"""Returns the collection name for the DLQ.
Keyword arguments:
test_run_name -- the unique id for this test run
"""
if test_run_name.startswith("db."):
return test_run_name
elif test_run_name.startswith("data."):
return test_run_name
retur... | 78e9d71277d9a31ec0272f2a30f126759ec3ef19 | 634,463 |
def top_menu_children(context, parent):
"""
Retrieves the children of the top menu items for the drop downs
"""
menu_items_children = parent.get_children()
menu_items_children = menu_items_children.live().in_menu()
return {
'parent': parent,
'menu_items_children': menu_items_chil... | 5441e6ee5d9077edd15e55a22aad8c331aa2569d | 634,466 |
from typing import List
def my_min(data_list:List[str]) -> int:
""" Retorna o valor mínimo
Função que emula o funcionamento da função built-in ``min()`` retornando o menor valor da lista.
:param data_list: Lista contendo os valores para se encontrar o valor mínimo.
:returns: Valor número representan... | 20c2ba40c031e7c6fab10bb10f023f6aab25d11f | 634,467 |
import re
def strip_var_name(var_name):
"""Strips variable name of sub-strings blocking variable name matching."""
# Strip trailing number, e.g. convert
# 'lstm/W_0:0' to 'lstm/W_0'.
var_name = re.sub(r':\d+$', '', var_name)
# Strip partitioning info, e.g. convert
# 'W_0/part_3/Adagrad' to 'W_0/Adagrad'.
... | b2f2fb37bc173913b3d5f74badfed4600422c283 | 634,468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.