content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def tag_in_tags(entity, attribute, value):
"""
Return true if the provided entity has
a tag of value in its tag list.
"""
return value in entity.tags | ad88be5f8848b387f2a261ce5506dffde285a1d8 | 1,296 |
import torch
def to_device(x, device):
"""Cast a hierarchical object to pytorch device"""
if isinstance(x, torch.Tensor):
return x.to(device)
elif isinstance(x, dict):
for k in list(x.keys()):
x[k] = to_device(x[k], device)
return x
elif isinstance(x, list) or isins... | a315905fb0cf6d6720103c0d22440418ebd41bf1 | 1,299 |
def f(x):
"""Cubic function."""
return x**3 | 13832221de3490dbd92f4f1a26854baec7010023 | 1,300 |
import textwrap
def dedent(ind, text):
"""
Dedent text to the specific indentation level.
:param ind: common indentation level for the resulting text (number of spaces to append to every line)
:param text: text that should be transformed.
:return: ``text`` with all common indentation removed, and... | 271b9fd270d78c4bc952af31d3d9be0ff6bdab73 | 1,301 |
def get_polarimeter_index(pol_name):
"""Return the progressive number of the polarimeter within the board (0…7)
Args:
pol_name (str): Name of the polarimeter, like ``R0`` or ``W3``.
Returns:
An integer from 0 to 7.
"""
if pol_name[0] == "W":
return 7
else:
retu... | 0068931868e214896f6263e58fc09215352d502c | 1,305 |
import io
import base64
def get_image_html_tag(fig, format="svg"):
"""
Returns an HTML tag with embedded image data in the given format.
:param fig: a matplotlib figure instance
:param format: output image format (passed to fig.savefig)
"""
stream = io.BytesIO()
# bbox_inches: expand the ... | f5c59a6f4f70fb6616cec4619d8cbf9ca2e28529 | 1,308 |
def reformat_language_tuple(langval):
"""Produce standardly-formatted language specification string using given language tuple.
:param langval: `tuple` in form ('<language>', '<language variant>'). Example: ('en', 'US')
:return: `string` formatted in form '<language>-<language-variant>'
"""
if lang... | 63c479d7dd273f31b9bdcc6c0ce81d4267a43714 | 1,309 |
def memdiff_search(bytes1, bytes2):
"""
Use binary searching to find the offset of the first difference
between two strings.
:param bytes1: The original sequence of bytes
:param bytes2: A sequence of bytes to compare with bytes1
:type bytes1: str
:type bytes2: str
:rtype: int offset of... | fbcb221c77730c45be4c81a6ae7515e602468af5 | 1,310 |
def stringify(li,delimiter):
""" Converts list entries to strings and joins with delimiter."""
string_list = map(str,li)
return delimiter.join(string_list) | a4c35a19d8ea654a802cd3f92ababcbdfdf0ecfb | 1,313 |
def load_module(module, app):
"""Load an object from a Python module
In:
- ``module`` -- name of the module
- ``app`` -- name of the object to load
Return:
- (the object, None)
"""
r = __import__(module, fromlist=('',))
if app is not None:
r = getattr(r, app)
re... | 858d9d0bf91ff7d83ad391218b8ff1b37007b43b | 1,315 |
from unittest.mock import Mock
def make_subprocess_hook_mock(exit_code: int, output: str) -> Mock:
"""Mock a SubprocessHook factory object for use in testing.
This mock allows us to validate that the RenvOperator is executing
subprocess commands as expected without running them for real.
"""
resu... | a047608503be8bc7fc4b782139e7d12145efb3cd | 1,316 |
def binstr2int(bin_str: str) -> int:
"""转换二进制形式的字符串为10进制数字, 和int2binstr相反
Args:
bin_str: 二进制字符串, 比如: '0b0011'或'0011'
Returns:
转换后的10进制整数
"""
return int(bin_str, 2) | 87c6ac16c2215e533cb407407bef926ed8668e3e | 1,317 |
def _scale(tensor):
"""Scale a tensor based on min and max of each example and channel
Resulting tensor has range (-1, 1).
Parameters
----------
tensor : torch.Tensor or torch.autograd.Variable
Tensor to scale of shape BxCxHxW
Returns
-------
Tuple (scaled_tensor, min, max), where min and max ar... | 64eed9bd70c543def6456f3af89fa588ec35bca8 | 1,318 |
def url(endpoint, path):
"""append the provided path to the endpoint to build an url"""
return f"{endpoint.rstrip('/')}/{path}" | dee733845984bfc4cf5728e9614cce08d19a2936 | 1,319 |
def is_collision(line_seg1, line_seg2):
"""
Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2)
and p2(x3, y3) -> q2(x4, y4)
"""
def on_segment(p1, p2, p3):
if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1],... | 17dba61faebe50336cbc2cd2cc56c49474db5431 | 1,320 |
def fibonacci(position):
"""
Based on a position returns the number in the Fibonacci sequence
on that position
"""
if position == 0:
return 0
elif position == 1:
return 1
return fibonacci(position-1)+fibonacci(position-2) | cc4fe0860fa97234ead2179e18d208a8567e0cb3 | 1,322 |
import asyncio
import functools
def bound_concurrency(size):
"""Decorator to limit concurrency on coroutine calls"""
sem = asyncio.Semaphore(size)
def decorator(func):
"""Actual decorator"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
"""Wrapper"""
... | 030e4dea0efccf9d5f2cbe4a40f3e6f32dfef846 | 1,323 |
def pg_index_exists(conn, schema_name: str, table_name: str, index_name: str) -> bool:
"""
Does a postgres index exist?
Unlike pg_exists(), we don't need heightened permissions on the table.
So, for example, Explorer's limited-permission user can check agdc/ODC tables
that it doesn't own.
"""
... | 98ebdc0db7f3e42050e61205fd17309d015352a0 | 1,326 |
def time_rep_song_to_16th_note_grid(time_rep_song):
"""
Transform the time_rep_song into an array of 16th note with pitches in the onsets
[[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0]
"""
grid_16th = []
for pair_p_t in time_rep_song:
grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)])
retur... | 8986819bd39ae4830d04bf40ab158d310bb45485 | 1,329 |
def require(*modules):
"""Check if the given modules are already available; if not add them to
the dependency list."""
deplist = []
for module in modules:
try:
__import__(module)
except ImportError:
deplist.append(module)
return deplist | 88df83cd33d8bddea63e4d2fbfb4d8351a3c23b1 | 1,331 |
def fixture_base_context(
env_name: str,
) -> dict:
"""Return a basic context"""
ctx = dict(
current_user="a_user",
current_host="a_host",
)
return ctx | fbfed439f784bdd64e93910bbb581955200af2bb | 1,332 |
def evaluation(evaluators, dataset, runners, execution_results, result_data):
"""Evaluate the model outputs.
Args:
evaluators: List of tuples of series and evaluation functions.
dataset: Dataset against which the evaluation is done.
runners: List of runners (contains series ids and loss... | ef3470edb8b2336bdc54507a5df8023f8095b995 | 1,333 |
import base64
def base64_decode(string):
"""
Decodes data encoded with MIME base64
"""
return base64.b64decode(string) | 38870882fca9e6595e3f5b5f8943d0bf781f006c | 1,335 |
import re
def convert_operand_kind(operand_tuple):
"""Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- qu... | 3d26a0b330ae64209655b24dfe86578cb4b8724c | 1,336 |
def _ensure_package(base, *parts):
"""Ensure that all the components of a module directory path exist, and
contain a file __init__.py."""
bits = []
for bit in parts[:-1]:
bits.append(bit)
base.ensure(*(bits + ['__init__.py']))
return base.ensure(*parts) | fc9bb95445cc1b0e8ec819dfafdaff7d5afbf372 | 1,338 |
import math
def sigmoid(z):
"""Sigmoid function"""
if z > 100:
return 0
return 1.0 / (1.0 + math.exp(z)) | 097e1a85fc46264cb1c7cd74498d6cfab97e5b88 | 1,339 |
def format_str_for_write(input_str: str) -> bytes:
"""Format a string for writing to SteamVR's stream."""
if len(input_str) < 1:
return "".encode("utf-8")
if input_str[-1] != "\n":
return (input_str + "\n").encode("utf-8")
return input_str.encode("utf-8") | 1b83a2c75118b03b7af06350e069775c0b877816 | 1,344 |
def _as_nested_lists(vertices):
""" Convert a nested structure such as an ndarray into a list of lists. """
out = []
for part in vertices:
if hasattr(part[0], "__iter__"):
verts = _as_nested_lists(part)
out.append(verts)
else:
out.append(list(part))
re... | c69bd2084aa8e76a53adf3e25286a8dd7ae23176 | 1,347 |
def A070939(i: int = 0) -> int:
"""Length of binary representation of n."""
return len(f"{i:b}") | 31b12e493645c3bdf7e636a48ceccff5d9ecc492 | 1,350 |
def char_to_num(x: str) -> int:
"""Converts a character to a number
:param x: Character
:type x: str
:return: Corresponding number
:rtype: int
"""
total = 0
for i in range(len(x)):
total += (ord(x[::-1][i]) - 64) * (26 ** i)
return total | f66ee13d696ec1872fbc2a9960362456a5c4cbe9 | 1,353 |
import json
def get_rate_limit(client):
"""
Get the Github API rate limit current state for the used token
"""
query = '''query {
rateLimit {
limit
remaining
resetAt
}
}'''
response = client.execute(query)
json_response = json.loads(respo... | ec5f853014f25c841e71047da62ca41907b02e13 | 1,356 |
from typing import List
def unique_chars(texts: List[str]) -> List[str]:
"""
Get a list of unique characters from list of text.
Args:
texts: List of sentences
Returns:
A sorted list of unique characters
"""
return sorted(set("".join(texts))) | 02bc9ce28498bd129fdb68c2f797d138ca584490 | 1,361 |
def count_str(text, sub, start=None, end=None):
"""
Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``.
Optional arguments start and end are interpreted as in slice notation.
:param text: The string to search
:type text: ``str``
:param ... | 1578f868a4f1a193ec9907494e4af613ca2a6d4d | 1,366 |
def _gnurl( clientID ):
"""
Helper function to form URL to Gracenote_ API service.
:param str clientID: the Gracenote_ client ID.
:returns: the lower level URL to the Gracenote_ API.
:rtype: str
"""
clientIDprefix = clientID.split('-')[0]
return 'https://c%s.web.cddbp.net/webapi/xml... | 6d1935c8b634459892e4ec03d129c791b1d8a06a | 1,367 |
def utf8_bytes(string):
""" Convert 'string' to bytes using UTF-8. """
return bytes(string, 'UTF-8') | 8e5423d2b53e8d5fbeb07017ccd328236ef8bea5 | 1,368 |
def gram_matrix(x):
"""Create the gram matrix of x."""
b, c, h, w = x.shape
phi = x.view(b, c, h * w)
return phi.bmm(phi.transpose(1, 2)) / (c * h * w) | 11de97b67f3f8ecb7d7d009de16c1a5d153ab8ff | 1,375 |
def matchesType(value, expected):
"""
Returns boolean for whether the given value matches the given type.
Supports all basic JSON supported value types:
primitive, integer/int, float, number/num, string/str, boolean/bool, dict/map, array/list, ...
"""
result = type(value)
expected = expecte... | 24949f01a1bc3ae63a120d91549ae06ba52298a8 | 1,382 |
def get_attr(item, name, default=None):
"""
similar to getattr and get but will test for class or dict
:param item:
:param name:
:param default:
:return:
"""
try:
val = item[name]
except (KeyError, TypeError):
try:
val = getattr(item, name)
except... | 0c68c7e54ef901e18a49d327188f29f72f54da01 | 1,390 |
def float2(val, min_repeat=6):
"""Increase number of decimal places of a repeating decimal.
e.g. 34.111111 -> 34.1111111111111111"""
repeat = 0
lc = ""
for i in range(len(val)):
c = val[i]
if c == lc:
repeat += 1
if repeat == min_repeat:
return float(val[:i+1] + c * 10)
else... | 07fc521e877387242a1e6cf951a6d5cbdc925aaf | 1,391 |
def format_sec_to_hms(sec):
"""Format seconds to hours, minutes, seconds.
Args:
sec: float or int
Number of seconds in a period of time
Returns: str
Period of time represented as a string on the form ``0d\:00h\:00m``.
"""
rem_int, s_int = divmod(int(sec), 60)
h_int, m_int,... | aa2cc5d6584cdebf4d37292435ecd46bb6adc4a4 | 1,395 |
def which_db_version(cursor):
"""
Return version of DB schema as string.
Return '5', if iOS 5.
Return '6', if iOS 6 or iOS 7.
"""
query = "select count(*) from sqlite_master where name = 'handle'"
cursor.execute(query)
count = cursor.fetchone()[0]
if count == 1:
db_version ... | 07b1dbcea3fb4bf65bba5c578257440d39b6784c | 1,400 |
import re
def repeating_chars(text: str, *, chars: str, maxn: int = 1) -> str:
"""Normalize repeating characters in `text`.
Truncating their number of consecutive repetitions to `maxn`.
Duplicates Textacy's `utils.normalize_repeating_chars`.
Args:
text (str): The text to normalize.
c... | 9dc326947a900d3531dcd59bf51d5c3396a42fea | 1,401 |
import json
def create_response(key, value):
"""Return generic AWS Lamba proxy response object format."""
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({key: value})
} | 9236a9e4504e6fbebe841b8cc6b6ad4602dae463 | 1,404 |
import re
def format_query(str_sql):
"""Strips all newlines, excess whitespace, and spaces around commas"""
stage1 = str_sql.replace("\n", " ")
stage2 = re.sub(r"\s+", " ", stage1).strip()
stage3 = re.sub(r"(\s*,\s*)", ",", stage2)
return stage3 | 5adb0f9c3314ba04bbf92c88e3ef17802b2afeb0 | 1,410 |
import re
def check_token(token):
"""
Returns `True` if *token* is a valid XML token, as defined by XML
Schema Part 2.
"""
return (token == '' or
re.match(
"[^\r\n\t ]?([^\r\n\t ]| [^\r\n\t ])*[^\r\n\t ]?$", token)
is not None) | b4e1d313fb64aad4c1c244cb18d3629e13b1c3af | 1,412 |
def get_phoible_feature_list(var_to_index):
"""
Function that takes a var_to_index object and return a list of Phoible segment features
:param var_to_index: a dictionary mapping variable name to index(column) number in Phoible data
:return :
"""
return list(var_to_index.keys())[11:] | a53995cd927d1cdc66fadb2a8e6af3f5e2effff0 | 1,413 |
def n_states_of_vec(l, nval):
""" Returns the amount of different states a vector of length 'l' can be
in, given that each index can be in 'nval' different configurations.
"""
if type(l) != int or type(nval) != int or l < 1 or nval < 1:
raise ValueError("Both arguments must be positive integ... | 98770fa5a5e62501bf365a4a5a40a932b2ba2450 | 1,415 |
def remove_items_from_dict(a_dict, bad_keys):
"""
Remove every item from a_dict whose key is in bad_keys.
:param a_dict: The dict to have keys removed from.
:param bad_keys: The keys to remove from a_dict.
:return: A copy of a_dict with the bad_keys items removed.
"""
new_dict = {}
for ... | 7c665e372c2099441f8a661f1194a76a21edf01c | 1,416 |
import re
def filter_strace_output(lines):
"""
a function to filter QEMU logs returning only the strace entries
Parameters
----------
lines : list
a list of strings representing the lines from a QEMU log/trace.
Returns
-------
list
a list of strings representing only ... | 01b6c048ebdf890e9124c387fc744e56cc6b7f4d | 1,419 |
def magerr2Ivar(flux, magErr):
"""
Estimate the inverse variance given flux and magnitude error.
The reason for this is that we need to correct the magnitude or
flux for Galactic extinction.
Parameters
----------
flux : scalar or array of float
Flux of the obejct.
magErr : scal... | 37c48c26f1b876ca4d77dc141b1728daaea24944 | 1,422 |
def save_file_in_path(file_path, content):
"""Write the content in a file
"""
try:
with open(file_path, 'w', encoding="utf-8") as f:
f.write(content)
except Exception as err:
print(err)
return None
return file_path | 7b1e453a9b2a8c1211e111a6e8db432811d84a7a | 1,426 |
def uncapitalize(string: str):
"""De-capitalize first character of string
E.g. 'How is Michael doing?' -> 'how is Michael doing?'
"""
if len(string):
return string[0].lower() + string[1:]
return "" | 1a294f171d16d7a4c41fb0546feca3c03b7ae37a | 1,430 |
def ensure_dict(value):
"""Convert None to empty dict."""
if value is None:
return {}
return value | 191b1a469e66750171648e715501690b2814b8b2 | 1,432 |
def merge_dicts(dicts, handle_duplicate=None):
"""Merge a list of dictionaries.
Invoke handle_duplicate(key, val1, val2) when two dicts maps the
same key to different values val1 and val2, maybe logging the
duplication.
"""
if not dicts:
return {}
if len(dicts) == 1:
retur... | 44c06ab30bb76920ff08b5978a6aa271abd3e449 | 1,434 |
def escape(s):
"""
Returns the given string with ampersands, quotes and carets encoded.
>>> escape('<b>oh hai</b>')
'<b>oh hai</b>'
>>> escape("Quote's Test")
'Quote's Test'
"""
mapping = (
('&', '&'),
('<', '<'),
('>', '>'),
(... | 2b4971c4e87e613cad457dde6d62806d299cdbcd | 1,438 |
def _get_db_columns_for_model(model):
"""
Return list of columns names for passed model.
"""
return [field.column for field in model._meta._fields()] | 181999f28ca659bf296bcb4dda7ac29ddfe61071 | 1,439 |
def issym(b3):
"""test if a list has equal number of positive
and negative values; zeros belong to both. """
npos = 0; nneg = 0
for item in b3:
if (item >= 0):
npos +=1
if (item <= 0):
nneg +=1
if (npos==nneg):
return True
else:
return False | e8cc57eec5bc9ef7f552ad32bd6518daa2882a3e | 1,442 |
def get_parents(tech_id, model_config):
"""
Returns the full inheritance tree from which ``tech`` descends,
ending with its base technology group.
To get the base technology group,
use ``get_parents(...)[-1]``.
Parameters
----------
tech : str
model_config : AttrDict
"""
... | 7220a57b770232e335001a0dab74ca2d8197ddfa | 1,443 |
def get_month_n_days_from_cumulative(monthly_cumulative_days):
"""
Transform consecutive number of days in monthly data to actual number of days.
EnergyPlus monthly results report a total consecutive number of days for each day.
Raw data reports table as 31, 59..., this function calculates and returns
... | 5ede033023d357a60ba5eb7e9926325d24b986e8 | 1,444 |
def harvest(post):
"""
Filter the post data for just the funding allocation formset data.
"""
data = {k: post[k] for k in post if k.startswith("fundingallocation")}
return data | 67f400caf87f2accab30cb3c519e7014792c84d7 | 1,447 |
def clut8_rgb888(i):
"""Reference CLUT for wasp-os.
Technically speaking this is not a CLUT because the we lookup the colours
algorithmically to avoid the cost of a genuine CLUT. The palette is
designed to be fairly easy to generate algorithmically.
The palette includes all 216 web-safe colours to... | ca95c95306f7f4762add01f2ffc113f348e29d3b | 1,450 |
import json
from typing import OrderedDict
def to_json_dict(json_data):
"""Given a dictionary or JSON string; return a dictionary.
:param json_data: json_data(dict, str): Input JSON object.
:return: A Python dictionary/OrderedDict with the contents of the JSON object.
:raises TypeError: If the input ... | e1264d88a4424630f7348cbe7794ca072c057bdf | 1,451 |
def _collect_scalars(values):
"""Given a list containing scalars (float or int) collect scalars
into a single prefactor. Input list is modified."""
prefactor = 1.0
for i in range(len(values)-1, -1, -1):
if isinstance(values[i], (int, float)):
prefactor *= values.pop(i)
return p... | bea7e54eec16a9b29552439cd12ce29b9e82d40b | 1,455 |
import itertools
def all_inputs(n):
"""
returns an iterator for all {-1,1}-vectors of length `n`.
"""
return itertools.product((-1, +1), repeat=n) | 526dff9332cf606f56dcb0c31b5c16a0124478ed | 1,456 |
def init_time(p, **kwargs):
"""Initialize time data."""
time_data = {
'times': [p['parse']],
'slots': p['slots'],
}
time_data.update(**kwargs)
return time_data | 2aff3819d561f0dc9e0c9b49702b8f3fbb6e9252 | 1,458 |
import socket
def get_socket_with_reuseaddr() -> socket.socket:
"""Returns a new socket with `SO_REUSEADDR` option on, so an address
can be reused immediately, without waiting for TIME_WAIT socket
state to finish.
On Windows, `SO_EXCLUSIVEADDRUSE` is used instead.
This is because ... | 6edbc0f0aaaeaebd9c6d0f31257de0b4dfe7df1c | 1,460 |
import functools
def skippable(*prompts, argument=None):
"""
Decorator to allow a method on the :obj:`CustomCommand` to be
skipped.
Parameters:
----------
prompts: :obj:iter
A series of prompts to display to the user when the method is being
skipped.
argument: :obj:`str`
... | 879106f4cc0524660fb6639e56d688d40b115ac4 | 1,464 |
import hashlib
def _cache_name(address):
"""Generates the key name of an object's cache entry"""
addr_hash = hashlib.md5(address).hexdigest()
return "unsub-{hash}".format(hash=addr_hash) | 6933b1170933df5e3e57af03c81322d68a46d91f | 1,465 |
def fizzbuzz(end=100):
"""Generate a FizzBuzz game sequence.
FizzBuzz is a childrens game where players take turns counting.
The rules are as follows::
1. Whenever the count is divisible by 3, the number is replaced with
"Fizz"
2. Whenever the count is divisible by 5, the number is replaced... | b68b1c39674fb47d0bd12d387f347af0ef0d26ca | 1,469 |
import six
import base64
import zlib
def deflate_and_base64_encode(string_val):
"""
Deflates and the base64 encodes a string
:param string_val: The string to deflate and encode
:return: The deflated and encoded string
"""
if not isinstance(string_val, six.binary_type):
string_val = st... | 31fc19cf134bc22b3fc45b4158c65aef666716cc | 1,472 |
import pickle
def load_pickle(file_path):
"""
load the pickle object from the given path
:param file_path: path of the pickle file
:return: obj => loaded obj
"""
with open(file_path, "rb") as obj_des:
obj = pickle.load(obj_des)
# return the loaded object
return obj | 4770a152dad9c7d123f95a53642aff990f3590f7 | 1,473 |
import json
import re
def create_summary_text(summary):
"""
format a dictionary so it can be printed to screen or written to a plain
text file
Args:
summary(dict): the data to format
Returns:
textsummary(str): the summary dict formatted as a string
"""
summaryjson = json.... | 3a8dd508b760a0b9bfe925fa2dc07d53dee432af | 1,476 |
def maximo_basico(a: float, b: float) -> float:
"""Toma dos números y devuelve el mayor.
Restricción: No utilizar la función max"""
if a > b:
return a
return b | f98db565243587015c3b174cf4130cbc32a00e22 | 1,477 |
def is_pattern_error(exception: TypeError) -> bool:
"""Detect whether the input exception was caused by invalid type passed to `re.search`."""
# This is intentionally simplistic and do not involve any traceback analysis
return str(exception) == "expected string or bytes-like object" | 623246404bbd54bc82ff5759bc73be815d613731 | 1,479 |
def _format_author(url, full_name):
""" Helper function to make author link """
return u"<a class='more-info' href='%s'>%s</a>" % (url, full_name) | 50f001c2358b44bb95da628cc630a2ed3ea8ddfd | 1,483 |
def validinput(x0, xf, n):
"""Checks that the user input is valid.
Args:
x0 (float): Start value
xf (float): End values
n (int): Number of sample points
Returns:
False if x0 > xf or if
True otherwise
"""
valid = True
if x0 > xf:
valid = False
... | 096e0702eb8fe47486d4f03e5b3c55c0835807cd | 1,484 |
import glob
def find_paths(initial_path, extension):
"""
From a path, return all the files of a given extension inside.
:param initial_path: the initial directory of search
:param extension: the extension of the files to be searched
:return: list of paths inside the initial path
"""
path... | 0220127050b765feaf423c195d020d65ece8d22e | 1,487 |
import requests
import io
import tarfile
def sources_from_arxiv(eprint):
"""
Download sources on arXiv for a given preprint.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``).
:returns: A ``TarFile`` object of the sources of the arXiv preprint.
"""
r = requests.get("http://a... | b26c46009b23c5a107d6303b567ab97492f91ad9 | 1,496 |
import csv
def read_manifest(instream):
"""Read manifest file into a dictionary
Parameters
----------
instream : readable file like object
"""
reader = csv.reader(instream, delimiter="\t")
header = None
metadata = {}
for row in reader:
if header is None:
header... | afa6c2bb0a9d81267b1d930026a229be924a1994 | 1,498 |
import webbrowser
def open_in_browser(path):
"""
Open directory in web browser.
"""
return webbrowser.open(path) | 41328b2b478f0bd69695da1868c412188e494d08 | 1,503 |
def encode_letter(letter):
"""
This will encode a tetromino letter as a small integer
"""
value = None
if letter == 'i':
value = 0
elif letter == 'j':
value = 1
elif letter == 'l':
value = 2
elif letter == 'o':
value = 3
elif letter == 's':
... | 6c72c4c9e44c93d045296ab1f49c7783f2b4fc59 | 1,504 |
import hashlib
import json
def get_config_tag(config):
"""Get configuration tag.
Whenever configuration changes making the intermediate representation
incompatible the tag value will change as well.
"""
# Configuration attributes that affect representation value
config_attributes = dict(fram... | 2cab6e9473822d0176e878114ceb3fda94d1e0f7 | 1,510 |
import requests
import re
def api_wowlight_version_check(version: str) -> bool:
"""
Checks incoming wow-lite wallet version, returns False when the version is too old and needs to be upgraded.
:param version:
:return: bool
"""
url = "https://raw.githubusercontent.com/wownero/wow-lite-wallet/ma... | 470f8580df357c206b595c1145e04e33fd897058 | 1,515 |
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0):
""" Construct list of ants dicts for each
timestamp with REAL, IMAG, WEIGHT = gains
"""
default_nif = [gain] * nif
rows = []
for ts in timestamps:
rows += [{'TIME': [ts],
'TIME INTERVAL': [0.1],
... | b81e45d2d5299042b3332a2386a0fd4d2d6d59d7 | 1,517 |
def isUniqueSeq(objlist):
"""Check that list contains items only once"""
return len(set(objlist)) == len(objlist) | 4522c43967615dd54e261a229b05c742676c7f99 | 1,528 |
def tag_to_dict(node):
"""Assume tag has one layer of children, each of which is text, e.g.
<medalline>
<rank>1</rank>
<organization>USA</organization>
<gold>13</gold>
<silver>10</silver>
<bronze>9</bronze>
<total>32</total>
</medalline>
"""
d =... | e2131e070dce8620630e994cc25578a9a8438c64 | 1,531 |
from typing import Dict
from typing import Any
import yaml
def yaml_dump(dict_to_dump: Dict[str, Any]) -> str:
"""Dump the dictionary as a YAML document."""
return yaml.safe_dump(dict_to_dump, default_flow_style=False) | 4635514ba8ff901656b8a4b5869a6ae101528fa8 | 1,533 |
import hashlib
def cache_key(path):
"""Return cache key for `path`."""
return 'folder-{}'.format(hashlib.md5(path.encode('utf-8')).hexdigest()) | 6b9afe1267e0cc0c7168bf3b0d5c7536e2b3c768 | 1,537 |
import torch
def quaternion2rotationPT( q ):
""" Convert unit quaternion to rotation matrix
Args:
q(torch.tensor): unit quaternion (N,4)
Returns:
torch.tensor: rotation matrix (N,3,3)
"""
r11 = (q[:,0]**2+q[:,1]**2-q[:,2]**2-q[:,3]**2).unsqueeze(0).T
r12 = (2.0*(q[:,1]*q[:... | feeed764ee179b31674790f9d2afc7b606a02aef | 1,538 |
def calculate_reliability(data):
""" Calculates the reliability rating of the smartcab during testing. """
success_ratio = data['success'].sum() * 1.0 / len(data)
if success_ratio == 1: # Always meets deadline
return ("A+", "green")
else:
if success_ratio >= 0.90:
return ("A", "green")
elif success_ratio... | d1c9ad7bba220beeae06c568cfd269aaaebfb994 | 1,545 |
def explode(screen):
"""Convert a string representing a screen
display into a list of lists."""
return [list(row) for row in screen.split('\n')] | a43a9d8c830c4a784bb9c3505c62aaf2077bb732 | 1,548 |
def fpath_to_pgn(fpath):
"""Slices the pgn string from file path.
"""
return fpath.split('/')[-1].split('.jpeg')[0] | 1cc6cad60c5356b6c731947a59998117bf15035a | 1,552 |
def data_zip(data):
"""
输入数据,返回一个拼接了子项的列表,如([1,2,3], [4,5,6]) -> [[1,4], [2,5], [3,6]]
{"a":[1,2],"b":[3,4]} -> [{"a":1,"b":3}, {"a":2,"b":4}]
:param data: 数组 data
元组 (x, y,...)
字典 {"a":data1, "b":data2,...}
:return: 列表或数组
"""
if isinstance(data, tuple):
... | 31dcaa3905a7d062cfe994543df31f293fdc962a | 1,553 |
from pathlib import Path
from typing import List
import re
def tags_in_file(path: Path) -> List[str]:
"""Return all tags in a file."""
matches = re.findall(r'@([a-zA-Z1-9\-]+)', path.read_text())
return matches | 1071c22ac79f51697b2ed18896aa1d17568ecb2c | 1,554 |
def check_ip_in_lists(ip, db_connection, penalties):
"""
Does an optimized ip lookup with the db_connection. Applies only the maximum penalty.
Args:
ip (str): ip string
db_connection (DBconnector obj)
penalties (dict): Contains tor_penalty, vpn_penalty, blacklist_penalty keys with i... | 2d6e3615d4b0d9b0fb05e7a0d03708856ffcbfef | 1,555 |
def is_validated(user):
"""Is this user record validated?"""
# An account is "validated" if it has the `validated` field set to True, or
# no `validated` field at all (for accounts created before the "account
# validation option" was enabled).
return user.get("validated", True) | c1ddfc52a62e71a68798dc07e7576a4ae42aa17f | 1,562 |
import pickle
def load_config(path):
"""Loads the config dict from a file at path; returns dict."""
with open(path, "rb") as f:
config = pickle.load(f)
return config | eb12aed2ebdeebacf3041f3e4880c714f99c052c | 1,563 |
def lower_strings(string_list):
"""
Helper function to return lowercase version of a list of strings.
"""
return [str(x).lower() for x in string_list] | 58dcaccbc0f4ce8f22d80922a3ac5da26d7f42b1 | 1,564 |
import hashlib
import hmac
def _HMAC(K, C, Mode=hashlib.sha1):
"""
Generate an HMAC value.
The default mode is to generate an HMAC-SHA-1 value w/ the SHA-1 algorithm.
:param K: shared secret between client and server.
Each HOTP generator has a different and unique secret K.
:type K: ... | db9bf26c52427acc259f3cb1590c7c13b0d0dd9e | 1,569 |
def nth_even(n):
"""Function I wrote that returns the nth even number."""
return (n * 2) - 2 | 26e1465a039352917647ae650d653ed9842db7f6 | 1,571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.