content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def interceptable_sender(func, key=None):
"""Get the signal sender to intercept a function call.
:param func: The function that should be intercepted
:param key: An optional key in case using just the function
name would be too generic (e.g. most utils)
"""
name = '{}.{}'.format(fun... | 6c74ee13b8ef60e712cf215d08ede801a4535fc1 | 693,523 |
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''').replace(":",":") | eb49c178c7f80766054371c973da156bf882f82d | 693,524 |
def is_float(s: str) -> bool:
""" Checks if input string can be turned into an float
Checks if input string can be turned into an float
:param s: input string
:type s: str
:return: True if input can be turned into an float
False otherwise
:rtype: bool
"""
try:
out = fl... | 553bee103337e46b73c710799a921f18950a19b3 | 693,525 |
def db2pow(x):
""" Converts from dB to power ratio
Parameters
----------
x - Input in dB
Returns
-------
m - magnitude ratio
"""
m = 10.0 ** (x / 10.0)
return m | f8f03139ccca73fe9aff97d56d6e41dbcaf3efb9 | 693,528 |
def _spreadsheet_list(api):
"""sheets 파일 리스트(google cloud account 내에 있는 모든 spreadsheets)
Args:
api (obj): gspread object
Returns:
[dict]: {<title>: <id>}
"""
return {
spreadsheet.title: spreadsheet.id
for spreadsheet in api.openall()
} | 8625c5cf7ec7460683ba65b21593b387d33fa8af | 693,533 |
from typing import Tuple
def get_text_dimensions(text: str, font) -> Tuple[int, int]:
"""
Compute the approximate text size for the given string and font.
:param text: String of text. Will be split over line breaks.
:param font: The font to use.
:return: Width and height of the text.
:raises ... | ed876693946637543c8fa453d8d28625148ef773 | 693,534 |
import configparser
def load_config(config_file_path):
""" Parse a WORC configuration file.
Arguments:
config_file_path: path to the configuration file to be parsed.
Returns:
settings_dict: dictionary containing all parsed settings.
"""
settings = configparser.ConfigParser()
... | 6cd20957234bec969b9e54fd35fe3965e6239c09 | 693,535 |
def strHypInd(i, j):
""" Returns string identifier for a hyperplane of ith and jth observation,
regardless of ordering.
"""
if i > j:
i, j = j, i
return str(i) + '-' + str(j) | f66c462d8ba0ca62878cfa92db7ce7d06bf47024 | 693,538 |
import random
def randomMAC(type="xen"):
"""Generate a random MAC address.
00-16-3E allocated to xensource
52-54-00 used by qemu/kvm
The OUI list is available at http://standards.ieee.org/regauth/oui/oui.txt.
The remaining 3 fields are random, with the first bit of the first
random field set 0... | ec5af0a24439f888376bf770e243193b10c9a5a3 | 693,539 |
def empty(list):
""" Checks whether the `list` is empty. Returns `true` or `false` accordingly."""
return len(list) == 0 | c1e94267226053e555627728dd4fc12cb337ff8d | 693,541 |
def moments_get_skew(m):
"""Returns the skew from moments."""
return m['mu11']/m['mu02'] | 03ece117646fa56719dee8abffc01226706100a9 | 693,543 |
def sanitize_str(string):
""" Sanitize string to uppercase alpha only """
return filter(str.isalpha, string.upper()) | e693d61f19ab56103395a798c930a1b9937eafd5 | 693,547 |
def parse_h5_attr(f, attr):
"""A Python3-safe function for getting hdf5 attributes.
If an attribute is supposed to be a string, this will return it as such.
"""
val = f.attrs.get(attr, None)
if isinstance(val, bytes):
return val.decode("utf8")
else:
return val | 75774def6f8ac3abf8c78aa97557fcb91cb2628e | 693,549 |
def invert_dict(d):
"""Invert a dictionary's key/value"""
#return dict(map(lambda t: list(reversed(t)), d.items()))
return dict([(v, k) for k, v in d.items()]) | b1327055cc613c0701355409e1d782f334bbe57b | 693,551 |
def strhash(*args, **kwargs):
"""
Generate a string hash value for an arbitrary set of args and kwargs. This
relies on the repr of each element.
:param args: arbitrary tuple of args.
:param kwargs: arbitrary dictionary of kwargs.
:returns: hashed string of the arguments.
"""
if kwargs:... | 8b56ab2c205e8d5788d6c3d1788c8353400c8f79 | 693,553 |
def over(*, aalpha, oomega):
"""Define the dyadic over ⍥ operator.
Monadic case:
f⍥g ⍵
f g ⍵
Dyadic case:
⍺ f⍥g ⍵
(g ⍺) f (g ⍵)
"""
def derived(*, alpha=None, omega):
if alpha is None:
return aalpha(alpha=alpha, omega=oomega(omega=omega))
else:
... | 68079977befc9ec576aaf8706579d05864f21d24 | 693,554 |
def has_duplicates2(t):
"""Checks whether any element appears more than once in a sequence.
Faster version using a set.
t: sequence
"""
return len(set(t)) < len(t) | 7c815aa1467648b3c5aa405b6359ba10d911ac77 | 693,555 |
def box_outside_box(v1, v2):
"""return true if v1 is outside v2"""
return (v1['p1'] < v2['p1']).all() and (v1['p2'] > v2['p2']).all() | dd25f563a1064a6b09d30f0f58932e1dbb7912ae | 693,557 |
def test_default_timeout(monkeypatch, fake_response, aqhttp):
"""Timeout should default to aqhttp.TIMEOUT is timeout is absent from
aqhttp.post."""
# A fake requests sessions object
class mock_request:
@staticmethod
def request(method, path, timeout=None, **kwargs):
assert t... | 44188a45e5a2780669377297b12b252b71663576 | 693,559 |
from pathlib import Path
from typing import Optional
from typing import Union
from typing import List
from typing import Iterator
import itertools
def directories(
PATH: Path,
INCLUDES: Optional[Union[str, List[str]]] = None,
EXCLUDES: Optional[Union[str, List[str]]] = None,
) -> Iterator[Path]:
"""It... | b0c3db317f298b75cd70844ca9538612e0e0a0c2 | 693,563 |
import glob
def get_file_names(directory):
"""
Get the names of the completed csv files used to store the plot details
"""
return glob.glob(directory + '/*.csv') | 49afbb85c7cf66c9f7df95a6dfa35b4005c83195 | 693,565 |
def _doublet(plist, J):
"""
Applies a *J* coupling to each signal in a list of (frequency, intensity)
signals, creating two half-intensity signals at +/- *J*/2.
Parameters
---------
plist : [(float, float)...]
a list of (frequency{Hz}, intensity) tuples.
J : float
The coupli... | 5b88ec2889bcbfecf6001e1c84fabe835ed4f678 | 693,569 |
def get_object_root_module(obj):
"""
Get the obj module version
:param T obj: Any object
:rtype: str
:return The root module of the object's type
"""
return type(obj).__module__.split('.')[0] | 2cfa6e05d1215227873dbd122112ef34b0795550 | 693,571 |
def _string_to_bool(value, triple=True):
"""Translates a string into bool value or None.
Args:
value: The string value to evaluate. (string)
triple: If True, None is returned if not found, if False, False
Returns:
The a bool value of tag or if triple is True None.
"""
if v... | b46ee6d517e353fae8d28caba6c20e80bd894a5e | 693,574 |
def int2bin(i: int) -> str:
"""Convert an 8-bit integer to a binary string.
Args:
i (int): Integer value to be converted.
Note:
The passed integer value must be <= 255.
Raises:
ValueError: If the passed integer is > 255.
Returns:
str: A binary string representatio... | e95fe826a432ec4e680864fbc36fcbf188912289 | 693,576 |
def join_regex(regexes):
"""Combine a list of regexes into one that matches any of them."""
if len(regexes) > 1:
return "(" + ")|(".join(regexes) + ")"
elif regexes:
return regexes[0]
else:
return "" | 616a4b51a64244e14b6029a91026f65a20077f06 | 693,578 |
def num_misses(df):
"""Total number of misses."""
return df.Type.isin(['MISS']).sum() | 72bb2277b5de1aa686cdaa1772a2d85f06d41a9e | 693,579 |
def explain_node_str(root, indent=0):
"""Returns an indendeted outline-style representation of the subtree.
"""
indent_string = " " * indent
buf = f"{indent_string}Node<item={root[0]}>"
if not root[1] and not root[2]:
buf += "\n"
else:
buf += ":\n"
if root[1]:
b... | 6bc6136fc12171841a0988b79107ab4032b108a3 | 693,582 |
def check_keys_in_dict(dictionary, keys):
"""
Checks that a list of keys exist in a dictionary.
Parameters
----------
dictionary: dict
The input dictionary.
keys: list of strings
The keys that the dictionary must contain.
Returns
-------
bool:
Returns *True... | a28a8a97e0a51196080c92400f01cb08b9ac6cc7 | 693,583 |
def parse_dhm_request(msg: str) -> int:
"""Parse client's DHM key exchange request
:param msg: client's DHMKE initial message
:return: number in the client's message
"""
return int(msg.split(':')[1]) | 8664b1998a5d19718efb0efdddc1a94ede76a281 | 693,587 |
def deparen(s):
"""
Remove all interior parantheses from sequence.
"""
return s.replace("(", "").replace(")", "") | 837eb4903da8437d6b2c14ba3cee7040431c6a43 | 693,589 |
def _clean_value(line1, line2):
"""Clean up attribute value for display."""
_line1 = line1.strip()
_line2 = line2.strip()
# Let trailing space to make the code easier to read
if _line1[-1:] in ["{", "}", "(", ")", "[", "]", ";", ","]:
_line1 += " "
return _line1 + _line2 | 8b0e4576a2aca6289a7420783def68c4f224fa97 | 693,592 |
from typing import Dict
from typing import List
import re
def get_repo_name_from_url(
repo_url: str,
default_version: str,
valid: Dict[str, List[str]],
) -> str:
"""
Extract repository name from URL.
If it cannot be extracted, the name of the first package of the default version is used.
... | f7dd60e89c3fd3db4c983c8a5ac5dc652d4ebe45 | 693,599 |
from datetime import datetime
def start_dt() -> datetime:
"""Show the start time.
Returns
-------
datetime
The date time this call was made.
"""
dt = datetime.now()
print('stop_watch', 'Started>', dt.isoformat(timespec='microseconds'), flush=True)
return dt | b815649d338f0d0a8823ecb7297c974e9bc81048 | 693,600 |
def Strip(txt):
"""Return stripped string, can handle None"""
try:
return txt.strip()
except:
return None | 44edfab97b1cdbfec4174cf554c78077fb31cfd7 | 693,601 |
def make_game(serverid, name, extras=None):
"""Create test game instance."""
result = {
'serverid': serverid,
'name': name,
'game_state': {'players': {}, 'min_players': 2, 'max_players': 4},
}
if extras:
result.update(extras)
return result | 1e97747c99ed0fa6cde87d1710b1fca7d9512f7b | 693,602 |
def knots_to_kmh(knots: float) -> float:
""" Convert velocity in knots to km/h
1 knot (i.e. 1 nm/h or 1 nautical mile per hour) is 1.852 km/h.
:param knots: velocity in knots
:returns: velocity in km/h
"""
return knots * 1.852 | 8793def54f9b7a8e3895cc8d32156e30f67c9d67 | 693,607 |
def find_min_y_point(list_of_points):
"""
Returns that point of *list_of_points* having minimal y-coordinate
:param list_of_points: list of tuples
:return: tuple (x, y)
"""
min_y_pt = list_of_points[0]
for point in list_of_points[1:]:
if point[1] < min_y_pt[1] or (point[1] == min_y_... | bdb2bfb654456c4b62c52faab45c249fc7a7d4e3 | 693,610 |
def get_data_id(data):
"""Return id attribute of the object if it is data, otherwise return given value."""
return data.id if type(data).__name__ == 'Data' else data | e869fd4d58b5a8d7c229301948608cc6be1b9d8c | 693,614 |
import math
def move_on_circle(x:float, y:float, radius:float, distance:float):
"""Move a distance on a circle with specific radius"""
# Calculate the theta of the differential angle
a, b, c = radius, radius, distance
theta = math.acos((a**2 + b**2 - c**2) / (2 * a * b))
# The new angle is the ... | b9546058ca8c162dad43df53843a02258c17451f | 693,617 |
def split_ae_outputs(outputs, num_joints, with_heatmaps, with_ae,
select_output_index):
"""Split multi-stage outputs into heatmaps & tags.
Args:
outputs (list(torch.Tensor)): Outputs of network
num_joints (int): Number of joints
with_heatmaps (list[bool]): Option to... | 220ddc0b0811c39d005135f0c6e38fd65f40a591 | 693,620 |
def get_branches_of_bus(B, j):
"""
Get the indices of the branches connected to the bus j
:param B: Branch-bus CSC matrix
:param j: bus index
:return: list of branches in the bus
"""
return [B.indices[k] for k in range(B.indptr[j], B.indptr[j + 1])] | 1fc3ecf911f590ff5da970fecc9e8cf1376e8449 | 693,625 |
import logging
def Handle(
logger,
handler=logging.NullHandler(),
formatter="%(asctime)s %(name)s - %(levelname)s: %(message)s",
level="WARNING",
):
"""
Handle a logger with a standardised formatting.
Parameters
-----------
logger : :class:`logging.Logger` | :class:`str`
L... | 0b2f2c7e29f3702c4154ca29f457bbba2f0677e4 | 693,631 |
def bezier_quadratic(p0, p1, p2, t):
"""Returns a position on bezier curve defined by 3 points and t."""
return p1 + (1-t)**2*(p0-p1) + t**2*(p2-p1) | 91b77f59d975c8077f9bbbbafd74d4ffddfbfffc | 693,636 |
def _Backward3b_v_Ps(P, s):
"""Backward equation for region 3b, v=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
v : float
Specific volume [m³/kg]
References
----------
IAPWS, Revised Supple... | d43bd7acea998b40196e64225d2cdd6dc995cdda | 693,639 |
import re
def find_functions(text):
"""Find all function names defined on all lines of the given text"""
return list(set([
re.split('[ (]*', line)[1]
for line in [
line.strip()
for line in text.splitlines()
if 'def ' in line
]
if line.st... | 960e9fbf750c0fe523658813b2fbac493e401733 | 693,641 |
from typing import List
def trim_any_prefixes(word: str, prefixes: List[str]) -> str:
"""Remove the provided prefixes from the given word."""
for prefix in prefixes:
if word.startswith(prefix):
return word.removeprefix(prefix)
return word | 6be47377f63750d6fe36609624551cfcf734c3db | 693,649 |
def split_PETSc_Mat(mat):
""" Decompose a PETSc matrix into a symmetric and skew-symmetric
matrix
Parameters:
----------
mat : :class: `PETSc4py Matrix`
Returns:
--------
H : :class: `PETSc4py Matrix`
Symmetric (or Hermitian) component of mat
S : :class: `PETSc4py Matri... | f78d85382e2ceda7d03e572493113f383e8dd17e | 693,652 |
def decode_word_two(word, mask):
"""
Decodes the second word in the standard 4 word header.
:param word: The word that we're going to decode.
:param mask: The mask we'll use to decode that word.
:return: A dictionary containing the decoded information
"""
return {
'event_time_high': ... | 138fd25e79879771f5177ccd7e3c5000153ac307 | 693,653 |
def strip_prefix(full_string, prefix):
"""
Strip the prefix from the given string and return it. If the prefix is not present
the original string will be returned unaltered
:param full_string: the string from which to remove the prefix
:param prefix: the prefix to remove
:return: the string wit... | d0fafcfdab873cd544d35362e092dd93301a5b3d | 693,654 |
def str_to_list(str):
"""
解析字符串,将字符串转换成列表
:param str: 需要解析的字符串
:return: List
"""
str_list = str.split(";")
str_list = [x.strip() for x in str_list if x.strip() != '']
return str_list | 4796a22c7212d12cd4e69aeb49a63f0d959c2b58 | 693,655 |
def get_price(item):
"""Given an SoftLayer_Product_Item, returns its default price id"""
for price in item.get('prices', []):
if not price.get('locationGroupId'):
return price.get('id')
return 0 | 1af38e528b4b95cef6e5f30cc4695e05146d869a | 693,656 |
from typing import Sequence
def is_seq_int(tp) -> bool:
"""Return True if the input is a sequence of integers."""
return tp and isinstance(tp, Sequence) and all(isinstance(p, int) for p in tp) | 98a78ab04f48b5d4f0b173f4700e7a9ee0824ce9 | 693,657 |
def normalize(seq):
"""
Scales each number in the sequence so that the sum of all numbers equals 1.
"""
s = float(sum(seq))
return [v / s for v in seq] | 68f4986ae9f45f70dd31d51c29fab91a9c055338 | 693,659 |
def _reduce_xyfp(x, y):
"""
Rescale FP xy coordinates [-420,420] -> [-1,1] and flip x axis
"""
a = 420.0
return -x/a, y/a | f36bf33d7d38163ca2401ad1b7dba29bbac577e3 | 693,660 |
import torch
def convert_to_radar_frame(pixel_coords, config):
"""Converts pixel_coords (B x N x 2) from pixel coordinates to metric coordinates in the radar frame.
Args:
pixel_coords (torch.tensor): (B,N,2) pixel coordinates
config (json): parse configuration file
Returns:
torch.t... | 404236c1c886d5425fe270a78fbcf7c25b5a28e6 | 693,661 |
def _tasklines_from_tasks(tasks: list[dict[str, str]]) -> list[str]:
"""Parse a list of tasks into tasklines suitable for writing."""
tasklines = []
for task in tasks:
meta = [m for m in task.items() if m[0] != "text"]
meta_str = ", ".join("%s:%s" % m for m in meta)
tasklines.appen... | 295a1adfeb68b69c0aabece5eed33d3e6f161773 | 693,664 |
def _idFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein id from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein id.
:param headerInfo: dict, must contain a key "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
... | 5e5433b320af1fe363eadc53dc7dd0bea160a73e | 693,665 |
def compile_wrfnnrp_bc_Salathe2014_locations(maptable):
"""
Compile a list of file URLs for the Salathe et al., 2014 bias corrected WRF NNRP data
maptable: (dataframe) a dataframe that contains the FID, LAT, LONG_, and ELEV for each interpolated data file
"""
locations=[]
for ind, row in ma... | 4471eacaa8e51c1f036e184d6b8b0e4f681c5c09 | 693,668 |
def prepare_for_file_dump(file_lines):
"""
Join lines together with linebreaks and remove negative zeros
"""
return '\n'.join([line.replace('-0.0000000000000', ' 0.0000000000000') for line in file_lines]) | 439f9c8fad152b82c3d0e8621b2c299243311f47 | 693,672 |
def sqrt_decimal_expansion(n: int, precision: int) -> str:
"""Finds the square root of a number to arbitrary decimal precision.
Args:
n: A positive integer value.
precision: The desired number of digits following the decimal point.
Returns:
A string representation of ``sqrt(n)`` in... | 5165f98a51a0522aa960a532b10fa07191cf9e12 | 693,676 |
def get_nodes_labels(properties):
"""Returns the node labels contained in given property graphs.
:param properties: An iterable of TimedPropertyGraph objects.
:return: A set containing all node labels used in given sequence of property graphs.
"""
labels = set()
for p in properties:
fo... | 8ddabf4ebdddcb557f36f6a841ef072975514f8b | 693,678 |
def get_vm(app, nodename, scope='deployment'):
"""Return the VM *nodename* from *app*."""
for vm in app.get(scope, {}).get('vms', []):
if vm['name'] == nodename:
return vm
raise RuntimeError('Application `{}` unknown vm `{}`.'.format(app['name'], nodename)) | feb507d3fc4f3e531f7bc3855ad8400dff871413 | 693,679 |
import itertools
def hamming_hashes(hashval, nbits, nmax=None):
"""Return an iterator over all (integer) hashes,
in order of hamming distance
Parameters
----------
hashval : integer
hash value to match
nbits : integer
number of bits in the hash
nmax : integer (optional)
... | 35fed0f21ddd46fcd536dcdc030267b8a30dcc5f | 693,681 |
from datetime import datetime
def make_timestamp(date_string):
"""
A row-operation that converts an Efergy timestamp of the form
"2015-12-31 12:34:56" into a Python datetime object.
"""
try:
return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
except:
return None | a23846aa19e97df9ad55cb9b303d3b07ce3b1d01 | 693,696 |
def format_kraken2_report_row(report_node):
"""
Formats the row that will be output in the kraken 2 style report. Input
is an instance of ReportNode.
"""
offset = 2 * report_node.offset * ' '
name = offset + report_node.name
if report_node.rank_depth == 0:
rank_depth = ''
else:
... | ca83aa5f94af50e94f39e609c271127275166be6 | 693,698 |
import re
def parse_shift_spec(spans : str = ""):
"""
Parse a shift specification line of the form
'09:00-12:00, 15:00-18:00, ...'
"""
if spans.replace(" ", "") == "":
return []
p = re.compile("^(\d\d):(\d\d)-(\d\d):(\d\d)$")
def parse_interval(s):
m = p.match(s.replace("... | 19593302bd333c47bc105db75371a26d97a9c3f7 | 693,703 |
def trace_depth(pair, stacks, depth):
"""
Helper function for tracing base pairs "depth" while building dot bracket notation string
:param pair: Pair to analyze
:param stacks: Current pair "stacks"
:param depth: Current depth of main function
:return: Depth at which make_dot_notation function s... | b7a44c5d2f1515eea76258a5b8efe93e2bce1475 | 693,704 |
import logging
def run_evaluation_episodes(env, agent, n_runs, max_episode_len=None,
explorer=None, logger=None):
"""Run multiple evaluation episodes and return returns.
Args:
env (Environment): Environment used for evaluation
agent (Agent): Agent to evaluate.
... | f750f2d411508698dd88e0e307f546d092499661 | 693,705 |
def abs(number): # real signature unknown; restored from __doc__
"""
abs(number) -> number
Return the absolute value of the argument.
"""
return 0 | 1530dc89e01700fac389447d41afbd90daf690d4 | 693,709 |
def power_provision_rule(mod, p, tmp):
"""
Provided power to the system is the load shifted down minus the load
shifted up.
"""
return mod.DR_Shift_Down_MW[p, tmp] - mod.DR_Shift_Up_MW[p, tmp] | 4f19418c9a2aca671439339c2c3c3c5f7f6a7ab2 | 693,711 |
def binary(n,count=16,reverse=False):
"""
Display n in binary (only difference from built-in `bin` is
that this function returns a fixed width string and can
optionally be reversed
>>> binary(6789)
'0001101010000101'
>>> binary(6789,8)
'10000101'
>>> ... | b322d57c2e395fc3377c359c77707167f5477111 | 693,712 |
def flip(fn, permutation=(1, 0)):
"""Flips argument order of function according to permutation."""
def inner(*args, **kwargs):
args = tuple(args[p] for p in permutation) + args[len(permutation):]
return fn(*args, **kwargs)
return inner | 8f6a748e93f3e397606d7f5d97afdc29527f175a | 693,713 |
def and_list(aList, bList):
"""Return the items in aList and in bList."""
tmp = []
for a in aList:
if a in bList:
tmp.append(a)
return tmp | 71b3be86552be659d601c598df27aff2853476ae | 693,714 |
import re
def is_ztf_name(name):
"""
Checks if a string adheres to the ZTF naming scheme
"""
return re.match("^ZTF[1-2]\d[a-z]{7}$", name) | 9962d093008b0352ef4f45e8f635cf6c714db0cd | 693,715 |
def build_limit_clause(limit):
"""Build limit clause for a query.
Get a LIMIT clause and bind vars. The LIMIT clause will have either
the form "LIMIT count" "LIMIT offset, count", or be the empty string.
or the empty string.
Args:
limit: None, int or 1- or 2-element list or tuple.
Returns:
A (str... | ac113586105486bc006d1ddaff1f6d5cdfb1b22f | 693,716 |
import gzip
import json
def read_selected_torsions(input_json):
""" Read data generated by select_torsions.py
Returns
-------
selected_torsions: dict
Dictionary for selected torsions, has this structure:
{
canonical_torsion_index1: {
'initial_molecules': [ ... | 22726136ffb69db5ab6464f4f583ba86f9912bb5 | 693,720 |
def load(filename):
"""Load the labels and scores for Hits at K evaluation.
Loads labels and model predictions from files of the format:
Query \t Example \t Label \t Score
:param filename: Filename to load.
:return: list_of_list_of_labels, list_of_list_of_scores
"""
result_labels = []
... | 273a4addc8b943469b22f7495291fee179e67e62 | 693,722 |
def filter_bad_pixels(dataset):
"""Use the Data Quality Flag (DQF) to filter out bad pixels.
Each pixel (value according to a specific X-Y coordinate) has a DQF, which ranges
from 0 (good) to 3 (no value). We follow NOAA's suggestion of filtering out all
pixes with a flag of 2 or 3.
Returns
--... | c484980e678dd1c09b6aad58000fc994a55f3495 | 693,724 |
def keep_step(metrics, step):
"""
Only keeps the values of the metrics for the step `step`.
Default to None for each metric that does not have the given `step`.
Args:
metrics (dict): keys are metric names, values are lists of
(step, value) pairs
e.g.
{
... | 6d1ea0adfcb8e311c312690117106c410082be32 | 693,725 |
def quantile(l, p):
"""Return p quantile of list l. E.g. p=0.25 for q1.
See:
http://rweb.stat.umn.edu/R/library/base/html/quantile.html
"""
l_sort = l[:]
l_sort.sort()
n = len(l)
r = 1 + ((n - 1) * p)
i = int(r)
f = r - i
if i < n:
result = (1-f)*l_sort[i-1] + f*l_... | 2fae67ed8caf55a4701d463687b0e0e4220a8e6d | 693,726 |
from typing import List
def get_metaworld_mt_benchmark_names() -> List[str]:
""" Returns a list of Metaworld multi-task benchmark names. """
return ["MT1", "MT10", "MT50"] | 594195927ce211c1a2da9f2be3853198f31c24cc | 693,728 |
def attr_names(attr_map):
"""return a list of attribute names from the map"""
if attr_map:
return list(sorted(attr_map.keys()))
return [] | e6dff4a416cf6d26e29ad01484cd26e307c6efb0 | 693,732 |
def resolve_location_type_enum(location_id):
"""Resolve the location item ID to its type name."""
if 30000000 <= location_id <= 39999999:
return "solar_system"
if 60000000 <= location_id < 64000000:
return "station"
if location_id >= 100000000:
return "item"
return "other" | 399699ba60f9f2ce82010731e1fa60f981b5ef96 | 693,734 |
def count_collisions(Collisions):
"""
Counts the number of unique collisions and gets the collision index.
Parameters
----------
Collisions : array_like
Array of booleans, containing true if during a collision event, false otherwise.
Returns
-------
CollisionCount : int
... | 15118945d9ccc7b8760e01d993e59b36943fc7a0 | 693,735 |
def quintic_ease_out(p):
"""Modeled after the quintic y = (x - 1)^5 + 1"""
f = p - 1
return (f * f * f * f * f) + 1 | ffd09fcc45f08861688257c254cc86a53bf13041 | 693,736 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"name": string,
... | b4d990e75204d9137d7f9fc39b38f10716972939 | 693,738 |
def classproperty(f):
"""
Create a property on a class, not an instance.
Works only for getting.
"""
class Descriptor(object):
def __get__(self, _obj, objtype):
return f(objtype)
return Descriptor() | 1f24a6d3c7470d5042089c5f8ab71c2949fdfe77 | 693,740 |
import time
def timestamp_to_datetime(timestamp, formatter="%Y-%m-%d %H:%M:%S"):
""" timestamp格式化为datetime
:参数 timestamp: 精确到秒的timestamp时间
:参数 formatter: 格式化后的时间格式,默认: %Y-%m-%d %H:%M:%S
:返回: CST时间
"""
ltime = time.localtime(timestamp)
timeStr = time.strftime(formatter, ltime)
return ... | 56b199e9054a278b22c25cc86d6905c8a2112c18 | 693,742 |
from typing import List
def convert_bio_tags_to_conll_format(labels: List[str]):
"""
Converts BIO formatted SRL tags to the format required for evaluation with the
official CONLL 2005 perl script. Spans are represented by bracketed labels,
with the labels of words inside spans being the same as those ... | efab766299a40f32e4886d32ec3e249891c2b084 | 693,744 |
import ssl
def load_ssl_context(cert_file, key_file=None):
"""Creates an SSL context from a certificate and private key file.
:param cert_file:
Path of the certificate to use.
:param key_file:
Path of the private key to use. If not given, the key will be obtained
from the certific... | 2696f0a9ddc4d841066d3e78e737856733942b09 | 693,748 |
def bt_addr_to_str(bt_addr):
""" Convert a Bluetooth address (6 bytes) into a human readable format.
"""
return ":".join([b.encode("hex") for b in bt_addr]) | 85b91da76d39a21c31b782e1365e3d9e63e1e836 | 693,749 |
def get_line_kind(line):
"""Return type kind of a line."""
return line.split()[2][1:-1] | e5be2657f373525726ca988f75215170f62b33fc | 693,752 |
import json
def load_jpeg_registry(jpeg_registry_path):
"""Load the jpeg registry JSON into a dictionary."""
with open(jpeg_registry_path) as f:
return json.load(f) | a1437f4742d80302537e666df79a8e393b5c489f | 693,753 |
def get(attribute_name, json_response, default=None):
"""
Get an attribute from a dictionary given its key name.
:param attribute_name: Attribute name.
:param json_response: Dictionary where the attribute should be.
:param default: Value that has to be returned if the attribute is not there.
:re... | e8d794564332fec7557ba13e16f392693fc488c2 | 693,755 |
import struct
def two_ints_to_long(intl, inth):
""" Interpert two ints as one long """
longint = struct.pack(">I", inth) + struct.pack(">I", intl)
return struct.unpack('>q', longint)[0] | c503e00f1ed934ad22590b942be85b7fd877bb47 | 693,756 |
def user_avatar_upload(instance, filename):
"""Upload user avatar."""
return f'{instance.user_id}/{filename}' | be0a34b4b7bedc0e7252127a33797a8c9bede4ce | 693,759 |
def build_path(tmp_path_factory):
"""Provides a temp directory with a single file in it."""
magic = tmp_path_factory.mktemp('build_magic')
hello = magic / 'hello.txt'
hello.write_text('hello')
return magic | 52a1f1a3735d80589e31e46214e9781ec03943d5 | 693,760 |
def iptup_to_str(formatted_tuple: tuple[str, int]) -> str:
"""
Converts a tuple IP address into a string equivalent
This function is like the opposite of ``ipstr_to_tup``
:param formatted_tuple: A two-element tuple, containing the IP address and the port.
Must be in the format (ip: str, port: ... | ff3cb457a1396935ee0c9d6834fa8f17c65c4970 | 693,762 |
def s3_read_write_policy_in_json(s3_bucket_name):
"""
Define an IAM policy statement for reading and writing to S3 bucket.
:return: an IAM policy statement in json.
"""
return {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"... | b872fd3c833e0384ed891ab3709826a9e9a823bf | 693,764 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.