content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Callable
def get_lr_schedule_rnd(
rnd: int, lr_initial: float, lr_decay: float
) -> Callable[[int], float]:
"""Return a schedule which decays the learning rate after each round."""
lr_rnd = lr_initial * lr_decay ** rnd
# pylint: disable-msg=unused-argument
def lr_schedule(epoch... | cd44feb673bb51f4c32276dd302d776fa17407e8 | 641,492 |
def thisorthat(this, that):
"""
If this is None takes that otherwise takes this.
:param this:
:param that:
:return:
"""
if this is None:
return that
else:
return this | 25e9fcc024d93335f296284bcf0822a9075f13e0 | 641,493 |
def errfun_sae(x,y):
"""
Sum of absolute errors
"""
return sum(abs(x-y)) | 15dd69b81a2781e5f815e0db5fdfdf808b9dfb1e | 641,497 |
def _calculate_value_in_range(min_val, max_val, percentage):
"""Get the value within a range based on percentage.
Example:
A percentage 0.0 maps to min_val
A percentage of 1.0 maps to max_val
"""
value_range = max_val - min_val
return min_val + int(percentage * value_range) | 5b2104ba0db7bb168b014fb6214d1e495ce785d8 | 641,503 |
def fmt_item_ipv4(entry):
"""Format an IPv4 range with lo and hi addresses in decimal form."""
return "%d,%d,%s\n"%(entry[0], entry[1], entry[2]) | f4eddcf377c769fa7943b725acdc713fe5818f57 | 641,506 |
import torch
def loss_loglik(y_mean, y_logvar, x):
"""
Args:
y_mean of shape (batch_size, 1, 28, 28): Predictive mean of the VAE reconstruction of x.
y_logvar of shape (batch_size, 1, 28, 28): Predictive log-variance of the VAE reconstruction of x.
x of shape (batch_size, 1, 28, 28): Trainin... | 227fdc0d65bfed8c375f1baf506d1fc15bc16615 | 641,508 |
def find_shift(p, row, test_col):
"""Find how many cells to shift up when encountering possible merged cells."""
max_shift = 4
for shift in range(max_shift):
test_val = p[test_col + str(row - shift)].value
# If None,the cells were merged vertically; look up.
if test_val is not None:... | 8a366655581fcb4b533ded920eb121444d4af23d | 641,509 |
def selective_title(str):
"""
Convert string to Title Case except for key initialisms
Splits input string by space character, applies Title Case to each element
except for ["NHS", "PCN", "CCG", "BNF", "std"], then
joins elements back together with space
Parameters
----------
str : str
... | 742f2a929353424b74199fa5c3ac0a55276b811c | 641,510 |
def CLSID(MyClass):
"""Return CLSID of MyClass as string"""
return str(MyClass._reg_clsid_) | 4651515afc9863d77c770256a0cf3f4d0fe9cc58 | 641,512 |
import re
def spec_add_spaces(text: str) -> str:
"""Add spaces around / and # in `text`. \n (code from `fastai`)"""
return re.sub(r"([/#\n])", r" \1 ", text) | 3ca3534b91a877636ca463493c0ba7b5061fb19d | 641,513 |
def bubble_sort(lst: list) -> list:
"""Sort a list in ascending order. The original list is mutated and
returned. The sort is stable.
Design idea: Swap adjacent out-of-order elements until the list is sorted.
Complexity: O(n^2) time, O(1) space. Stable and in-place.
See quicksort, merge sort and ... | 0acc4561a7c1cbdd04ff9e3f054533b5a3e1aea4 | 641,514 |
def datetime2hr(dtime):
""" Calculate hours of day from datetime
Parameters
----------
dtime : (dt.datetime)
Universal time as a timestamp
Returns
-------
uth : (float)
Hours of day, includes fractional hours
"""
uth = dtime.hour + dtime.minute / 60.0 \
+ ... | f1434eff301ad953760cbc333b248e6c4e09afe6 | 641,515 |
def get_indeces(a, b):
"""
Extracts the indices multiple items in a list.
Parameters:
a: list. where we want to get the index of the items.
b: list. the items we want to get index of.
#example:
x = ['SBS1', 'SBS2', 'SBS3', 'SBS5', 'SBS8', 'SBS13', 'SBS40']
y = ['SBS1... | a4010d30dcf107983e9169f8adeb1e608c4e8bb2 | 641,517 |
import hashlib
def sha256(x):
""" Simple wrapper of hashlib sha256. """
return hashlib.sha256(x).digest() | 19f0d01d024058f8a35d9c4cf2faa4bf7ac5ea10 | 641,522 |
import yaml
def load(filename):
"""Load a dictionary from a yaml file.
Expects the file at filename to be a yaml file.
Returns the parsed configuration as a dictionary.
:param filename: Name of the file
:type filename: String
:return: Loaded configuration
:rtype: Dict
"""
with open... | 6df97f1d2554dde578298e35fd9c548fbf4382f4 | 641,523 |
def unique_family(data):
"""A list of unique families in the USDA data provided
Iterates through the DictReader for the family names, and returns a list of
names
Args:
A DictReader instance of the usda plant checklist
Returns:
A list of strings containing all the unique family... | 3040e4ce089a438aa6be6ea8ee55a9ba73ef1541 | 641,526 |
def raw(s):
"""
Coverts ScholarOne MS_ID into its base form (i.e. removes revision number if present)
"""
if '.R' in s:
s = s.split('.R')[0]
return s | 499d2a7c4d5056ccc0a61a01d31bb3c952b500f8 | 641,528 |
def is_inverted(c):
"""Returns True if the ordering of the candidates in the sentence is
inverted."""
if len(c) != 2:
raise ValueError("Only applicable to binary Candidates")
return c[0].get_word_start() > c[1].get_word_start() | a09c50b9e19d4dc43cb5276a12ab616302d93bcd | 641,529 |
import unicodedata
def remove_non_ascii(words):
"""Remove non-ASCII characters from list of tokenized words"""
# replaces non-ascii tokens with ""
# example £ §
new_words = []
for word in words:
new_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignor... | dd21eea6ec340bbfc6984d11424778ebe2725c1a | 641,532 |
def allsame(xs):
"""
Returns whether all elements of sequence are the same
"""
assert len(xs) > 0
return all(x == xs[0] for x in xs[1:]) | 74f4830345b152dedf6b269943a15308f223b5fa | 641,537 |
def bytes_to_gb(bytes_val):
""" Convert bytes to GB, rounded to 2 decimal places """
BYTES_IN_GB = 1024 * 1024 * 1024
gbytes = bytes_val / BYTES_IN_GB
return round(gbytes, 2) | 97837c3060aac2ac75af6e20a9589d3ad02a4d22 | 641,539 |
import hashlib
def generate_object_key(lookup_key, resolution, time_sample, morton_id):
"""
Generates an object key assumes iso=False. Based on spdb.spatialdb.object.AWSObject.generate_object_key()
Args:
lookup_key (str): lookup key collection_id&experiment_id&channel_id
resolution (int ... | e4d80f8a0b7fdb258dd5d121fcc30f6672827e0a | 641,543 |
from typing import Optional
from typing import Dict
def prepare_ids_str(ids: Optional[Dict]) -> Optional[str]:
"""Prepare string with EntitySet IDs."""
if isinstance(ids, dict):
# Generate ID string (id1='value',id2='value')
ids_str = ','.join("{}='{}'".format(k, v) for k, v in ids.items())
... | 6e1150f9596b4eb52ca210ceb1a65327783b4724 | 641,545 |
def _to_xml(number):
"""
convert Python number to XML String representation
Keyword Parameters:
number -- Python numeric variable
>>> _to_xml(0)
'0'
>>> _to_xml(0.09834894752)
'0.09834894752'
>>> _to_xml(None)
''
"""
if number is None:
return ''
return str(... | e41dc380cb2f9237b4946a2b7f008b0efdb907c5 | 641,546 |
from typing import Union
def check_outliers(lower_bound: float, upper_bound: float, current_value: Union[int, float]) -> bool:
"""
Check if a value is an outliers by comparing it with interquartile range
:param lower_bound: lower bound of interquartile range
:param upper_bound: upper bound of interqu... | 68468f67ca3ad0aacac95a524366afecf9dd02b2 | 641,547 |
def convert_cost_units(items):
"""To convert cost_unit choice type to it's
value. For example, for each item's cost_unit
tuple (type="per-packet", value="Per Packet")
will be converted to a `str` "Per Packet".
"""
for item in items:
item.cost_unit = item.cost_unit.value
return items | 8fd736ab68cd6008f33a944efcc4a8b5238af5e7 | 641,548 |
def ap(docs, n=10):
"""Average Precision"""
precision_values = [
len([
doc
for doc in docs[:idx]
if doc["relevant"] == "true"
]) / idx
for idx in range(1, n + 1)
]
return sum(precision_values) / len(precision_values) | 96542a81a4698ed7a97a9739328babeb7d73169f | 641,549 |
def shinglelize(text, shingle_size=3):
"""
Transform an input string to a list of shingles (or n-grams) with a given size.
Parameters
----------
text : string
Text to shinglelize
shingle_size: int, optional, default 3
Size of a shingle
Returns
-------
shingles : li... | 5bb6a6a7b6f886f509b1ef5c86bca30ab7e411ae | 641,553 |
def format_fold_run(rep=None, fold=None, run=None, mode="concise"):
"""Construct a string to display the repetition, fold, and run currently being executed
Parameters
----------
rep: Int, or None, default=None
The repetition number currently being executed
fold: Int, or None, default=None
... | ce14f51a97552d1292cf4fd1e3431ba36929d445 | 641,554 |
def read_tles(tle_path):
"""
Convert TLE text files in a given directory to a list of TLEs.
Parameters
----------
tle_dir : str
Path to the directory containing TLE .txt files.
Returns
-------
sats : List of lists.
Each internal list has the 3 lines of a TLE as its elem... | aa8aae9ec1eb286abf5fd5b4eb1474e807d3f34d | 641,557 |
import hashlib
def file_md5(file_path, buffer_size=1024 * 16):
"""
Calculate the md5 checksum for the provided file path
:param str file_path: path of the file to read
:param int buffer_size: read buffer size, default 16k
:return str: Hexadecimal md5 string
"""
md5 = hashlib.md5()
wit... | 9ab399e07f43c56801c41e266199a488d393f2f6 | 641,559 |
def unify_equivalent_indels(df):
"""Unify equivalent indels with highest somatic probability
Args:
df (pandas.DataFrame): df after left-alignment
-> all equivalent indels have same
'chr', 'pos', 'ref', 'alt'
Returns:
df (pand... | de4ca7bf81df6edf093d40739efe07dc85f2af89 | 641,564 |
import socket
def getFQDN(default=None):
"""Return the FQDN."""
fqdn = socket.gethostname()
if not '.' in fqdn:
return default
return fqdn | 33157712a5e4ec7bf198005389d2718d7895463c | 641,568 |
def check_for_reqd_cols(data, reqd_cols):
"""
Check data (PmagPy list of dicts) for required columns
"""
missing = []
for col in reqd_cols:
if col not in data[0]:
missing.append(col)
return missing | 3712046e59047e3c365279935fd93ee00c78237c | 641,572 |
def sanitize_html(text):
"""Prevent parsing errors by converting <, >, & to their HTML codes."""
return text\
.replace('<', '<')\
.replace('>', '>')\
.replace('&', '&') | b14e4836be1cda20c7b2ae5eb185234dc8b1d112 | 641,573 |
def get_overridable_template_name(name, plugin, core_prefix='', plugin_prefix=''):
"""Return template names for templates that may be overridden in a plugin.
:param name: the name of the template
:param plugin: the :class:`IndicoPlugin` that may override it (can be none)
:param core_prefix: the path pr... | d92d63483ef8953a58d198505b64f90277ece27e | 641,575 |
def ndre(nm790, nm720):
"""function returning a NDRE map.
NDRE is calculated as:
NDRE = (790nm - 720nm) / (790nm + 720nm)
which corresponds to:
NDRE = (NIR - RE) / (NIR + RE)
Parameters
----------
nm790 : numpy.ndarray
2d-numpy array of the target response at 790nm (NIR)
n... | 2989a9d9a2eb6dfd43584495890d4868f42090e1 | 641,583 |
from typing import Dict
def prettify_wildfire_rule(rule: Dict) -> Dict:
"""
Args:
rule: The profile security rule to prettify.
Returns: The rule dict compatible with our standard.
"""
pretty_rule = {
'Name': rule['@name'],
}
if isinstance(rule.get('application'), dict) an... | 1bf153d81a611c1cb275ed1025cd0680ebbf0267 | 641,587 |
def convert_v4_address_string_to_bits(ip_address):
"""
return v4 address string to bits
for example: '255.255.0.0' -> '11111111111111110000000000000000'
"""
return ''.join([bin(int(octet))[2:].zfill(8) for octet in ip_address.split('.')]) | a0d1fb710e600c47b41ee80e5aa5a5a40c73401b | 641,589 |
def is_closed(instance, *args, **kwargs):
"""
Helper function to test if some instance is closed (to be used with
``raise_if`` decorator)
:param instance: some instance with ``is_closed`` property accessible
:returns: value of ``instance.is_closed`` or False
"""
return getattr(insta... | 307178eacc07a39743243fd693af414b40619c74 | 641,590 |
def find_sublist_containing(el, lst, index=False):
"""
Parameters
----------
el :
The element to search for in the sublists of `lst`.
lst : collections.Sequence
A sequence of sequences or sets.
index : bool, default: False
If False (default), the subsequence or subset co... | 6c9edb33091a1eca96cb77f239abc365bd10d22a | 641,591 |
def round_coordinates(cell_poly):
"""
Rounds the coords of the polygon
Only implemented to pass tests.
:param cell_poly: polygon feature
:returns: polygon feature
"""
coords = cell_poly["geometry"]["coordinates"]
coords = [
[[round(coord, 6) for coord in point] for point in l... | cd6d2de31670b166a1577f4bcb67a3effa655f57 | 641,593 |
def user_is_mentor(user):
"""Check if a user belongs to Mentor group."""
return user.groups.filter(name='Mentor').exists() | 34de16d61b79b189b591c43dbb67f62d164978d2 | 641,594 |
def dynamic_import(name):
"""
Dynamically import a class from an absolute path string
"""
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | 7467cf8050b0b700a14d72e39ef8d8a7c1652ad7 | 641,598 |
def _get_node_value(nod):
"""XML parsing helper for extracting text value from an ElementTree Element. No error checking performed.
Parameters
----------
nod : ElementTree.Element
the xml dom element
Returns
-------
str
the string value of the node.
"""
if nod.text... | 0c01311eb347b52c4e9971c864f93a7a904cd245 | 641,601 |
def n_eff(dlnsdlnm):
"""
Return the power spectral slope at the scale of the halo radius,
Parameters
----------
dlnsdlnm : array
The derivative of log sigma with log M
Returns
-------
n_eff : float
Notes
-----
Uses eq. 42 in Lukic et. al 2007.
"""
... | 33b433b18591afa0b12cf9adcd5f62f5db3e12d9 | 641,602 |
def apply_weight_decay_data_parameters(args, loss, class_parameter_minibatch, inst_parameter_minibatch):
"""Applies weight decay on class and instance level data parameters.
We apply weight decay on only those data parameters which participate in a mini-batch.
To apply weight-decay on a subset of data para... | 8d979f01e62091bd81c66bdc283e3986638f4e34 | 641,604 |
def compute_hash(*args):
"""Compute a hash vlaue from all given arguments."""
return hash(args) | 1632f22c3127cfa1ad50144674a1a8cd26e7e480 | 641,606 |
def get_ospf(engine):
"""
Get OSPF settings for the engine
:return: dict of entries only if OSPF is enabled
"""
ospf = engine.dynamic_routing.ospf
data = dict(
enabled=ospf.status,
router_id=ospf.router_id)
if ospf.status:
data.update(ospf_profile=ospf.profile.na... | d6a5a0e08dcc75705bd6c4a692027c91f924676d | 641,608 |
def clean_name(name):
"""Replace dashes and spaces with underscores"""
return '_'.join(name.split()).replace('-', '_') | 5de49ec064b3e6b4359d29d822fd732d080f8a43 | 641,612 |
def flatten_dictionary(dictionary):
"""Get a list of tuples with the key value pairs of the dictionary. """
result = []
for k, s in dictionary.items():
for v in s:
result.append((k, v))
return result | 7da8eeb1716cbd1664b921943cb70774ced2cbe7 | 641,613 |
def flake8(ctx, noerror=False):
"""check the project files for correctness with flake8"""
return ctx.run(f'python -m flake8 w3modmanager{" --exit-zero" if noerror else ""}').exited | 2bb91c621d877c388daa28aabbe7b513184cac9a | 641,614 |
import shutil
def create_make_command(keyboard, keymap, target=None):
"""Create a make compile command
Args:
keyboard
The path of the keyboard, for example 'plank'
keymap
The name of the keymap, for example 'algernon'
target
Usually a bootloader.... | dccd741fec64799afa9fcabc18a7e458d60c2b4f | 641,615 |
import binascii
def gotenna_to_intelhex(firmware_data):
"""
Convert raw bytes in goTenna firmware to the hex encoded INTELHEX
"""
firmware_bytes = bytearray(firmware_data)
output_bytes = bytearray()
while firmware_bytes:
header_byte = firmware_bytes.pop(0)
assert header_byte =... | 32274ee02574098795f23741d09a9f798c7c240d | 641,618 |
def arg_list(items, prefix=''):
"""Process a list or string of arguments into a string containing them
Used so users can pass arguments as a string or list in the configuration file.
:param items:
:param prefix:
:return:
"""
if not items:
return ''
list_of_items = items.split(... | 2374d9504190452d0a9e17e5b3330c57fe988fc5 | 641,621 |
def is_number(s):
"""
Args:
s: A string
Returns:
True iff the string represents a number
"""
try:
float(s)
return True
except (ValueError, TypeError):
return False | 00da2e9d30d4a37a5f4ec97c34aa261c06da08d8 | 641,623 |
def remove_non_name_matches(entries, query_obj):
"""Filter out Person entries if there is no overlap between names_prefixes
and query_obj.query_words."""
filtered_entries = []
for entry in entries:
for word in query_obj.query_words:
if word in entry.names_prefixes:
fi... | 06df0c35891528003ce15c083c4d0d0cf3152be9 | 641,625 |
def rotate_matrix(matrix):
"""
Rotate the n x n matrix 90 degrees clockwise.
Given the original matrix.
initial_matrix = [
[1, 2],
[3, 4]
]
The rotated matrix should look like this.
rotated_matrix = [
[3, 1],
[4, 2]
]
... | a3f77f4dcc96fa519af561c4e9c5b351a48dc549 | 641,627 |
def commonprefix(m):
"""Return the longest prefix of all list elements."""
if not m: return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0: return ''
break
... | 4bac90c54def505cf3fc3573c079030f33cddc7f | 641,632 |
def isnamemacro(function):
"""Return whether the macro function `function` has been declared as an identifier macro."""
return hasattr(function, "_isnamemacro") | c859bffb1c85e207c5119f57bd1d11bd479ad1fd | 641,634 |
def get_class_properties(class_name: str, vocab: dict) -> list:
"""
Return all the properties of the given class.
"""
properties = list()
defines = vocab['@graph']
for obj in defines:
if obj.get('propertyOf'):
propertyof = obj['propertyOf'].split('#')[1]
if proper... | a0f74c9d3bf78b821e5c1af19256628bdc3cecac | 641,635 |
def updated_with(orig_dict, *new_values):
"""Return a copy of orig_dict updated with new_values.
New keys are added, and the values of existing keys will take the
values in new_values.
You can specify more than one update dictionary.
They are applied in order, so the values of any keys in later di... | eb32696da3d807804c4b1f8cf85405eac2c5ec5a | 641,636 |
def add_three(one, two, three):
"""Adds three values together and returns it."""
return one + two + three | a35b80364cc823c4eb306d4a84bfa12db79252f6 | 641,637 |
from typing import List
def find_all_matchstrings_in_string(string: str,
matchstrings: List[str]):
""" check if string has all matchstrings in it """
return all([matchstring in string for matchstring in matchstrings]) | 60e8ba7f3ce3b63b0e380a536ded8bad58a0f53c | 641,639 |
import torch
def has_tensor(obj) -> bool:
"""
Given a possibly complex data structure,
check if it has any torch.Tensors in it.
"""
if isinstance(obj, torch.Tensor):
return True
elif isinstance(obj, dict):
return any(has_tensor(value) for value in obj.values())
elif isinsta... | ed70ce8443625ab66d7b36b3aa57c799855b7fc5 | 641,640 |
def first_not_none(itr):
"""
returns the first non-none result from an iterable, similar to any() but return value not true/false
"""
for x in itr:
if x:
return x
return None | de04721394fd45f8d3886b6adb17a9db0893825b | 641,641 |
def max_with_none(first, second):
"""Returns the maximum of the two inputs, ignoring Nones."""
if first is None:
return second
elif second is None:
return first
else:
return max(first, second) | 63c9ea7d9095994fe2ae8462501e785e8918a747 | 641,647 |
def _quote_filter_value(s):
"""Put a string in double quotes, escaping double quote characters"""
return '"%s"' % s.replace('"', r'\"') | 9a6961c731408759083fad399ea4a7250d052830 | 641,654 |
import random
def encode_string(value):
"""
Encode a string into it's equivalent html entity.
The tag will randomly choose to represent the character as a hex digit or
decimal digit.
"""
e_string = ""
for a in value:
e_type = random.randint(0, 1)
if e_type:
en... | 76af82e3495c605a5ddaf3df9bdd352749856c07 | 641,657 |
def _default_kwargs_split_fn(kwargs):
"""Default `kwargs` `dict` getter."""
return (kwargs.get('distribution_kwargs', {}),
kwargs.get('bijector_kwargs', {})) | 3d39d73ba6d7bfd673fa7216f3e386e61abca795 | 641,658 |
def worker_process_control(_destination, _destination_process_id, _command, _reason, _message_id, _source,
_source_process_id, _user_id):
"""
Creates a worker process control message. Tells a worker process to stop, kill, etcetera.
"""
return {
"destination": _destinat... | 3f54e25a6b97458176c30a1b0d4b36b3ff2b6688 | 641,659 |
def features(indel_class):
"""Manage feature names
Args:
indel_class (str): "s" for single-nucleotide indels (1-nt indels)
"m" for multi-nucleotide indels (>1-nt indels)
Returns:
features (list): a list of feature names
"""
assert indel_class == "s" or in... | fcfbe4a4f5df5b25222d4d8a52a49d77849f9683 | 641,664 |
def get_var_names(variable):
"""
get the long variable names from 'flow' or 'temp'
:param variable: [str] either 'flow' or 'temp'
:return: [str] long variable names
"""
if variable == "flow":
obs_var = "discharge_cms"
seg_var = "seg_outflow"
elif variable == "temp":
o... | 2d9298f9181cc3375039a75e0dff04050a3a138e | 641,665 |
def replace_module_suffix(state_dict, suffix, replace_with=""):
"""
Replace suffixes in a state_dict
Needed when loading DDP or classy vision models
"""
state_dict = {
(key.replace(suffix, replace_with, 1) if key.startswith(suffix) else key): val
for (key, val) in state_dict.items()
... | 4c85e37bd8e871cfb71786839f1defe0bda23f7c | 641,667 |
def check_response(response):
"""Check the status of responses from polyswarmd
Args:
response: Response dict parsed from JSON from polyswarmd
Returns:
(bool): True if successful else False
"""
status = response.get('status')
return status and status == 'OK' | 49ded72d3dda5c88add399923b0e14c5ec2ff89d | 641,669 |
def stations_level_over_threshold(stations,tol):
"""This function returns a list of tuples, where each tuple holds a station at which the latest relative water level is over tol and the relative water level at the station"""
stations_over_threshold = []
for station in stations:
relative_level = stat... | da6b32eaf4970ef8e4845aa292e0074a9cb3df08 | 641,675 |
def Collect(iterable, container=list):
"""
iterable >> Collect(container)
Collects all elements of the iterable input in the given container.
>>> range(5) >> Collect()
[0, 1, 2, 3, 4]
>>> [1, 2, 3, 2] >> Collect(set) # doctest: +SKIP
{1, 2, 3}
>>> [('one', 1), ('two', 2)] >> Collect... | 7f69937badb3626c0b85fec8db6aab14887f19b2 | 641,676 |
def unread(thread, user):
"""
Check whether there are any unread messages for a particular thread for a user.
"""
return thread.user_threads.filter(user=user, is_read=False).exists() | e843005145e69261a2bebaee50443219d8f4b2e6 | 641,677 |
import torch
def hard_example_mining(dist_mat, is_pos, return_indices=False, bound=9999.0):
"""For each anchor, find the hardest positive and negative sample.
Args:
dist_mat: pair wise distance between samples, shape [N, M]
is_pos: positive index with shape [N, M]
Returns:
dist_ap: pytor... | f3d2825056ed8c49d7241155b685ccf893244a8a | 641,678 |
def add(a, b):
"""
Return the addition of the arguments: a + b
>>> add(1, 2)
3
>>> add(-1, 10)
9
>>> add('a', 'b')
'ab'
>>> add(1, '2')
Traceback (most recent call last):
File "test.py", line 17, in <module>
add(1, '2')
File "test.py", line 14, in add
... | 8c3bdaca7beea41ec661cabd075b5c2ef042c121 | 641,679 |
def _get_vector_identifier(line):
"""Return the identifier from the vector string. """
return line.split()[0] | f3d8dd43d1e49461474fe855fec1ecd7707d34f7 | 641,681 |
def clip(data, start_idx):
"""Return data[start_idx:]"""
return data[start_idx:] | 90fa56f3bf5f95303274f052bcd3baf7518436a1 | 641,687 |
def normalizeAudio(audio, width):
"""
Returns audio file that with range +/-1
:param audio: numpy array of audio samples
:param width: sample width in bytes (1 = 8 bit, 2 = 16 bit...)
:returns: noramlized audio file
"""
max_val = 2**(8*width-1)
return audio/max_val | 0210a4d1435577a6f30b009ee5b08917c8e0db29 | 641,690 |
def compare_versions(version1, version2, split_char="."):
"""
Compares two version strings.
Each string is to be split into segments by the given string.
Each segment is only compared by numerical character value (e.g. a, b, rc are ignored)
Ordinality is determined by the first non equal numeric seg... | 458eab960571a5acd9dae5729f6276e416651bcc | 641,692 |
def IsWithinTMRegion(pos, posTM):#{{{
"""Check whether a residue position is within TM region
"""
isWithin = False
for (b,e) in posTM:
if pos >= b and pos < e:
return True
return False | e12106e8857809dbf31fd88a39e3ea38440a72d7 | 641,695 |
def filter_private_methods(method):
"""Simple filter method. Ignores private functions"""
return not method.startswith('_') | b9cd2881c70e340b0311d8ac349ea2d082d1c156 | 641,702 |
def trunc_time_minute(date):
"""
Truncate an object of type DateTime with time to 00:00:00
:param date: Date for truncate
:return: Date truncated
"""
return date.replace(second=0, microsecond=0) | 3d7345254f9e38bd8085b1de3adea1cbc5acd642 | 641,705 |
def fifo_path(dest, channel, epoch):
"""Construct full FIFO path.
:param dest: Path to directory of FIFO
:param channel: FIFO name
:param epoch: Integer appended to FIFO name indicating the training epoch
:return: full FIFO path
"""
return dest + '/' + channel + '_' + str(epoch) | 9f4b2a1de8778646f639416f5d790231d206e3ca | 641,706 |
def _area(bbox):
"""Computes area of a 2D bounding box.
Args:
bbox: A dict with keys 'x1', 'x2', 'y1', 'y2' encoding spatial
co-ordinates.
Returns:
The area of the bounding box.
"""
return (bbox['x2'] - bbox['x1']) * (bbox['y2'] - bbox['y1']) | 2df8bcb275f2592477dfcd08479df374b7a38874 | 641,707 |
import requests
def get_alert(service, resource):
"""
Get an entry from alerta
:param service: alerta service
:param resource: unique resource id of required entry
:return: dict
"""
resp = requests.get(service.data['url'] + "/alerts",
params={'environment': service.... | 001f21c83ad085a27b25616b9a4d568eb5f6625b | 641,708 |
from pathlib import Path
def gen_geojson(conn, model_num):
""" Queries postgres and returns a geoJSON file with boundary data
and properties that give us demographics and transit access data.
Parameters
----------
model_num: int
The number of the model in question
Returns
... | d6c308923776d3e8b1e6e182572b8cc0dc39176c | 641,711 |
def get_member_hp(checks, member_uuid, pool_uuid):
"""Helper function to find a members health in a given pool
:param checks list: https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Pool/#healthMonitor
:param member_uuid: server UUID we are looking for
:param pool_uuid: Connection p... | fca01210c9e0dc592be732dca926c3ef95282a25 | 641,715 |
def clip_candidates(a, b, numCandidates):
"""
Clip retrieved candidates to numCandidates or, in case
one method retrieived a smaller list than numCandidates,
clip retrieved candidates to the same number as the smaller
list.
"""
a = a[:numCandidates]
b = b[:numCandidates]
if len(b) <=... | 5016b96d1d1e62374f76179968d1b71f57b2619d | 641,719 |
def config_lower_get(tgt_dict, query, default=None):
"""
Case Insensitve dict get.
:param tgt_dict: Dictionary
:param query: String to look for key from
:param default: Default value to return if not found.
:return: Value in dict if found, otherwise default
"""
value = {k.lower(): v for ... | 5cacbd397491c485804ef5e24cf053aef45e4a4d | 641,723 |
def flatten_nested(iterable):
""" Recursively flatten nested structure of tuples, list and dicts. """
result = []
if isinstance(iterable, (tuple, list)):
for item in iterable:
result.extend(flatten_nested(item))
elif isinstance(iterable, dict):
for key, value in sorted(iterab... | 794ef2d05fd9bd1541c3a267cdeefc4337d82584 | 641,724 |
import base64
def _b64decode(s: str) -> bytes:
""" Base 64 decodes a string to bytes. """
return base64.b64decode(s.encode("utf-8")) | 587918e0cce5712fdaa9093d14eb3814766fc566 | 641,725 |
def alias(aliases):
"""Decorator for slashcommand aliases that will add the same command but with different names.
Parameters
----------
aliases: List[:class:`str`] | :class:`str`
The alias(es) for the command with wich the command can be invoked with
Usage:
.. code-block::
... | 95c20f61348dc043ced53f4e95fac0fb24ee117f | 641,732 |
from typing import Dict
from typing import Any
def response_state_from_mediation_record(record: Dict[str, Any]):
"""Maps from acapy mediation role and state to AATH state"""
state = record["state"]
mediator_states = {
"request": "request-received",
"granted": "grant-sent",
"denied... | 15062fc26f13d907299793df692bf1e39932691c | 641,733 |
def splitname(obj):
"""
Given an object that has a __module__ and __qualname__,
return a list of name components from both.
If __module__ is None, 'builtins' is used.
"""
modname = obj.__module__ or 'builtins'
return modname.split('.') + obj.__qualname__.split('.') | 2fb223234d01aefa6a9e70269aee36df770e6bae | 641,738 |
def double_quote(text):
"""double-quotes a text"""
return '"{}"'.format(text) | def68008cda5f9cccbaf8d88b6f96df2076938bd | 641,740 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.