content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
import hashlib
def hashes() -> List[str]:
"""
Return a list of available hashing algorithms.
:rtype: list of strings
"""
t = []
if 'md5' in dir(hashlib):
t = ['MD5']
if 'md2' in dir(hashlib):
t += ['MD2']
hashes = ['SHA-' + h[3:] for h in dir(ha... | 4077694caa1200e923821515a3ec77e720fe755c | 37,096 |
from math import sqrt, ceil
def grid_shape(i, max_x=4):
"""Return a good grid shape, in x,y, for a number if items i"""
x = round(sqrt(i))
if x > max_x:
x = max_x
y = ceil(i / x)
return x, y | e0f5109dc410f2dae632e002600e1c0094585b29 | 37,097 |
def scene_element_slicer(r_i, c_i, scene_element_position_dict, scene_element_dimension, as_slice=False):
"""
Returns the starting and ending row and column indices needed to slice pixels from a scene element.
Parameters
----------
r_i
Scene element row
c_i
Scene element column
... | 0dfa1611eb56865507e6be78dd5a31b72c95d7a7 | 37,100 |
def psfScale(D, wavelength, pixSize):
"""
Return the PSF scale appropriate for the required pixel size, wavelength and telescope diameter
The aperture is padded by this amount; resultant pix scale is lambda/D/psf_scale, so for instance full frame 256 pix
for 3.5 m at 532 nm is 256*5.32e-7/3.5/3 = 2.67 arcsec fo... | cbd98743f8716bfe935daeaa0a11f87daeb873f3 | 37,105 |
def _render_namespace_prefix(namespace):
"""Returns namespace rendered as a prefix, like ::foo::bar::baz."""
return "".join(["::" + n for n in namespace]) | 68e20189cdfd47872b9e9db34451da15b036d280 | 37,107 |
from typing import FrozenSet
import dateutil
def get_known_timezones() -> FrozenSet[str]:
"""
Return a cached set of the known timezones.
This actually pulls its list from the internal database inside `dateutil`
as there doesn't seem to be a nice way to pull the data from the system.
These are e... | ad149814bf72ea8dd13eebd9c0affc4eabf90c76 | 37,110 |
def _checkNconvertStr(texts):
"""
Checks whether input is a string or if it can be casted into one
:param texts: A string or a type which can be converted into one
:return: Text as a string if successful otherwise nothing (exception)
"""
concatTextLst = []
for text in texts:
# Test t... | 430157ecf0f404f77fef497c39d4b0525b1b4f71 | 37,113 |
from typing import List
from typing import Any
def getListDifference(listOne: List[Any], listTwo: List[Any]) -> List[Any]:
""" Return difference (items that are unique just to a one of given lists)
of a given lists.
Note:
Operation does not necessary maintain items order!
Args:
listO... | 5839988761a8f242828c8526d75e2b7ea8aea2f3 | 37,114 |
def _get(isamAppliance, id):
"""
Internal function to get data using "id" - used to avoid extra calls
:param isamAppliance:
:param id:
:return:
"""
return isamAppliance.invoke_get("Retrieve a specific mapping rule",
"/iam/access/v8/mapping-rules/{0}".form... | fbaccf5cf8a0b1b8f4be12e07d0ac2bf7dd20463 | 37,118 |
from typing import Iterable
def dedupe(iterable: Iterable) -> Iterable:
"""
Removes duplicates.
In python 3.6+, this algorithm preserves order of the underlying
iterable.
"""
return iter(dict.fromkeys(iterable)) | 67c46849b279a1423f81aaa64e0e2d80c4900aa5 | 37,119 |
import time
def create_export_file(converted_posts):
"""
Create a Ghost import json from a list of Ghost post documents.
:param converted_posts: Ghost formatted python docs.
:return: A Dict representation of a ghost export file you can dump to json.
"""
return {
"db": [
{
... | e0ee20a9b61ea6e86e3efb96fbe95085a2a9b2d0 | 37,124 |
def get_prots(docked_prot_file):
"""
gets list of all protein, target ligands, and starting ligands in the index file
:param docked_prot_file: (string) file listing proteins to process
:return: process (list) list of all protein, target ligands, and starting ligands to process
"""
process = []
... | 17b31a045004d19f5b79345cb53eded38df1a8e5 | 37,126 |
from pathlib import Path
def relative_to(path: Path, root: Path) -> Path:
"""Returns a path to `path` relative to `root`
Postcondition: (root / relative_to(path, root)).resolve() = path.resolve()
"""
while True:
try:
return path.relative_to(root)
except ValueError:
... | 5a1091ba87d45917302778b4cee8b30a6d9f6bf9 | 37,127 |
def strip_quotes(arg):
""" Strip outer quotes from a string.
Applies to both single and double quotes.
:param arg: str - string to strip outer quotes from
:return str - same string with potentially outer quotes stripped
"""
quote_chars = '"' + "'"
if len(arg) > 1 and arg[0] == arg[-1] an... | 97c8cefe2d0de2b3cecb8b6ed94a40ce4be89b94 | 37,134 |
import math
def BytesPerRowBMP(width, bpp):
"""Computes the number of bytes per row in a Windows BMP image."""
# width * bpp / 8, rounded up to the nearest multiple of 4.
return int(math.ceil(width * bpp / 32.0)) * 4 | 72f0df2951a27905bbf5b612d3f328696b6434f4 | 37,135 |
def str_to_bool(str_):
"""Convert string to bool."""
if str_ == "True":
return True
elif str_ == "False":
return False
else:
raise TypeError(str_) | 929a2fe459e43751a90f1bd918ef6447eb2b68c2 | 37,137 |
def generate_name(route, deployment):
"""
Generate the name for a route in a given deployment
:param route: the id of the route
:param deployment: the id of the route
:return: the unique name for the route
"""
return f"{route}_{deployment}" | 4f957cea79e5dc05af7cef5a490a56c2690c09ed | 37,138 |
def limit(val: int) -> int:
"""
= min(max(val, 0), 255)
"""
tmp = 255 if val>255 else val
return 0 if tmp<0 else tmp | d69f236f4635d1a91a253dfe614e8a786c08753d | 37,147 |
import itertools
def normalize_padding(padding, rank):
"""
normalized format of padding should have length equal to rank+2
And the order should follow the order of dimension
ex. Conv2d (rank=2) it's normalized format length:2+2 ==>(left, right,top bottom)
Args:
padding (None, int, tuple)... | 6e67d1a7ff408c013fe7fc122a0b0320025e2373 | 37,154 |
import string
import secrets
def get_alphanumeric_unique_tag(tag_length: int) -> str:
"""Generates a random alphanumeric string (a-z0-9) of a specified length"""
if tag_length < 1:
raise ValueError("Unique tag length should be 1 or greater.")
use_chars = string.ascii_lowercase + string.digits
... | 098c9888790faf6b771062e13a31f5e8f6eba4e0 | 37,156 |
from typing import Any
from typing import TypeGuard
import numbers
def is_complex(x: Any) -> TypeGuard[complex]:
"""Return true if x is complex."""
return isinstance(x, numbers.Complex) | fc1c98d9d8074ce5ffc1729a44d4daf463052e69 | 37,157 |
def is_obj(x):
"""
A quick (but maybe not perfect) check for object types
Returns:
bool: True if the object has __dict__ attribute, otherwise False
"""
try:
getattr(x, '__dict__')
return True
except:
return False | 324dccfd2d2c436940e5347055ec1b5aa5f021c0 | 37,158 |
from typing import Any
from typing import Callable
def verify_operands_classes_and_forward_to_callable(
x_operand: Any,
y_operand: Any,
operand_class: type,
function: Callable[[Any, Any], Any],
) -> Any:
"""
verify_operands_classes_and_forward_to_callable verifies both operands are
of type... | 8553b0ae796641226724cc9b0557b59dfe7a8fbf | 37,161 |
from typing import List
def staircase(size: int) -> List[str]:
"""
>>> staircase(4)
[' #', ' ##', ' ###', '####']
"""
# ret = [f"{'#' * i:>{size}}" for i in range(1, size+1)]
ret = [('#' * i).rjust(size) for i in range(1, size+1)]
return ret | e75508019be90223a49aa5161876e34018b387e5 | 37,165 |
from pathlib import Path
def load_groups(input_path: Path) -> list:
"""
Load in the customs quesetionarre response data into a buffer and group
together the responses that are associated with a single group.
Responses belonging to a single group are on contiguous lines,
and groups are separated by... | f23eb0398757e749786a7ba1fdcb8dede18736fd | 37,170 |
def get_trip_distance(distances_matrix, path):
"""
:param distances_matrix: Matrix of distances between cities
:param path: List of city indices
:return: Trip distance
"""
distance = 0
for index in range(len(path))[1:]:
distance += distances_matrix[path[index - 1], path[index]]
... | aabb74cb8b876911e384eceb86c33f4114327fb2 | 37,175 |
def gift_list(number):
"""Generates the list of gifts for a given verse
Parameters
----------
number: Integer
The number of the verse we want the list for
Returns
-------
string
The list of gifts
"""
gifts = {
1: 'a Partridge in a Pear Tree',
2: 'two... | 20c9cf10f80e8ee0650721253b31554ed0cda6a4 | 37,179 |
def get_adjusted_unsuccessful(row, outcome_col, num_unsuccess_col):
"""
Returns adjusted number of unsuccesful contacts given column of outcome and num_unsuccess
"""
outcome = row[outcome_col]
num_unsuccess = row[num_unsuccess_col]
if outcome == 0:
adj_num_unsuccess = num_unsuccess - 3 i... | 77f0b0d46269bfe299d8791c04a152a1d2df27ed | 37,180 |
def triangular_force(t_start, t_max, t_end, f_max):
"""
Returns a triangular force:
f_max at t_max
/\
/ \
/ \
/ \
---- -----
| |
| |__ t_end
|__ t_start
Parameters
----------
t_start: float
... | 91a69292b9ff641a9b47c280438f64c13ba89bc9 | 37,181 |
from datetime import datetime
def FormattedTime(DateTimeObject = None) -> str:
"""Returns a formatted time string."""
if DateTimeObject == None:
DateTimeObject = datetime.now()
return DateTimeObject.strftime("%H:%M:%S") | 51d431e40691371579530419aebd19de4655455c | 37,185 |
import re
import click
def parse_port(port: str) -> str:
"""Check if port is valid.
Parameters
----------
port : str
Possible port name.
Returns
-------
port : str
Valid port name
Raises
------
click.BadParameter
If ``port`` is not a four-digit number... | e6acb439117f0d30ec161875371aa7e7b9f10c76 | 37,187 |
def get_nlp_bib_neotoma(nlp_sentences, bibliography, neotoma_summary):
"""
Uses all main datasets to create preprocessed_df dataframe
Parameters
----------
nlp_sentences : pd.DataFrame
pd.DataFrame with all NLP Sentences database information
bibliography : pd.DataFrame
pd.DataFr... | 0c706502b79de5e10736192dfd6e6aa05593e61d | 37,196 |
def find_link_joints(model, link_name):
"""Find the joints attached to a given link
Parameters
----------
model : <ModelSDF>
SDF model
link_name : <str>
Name of the link in the sdf
Returns
-------
out : <tuple>
Tuple of joint names attached to the link
"""
... | 1d09cdf09889e19b7d8b911686ce90765d772a1c | 37,203 |
def polyfill_filename(api):
"""Gets the filename associated with an API polyfill.
Args:
api: String name of API.
Returns:
Filename of API polyfill.
"""
return "{}.polyfill.js".format(api) | efb54fddafb846985c77e44837f7a24c57596581 | 37,204 |
def standardize_survey_list(row):
"""This function takes in a list for a given row of a survey result and will
lower-case it and strip out white space from left and right of the string.
Args:
row (list): A list of survey results
Returns:
list: standardized survey results
"""
# ... | cf1e627e25a1dc98d8748a8bc1e0b78e420eb043 | 37,205 |
def make_ucsc_chr(interval):
"""
Converts interval from ENSEMBL chroms to UCSC chroms
(appends str to each chrom)
"""
interval.chrom = "chr" + interval.chrom
return interval | d5878670494dc51e29922d43a605634f26cd8e00 | 37,207 |
from typing import Any
def verbatim(text: Any) -> str:
"""
Returns the main string argument as-is.
It produces a TypeError if input text is not a string.
"""
if not isinstance(text, str):
raise TypeError("argument to verbatim must be string")
return text | 0f735833f1514f0f5bd45efc07af783ffc72cbd3 | 37,210 |
def format_bool(value):
"""Converts boolean to yes/no string."""
return 'bez dat' if value is None else ('Ano' if value else 'Ne') | 04aa58c8d280bc90c52169bf563650075963d6a2 | 37,211 |
def get_mappings(all_tweets_itr):
"""Returns a tuple with two dictionaries.
The first is a mapping username -> userid, where username is the one @foo, with @.
The second is a mapping tweetid -> userid of the creator"""
map_usrname_usrid = {}
map_twtid_usrid = {}
print(" [*] Extracting user mapp... | 7794676f45a9610b48e569c2c115faa04dc48904 | 37,214 |
def get_message_source_from_event(event):
"""
Helper function to get the message source from an EventHub message
"""
return event.message.annotations["iothub-message-source".encode()].decode() | 37d8c0aa2304f930c8e1507bf5a2355e3ccb66e9 | 37,215 |
def recover_bps(delt, bps, bps_star):
"""
delt, bps, bps_star - seqlen+1 x bsz x K
returns:
bsz-length list of lists with (start_idx, end_idx, label) entries
"""
seqlenp1, bsz, K = delt.size()
seqlen = seqlenp1 - 1
seqs = []
for b in range(bsz):
seq = []
_, last_la... | 1f0adca5aa25ae818b8738ef0bfefb0a6f44fe6c | 37,220 |
def _ops_equal(op1, op2):
"""Checks if two operators are equal up to class, data, hyperparameters, and wires"""
return (
op1.__class__ is op2.__class__
and (op1.data == op2.data)
and (op1.hyperparameters == op2.hyperparameters)
and (op1.wires == op2.wires)
) | dd73cc9f89ec0fc8540043b7982a6c5b6fc8609b | 37,222 |
import requests
def extract_wiki_text(wikipedia_title, language='en'):
"""Get the text of the given wikipedia article."""
base_url = ('https://' + language + '.wikipedia.org/w/api.php?action=query'
+ '&prop=extracts&format=json&explaintext='
+ '&exsectionformat=plain&titles=')
... | 231bfec347c0a92b19081bb852feb3b6c7674413 | 37,225 |
from typing import Dict
from typing import Any
import torch
def load_to_cpu(path: str) -> Dict[str, Any]:
"""
This is just fairseq's utils.load_checkpoint_to_cpu(), except we don't try
to upgrade the state dict for backward compatibility - to make cases
where we only care about loading the model param... | aa30621b7230a3f22afbfd3db50f74d8f385493a | 37,226 |
def bootstrap_predictions(train_x, train_y, test_x, model, boot_idx=None, permute_idx=None):
"""
fits a model to training data and predicts output using test data. features are selected with boot_idx.
Optional permutation of rows for significant testing.
train_x, test_x: dataframes containing train and... | dbe328094a2eda06a048f0d3cdcee182e8558db2 | 37,232 |
def bag_of_words(text):
"""Returns bag-of-words representation of the input text.
Args:
text: A string containing the text.
Returns:
A dictionary of strings to integers.
"""
bag = {}
for word in text.lower().split():
bag[word] = bag.get(word, 0) + 1
return bag | 75993f3bd5fb20e3015afee499a14bf1574902ca | 37,234 |
def find_list_string(name, str_list, case_sensitive=True, as_prefix=False, first_matched=False):
"""
Find `name` in the string list.
Comparison parameters are defined in :func:`string_equal`.
If ``first_matched==True``, stop at the first match; otherwise if multiple occurrences happen, raise :exc:`... | f485ae3cdebcee9e4cfe85378c38f7f27d737b96 | 37,236 |
def rmRTs(tokens) :
"""Remove RTs"""
return [x for x in tokens if x != "rt"] | 00df94bcfba29784bae736bb41c964cea7589657 | 37,237 |
def test_attr(attr, typ, name):
"""Tests attribute.
This function tests if the attribute ``attr`` belongs to the type ``typ``,
if not it gives an error message informing the name of the variable.
"""
try:
return typ(attr)
except:
raise TypeError('"{}" keyword must be a {} object... | 28e0bdad00117cca25a67057db2f1525387cf39d | 37,241 |
def get_phylogenetic_weight(node):
"""Calculate the weight at a phylogenetic node.
Args:
node (`Node`): The phylogenetic node.
Returns:
float: (weight of the parent) / (number of siblings + 1).
"""
if node.parent is None:
return 1.0
return 1.0*get_phylogenetic_weight(node.parent)/len(node.parent.childr... | 2a57eb9cac2f5939d13552ea1e99e8dc99313db9 | 37,242 |
import json
def create_button(action,
payload,
label,
display_mode='popup',
disabled=False):
"""
This function creates an HTML button the user can interact with from
a CloudWatch custom widget.
Parameters:
action ... | 33d7255888b956275e9783ee91c297b81fdc6ae7 | 37,246 |
def order_validation(order):
"""
Validate the order. If it's under 2 then raise a ValueError
"""
if order < 2:
raise ValueError("An order lower than two is not allowed.")
else:
return order | ee9f9c64c30a9625246d5e139c94a53d144270db | 37,247 |
import requests
import io
import zipfile
def download_zip(url, to_path):
"""Download zipfile from url and extract it to to_path.
Returns the path of extraction.
"""
filename = url.split('/')[-1]
r = requests.get(url)
r.raise_for_status()
content = io.BytesIO(r.content)
with zipfile.Zi... | 904a4a0082040ec40e09f8cac8275c36943a3acc | 37,251 |
def to_gib(bytes, factor=2**30, suffix="GiB"):
""" Convert a number of bytes to Gibibytes
Ex : 1073741824 bytes = 1073741824/2**30 = 1GiB
"""
return "%0.2f%s" % (bytes / factor, suffix) | 1006d69275c212d978b06ab248f02ea966f1490e | 37,255 |
def fn_middleware(get_response):
"""Function factory middleware."""
def mw(request):
response = get_response(request)
return response
return mw | e4261f99c2acd939dfb6198f1e253a680c2d9184 | 37,258 |
def include_key_in_value_list(dictio):
"""
Returns a list that contains the cases in the log,
starting from the dictionary returned by PM4Py
Parameters
---------------
dictio
Dictionary of cases
Returns
---------------
list_cases
List of cases
"""
ret = []
... | 917cf7a280daad5372ff9ac312d96dc46fdcc5e6 | 37,259 |
def var_number(i, j, d, k):
"""
Convert possible values into propositional vars
:param i: row number 1 - 9
:param j: col number 1 - 9
:param d: digit 1 - 9
:param k: size of suduko
:return: variable number 1- 729
"""
return (k ** 2 * k ** 2) * (i - 1) + (k ** 2) * (j - 1) + d | 676bd8c4e67466926b21542bad96c9864ca6da2c | 37,261 |
import pickle
def load(input_filename):
"""unpickle an object from a file"""
with open(input_filename, "rb") as input_file:
res = pickle.load(input_file)
return res | 7401114353e671fa52a035159dd564882b771bc3 | 37,266 |
def s3_object_exists(s3):
"""Provide a function to verify that a particular object exists in an
expected bucket."""
def check(bucket_name, key):
bucket_names = [
bucket_info["Name"] for bucket_info in s3.list_buckets()["Buckets"]
]
if not bucket_names:
return... | a0f549de4b2acc3fbbc4077d31f4feca9eec5cae | 37,272 |
def binary(i, width):
"""
>>> binary(0, 5)
[0, 0, 0, 0, 0]
>>> binary(15, 4)
[1, 1, 1, 1]
>>> binary(14, 4)
[1, 1, 1, 0]
"""
bs = bin(i)[2:]
bs = ("0" * width + bs)[-width:]
b = [int(c) for c in bs]
return b | 0a9ee440d14cc0fccc8b3d7c83c36582a4583749 | 37,280 |
def price_index(price_of_product_x, price_of_product_y):
"""Return the price index of product X over product Y.
Args:
price_of_product_x (float): Price of product X.
price_of_product_y (float): Price of product Y.
Returns:
price_index (float): Price of X / Price of Y
"""
r... | e3f6eeec3395cf039e037eca97bca5e1b7eb55ca | 37,281 |
def kelvin_to_level(kelvin):
"""Convert kelvin temperature to a USAI level."""
if kelvin < 2200:
return 0
if kelvin > 6000:
return 100.0
return (kelvin-2200)/(6000-2200) * 100 | 993cce9c7b85dea718a0eb21fd1e20a088a403f9 | 37,286 |
def hexinv(hexstring):
"""
Convenience function to calculate the inverse color (opposite on the color wheel).
e.g.: hexinv('#FF0000') = '#00FFFF'
Parameters
----------
hexstring : str
Hexadecimal string such as '#FF0000'
Returns
-------
str
Hexadecimal string suc... | a38f1bc031ddc7f15fa462c32de4af93fa42a6c3 | 37,290 |
def has_changes(statements):
""" See if a list of SQL statements has any lines that are not just comments """
for stmt in statements:
if not stmt.startswith('--') and not stmt.startswith('\n\n--'):
return True
return False | d357443e34a575af2cb1827064fa372668097895 | 37,296 |
def disconnect(signal, slot):
"""Disconnect a Qt signal from a slot.
This method augments Qt's Signal.disconnect():
* Return bool indicating whether disconnection was successful, rather than
raising an exception
* Attempt to disconnect prior versions of the slot when using pg.reload
"""
... | 6aee43431c153a48111f21541448009496f27dd3 | 37,297 |
from typing import Dict
from typing import List
from typing import Optional
import queue
def find_node_distance(
i: int, vertex_connections: Dict[int, List[int]], target: Optional[int] = None
):
"""
Finds the distances from one node to all others.
Args:
i: starting vertex idx
vertex_co... | 38f68e536d1863e1f00d5b429ce1ba359ff65977 | 37,301 |
import _warnings
def discard_short_fixations(fixation_sequence, threshold=50):
"""
Deprecated in 0.4. Use `eyekit.fixation.FixationSequence.discard_short_fixations()`.
"""
_warnings.warn(
"eyekit.tools.discard_short_fixations() is deprecated, use FixationSequence.discard_short_fixations() inst... | dfd09cc1db421e480e569d94caf479c4d496906b | 37,304 |
def sort_notes_into_folders(notes, folders):
"""
sorts notes into a dictionary with the folder names as the key
:param notes:
A list of notes objects
:param folders:
a list of tuples with each tuple holding (folder_id, folder_name)
:return:
a dictionary with all the notes, s... | fb4d788e59b2796c6a01a0b9ad132f44bb1693c1 | 37,305 |
def get_url(post):
"""
Gets the url of the actual JPG file from the post object.
"""
url = post['data']['url']
if url.endswith == 'jpg':
return url
elif url.endswith == '/':
return url.strip('/') + '.jpg'
else:
return url + '.jpg' | f4a953a1602e80fff50e0e2730f4976ffb79ff78 | 37,308 |
def cleanString(s):
"""converts a string with leading and trailing and
intermittent whitespace into a string that is stripped
and has only single spaces between words
>>> cleanString('foo bar')
u'foo bar'
>>> cleanString('foo bar')
u'foo bar'
>>> cleanString('\\n foo \\n\\n bar ')
u'foo bar'
>>> cleanStri... | 5a816b6bb0b93e869b2ce144cf8aaed305c0e9e8 | 37,310 |
def get_short_name(full_path):
"""
Returns the short name of an operation or service,
without the full path to it.
"""
return full_path.rsplit('/')[-1] | 820a2e8444cecbd7f164563ecd8887dc122bd126 | 37,315 |
from typing import Any
from typing import OrderedDict
def getvalue(object: Any, key: Any) -> Any:
"""Access a dict or class instance attribute value in a unified way"""
if type(object) == dict or type(object) == OrderedDict:
# Dict or OrderedDict
return object.get(key)
else:
# Clas... | e9e278c184771efa3505d266b6b7f2b50a8217f0 | 37,316 |
def parse_test_id(test_id):
"""
Parse a test ID into useful parts.
Takes a test ID and parses out useful parts of it::
> parse_test_id('foo.bar.baz.test_mod.MyTestClass.test_method')
{
'scope': 'foo',
'type': 'bar',
'accreditation': 'baz',
'f... | facd326fb5e31b72369fa1fc0dc17506ce128af1 | 37,322 |
def parse_cellType(file_name):
"""
Parsing file_name and extracting cell-type
input file must be EXPERIMENT_AREA_CELL-TYPE.bam so bamtools create
EXPERIMENT_AREA_CELL-TYPE.REF_chrN.PEAK
:param file_name:
:return: cell_type
"""
parse = file_name.split('.')[0].rsplit('_')
return parse... | 872886d5f267452b105794e6befc9c88946350b0 | 37,325 |
def point_num_to_text(num_fita):
""" Transform point's order number into text """
num_fita = int(num_fita)
num_fita_str = str(num_fita)
if len(num_fita_str) == 1:
num_fita_txt = "00" + num_fita_str
elif len(num_fita_str) == 2:
num_fita_txt = "0" + num_fita_str
else:
num_f... | 5042a7c200c4987748f825213f08788b44b091c1 | 37,326 |
def merge_dictionaries(dictionaries):
""" Merge a sequence of dictionaries safely.
This function merges dictionaries together, but ensures that there are
not same keys which point to different values. That is,
merge_dictionaries({'alpha':True}, {'alpha':True}) is OK, but
merge_dictionaries({'alpha'... | b536f68d79e1e55d2d1fa8f2ed4e26c5452003ad | 37,327 |
import asyncio
async def my_task(seconds):
"""
A task to do for a number of seconds
"""
print('This task is taking {} seconds to complete'.format(seconds))
await asyncio.sleep(seconds)
return 'task finished' | 25decc9efbbd47a99cfe698a5565a689f9cc5a00 | 37,331 |
def hash_to_dir(hash):
"""
Transforms a given hash to a relative path and filename
ex: '002badb952000339cdcf1b61a3205b221766bf49' ->
'00/2badb952000339cdcf1b61a3205b221766bf49'
:param hash: the hash to split
:rtype: string
"""
return hash[:2]+'/'+hash[2:] | c3800e89da7ab6319076e45cbd051a84a55ff9f7 | 37,332 |
def ReadBBoxPredictFile(file_path):
"""
Args:
file path : str
File format:
image_name:<image_name.jpg>
(percentage) (abs)
<class_name>,<confidence>,<x1>,<y1>,<x2>,<y2>
...
end
example:
image_name:a.jpg
... | 086865ca68bd3387f090ffd5cdedac659cd10bbf | 37,333 |
def element_to_set_distance(v, s):
"""Returns shortest distance of some value to any element of a set."""
return min([abs(v-x) for x in s]) | af77a125773312fd815cbad639b81601c427cf6b | 37,338 |
import re
def find(seq, pattern, matcher=re.match):
"""
Search pattern in each element in sequence and return the first
element that matches the pattern. (Like re.search but for lists.)
"""
for elem in seq:
if matcher(pattern, elem) is not None:
return elem | 956c640d52ab2161cf4cf8f5b270511fb514d4a8 | 37,339 |
def _get_shading(idf):
"""Get the shading surfaces from the IDF."""
shading_types = ["SHADING:ZONE:DETAILED", "SHADING:SITE:DETAILED"]
shading = []
for shading_type in shading_types:
shading.extend(idf.idfobjects[shading_type])
return shading | 48a212035dae232265a1bb7979d11a0cd1b70d41 | 37,341 |
def compute_taw(fc, pwp, depth, fraction):
"""
Compute total available water
:param fc: Field capacity
:param pwp: permanent wilting point
:param depth: depth of soil in mm
:param fraction: float value
:return: a float value for TAW
"""
return depth * fraction * (fc - pwp) | d97a1e4cc918228fc7b0e457f1fac3ce2502f62e | 37,346 |
def parse_list_arg(args):
"""
Parse a list of newline-delimited arguments, returning a list of strings with leading and
trailing whitespace stripped.
Parameters
----------
args : str
the arguments
Returns
-------
list[str]
the parsed arguments
"""
return [u.... | 5df3a59b4ced466e4107f494b8ed0e2fc6de917c | 37,349 |
def after_n_iterations(n):
"""Return a stop criterion that stops after `n` iterations.
Internally, the ``n_iter`` field of the climin info dictionary is
inspected; if the value in there exceeds ``n`` by one, the criterion
returns ``True``.
Parameters
----------
n : int
Number of ite... | 134da90fa5890055417a3f89d185f74b082906d1 | 37,350 |
def _encode_asn1_str(backend, data):
"""
Create an ASN1_OCTET_STRING from a Python byte string.
"""
s = backend._lib.ASN1_OCTET_STRING_new()
res = backend._lib.ASN1_OCTET_STRING_set(s, data, len(data))
backend.openssl_assert(res == 1)
return s | 2b673060b2793c740b0111e8280fd92a9b291fec | 37,353 |
import re
def ignore_template_file(filename):
"""
Ignore these files in template dir
"""
pattern = re.compile('^\..*|.*\.cache$|.*~$')
return pattern.match(filename) | 0a9402e968cd3cc8a2ca7839c7d7100206ee663f | 37,354 |
from typing import List
def dna_union(
start, end, audio_length: int, do_not_align_segments: List[dict],
) -> List[dict]:
""" Return the DNA list to include [start,end] and exclude do_not_align_segments
Given time range [start, end] to keep, and a list of do-not-align-segments to
exclude, calculate t... | efabb0391187500cb157bae20b2720028676c50b | 37,359 |
def dict_updater(source: dict, dest: dict) -> dict:
"""
Updates source dict with target dict values creating
new dict and returning it
"""
target = dest.copy()
for k, v in source.items():
if isinstance(v, dict) and k in dest:
target[k] = dict_updater(v, dest[k])
else... | cf2aa4aa238b4d7a8057fc8c29fd6755eaf02ff4 | 37,361 |
def function_star(list):
"""Call a function (first item in list) with a list of arguments.
The * will unpack list[1:] to use in the actual function
"""
fn = list.pop(0)
return fn(*list) | 5ff784703b9238bf5d99dd4a0e1313ed8f97df88 | 37,362 |
def _pdf_url_to_filename(url: str) -> str:
"""
Convert a PDF URL like 'https://www.mass.gov/doc/weekly-inmate-count-4202020/download'
into a filename like 'weekly-inmate-count-4202020.pdf'
"""
name_part = url[25:-9]
return f"{name_part}.pdf" | 45d4e6608813161227a19bbc29b611d6568c8d23 | 37,364 |
def get_freq_weights(label_freq):
"""
Goal is to give more weight to the classes with less samples
so as to match the ones with the higher frequencies. We achieve this by
dividing the total frequency by the freq of each label to calculate its weight.
"""
total_size = 0
for lf in label_freq.v... | 7e0275365eb014806a6cf7c8f69415f243301d35 | 37,365 |
def subtract_number(x, y):
"""This function will subtract 2 numbers"""
return x - y | 32868ec101c36f5fb7267361a6da4eb017e38a47 | 37,367 |
def nearest(array, pivot):
"""find the nearest value to a given one
Args:
array (np.array): sorted array with values
pivot: value to find
Returns:
value with smallest distance
"""
return min(array, key=lambda x: abs(x - pivot)) | 75d468613a766425346ae980cef3ab0bd19d5e1c | 37,373 |
import logging
def get_builder_log(name):
"""Get a logging object, in the right place in the
hierarchy, for a given builder.
:param name: Builder name, e.g. 'my_builder'
:type name: str
:returns: New logger
:rtype: logging.Logger
"""
return logging.getLogger("mg.builders." + name) | 2a158c3cff310f005fd42f8b9ee9ad61d68e08be | 37,374 |
def replace_redundant_grammemes(tag_str):
""" Replace 'loc1', 'gen1' and 'acc1' grammemes in ``tag_str`` """
return tag_str.replace('loc1', 'loct').replace('gen1', 'gent').replace('acc1', 'accs') | 5469efb333a8c0174d4696d6559442f77a1fb6da | 37,376 |
def seating_rule(max_neighbours):
"""
If a seat is empty (L) and there are no occupied seats adjacent to it,
the seat becomes occupied.
If a seat is occupied (#) and max_neighbours or more seats adjacent to it
are also occupied, the seat becomes empty.
Otherwise, the seat's state does not change... | 7011b060d8ccfb378ccf15225af081ae09454e7f | 37,380 |
def crossProduct(p1, p2, p3):
"""
Cross product implementation: (P2 - P1) X (P3 - P2)
:param p1: Point #1
:param p2: Point #2
:param p3: Point #3
:return: Cross product
"""
v1 = [p2[0] - p1[0], p2[1] - p1[1]]
v2 = [p3[0] - p2[0], p3[1] - p2[1]]
return v1[0] * v2[1] - v1[1] * v2[0... | 4faf8f1d63192913c6a3abf726e343e377e9622a | 37,383 |
from datetime import datetime
def date_passed(value):
""" Checks if the embargoded date is greater than the current date
args:
value (str): Date in the format yyy-mm-dd that needs to be checked
returns:
(bool): If the given date is less than the current date or not
"""
value_date =... | fa3b3a47265dd15c6a9a6ba1820a3e7e61bbe945 | 37,385 |
from typing import Dict
from typing import Any
def value_from_dot_notation(data: Dict[str, Any], path: str) -> Any:
"""Take a dictionary `data` and get keys by the `path` parameter,
this path parameter will use the dots (.) as delimiter.
"""
for key in path.split('.'):
data = data[key]
ret... | 847f08c3132d17da9923d5a78a06f6f831be34c8 | 37,389 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.