content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def log_channel_str_messages(client, channel_str):
"""
Arguments:
client: A discord.py Client Object
channel_str: A channel STRING.
Do not confuse with log_channel_obj_messages, as this only works when the channel is a string.
Returns:
Searches for channels matchin... | 5,293,200 |
def load_data_and_labels_lemonde(filepathXml):
"""
Load data and label from Le Monde XML corpus file
the format is ENAMEX-style, as follow:
<sentence id="E14">Les ventes de micro-ordinateurs en <ENAMEX type="Location" sub_type="Country"
eid="2000000003017382" name="Republic of France">France</E... | 5,293,201 |
def SelectService(userCard):
# Method Description:
"""Selects and Runs Different ATM Services in A Terminal As UI"""
# Endless Loop For User To Select a Service
while(True):
print("Avaliable Services Are:", "1. Check Balance", "2. Withdraw", "3. Deposit", "4. Transaction History", "5. Qui... | 5,293,202 |
def view_user_issues(username):
"""
Shows the issues created or assigned to the specified user.
:param username: The username to retrieve the issues for
:type username: str
"""
if not pagure_config.get("ENABLE_TICKETS", True):
flask.abort(
404,
description="Tic... | 5,293,203 |
def i0(x):
"""
Modified Bessel function of the first kind, order 0.
Usually denoted :math:`I_0`. This function does broadcast, but will *not*
"up-cast" int dtype arguments unless accompanied by at least one float or
complex dtype argument (see Raises below).
Parameters
----------
x : ... | 5,293,204 |
def generate_registers_sifive_clic0_clicintip(intr, addr):
"""Generate xml string for riscv_clic0 intip register for specific interrupt id"""
return """\
<register>
<name>clicintip_""" + intr + """</name>
<description>CLICINTIP Register for interrupt id """ + ... | 5,293,205 |
def close_poll():
""" Closes a poll. """
form = DeletePost()
if form.validate():
try:
post = SubPost.get(SubPost.pid == form.post.data)
except SubPost.DoesNotExist:
return json.dumps({'status': 'error', 'error': _('Post does not exist')})
if post.ptype != 3:... | 5,293,206 |
def whiteball_push_gauss1_10_25_2021():
"""
t = 20
"""
r = RunnerWithIDs(command='python bin/counterfactual_hdf5.py --scenario intervenable_bouncing_white_action.py', gpus=[])
r.add_flag('num_episodes', ['2000'])
r.add_flag('max_episode_length', ['10'])
r.add_flag('t_intervene', ['0'])
... | 5,293,207 |
def check_cmds():
"""
Checks if the required commands to run are installed and if not, installs them via pip
:return: none
"""
# Command list
cmds = ('ssh', 'xterm')
for c in cmds:
if subprocess.check_output(['command -v ', c], shell=True) == 'b''':
if platform == 'linux'... | 5,293,208 |
def TUInt_JavaUIntToCppUInt(*args):
"""
TUInt_JavaUIntToCppUInt(uint const & JavaUInt) -> uint
Parameters:
JavaUInt: uint const &
"""
return _snap.TUInt_JavaUIntToCppUInt(*args) | 5,293,209 |
def _storeUploadId(event):
"""
Called after an upload is first initialized successfully. Sets the authorized upload ID
in the token, ensuring it can be used for only this upload.
"""
returnVal = event.info['returnVal']
token = getCurrentToken()
tokenModel = Token()
isAuthorizedUpload = t... | 5,293,210 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
if hass.data[DOMAIN].get(DISPATCHERS) is not None:
for cleanup in hass.data[DOMAIN][DISPATCHERS]:
cleanup()
if hass.data[DOMAIN].get(DATA_DISCOVERY_INTERVAL) is not None:
hass.dat... | 5,293,211 |
def texts2(score, coins):
"""Displays Game Over Text."""
a = pygame.image.load('stuff/sprites/death_racccoon.png')
largeText = pygame.font.SysFont("comicsansms",115)
smallText = pygame.font.SysFont('comicsansms', 25)
TextSurf, TextRect = text_objects("You Died", largeText)
TextSurf2, TextR... | 5,293,212 |
def extract_pdbs(input_filelines):
""" Given a list of lines from SSM output txt, returns a list of upper case PDBs
The input file should have a range of lines enumerating the PDBS that looks like this:
.....
.....
## Structure Nres Nsse RMSD Q-score
1 PDB 5cxv... | 5,293,213 |
def result():
"""Route to results page after submitting form on index page"""
# declare form from form.py
form = pathToVideo()
# user option selections from form saved as sessions to be accessible via different routes
session['firstPath'] = form.firstPathSelect.data
session['secondPath'] = form... | 5,293,214 |
def is_conv2d(module):
"""Determine Conv2d."""
# depth-wise convolution not in pruned search space.
return isinstance(module, Conv2d) and not is_depth_wise_conv(module) | 5,293,215 |
def make_date(d_str: str) -> Date:
""" Returns new Date instance from given date string
REQUIRES: d_str is in format 'yyyy-mm-dd'
"""
year = int(d_str[:4])
month = int(d_str[5:7])
day = int(d_str[8:])
return Date(year, month, day) | 5,293,216 |
def get_device_id():
""" GEt unique id for device"""
flash_id = '{0:x}'.format(esp.flash_id())
manufacturer = flash_id[-2:]
device_id = flash_id[2:4] + flash_id[0:2]
return (manufacturer, device_id) | 5,293,217 |
def cc_flatbuffers_library(
name,
srcs=[],
deps=[],
data=[],
include=None,
**kargs):
"""Bazel rule to create a C++ flatbuffers library from .fbs source files"""
includes = []
if include != None:
includes = [include]
out_cpp = [s.replace('.fbs', '_g... | 5,293,218 |
def search_link_signal(content_type_id, object_id, lang, page, **_):
"""
Delay search Wikipedia links in references of wikipedia page
"""
search_roles_links.delay(content_type_id, object_id, lang, page.links) | 5,293,219 |
def view_complex_native(x: torch.FloatTensor) -> torch.Tensor:
"""Convert a PyKEEN complex tensor representation into a torch one using :func:`torch.view_as_complex`."""
return torch.view_as_complex(x.view(*x.shape[:-1], -1, 2)) | 5,293,220 |
def cross_corr_norm(patch_0, patch_1):
"""
Returns the normalized cross-correlation between two same-sized image
patches.
Parameters :
patch_0, patch_1 : image patches
"""
n = patch_0.shape[0] * patch_0.shape[1]
# Mean intensities
mu_0, mu_1 = patch_0.mean(), patch_1.... | 5,293,221 |
def main(args=None):
"""Run program."""
from docopt import docopt
args = docopt(__doc__, version=__version__)
if args.get('--verbose'):
log.setLevel(logging.INFO)
elif args.get('--quiet'):
log.setLevel(logging.ERROR)
elif args.get('--debug'):
log.setLevel(logging.DEBUG)
... | 5,293,222 |
def fixture_config_file(empty_file: str) -> Generator[str, None, None]:
"""Creates a config file and returns the path"""
with open(empty_file, "w", encoding="utf-8") as temp_file:
json.dump(MOCK_CONFIG, temp_file, indent=4)
yield empty_file | 5,293,223 |
def add_message(phone_code, msg):
"""
Add message to a user specific queue
@param phone_code: Phone unique code
@type phone_code: basestring
@param msg: Message
@type msg: dict
"""
msg = json.dumps(msg)
logger.debug("Message from phone {0}: {1}".format(phone_code, msg))
settings.... | 5,293,224 |
def datetime_to_W3CDTF(dt):
"""Convert from a datetime to a timestamp string."""
return datetime.datetime.strftime(dt, W3CDTF_FORMAT) | 5,293,225 |
def test_append_success(querylang_set, querylang_item):
"""Test :meth:`append`. Expect test three cases depends on the type of :attr:`value`.
Such as :class:`BaseDriver`, :class:`QueryLangProto` and :class:`QueryLang`.
.. note::
Please parameterize this test with pytest.mark.parameterize.
"... | 5,293,226 |
def get_device_value_oid(ip, oid, community_string="public"):
"""
Get value from specified device with OID
Args:
ip: The device's IP address
oid: SNMP OID
community_string: The community string for the network. Usually 'public' or 'private'
Returns:
... | 5,293,227 |
async def test_mode_property(mode):
"""Test iterating over lines from a file."""
filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt')
async with aioopen(filename, mode=mode) as file:
assert file.mode == mode
assert file.closed | 5,293,228 |
def test_manages_team_student_2():
"""Students don't manage teams (by name)"""
u = User.create_user("student_coll1_1", "cows")
assert not any([u.manages_team(t.name) for t in u.teams]) | 5,293,229 |
def get_flip_set(index):
"""Make flip set"""
n = 1
while n <= index:
n *= 2
def get(n, j):
if j <= 1:
return {b for b in range(j)}
n_half = n // 2
if j < n_half:
return get(n_half, j)
f = {b + n_half for b in get(n_half, j - n_half)}
... | 5,293,230 |
def cosineDistance(a, b):
""" Calculates the cosine distance between lists of numbers `a` and `b`.
Args
---
`a : float[]` The first list of floats (or ints)
`b : float[]` The second list of floats (or ints)
Returns
---
`distance : float` The distance between `a` and `b`
"""
n =... | 5,293,231 |
def calculate(path1, path2, k, k2, max_wavs=120, max_num_psds=10000):
"""calculate songdkl metric
Parameters
----------
path1 : str
path to folder with .wav files of songs from bird 1
path2 : str
path to folder with .wav files of songs from bird 2
k : int
number of sylla... | 5,293,232 |
def tensor2sparse(tensor):
"""Convert pytorch tensor to sparse csr matrix."""
return sparse.csr_matrix(tensor.detach().cpu().numpy()) | 5,293,233 |
def optional(*decls: str, nilstr: bool = False, **attrs: Any) -> Callable[[FC], FC]:
"""
Like `click.option`, but no value (not even `None`) is passed to the
command callback if the user doesn't use the option. If ``nilstr`` is
true, ``--opt ""`` will be converted to either `None` or (if ``multiple``)
... | 5,293,234 |
def cli():
"""Command line interface to Faculty."""
try:
faculty_cli.update.check_for_new_release()
except Exception: # pylint: disable=broad-except
pass | 5,293,235 |
def get_model_base() -> dict:
"""The base model for running a WLTC experiment.
It contains some default values for the experiment
but this model is not valid - you need to override its attributes.
:return: a tree with the default values for the experiment.
"""
instance = {
"unladen_ma... | 5,293,236 |
def triplet_loss(y_true:tf.Tensor, y_pred:tf.Tensor, alpha:float = 0.2):
"""
-- Explanation :
this function compares the triplet loss ()
-- Args:
y_true -- true labels,
y_pred -- python list containing three objects:
anchor -- the encodings for the anchor images, of shape (None, 12... | 5,293,237 |
def test_read_file_in_exception_1():
""" test_read_file_in_exception_1 """
xky_file = "in/read_in_exception_1.xky"
dir_path = os.path.dirname(os.path.realpath(__file__))
xky_file = dir_path + "/" + xky_file
with pytest.raises(Exception):
xkye = io(xky_file)
dictionary = xkye.read(... | 5,293,238 |
def test_tar_cmd_when_tar_not_found():
"""Test tar cmd."""
a_mock = MagicMock()
a_mock.return_value = None
a_mock.returncode = None
a_mock.side_effect = OSError()
with patch('subprocess.Popen', a_mock):
tar = mech.utils.tar_cmd()
assert tar is None | 5,293,239 |
def x_view_function():
""" underspecified library view """
return Response(1.234) | 5,293,240 |
def mkXRDTag(t):
"""basestring -> basestring
Create a tag name in the XRD 2.0 XML namespace suitable for using
with ElementTree
"""
return nsTag(XRD_NS_2_0, t) | 5,293,241 |
def auth(
func=None,
roles=None,
permissions=None,
requires=None,
login_redirect=None,
should_remember_referrer=True):
"""Guards a controller action against unauthorized and unauthenticated access.
Args:
roles (list|string): A list of roles that are able ... | 5,293,242 |
def site_stat_stmt(table, site_col, values_col, fun):
"""
Function to produce an SQL statement to make a basic summary grouped by a sites column.
Parameters
----------
table : str
The database table.
site_col : str
The column containing the sites.
values_col : str
T... | 5,293,243 |
def to_time_units(obj, freq):
"""Multiply each element with `freq_delta` to get result in time units."""
if not checks.is_array(obj):
obj = np.asarray(obj)
return obj * freq_delta(freq) | 5,293,244 |
def perform_learning_step(epoch):
""" Makes an action according to eps-greedy policy, observes the result
(next state, reward) and learns from the transition"""
def exploration_rate(epoch):
"""# Define exploration rate change over time"""
start_eps = 1.0
end_eps = 0.1
const_... | 5,293,245 |
def read_bhrc(filename, **kwargs):
"""Read the Iran BHRC strong motion data format.
Args:
filename (str): path to BHRC data file.
kwargs (ref):
Other arguments will be ignored.
Returns:
list: Sequence of one StationStream object containing 3
StationTrace objects... | 5,293,246 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Flo switches from config entry."""
devices: List[FloDeviceDataUpdateCoordinator] = hass.data[FLO_DOMAIN]["devices"]
async_add_entities([FloSwitch(device) for device in devices]) | 5,293,247 |
def random_pdf(x, dx, seed_i=False, n_iter=1000, silent=True):
"""
Created on 24/06/2016
Modified on 29/06/2016 to reverse shape
"""
len0 = len(x)
if not silent:
print(len0)
# Mod on 29/06/2016
x_pdf = np.zeros((len0, n_iter), dtype=np.float64)
# x_pdf = np.zeros((n_iter, l... | 5,293,248 |
def test_port_algo_config_str():
"""Function should convert string to compliant dict"""
assert backward.port_algo_config("algo_name") == {"of_type": "algo_name"} | 5,293,249 |
def vertical_split(im):
"""
Split an image vertically. This works for member list as well as (well, most times) scouting screenshots
:param im: screenshot data
:return: the ratio for resizing the screenshot, a list of (start, stop) chunks to use when looping
"""
im_gray = cv2.cvtColor(im, cv2.C... | 5,293,250 |
def interp2d(image):
"""
Bilinear interpolation method to be used for upscaling
Args:
tensor_nchw (tensor): tensor of shape (N, C, H, W)
Return:
tensor of shape (N, C, Hout, Wout), where Hout and Wout are computed
by applying the scale factor to H and W
"""
# return ... | 5,293,251 |
def log_data(download_dir,
logfile, verbose=True):
"""record manifest and file hashes"""
imgfiles = {}
# traverse root directory, and list directories as dirs and files as files
for root, _, files in os.walk(download_dir):
path = root.split(os.sep)
for file in files:
... | 5,293,252 |
def test_full_select():
"""Select all employees and their referenced companies"""
Employee.many(projection={
'company': {
'$ref': Company,
'departments': {'$sub': Department}
}
}) | 5,293,253 |
def create_app(config_object="chaos_genius.settings"):
"""Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split(".")[0])
app.config.from_object(config_object)
regis... | 5,293,254 |
def get(cls, key):
"""
Get an entity by key
"""
return build_key(cls, key).get() | 5,293,255 |
def page_not_found(__=None):
"""
What to return if a user requests an endpoint that doesn't exist.
"""
print(app.root_path)
return transiter_error_handler(exceptions.PageNotFound(flask.request.path)) | 5,293,256 |
def rational_diagonal_form(self, return_matrix=False):
"""
Returns a diagonal form equivalent to Q over the fraction field of
its defining ring. If the return_matrix is True, then we return
the transformation matrix performing the diagonalization as the
second argument.
INPUT:
none
... | 5,293,257 |
def _format_source_error(filename, lineno, block):
""" A helper function which generates an error string.
This function handles the work of reading the lines of the file
which bracket the error, and formatting a string which points to
the offending line. The output is similar to:
File "foo.py", li... | 5,293,258 |
def full_database_setup():
"""Sets up a clean database based on the model metadata. It also
calculates the FK relationships between tables so we can delete them in
order. It yields a tuple the _DB and ordered list of tables."""
rand_id = str(randint(1, 9999))
config = dataactcore.config.CONFIG_DB
... | 5,293,259 |
def calc_exposure(k, src_rate, bgd_rate, read_noise, neff):
"""
Compute the time to get to a given significance (k) given the source rate,
the background rate, the read noise, and the number
of effective background pixels
-----
time = calc_exposure(k, src_rate, bgd_rate, read_noise, neff)
... | 5,293,260 |
def decode_image(contents, channels=None, name=None):
"""Convenience function for `decode_gif`, `decode_jpeg`, and `decode_png`.
Detects whether an image is a GIF, JPEG, or PNG, and performs the appropriate
operation to convert the input bytes `string` into a `Tensor` of type `uint8`.
Note: `decode_gif` return... | 5,293,261 |
def exec_mkdir(dirname):
"""
Create a directory.
Parameters
----------
dirname: str
The full path of the directory.
Returns
-------
bool:
True on success, False otherwise.
"""
_logger.debug('__ Creating %s.', dirname)
try:
if not os.path.exist... | 5,293,262 |
def step_impl(context):
"""
For the first step we setup the APIClient, and the related tag_list
"""
world.client = APIClient(
"http://test_host",
username="username",
password="password")
world.tag_list = EntityList(Constants.TAG_ENTITY) | 5,293,263 |
def get_all_round_info_from_cache():
"""Returns a dictionary containing all the round information.
example: {"rounds": {"Round 1": {"start": start_date, "end": end_date,},},
"competition_start": start_date,
"competition_end": end_date}
"""
rounds_info = cache_mgr.get_cache('r... | 5,293,264 |
def type_or_null(names):
"""Return the list of types `names` + the name-or-null list for every type in `names`."""
return [[name, 'null'] for name in names] | 5,293,265 |
def scratch(request, slug=None):
"""
Get or create a scratch
"""
if request.method == "GET":
db_scratch = get_object_or_404(Scratch, slug=slug)
return Response(ScratchSerializer(db_scratch).data)
elif request.method == "POST":
data = request.data
if "target_as... | 5,293,266 |
def test_prev(years):
"""Test of the prev method.
"""
assert years[0].prev() == ttcal.Year(2004) | 5,293,267 |
def variables_pool(variable, question='Variable to analyze'):
"""
:param variable: the variable chosen from variable pool in your dataframe
:param question: default parameter ("Variable to analyze")
don't :return:
"""
def guide(diz):
"""
function that guides user to chose the ri... | 5,293,268 |
def add_topic():
"""
Endpunkt `/topic`.
Route zum hinzufügen eines Themas.
"""
try:
if "config" not in request.files:
err = flask.jsonify({"err_msg": "Missing File"})
return err, 400
if "name" not in request.form:
err = flask.jsonify({"err_msg": ... | 5,293,269 |
def quadratic_matmul(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor:
"""Matrix quadratic multiplication.
Parameters
----------
x : torch.Tensor, shape=(..., X)
A batch of vectors.
A : torch.Tensor, shape=(..., X, X)
A batch of square matrices.
Returns
-------
torch.T... | 5,293,270 |
def get_global_step(estimator):
"""Return estimator's last checkpoint."""
return int(estimator.latest_checkpoint().split("-")[-1]) | 5,293,271 |
def test_q():
"""Test fixtures of priority qs."""
from src.priorityq import PriorityQ
q0 = PriorityQ()
q1 = PriorityQ()
q1.insert('sgds', 10)
q1.insert('another', 9)
q1.insert('another', 8)
q1.insert('another', 7)
q1.insert('another', 6)
return q0, q1 | 5,293,272 |
def use_opengl(test_options):
"""Fixture to flag test using a OpenGL.
This can be skipped with `--no-opengl`.
"""
if not test_options.WITH_GL_TEST:
pytest.skip(test_options.WITH_GL_TEST_REASON, allow_module_level=True) | 5,293,273 |
def mock_single_site_api() -> Generator:
"""Return a single site."""
instance = Mock()
site = Site("01FG0AGP818PXK0DWHXJRRT2DH", "11111111111", [])
instance.get_sites.return_value = [site]
with patch("amberelectric.api.AmberApi.create", return_value=instance):
yield instance | 5,293,274 |
def message_error(text: str) -> None:
"""Show an error message in the statusbar.
Args:
text: The text to show.
"""
message.error(text) | 5,293,275 |
def make_mlb_classifier_and_data_with_feature_extraction_pipeline():
"""Create data set and classifier for testing a multi-label
classification scenario with a feature extraction pipeline.
"""
newsgroups_train = fetch_20newsgroups(subset="train")
X, Y = newsgroups_train.data, newsgroups_train.targe... | 5,293,276 |
def read_volume(filepath, dtype=None, return_affine=False):
"""Return numpy array of data from a neuroimaging file.
Args:
filepath: path-like, path to volume file.
dtype: dtype-like or str, data type of the volume data.
return_affine: boolean, if true, return tuple of volume data and
... | 5,293,277 |
def Import(context, request):
""" FOSS FIAStar analysis results
"""
infile = request.form['data_file']
fileformat = request.form['format']
artoapply = request.form['artoapply']
override = request.form['override']
sample = request.form.get('sample',
'requestid')
... | 5,293,278 |
def meantime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime):
"""
Approximate unconditional mean time blocked in ldr or csect waiting for a pp bed.
Modeling pp as an M/G/c queue and using approximation by Kimura.
"""
pp_svcrate = 1.0 / pp_mean_svctime
meantime = qng.mgc_mean... | 5,293,279 |
def _combine_grad(evoked, picks):
"""Create a new instance of Evoked with combined gradiometers (RMSE)."""
def pair_and_combine(data):
data = data ** 2
data = (data[::2, :] + data[1::2, :]) / 2
return np.sqrt(data)
picks, ch_names = _grad_pair_pick_and_name(evoked.info, picks)
th... | 5,293,280 |
def save_model(model, model_filepath):
"""
export model as a pickle file
Argument:
model -- trained model
model_filepath -- destination of saved file
"""
filename = 'classifier.pkl'
pickle.dump(model, open(filename, 'wb')) | 5,293,281 |
def test_tc4():
""" Test conditional T """
d = n_mod_m(4, 2)
assert T(d, [[0], [1]], [2, 3]) == pytest.approx(1.0)
d.set_rv_names("XYZW")
assert T(d, [['X'], ['Y']], ['Z', 'W']) == pytest.approx(1.0) | 5,293,282 |
def each_segment(time_ci, energy_ci, rate_ref, meta_dict,\
start_time, end_time):
"""
Turns the event list into a populated histogram, stacks the reference band,
and makes the cross spectrum, per segment of light curve.
Parameters
----------
time_ci : np.array of floats
1-D array of... | 5,293,283 |
def box_iou(boxes1, boxes2):
"""Compute pairwise IoU across two lists of anchor or bounding boxes.
Defined in :numref:`sec_anchor`"""
def box_area(boxes): return ((boxes[:, 2] - boxes[:, 0]) *
(boxes[:, 3] - boxes[:, 1]))
# Shape of `boxes1`, `boxes2`, `areas1`, `areas2... | 5,293,284 |
def merge(lsf_dir, lsf_out):
"""
Merge all lsf files contained in the subdirectories into a single lsf-file. The messages are sorted by timestamp.
:param lsf_dir: The root directory to start search for lsf files
:param lsf_out: The output path of the target lsf file
:return:
"""
msgs = []
... | 5,293,285 |
def getBranchPath(path):
"""Get a path rooted in the current branch.
@param path: A path relative to the current branch.
@return: A fully-qualified path.
"""
currentPath = os.path.dirname(__file__)
fullyQualifiedPath = os.path.join(currentPath, '..', path)
return os.path.abspath(fullyQualif... | 5,293,286 |
async def status(ctx):
"""System's status. Note this will take 2.5 seconds or longer to run"""
message = await ctx.send(embed=discord.Embed(color=grab_color(), description="Please wait..."))
# grabbing the CPU / Memory status
psutil.cpu_percent()
# psutil needs some time to calculate (more info in... | 5,293,287 |
def _get_train_sampler(val_ratio:float, val_fold:int, trainset, horovod,
target_lb:int=-1)->Tuple[Optional[Sampler], Sampler]:
"""Splits train set into train, validation sets, stratified rand sampling.
Arguments:
val_ratio {float} -- % of data to put in valid set
val_fold {int} -- Total... | 5,293,288 |
def feature_reconstruction_loss(base, output):
"""
Compute the content loss for style transfer.
Inputs:
- output: features of the generated image, Tensor with shape [height, width, channels]
- base: features of the content image, Tensor with shape [height, width, channels]
Returns:
- scala... | 5,293,289 |
def clone(
src_dir: Path = arg_src_dir,
dest_dir: Path = typer.Argument(..., help="New project dir."),
new_project_name: Optional[str] = typer.Option(
None,
"--project-name",
"-p",
help="New project name. By default it's inferred from 'DEST'.",
),
):
"""Clone KiCad pr... | 5,293,290 |
def attempt_to_acquire_lock(s3_conn, lock_uri, sync_wait_time, job_name,
mins_to_expiration=None):
"""Returns True if this session successfully took ownership of the lock
specified by ``lock_uri``.
"""
key = _lock_acquire_step_1(s3_conn, lock_uri, job_name, mins_to_expiration... | 5,293,291 |
async def test_query_raw_partial_model(client: Prisma) -> None:
"""Transforms results to a partial model"""
posts = [
await client.post.create({'title': 'foo', 'published': False}),
await client.post.create({'title': 'foo', 'published': True}),
await client.post.create({'title': 'foo', '... | 5,293,292 |
def multiclass_nms(
multi_bboxes,
multi_scores,
score_thr,
nms_cfg,
max_num=-1,
score_factors=None,
multi_attrs=None,
multi_feats=None,
):
"""NMS for multi-class bboxes.
Args:
multi_bboxes (Tensor): shape (n, #class*4) or (n, 4)
multi_scores (Tensor): shape (n, #... | 5,293,293 |
def get_device():
""" Get the device on which running."""
return torch.device("cuda" if torch.cuda.is_available() else "cpu") | 5,293,294 |
def make_png_thumbnail():
"""Make a thumbail of the first page of a PDF and return it.
:return: A response containing our file and any errors
:type: HTTPS response
"""
f = request.files["file"]
max_dimension = int(request.args.get("max_dimension"))
with NamedTemporaryFile(suffix=".%s" % "pd... | 5,293,295 |
def rand_uuid():
"""Generate a random UUID string
:return: a random UUID (e.g. '1dc12c7d-60eb-4b61-a7a2-17cf210155b6')
:rtype: string
"""
return str(uuid.uuid4()) | 5,293,296 |
def get_logfile_name():
"""
Return the current logfile name
"""
return logging.getLoggerClass().root.handlers[0].baseFilename | 5,293,297 |
def sign(x, y):
"""Fortran's sign transfer function"""
return x * tf.math.sign(y) | 5,293,298 |
def filter_linksearchtotals(queryset, filter_dict):
"""
Adds filter conditions to a LinkSearchTotal queryset based on form results.
queryset -- a LinkSearchTotal queryset
filter_dict -- a dictionary of data from the user filter form
Returns a queryset
"""
if "start_date" in filter_dict:
... | 5,293,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.