content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def delta(v, d):
"""
Limits of v +/- d for array v and d.
"""
return zip(v - d, v + d) | 091d757135625e02a2d73b94d22446bd46520031 | 580,357 |
import torch
def gradient_clip(z: torch.Tensor, limits: tuple,
scheme: str='element-wise', **kwargs) -> torch.Tensor:
"""Clips the gradients within the specified limits using the specified scheme.
z: tensor of gradients to be clipped
limits: a tuple of (lower-limit, upper-limit)
scheme: the ... | c39ae45084e5bc1809262227cedc2445ee645e44 | 580,358 |
def dict2list_param(param):
"""Convert dictionary to list and add name by key."""
if isinstance(param, dict):
out = []
for key in param:
item = param[key]
item["name"] = key
out.append(item)
return out
return param | 86fb42be91598987c06c8f6f229b9948b3ffc59a | 580,360 |
def _preprocess(statement: str):
"""Preprocess the input statement."""
statement = statement.strip()
# Replace any occourance of " with '.
statement = statement.replace('"', "'")
if statement[-1] != ";":
statement += ";"
return statement | 48faedb198d937c8efbd655820510df147b11be2 | 580,361 |
def hex2rgb(str_rgb):
"""Transform hex RGB representation to RGB tuple
:param str_rgb: 3 hex char or 6 hex char string representation
:rtype: RGB 3-uple of float between 0 and 1
>>> from colour import hex2rgb
>>> hex2rgb('#00ff00')
(0.0, 1.0, 0.0)
>>> hex2rgb('#0f0')
(0.0, 1.0, 0.0)
... | 721b60379bf0fc5b9f6135ca89fbd56885e042de | 580,363 |
import requests
def get_nbu_exchange_rates() -> list:
"""
Fetch exchage rates of UAH to many foreign currencies from NBU.
Docs:
https://bank.gov.ua/ua/open-data/api-dev
Args:
None
Returns:
list - list of dictionaries which describe exchange rates for different currencies... | 1af8b7ba0210349e4bb2da445974b768743c24f0 | 580,366 |
def aliased2seabed(aliased, rlog, tpi, f, c=1500,
rmax={18:7000, 38:2800, 70:1100, 120:850, 200:550}):
"""
Estimate true seabed, given the aliased seabed range. It might provide
a list of ranges, corresponding to seabed reflections from several pings
before, or provide an empty list... | 0a4056c429be6109f35b63c7b970d0251d1a4134 | 580,367 |
def generate_offset6(value):
"""Returns the 6-bit two's complement representation of the number."""
if value < 0:
# the sign bit needs to be bit number 6.
return 0x1 << 5 | (0b11111 & value)
else:
return value | ee16e427eb69fa95f9b295059d20989295b81b80 | 580,369 |
def select_host_ids(self):
"""Select the IDs of all the hosts.
:return: A dict of host names to IDs.
"""
return dict((str(x[1]), int(x[0]))
for x in self.hosts.select().execute().fetchall()) | a5c44321f70aabe68c090e16630ad912749c1ddb | 580,370 |
def if_then_else(cond, trueval, falseval):
"""
Returns one of two values depending on choice bit
:param cond: Choice bit (function does not ensure that this is a bit)
:param trueval: Value if choice bit is 1
:param falseval: Value if choice bit is 0
:return: Value given by choice bit
"""
... | 6d5d6748a8206ee4400a6161c7cdf0994b1d4ab5 | 580,372 |
def sub(a, b):
"""
Returns the difference of the values at each index of a and b
Keyboard arguments:
a -- the first array
b -- the second array
Returns:
The difference of the arrays
"""
return([a[i] - b[i] for i in range(len(a))]) | d42180724caadf44c34823fe52cc44c4674cc534 | 580,375 |
def pkcs_7(b: bytes, size: int) -> bytes:
"""
PKCS#7 padding.
Given the block size, pad the input buffer,
so that the result is a multiple of the specified size.
Please note that this function will always pad,
even if the buffer is already a multiple of the size.
So, if size is 16 and b is ... | bbea53da9c5fa027ce5d8da5339bae0c9b798421 | 580,376 |
import importlib
def get_function(name):
"""
Returns a function from a fully qualified name or global name.
"""
# Check if already a function
if callable(name):
return name
if not isinstance(name, str):
raise ValueError(f'{name} must be callable or a string.')
if name in... | 5b11c3bf9335c1707aca1caa4843d49f9933c118 | 580,377 |
def _get_slave_address(config):
"""
Get the slave address to be used for the tests.
"""
return config.getoption("--slave-address") | 886c7a222e46d093e8d641724cca85b74ad5ccbd | 580,380 |
def producto_complejos(num1:list,num2:list) -> list:
"""
Funcion que realiza el producto de dos numeros complejos.
:param num1: lista que representa primer numero complejo
:param num2: lista que representa segundo numero complejo
:return: lista que representa el producto de los numeros complejos.
... | 9a4ff1c19d8d5bec69eb070c76cb384b28863e97 | 580,381 |
def _ListRunTargets(test_bench):
"""List the run targets in the test bench.
Args:
test_bench: a test bench
Returns:
a sorted list of run_target names
"""
groups = test_bench.host.groups
run_targets = []
for group in groups:
for run_target in group.run_targets:
run_targets.append(run_tar... | f46273366916030b8be5674372a4f375899aea7b | 580,382 |
def statement(engine, query):
""" Statement compiler for a given SQLAlchemy engine + query.
Arguments:
engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine
query (sqlalchemy.orm.Query): SQLAlchemy query
Returns:
Compiled engine-specific stateme... | 4ddd495a2c91ebaa0cf82a81e746467efefa1ffc | 580,387 |
def _path_to_short_path_mapping_for_singlejar(file):
"""Helper for the singlejar tool to create a path with mapping.
Args:
file: the file object
"""
return file.path + ":" + file.short_path | d3060bac2bf96256b98134d63bec72e08b1727d0 | 580,394 |
def _get_2d_field_and_dims(cube):
"""Get a 2D horizontal field, and the horizontal coord dims, from an nD cube."""
cube_x_coord, = cube.coords(axis='X', dim_coords=True)
cube_y_coord, = cube.coords(axis='Y', dim_coords=True)
cube_x_coord_name = cube_x_coord.name()
cube_y_coord_name = cube_y_coord.na... | 9f9ddc7db384b67a7ecefab84792477407768f10 | 580,401 |
import torch
def build_design_tensor(item_thetas, individual_assignment):
"""
Given a sequence of angles representing objects on S^1, and
assignments of those objects to individuals, creates a design tensor
of the appropriate dimensions.
:param torch.Tensor item_thetas: a tensor of dimension batc... | 16dfa55a98b04e67ba68e6b50d4e0ff53a38d5e3 | 580,403 |
from typing import List
from typing import Any
def group_with(predicate, xs: List[Any]):
"""Takes a list and returns a list of lists where each sublist's elements are
all satisfied pairwise comparison according to the provided function.
Only adjacent elements are passed to the comparison function
Original im... | cf54cb6dbdf7d217ec3c40b6690c7207067beafc | 580,405 |
def _lookup_ami_id(ec2, image_filters):
"""Returns AMI id that matches `image_filters`"""
images = ec2.get_all_images(filters=image_filters)
if len(images) == 0:
raise RuntimeError('cannot find image')
if len(images) != 1:
raise RuntimeError('found multiple images: {}'.format(', '.join(... | f735522526312f37ba01fd8affe07b362410fcfd | 580,408 |
from pathlib import Path
def strip_extension(path):
"""Function to strip file extension
Parameters
----------
path : string
Absoluate path to a slide
Returns
-------
path : string
Path to a file without file extension
"""
p = Path(path)
return str(p.with_suffi... | b05adb2a37b65e027504f3c85c9c44161f21d126 | 580,415 |
def get_commands(settings):
"""Opens the command file from the settings namespace.
Args:
settings: the argparse namespace from the cmdline
Returns:
tuple of (commands list, settings namespace)
"""
if settings.command_file:
settings.servers.insert(0, settings.command)
... | 02bc9552a8619cbf7a54d23dc92376ef36c6e1e2 | 580,416 |
import tqdm
def _progressbar(secs):
""" Makes a simple progress bar that goes away after it finishes """
return tqdm.tqdm(secs, leave=False, bar_format='{l_bar}{bar}') | 8d32cd56e804ef1aa871ff484ba494d702c7217b | 580,418 |
def namedtuple_to_dict(named_tuple):
"""Converts named tuple to flat dictionary"""
init_dict_flat = dict(named_tuple._asdict())
return init_dict_flat | 37d1a38ddab12abeacf10da4c81b956ebe4efbd3 | 580,429 |
def getTypeOfHourDay(x):
"""
This function returns a string representation of the type of hour of day
:param x: int value of hour
:return: string representation of the type of hour of day
"""
hour = int(x.split('.')[0])
if hour >= 0 and hour <= 5:
return 'Early Morning'
elif hour... | 5dc444638ad5cdcd2f3bb312f6dcad5a00d9bb66 | 580,430 |
def any_are_none(*args) -> bool:
"""
Return True if any arg is None.
"""
return any([arg is None for arg in args]) | 2deaf1d957f279a14e5f3f5ee155c01bea78b1a6 | 580,431 |
def percent_to_hex(percent: float) -> int:
"""Convert percent values 0-100 into hex 0-255."""
return int(round((percent / 100) * 255)) | 5b183908363466af15b09fb2d96c03885a579354 | 580,432 |
def recursive_set(data, keys, value):
""" Recursively slice a nested dictionary by a
list of keys and set the value.
Parameters:
data (dict): nested dictionary to get from.
keys (list): list of keys/indices to delve into.
value: value to store under key.
Raises:
KeyErro... | c76053f5df64a0ee325fa5908edf52e40fb43941 | 580,436 |
def identity(n):
"""
Get the identity permutation in :math:`S_n`.
:param n: Length of the permutation.
:return: Identity permutation.
.. rubric:: Examples
>>> identity(3)
(0, 1, 2)
"""
return tuple(range(n)) | ab0c785949078ea682ced7d155aded971ce1f561 | 580,440 |
def _is_positive_row(start, end,
feature_start, feature_end,
threshold):
"""
Determine if a feature annotation overlaps enough with a query
region to meet a minimal overlap threshold and be considered a
positive example of said feature.
Parameters
-----... | bc0b0cdd5e36a1257dbbbb03962d07199406bb28 | 580,442 |
def prompt_major(tracked_majors=("cs", "data", "cyber"),
minors_are_tracked=True,
majors_with_minors=None,
tracked_minors=("data", "cyber", "math")):
"""Prompts the user to enter their major. Will continue this until
'done' is entered. For certain majors, the u... | aaf5127fcf71627cf21d05982c89b23eac8ec2ec | 580,443 |
def transform_table(table):
"""
Transforms a contingency table into a point on a two-dimensional
plane, in which the distance to the origin shows the suitability
of a contingency table for separating cases and controls.
"""
# Yes, this ordering is correct. Please refer to our paper for
# more details.
... | 90b6f74c96c9149ce6d9abb96665e83e9c5722d3 | 580,446 |
def once(f):
"""Execute the given function only once and cache the result
Examples:
Without `once`
```python
>>> def f(x=[]):
... x.append(1)
... return x
>>> f()
[1]
>>> f()
[1, 1]
```
With `once`
```python
>>> @once
... def f(x=[]):
...... | a2107e40c998ad7a1f0ed885b113d6c266a7497c | 580,449 |
from time import time
def _gen_newid() -> str:
""" Generate new simulation ID. """
return str(time()).replace(".", "") | 79c9297aaf437633d5d80a1ae60de069a21139f5 | 580,450 |
def DropoutIfTraining(model, blob_in, blob_out, dropout_rate):
"""Add dropout to blob_in if the model is in training mode and
dropout_rate is > 0."""
if model.train and dropout_rate > 0:
blob_out = model.Dropout(
blob_in, blob_out, ratio=dropout_rate, is_test=False)
return blob_o... | 3ed3ab4114704360e74da19a084851a05f710be2 | 580,451 |
def generate_access_token_cache_key(token):
""" Generate cache key for WOPI access token
"""
return 'wopi_access_token_' + str(token) | fa43691988600ad66f771210dca276174b462d9c | 580,455 |
import gzip
def compress_file(src_file: str) -> str:
"""
Compress file to save space.
:return: compressed file name
"""
compressed_file = f"{src_file}.gz"
with open(src_file, "rb") as f_in:
with gzip.open(compressed_file, "wb") as f_out:
for line in f_in:
f... | cd77c01489a5720d2e4d3d7dd80bdef70ccb3bc9 | 580,461 |
from typing import Tuple
import math
def haversine(coord1: Tuple[float, float], coord2: Tuple[float, float]) -> float:
"""Compute distance in meters between to GPS coordinates using Harvesine formula.
source: https://janakiev.com/blog/gps-points-distance-python/
Args:
coord1: Tuple with latitude... | 2d3fc56349de4b17e0e3b6634a12cebc370e52be | 580,464 |
def getCentralRect(width, height, divisor=1):
"""Select central rectangle with reduced size.
MMstudio-like.
1: 2048 1536 ( 0, 0, 2048, 1536)
2: 1024 768 (512, 384, 1536, 1152)
4: 512 384 (768, 576, 1280, 960)
8: 256 192 (896, 672, 1152, 864)
16: 128 96 (960, 720, 10... | bb6f28bb5812da553dfa4cb8aa27e73880e49371 | 580,467 |
from typing import Iterable
from typing import Sized
def are_same_length(collections: Iterable[Sized]) -> bool:
"""Checks if all arguments have the same length."""
it = collections.__iter__()
first = next(it, None)
if first is not None:
first = len(first)
for elem in it:
if... | 2a858ab34f22c5090795ac38976f2e376879f5fe | 580,468 |
def sizecmp(dbent1, dbent2):
"""
Comparison function for (pdbid,dbtablist)
tuples used to sort database by size
"""
tab1 = dbent1[1][0]
tab2 = dbent2[1][0]
if len(tab1) < len(tab2):
return -1
elif len(tab1) > len(tab2):
return 1
else:
return 0 | d1375458c8ca5d3ab43251d037925cdfa4aa9a8f | 580,469 |
def temperature(self):
"""Return the temperature of the micro:bit in degrees Celcius."""
return 26.2 | abd3642be3f4538e590d56febb1a46d1503eb179 | 580,470 |
def quick_sort(iterable):
"""Sorts the iterable.
Quicksort sort is a divide and conquer, comparison sorting algorithm.
Conceptually, the steps are:
* Select a pivot from the collection.
* Partition the collection so that all the items less than the pivot come
before the pivot and all the items greater th... | 591e32308458d2326bd83d86d26733fb71bdc87f | 580,472 |
import random
def train_test_split(x, y, train_fraction):
"""
Randomly split data into training & testing set.
Inputs:
x: np.array or torch.Tensor, input feature vector
y: np.array or torch.Tensor, output vector to predict
train_fraction: float, number between 0 and 1 t... | f1234b73cd33a7a673d6d6425005ba8b682eeac6 | 580,473 |
def flatten_parameters(parameters):
"""This takes a hierarchy of parameters as obtained from the SSM parameter store,
and flattens it in simple key/value pairs {"AccountID1": "ProjectName1", ...}
Args:
parameters (dict): the parameters obtained from the SSM
Returns:
[dict]: a flat dict... | 286747fc797bc95e4fc6056e96239e1759fbafa3 | 580,474 |
def get_variant_id(variant):
"""Get a variant id on the format chrom_pos_ref_alt"""
chrom = variant.CHROM
if chrom.lower().startswith('chr'):
chrom = chrom[3:]
variant_id = '_'.join([
str(chrom),
str(variant.POS),
str(variant.REF),
str(variant.ALT[... | 0d928b9babf0defcbdc54f5b5ff0632b34cc9952 | 580,478 |
def manifestations(complex_types, abstract_type, is_obj = False):
"""Returns a list of type names which are manifestations of a given abstract type.
arguments:
complex_types (dict): as returned by xsd_to_dicts()[1]
abstract_type (str): the name of the abstract type of interest
is_obj (b... | 50bb06789917354890402fccfa9ac1a47e6bdc90 | 580,480 |
def build_kmatci_cli_options(namespace=None,
cluster_name="testcluster-1"):
"""Build a dictionary with defaults and user provided options"""
kmatic_options = {}
if namespace:
kmatic_options['namespace'] = namespace
kmatic_options['cluster_name'] = cluster_name
r... | ed491a1c3c165af56a01e07a2e5cc173e8459f10 | 580,494 |
def tag_fields_to_sql(fields):
"""Converts a list of fields stored in the tags hstore into a list of SQL fields:
name:en => NULLIF(tags->'name:en', '') AS name:en
"""
return [f"NULLIF(tags->'{fld}', '') AS \"{fld}\"" for fld in fields] | 5a5a6182206a6da4072441fd7b752ff8da1be08f | 580,500 |
import re
def GetCpuRamFromCustomName(name):
"""Gets the CPU and memory specs from the custom machine type name.
Args:
name: the custom machine type name for the 'instance create' call
Returns:
A two-tuple with the number of cpu and amount of memory for the custom
machine type
custom_cpu, the... | c562cd761a51400743b49cfefcda02873d847916 | 580,501 |
def expand_locations(ctx, values, targets = []):
"""Expands the `$(location)` placeholders in each of the given values.
Args:
ctx: The rule context.
values: A list of strings, which may contain `$(location)` placeholders.
targets: A list of additional targets (other than the calling rul... | 1c5f5a2774b45ed6fc45a403b9ff887e6f8d0fb3 | 580,502 |
import io
import gzip
def compress(data, compresslevel=9):
"""Compress data in one shot and return the compressed string.
Optional argument is the compression level, in range of 1-9.
"""
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f:
f.wri... | e16bc78cda447bd18e8a7bed0801fcb1968139ea | 580,503 |
import decimal
def pi_using_decimal_lib(precision):
"""Get value of pi via BBP formula to specified precision using decimal library.
See: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
:param precision: Precision to retrieve.
:return: Pi value with specified precision.
... | b98907ef04de8b4da33232a095a6ee2e61e1069c | 580,506 |
def lcfirst(string):
""":return: a string with its first character lowercase"""
if string:
if len(string) > 1:
return string[0].lower() + string[1:]
else:
return string.lower()
else:
return '' | ab077d24a176109df97ba9e22d99b775858975ae | 580,509 |
import torch
from typing import Optional
def mask_center(
x: torch.Tensor, mask_from: Optional[int], mask_to: Optional[int], mask_type: str = "2D"
) -> torch.Tensor:
"""
Apply a center crop to the input real image or batch of real images.
Args:
x: The input real image or batch of real images.... | 745000ac1d01934eb67f7e0b3c2bddb7d8d829c8 | 580,511 |
def get_reg_part(reg_doc):
"""
The CFR Part number for a regulation is contained within
an EAR tag, for a Federal Register notice it's in a REGTEXT tag. Get the
part number of the regulation.
"""
#FR notice
reg_text_xml = reg_doc.xpath('//REGTEXT')
if reg_text_xml:
return reg_te... | fbc5d49d188297ed26535e1bcf1ead03fb48ad28 | 580,513 |
def _is_equal_all_type(data, type_pattern):
"""
:type data: list or tuple
:type type_pattern: type
:rtype: bool
>>> _is_equal_all_type([1, 2, 3], int)
True
>>> _is_equal_all_type([1.0, 2.0, 3.0], float)
True
>>> _is_equal_all_type([1, 2.0, 3], int)
False
"""
if all(isins... | 4f9003cfd9b7e4b1b5072e2854bba480d094904a | 580,514 |
def slim_down_df(godb, df_clean, go_colname):
"""
Maps GO column to slim GO
:param godb: The GO database
:param df_clean: DataFrame with one GO term per row
:param go_colname: Name for the column with GO terms
:return: DataFrame with old GO terms replaced with slim GO terms
"""
# make a ... | cde763ff0495cca17d94c2f8c773f5e938e3af09 | 580,516 |
def _next_segment(truth, start_index):
""" Find the end of the segment
Args:
truth (:obj:`numpy.ndarray`): Ground truth
start_index (:obj:`int`): start index of current segment
Returns:
:obj:`int`: end index of current segment
"""
stop_index = start_index + 1
while stop... | 3c6f01721269c989fdb5a761e821e465ddf955dc | 580,518 |
def find_grade(total):
# write an appropriate and helpful docstring
"""
convert total score into grades
:param total: 0-100
:return: str
"""
grade = 0 # initial placeholder
# use conditional statement to set the correct grade
grade = 'A' if total>=93 else 'A-' if total >= 90 else 'B+' if total >= 87 ... | 61f2727851a1e92adc12e2ebd7f369e933398ccf | 580,519 |
def count_in_range(bot, bots):
"""
Returns the number of bots in range of the given bot.
"""
x, y, z, r = bot
# Get distances from the given bot
xs = abs(bots[:, 0]-x)
ys = abs(bots[:, 1]-y)
zs = abs(bots[:, 2]-z)
# Return count less than r
return sum(xs+ys+zs < r) | 53b0c5013748a5cb994ae19eb78189ac9c15b3c2 | 580,520 |
import re
def find_knock_params(args, knock_param_list):
"""Matches knock params to a list of arguments.
Args:
args: iterable of strings to check
knock_param_list: iterable of (string, {string: ?}) where
the first string being a regular expression, the remaining
dict i... | bd25a72e53da7407f1f7ce7939618e7f84e4fec8 | 580,523 |
import torch
import pickle
def obj2tensor(pyobj, device='cuda'):
"""Serialize picklable python object to tensor."""
storage = torch.ByteStorage.from_buffer(pickle.dumps(pyobj))
return torch.ByteTensor(storage).to(device=device) | 94f14dfa4ca648566d33117d2bf30ebfcaf64469 | 580,525 |
def make_test_class(model_tester, instance):
"""
Return a string with a plausible source code representation for a
ModelTester test class.
"""
base_names = ", ".join(cls.__name__ for cls in type(model_tester).__bases__)
base = f"""
class {model_tester.__class__.__name__}({base_names}):
... | be4fb250da9a29243c656e21f08b2fe0ede355e2 | 580,526 |
def aci_logo(dispatcher):
"""Construct an image_element containing the locally hosted ACI logo."""
return dispatcher.image_element(
dispatcher.static_url("nautobot_plugin_chatops_aci/aci-transparent.png"), alt_text="Cisco ACI"
) | d841ff491a499dd736959b29ac1e4be9af585b9c | 580,528 |
def get_entity_repr(serialization_context, serializer_cls, entity):
"""
Retrieves the dictionary representation of an entity.
:param serialization_context: The context used for serialization. This
is useful because it contains the request context, which in turns contain
the user who made the request... | 6a140a518251972e57f9b1cb2a1a82166cd64883 | 580,531 |
def insertion_sort(arr):
"""
Sorts a list using the insertion sort algorithm
Input: A list of integers
Output: A list containing the same integers as the input, but sorted in ascending order
For each element in the unsorted list, swap with the previous element until it is correctly placed in the sorted list
"""
... | 7fdc2921351025634df63e78d365aee811a12eec | 580,533 |
def identity(x):
""" Identity function: returns its input """
return x | 8c2e756571203f3c112874fdf5fd43094231c96c | 580,536 |
def uniqify(L):
"""
Uniqify a list, maintains order (the first occurrence will be kept).
"""
seen = set()
nL = []
for a in L:
if a in seen:
continue
nL.append(a)
seen.add(a)
return nL | 21d7715115e67b72e2011a70f3acf3d64a91a656 | 580,538 |
def get_command_pattern(prefix, command):
"""Get the uncompiled regex pattern for standard commands.
:param str prefix: the command prefix (interpreted as regex)
:param str command: the command name
:return: a regex pattern that will match the given command
:rtype: str
"""
# This regexp mat... | f2e1b1eae584c47c28d513947a5c55b57ebff8ac | 580,540 |
from typing import List
import math
def binary_search(array: List, target: int) -> int:
"""binary search algorithm using iteration
args:
array: must be ascending sorted array of items of the same type
target: the element you're searching for
returns:
int: the index of the target, if fo... | ed56795aedec30ce402e37246980fe553a86e8c7 | 580,541 |
def to_base01(color255):
"""converts base 255 color to base 01 color"""
color01 = [channel / 255.0 for channel in color255]
return color01 | 3c4754a6735cd26dfc20c066086408dca908d6ad | 580,543 |
def calculate_appointments(new_set, old_set):
"""
Calculate different appointment types. Used for making useful distinctions in the email message
Ex1: Addition of HONEOYE
new_set = {'LIVERPOOL', 'BROOKLYN', 'HONEOYE', 'KINGSTON'}
old_set = {'LIVERPOOL', 'BROOKLYN', 'KINGSTON'}
returns ->->
... | 250930cd63591984f563fc3fd0646168c6d4c9c3 | 580,544 |
def count_parameters(model):
"""Counts the number of parameters in a model."""
return sum(param.numel() for param in model.parameters() if param.requires_grad_) | 3ec4dfd45ee185fbb80def07e5d9c662131c3661 | 580,546 |
def get_local_name(full_name):
"""
Removes namespace part of the name.
Namespaces can appear in 2 forms:
{full.namespace.com}name, and
prefix:name.
Both cases are handled correctly here.
"""
full_name = full_name[full_name.find('}')+1:]
full_name = full_n... | 019093f9951e36bfaa6dc11e8f3d689df33c7691 | 580,548 |
def _getSetStatusLabel(exposure):
"""Returns the set status for an exposure or None."""
try:
return exposure._mangaExposure.set.status.label
except (AttributeError, IndexError):
return None | 0c46929c2f53f726c1d966a1774b3f3a53310498 | 580,549 |
def unique(x):
"""Convert a list in a unique list."""
return list(set(x)) | 105df86a8a5df1cd1981bbfab304bc4f8b759fa0 | 580,550 |
def http_ok_status() -> dict:
"""
Return an HTTP 200 ok status
"""
return {"statusCode":200, "body":""} | e88f3f4f2c7a4ac900d52f58f5601d3782ff4867 | 580,552 |
def has_stride_unity(layer):
"""Return `True` if the strides in all dimensions of a ``layer`` are 1."""
return all([s == 1 for s in layer.strides]) | c459e2b5ac0c1e3542d0946d4f1c3d2972034815 | 580,554 |
import pickle
def loads(value):
"""
Deserialize value using ``ujson.loads``.
:param value: str
:returns: output of ``json.loads``.
"""
if value is None:
return None
return pickle.loads(value) | 12d9944dbadf5ab1a5f2f06e72ae59de55cf9319 | 580,555 |
import torch
def build_linear_positions(index_dims, output_range=(-1.0, 1.0)):
"""
Generate an array of position indices for an N-D input array.
Args:
index_dims (`List[int]`):
The shape of the index dimensions of the input array.
output_range (`Tuple[float]`, *optional*, defaults to ... | 7995d88152b6b09b365b6e5fd58ae564b878da9b | 580,562 |
import pprint
def display_content(js):
"""
Displays JSON structure if user wants it.
dict -> None
"""
proved = {'y', 'yes'}
user_input = input('Would you like to see the JSON structure (y/n): ')
if user_input .lower() in proved:
print('Approved ..')
pprint.pprint(js)
elif user_input == 'q':
quit(0)
... | 4fd4b82758dd1d6e3aca7cdee2811e7eb0be024f | 580,563 |
def fail_safe(temperature, neutrons_produced_per_second, threshold):
"""
:param temperature: int - Temperatur of the reactor core
:param neutrons_produced_per_second: int - Neutrons produced per second
:param threshold: int - Threshold used to decide the criticality of the reactor
:return: str one o... | e2271b6e891afb979f626f5dc88d8b8a1e95d6d3 | 580,566 |
def counts_to_tfidf(count_matrix, idfs):
"""Convert counts to Tf-Idf scores given diagonal idf matrix."""
tfs = count_matrix.log1p()
tfidfs = idfs.dot(tfs)
return tfidfs | 5be57dfdadad41552576cb2c8821f2227347a437 | 580,573 |
import requests
def make_api_request(url, PARAMS):
""" Makes request to an end point to get data
Parameters:
url (str): The Api url end point
PARAMS (obj): The parameters to be used as arguments
Returns:
data (obj): Json object of the recieved data.
"""
... | f8ecdb1b580c5d6b62569d3dd398b8163bc01d21 | 580,574 |
import torch
from typing import OrderedDict
def load_torch_model(model, model_path):
"""Load state dict to model.
Args:
model: model to be loaded
model_path: state dict file path
Returns:
loaded model
"""
pretrained_model_dict = torch.load(model_path)
new_state_dict =... | c33e94d04222670cf85204abe0f721baa02d4842 | 580,577 |
def init_individual(ind_cls, model, value_func):
""" Initialises a JspSolution
:ind_cls: class to init (has to be drawn from JspSolution
:model: the JspModel to use
:value_func: a function to create the value array
"""
values = value_func()
return ind_cls(model, values) | da4d0082ae2087ad76175b5b0670d73e0dd983ae | 580,578 |
from typing import Dict
def get_location(grid: Dict, point: str) -> tuple:
""" Returns the coordinates of the requested point
Args:
grid (Dict): Dictionary of point names and coordinates
point (str): Point name
Returns:
(x, y) (tuple): Coordinates of the desi... | a4c596c17cfe42c670f4fc022072b960ffdbaa4c | 580,582 |
from typing import Tuple
def get_clicked_position(coords: Tuple[float, float], total_rows: int, surface_width: int) -> Tuple[int, int]:
"""Calculate and return row and column from the mouse coordinates given by pygame.
:param coords: mouse coordinates given by pygame
:param total_rows: number of rows; is... | 71d689a96555bdf2e02380facf2d560e6bc2d0a6 | 580,583 |
def calc_SSE(data, means, idx):
"""
Returns the total squared error.
"""
K = means.shape[0]
SSE = 0.0
# Loop over all clusters
for j in range(K):
# Squared distance from the cluster center
d = (data[idx==j, :] - means[j, :]) ** 2
# Total squared error
SSE +... | bf9b53ff58506a55cf9aa91c27aafe4c7e227475 | 580,584 |
def pixel_size_based_on_coordinate_transform(dataset, coord_trans, point):
"""Get width and height of cell in meters.
Calculates the pixel width and height in meters given a coordinate
transform and reference point on the dataset that's close to the
transform's projected coordinate sytem. This is only... | 4632fc8703d75b3e63974efc6383578a902639b2 | 580,585 |
def build_args(build_version, executor_jenkins_job=False,
jenkins_job=False, install_failure=False):
"""
Build a dictionary of arguments needed for the program
:param build_version: Couchbase build version of the job
:type build_version: str
:param executor_jenkins_job: Run with curre... | d06a08a17dd3fcb1e55901f1e0ceb2c4ea33b8ba | 580,586 |
def average_trade_net_profit(total_net_profit: float, total_trades: int) \
-> float:
""" Average trade net profit
.. math::
Total Net Profit / Total Trades = Trade Net Profit
:param total_net_profit: float of the total net profit
:param total_trades: int of the total number of trades e... | ccb64d531c3bcba3fdb13074e697bc156f3accde | 580,587 |
def move_spines(ax, sides, dists):
"""
Move the entire spine relative to the figure.
Parameters:
ax: axes to operate on
sides: list of sides to move. Sides: top, left, bottom, right
dists: list of float distances to move. Should match sides in length.
Example:
move_spines(ax, sides... | d0848c5ce109a18ce485d845b7bad9a635de6d37 | 580,591 |
from typing import Counter
def sock_merchant(colors: list[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([1, 2, 1, 2, 1, 3, 2])
2
"""
return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) | 5493bfea83141e253e94ad2f7090f5c19922360c | 580,592 |
import torch
def clipify(tensor, clip_len):
"""
Divide tensor of video frames into clips
Args:
tensor: torch.Tensor(C, n_clip*clip_len, H, W)
clip_len: int, number of frames for a single clip
n_clip: int, number of clips to form
Returns:
torch.Tensor(n_clip, C, clip_len... | e961b59b634c67faff1bb406ce87f11c426a13b3 | 580,595 |
def _generate_unique_filename_with_timestamp_and_increment(
timestamp, users_existing_manifest_files
):
"""
A helper function for _generate_unique_manifest_filename(), which facilitates unit testing.
Adds an increment to the filename if there happens to be another timestamped file with the same name
... | b3d9621b14f583986f456dcb23ad1c7cae638e20 | 580,599 |
import random
def select_user_agent(agent_list):
"""Select random user agent from pre-loaded list of agents. """
n_agents = len(agent_list)
agent = {}
agent["user-agent"] = agent_list[random.randint(0, n_agents-1)].replace("\n", "").replace("\"", "")
return agent | 95eb33781b25ee95e8e49b70eb8acf010124a927 | 580,600 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.