content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Callable
from typing import Any
from typing import Tuple
import time
def time_fn(fn: Callable) -> Callable:
"""Decorator/wrapper for to measure the execution of a callable.
A function using this decorator will return a tuple whose
first item is the result of the function itself, and the... | c689575dc61f6bfe4cf1b04ed9350310211b0f93 | 590,194 |
def es_base(caracter):
"""
(string) -> bool
>>> es_base("A")
True
>>> es_base("x")
False
>>> es_base("0")
False
Valida si un caracter ingresado corresponde o no a una base
:param caracter: string Caracter ingresado sobre el cual se requiere identificar si corresponde o no... | 32cd7c2adbd9095262882d294048e557c67a8f6b | 590,195 |
def get_month_number(value: str) -> int:
"""
Parameters
----------
value: string containing short or full month name - min 3 chars long
Returns
-------
int representing month number
"""
return {'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4,
... | a42b80dbf55ae6a8120df19581f628400f338f7a | 590,197 |
def has_callables(iterable):
"""
A function used to determine if an iterable contains at least one callable.
"""
for item in iterable:
if callable(item):
return True
return False | 937bfc1b6fb7029268db40902a746028043abead | 590,198 |
def get_spacing(sitk_obj):
"""
flip spacing from sitk (x,y,z) to numpy (z,y,x)
"""
spacing = sitk_obj.GetSpacing()
return (spacing[2], spacing[1], spacing[0]) | b744e3ae62234325c5d692418a1a9eeff0da136c | 590,199 |
import itertools
def itail(iterable):
"""Returns an iterator for all elements excluding the first out of
an iterable.
:param iterable:
Iterable sequence.
:yields:
Iterator for all elements of the iterable sequence excluding
the first.
"""
return itertools.islice(iterable, 1, None, 1) | df7f0ddabc493a3c9ae84b13e82208d7d05ef2e3 | 590,200 |
def str_or_blank(value):
"""return '' if the provided value is `None`, else return value"""
return "" if value is None else str(value) | 115b8079145d6cd97b1250e5aaf32c1507620f90 | 590,203 |
def match(msg, key_set):
""" Match message properties.
:param msg: Message containing properties.
:param key_set: Set of property keys to match.
:returns: (key, value) of first property matched; None otherwise.
:raises: :exc:`ValueError` if key_set is not a set
"""
if type(key_set) is n... | 9f72af735eeb7ca13f093251ea90e873937e38a4 | 590,204 |
import torch
def calc_metrics(out, trg) -> torch.Tensor:
"""
Calculates the metrics necessary to evaluate how good the model is.
For now, it has two zeros as placeholders.
:param out: output of the model.
:param trg: target translation.
:return: number of tokens, number of correct tokens, pl... | eae0eb3942040230a5e03b35173f3732e4b151e1 | 590,206 |
def check_words(title, wordlist, verbose=False):
"""Helper function to check if any words in wordlist are in title."""
for word in wordlist:
if title.find(word) >= 0:
if verbose:
print("\t\tFOUND '"+word+"' IN:", title)
return True
return False | 37e664a02bf38c7dcd9e0ec330757fe324b66bed | 590,207 |
from typing import Tuple
def extract_parameter_name_and_type(line: str) -> Tuple[str, str]:
"""Read configuration parameter name from text"""
# Remove default value if any
line, *_ = line.split("=")
line = line.strip()
# Parameter is now the last entry of the line
*_, type_, param_name = line... | 0753bc68f1c56766a42ee0707b355d65226e3307 | 590,208 |
def get_label_RAVDESS(path):
"""Given a path to a RAVDESS audio file, extract the emotion and return the label"""
path = path.split("\\")
gender = path[-2][6:8]
if int(gender) % 2:
gender = "male"
else:
gender = "female"
emotion = path[-1][6:8]
# Convert calm to neutral; surp... | 8f174d1ae6259bc5d9bbdef5f35226d1969dd835 | 590,209 |
def changelog2dict(changelog):
"""
Helper turning internal list-o-releases structure into a dict.
See `parse_changelog` docstring for return value details.
"""
return {r["obj"].number: r["entries"] for r in changelog} | 31bc860dc5e670d096b3895da99a9ab19be46af9 | 590,211 |
def max_values_squad(data_train):
"""
Function to compute the maximum length of sentences in
paragraphs and questions
Arguments:
-----------
data_train: list containing the entire dataset
Returns:
--------
maximum length of question and paragraph
"""
max_hypothesis = len(dat... | f3794b512844cbe8d2aa72c4a8e3263356b1fa4d | 590,213 |
def filter_images_by_tags(annotations_df, include=None, exclude=None):
"""Filter images on tags
:param annotations_df: pandas DataFrame of project annotations
:type annotations_df: pandas.DataFrame
:param include: include images with given tags
:type include: list of strs
:param exclude: exclud... | 9164b1452dd66145ecd3b1ef4089123330ef04d5 | 590,218 |
def get_article(word):
"""Return English article for word.
Returns 'an' if word starts with vowel. Technically
it should check the word sound, compared to the
letter but this shouldn't occur with our words.
Args:
word (str): Word to create article for.
Returns:
'a' or 'an' (st... | 6f7e6a4461ab4b112b19c0e12b066a11b3b9047d | 590,220 |
def find_deltas(arr):
"""
Creates a new array that is the differences between consecutive elements in
a numeric series. The new array is len(arr) - 1
"""
return [j-i for i, j in zip(arr[:-1], arr[1:])] | fbd91938be06a62228a74422f4f4f86395b0080a | 590,225 |
import hashlib
def simple_hash(value: object, num_features: int) -> int:
"""Deterministically hash a value into the integer space."""
encoded_value = str(value).encode()
hashed_value = hashlib.sha1(encoded_value)
hashed_value_int = int(hashed_value.hexdigest(), 16)
return hashed_value_int % num_fe... | 114074377f82e863a8ec5e7cd587d1a67624931b | 590,227 |
def as_bool(a_string):
"""Returns python bool value from string."""
return a_string.lower() == "true" | 18828ef8f3001c42dc1001359a1d511137c918ec | 590,228 |
import re
def mergeinfo_notify_line(revstart, revend, target=None):
"""Return an expected output line that describes the beginning of a
mergeinfo recording notification on revisions REVSTART through REVEND."""
if target:
target_re = re.escape(target)
else:
target_re = ".+"
if (revend is None):
i... | a1e1dd546f815f84aef9dee4c0b85afd34750cae | 590,230 |
def FormatDateString(dt, time=True):
"""Formats a DateTime object into a string for display. If dt is not
a DateTime, then the empty string is returned.
Parameters:
* dt - An instance of DateTime.DateTime
* time - If True, displays the time. If False, only the date is
... | 8bc7b4fb08c3f0799055fdffeacd1c9994a98f5f | 590,231 |
import hashlib
def hash_file(file_content):
"""
Computes the MD5 hash of a file (input should be binary string of file's data).
"""
return hashlib.md5(file_content).hexdigest() | e684d7320cccb33361ab9739e199a0946f124d13 | 590,232 |
def parse_address(string):
"""Parses the address and port number from the command line.
Returns addres and port. Both can be None if config should be used instead.
"""
if string is None:
return None, None
if ':' in string:
addr, port = string.split(':')
return addr, int(port... | 3818fd52955244c16b251752fc15c9d5277760a8 | 590,234 |
import time
import requests
import uuid
import webbrowser
def _check_for_api(launch_browser=False, timeout=5):
"""Helper method to check for the API to be live for up to 15 seconds and then optionally launch a browser window
Args:
launch_browser(bool): flag indicating if the browser should be launche... | ffed20b56e7acb1625593f30cb452f9c9dea8681 | 590,235 |
import requests
import logging
def connect_to_endpoint(url, headers, params):
"""This function fetches tweets from specific twitter handle timelines
Args:
url: API endpoint to fetch tweets
headers: Headers
params: Additional parameters
Returns:
List of tweets as json paylo... | 3a5dff93101c22dec6da84c0ea8900d48bf7a6fd | 590,236 |
def eqir(registers, opcodes):
"""eqir (equal immediate/register) sets register C to 1 if value A is
equal to register B. Otherwise, register C is set to 0."""
test_result = int(opcodes[1] == registers[opcodes[2]])
return test_result | 0c2d23c1f1377cebb8d658edf8b764891c748094 | 590,237 |
def get_result_file_type(file_name):
"""
Given a name of an Ocellaris output file (either log or restart file)
return 'h5' or 'log' depending on the file type. Returns None for
unknown files
"""
if file_name.endswith('.h5'):
return 'h5'
elif file_name.endswith('.log'):
return... | eb85e95cacf8bb54c5fc88acfdfafa09280c5c9f | 590,238 |
def not_all_alpha(r):
"""
:param r: (str) User's input
:return: (bool) Whether user's input are all letters and no punctuation marks
"""
a = 0
for ch in [r[0], r[2], r[4], r[6]]:
if not ch.isalpha():
a += 1
if a > 0:
return True | 49517a74d227e096a65c610ad9f1df604320a683 | 590,239 |
def matching_loss_name_normalizer(name: str) -> str:
"""Normalize the class name of a MatchingLoss."""
return name.lower().replace('matchingloss', '') | 805b853a3b4d1e5a4b94d944191cb8c927c45bd1 | 590,241 |
from functools import reduce
def to_dense_hash(hash):
"""Returns the dense hash from a sparse hash by XOR-ing 16 elements
from consecutive blocks"""
dense_hash = []
for i in range(0, len(hash), 16):
block = reduce(lambda x, y: x ^ y, hash[i:i+16])
dense_hash.append(block)
return de... | 96bb839a04675f137f82b5e5f6c91a6f525066e4 | 590,242 |
def ShouldCheckFile(file_name):
"""Returns True if the given file is a type we want to check."""
if len(file_name) < 2:
return False
return file_name.endswith(".cc") or file_name.endswith(".h") | c70a4ea1ee559610127cfc6d092127cbf72b273a | 590,244 |
import yaml
def load_yaml(filename):
""" Helper function for loading a single yaml entry from file """
with open(filename, "r", encoding='utf-8') as stream:
content = stream.read()
return yaml.safe_load(content) | f646b1bc4516d52c58c6097efddba001d3607b1f | 590,246 |
def rh(qtot, qsat):
"""Fraction of total specific water and saturation specific humidity."""
return qtot / qsat | 189196c81959e4fe166d03ef94ed5507d92a22a5 | 590,247 |
import re
def format_setenv(key, value):
"""Format key,value pair as 'setenv' with newline for C-shell.
A leading '#' for key adds a comment character to the entire line.
A value of 'None' corresponds to 'unsetenv'.
"""
if key.startswith('#'):
return '## setenv {0} {1}\n'.format(re.sub(r'^... | 0c92286c751f2907fd9c1619a1edbcd80c7e7fcf | 590,249 |
import re
def strip_concat(sequence: str,
) -> str:
"""
Cleans up concat sequences (peptide_charge) and remove modifications
to return peptide string for labeling site calculations
:param sequence: concat sequence containing charge and modificaitons
:return:
"""
# 2021... | c646f90a68873661049dd39b7cc4c9bcf47134b5 | 590,251 |
import random
def strictExp(min_wait,max_wait,mu=1):
"""
Returns an exponentially distributed time strictly between two bounds.
"""
while True:
x = random.expovariate(mu)
increment = (max_wait-min_wait)/(mu*6.0)
result = min_wait + (x*increment)
if result<max_wait:
... | 9d9ca88ac078b9a50d60cb7f4c2a1f3b89d9d2c1 | 590,254 |
def _get_only_elem_child_node(node):
"""
Internal method to return only first element child node
"""
child_list = [child_node for child_node in node.childNodes
if child_node.nodeType == child_node.ELEMENT_NODE]
return child_list[0] | 104a06de5184caf21aa505f6099207c5dd6056ad | 590,256 |
def kind(n, ranks):
"""Return the first rank that this hand has exactly n of.
Return None if there is no n-of-a-kind in the hand.
"""
for r in ranks:
if ranks.count(r) == n:
return r
return None | bcf6d4ce0799e248f218d458283bdac483f7028f | 590,261 |
def subdivise(tiles, zoom_current, zoom_target):
"""
Subdivise a list of tiles at level zoom_current into tiles at level zoom_target.
"""
coords = list()
ratio = 2 ** (zoom_target - zoom_current)
for x, y in tiles:
for X in range(ratio):
for Y in range(ratio):
... | 3c0ca43f7f14eb53c6dc51e4cef7f469db09558f | 590,262 |
def check_submission(sub):
"""
Checks that the submission meets all the requirements.
1. No more than 22 Boxes per frame.
2. Only one label prediction per video/frame
3. No duplicate boxes per frame.
4. Boxes must be within video area:
- `top` and `left` must each be >= 0
- The s... | 28ee721b0da5abfb13183d26cabf5687eeb94f5b | 590,263 |
def is_build_id(log, ad, build_id):
"""Return if ad's build id is the same as input parameter build_id.
Args:
log: log object.
ad: android device object.
build_id: android build id.
Returns:
True if ad's build id is the same as input parameter build_id.
False otherw... | 3aeab00b2e9d9d21e7eabe3394587763f2ec812d | 590,267 |
from typing import List
def split_key(parent_key: List[str]) -> List[List[str]]:
"""Split group key into parts."""
key_parts = []
while parent_key:
key_parts.append(parent_key)
parent_key = parent_key[:-1]
return key_parts[::-1] | 157c02092452c4757e03f963cce9b2cccd456c4b | 590,268 |
def validate_extension(filename: str) -> bool:
"""Validates extension in filename.
Args:
filename (str): name of the file.
Returns:
bool: if extension is valid.
"""
valid_extensions = [".toml"]
for extension in valid_extensions:
if filename.endswith(extension):
... | 592b91631693dd13a1f1317d22e683c24506139e | 590,274 |
def fuel(mass: int) -> int:
""" Calculate needed fuel based on mass """
return mass // 3 - 2 | 81bce143ebb942ee6ae64c435a18925dbb427288 | 590,276 |
def get_cookie_from_response(response, cookie_name):
"""Returns cookie value of cookie_name"""
for c in response.cookies:
if c.name == cookie_name:
return c.value
return None | afcd458cfdbe978715c7aca5aa6aa4cf4cc5258c | 590,277 |
from typing import Type
from typing import Iterable
from typing import Optional
from textwrap import dedent
def get_docstring(
cls: Type,
*,
flatten: bool = False,
fallback_to_ancestors: bool = False,
ignored_ancestors: Iterable[Type] = (object,),
) -> Optional[str]:
"""Get the docstring for a... | 402d7365749f8eb687a145de50ab4330c2a129fc | 590,278 |
def datetime_to_ldap(dt):
"""
Convert datetime object to LDAP generalized time format
"""
return dt.strftime("%Y%m%d%H%M%S") + "Z" | 92099c9467a4452a0d199e53af6b802a98c3bb99 | 590,284 |
def get_unit_q(unit):
"""
Given a unit abbreviation return the appropriate qid.
Powers can be given as either a plain number or a raised number, e.g.
km2 or km².
@param unit: the unit abbreviation to look up
@type unit: str
@return: Q-value of matching wikidata entry or None if not mapped
... | 1e3212a83220f41f0128ee6cc60858fccce23b5e | 590,286 |
def square2(x):
"""Calculate the square of the given number."""
return x * x | c4f6c1e6a1be62cb14f15eb08a5c0224178775f6 | 590,289 |
import re
def isCapitalized(token):
"""
Returns true if a given token starts with a capital letter.
"""
return re.match(r'^[A-Z]', token) is not None | 8b71a0e20e64b3a7d29eff2f1fe9a2bca74bd6fd | 590,290 |
import requests
def post_query(query, page_number):
""" Posts a query to the xeno-canto API.
Arguments:
query (str): Xeno canto search query.
page_number (int): Which page to download.
Returns:
response_json (dict): A dictionary containing all metadata of a recording.
"""
... | 1a8a236e93488610f142b4baf1cdfb088ddefc46 | 590,294 |
def client(app):
"""
Setup an app client, this gets executed for each client.
:arguments: app {object} -- Pytext fixture
:return: Flask app client
"""
return app.test_client() | d2e88b119c67d6bea7da04ad00c9bb6f20b07d66 | 590,296 |
def flatten_list(lol):
""" Given list of lists, flattens it into a single list. """
output = []
for el in lol:
if not isinstance(el, list):
output.append(el)
continue
output.extend(flatten_list(el))
return output | c7fa30f53f8668716dea3e7b651f32cb4c572587 | 590,298 |
def find_next_link(root, current_joint, next_link_name):
"""
Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automati... | 826e9da7bb3f8380fe2f47273398411d92031181 | 590,300 |
from operator import and_
def create_attr_filter(request, mapped_class):
"""Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
... | c862a86a9caaec3679c7fb1cb0e74fb501ba188d | 590,303 |
def unwrap_array(data, period, in_place=False):
"""
Removes jumps (due to fixed bit-width windowing, or something)
from a data array. "data" should be an array of signed values,
with possible jumps of size "period" in its right-most dimension.
With in_place=True, the data is unwrapped in place, ra... | 8c24180949e37c3dc3c8feca248bb74177264fb7 | 590,304 |
def _get_max_id(traj):
"""Get the biggest id within a trajectory
"""
return max([int(ids) for ids in traj.keys()]) | 8cbe1560a8dddcb81fb3fc20d83ca8c1aec92f82 | 590,311 |
def get_total_item_size(info, split):
"""Get total item size for given split.
inputs:
info = tensorflow dataset info
split = data split string, should be one of ["train", "validation", "test"]
outputs:
total_item_size = number of total items
"""
assert split in ["train", "tra... | 84432dabe790dac0b95fae4dff65fc9e787e51d7 | 590,313 |
def basin_finder(loc):
"""
Finds basin to load data from.
Input
loc: list of coordinates [lat, lon] or string refering to an area.
Output
basin , string: name of the basin.
"""
basin_dic = {'indus': 'indus', 'uib': 'indus', 'sutlej': 'indus',
'beas': 'indus', 'be... | db3a2f64539dafacc7d3a9747f00f44da428556a | 590,316 |
def floatizeL(aList):
""" Convert elements in aList to float number. """
return map(float, aList) | e513872f7427d654e905fb5e34540edf61fdc294 | 590,320 |
import inspect
def is_subclass(cls, base_class):
"""
Returns True if cls is an actual class (type)
and a subclass of base_cls
"""
return inspect.isclass(cls) and issubclass(cls, base_class) | cc5a5e5716d203485398cb34ef2fee87d3601196 | 590,322 |
def md_photo_location_uri(image_uri):
"""The URI of the location where a photo was taken."""
return image_uri+"/location" | e722453b16443b777b3fc8d8e75c4c599e99fd76 | 590,324 |
def append_csv_data(file_strings):
""" Append data from multiple csv files for the same time period
Parameters
-----------
file_strings : array-like
Lists or arrays of strings, where each string contains one file of data
Returns
-------
out_string : string
String with all d... | 479fd0b905ac0b6d34012ab81cde1b5b7935d5fd | 590,327 |
def get_number_of_word_in_a_list(word_to_search, word_list):
"""
Return the number of a given word in a given text
:type word_to_search: str
:param word_to_search: The given word to count instance of
:type word_list: list(str)
:param word_list: The list of word to search into
"""
number_of_occurence = 0
fo... | 2f5ebf2810f20587a4370ba5e58d693542f8f27a | 590,328 |
import struct
def _compute_program_checksum(data, program_size):
"""Compute checksum a "Stepleton" bootloader uses to verify program integrity.
This disk image creation tool directs the bootloader to load only as many
sectors as are required to fit the program. The bootloader will then compute
a checksum for... | 44031a478512cbb8bc153c9445d09e333cdff3d8 | 590,330 |
def net_city_blocks_from_places(place_gdf):
"""
Filter place gdf to retain net city_blocks and minimal columns.
Parameters
----------
gdf: GeoDataFrame
Returns
-------
GeoDataFrame
"""
# filter place polygons to retain only city blocks
net_city_blocks = place_gdf.loc[place... | ba2d9e40d924f7df011aefcb249f17c2db4231e2 | 590,333 |
def get_next_color(
ax_plot,
properties=['color', 'linestyle', 'marker', 'markersize','linewidth',
'markevery']
):
"""Utility which gets the next color in the axis `ax_plot` color cycle by
adding and removing a dot at the centre of the plot."""
x_min, x_max = ax_plot.get_xlim()
... | e41efb9ebbf023f2eb284af98695584013b14d17 | 590,334 |
def get_block_coords(row_num, col_num):
""" returns the upper left coordinates of the block in which the input coords exist """
return [row_num - (row_num % 3), col_num - (col_num % 3)] | 1df14eda875e52ced9cef1960ffb9eddc4247ab5 | 590,339 |
def is_number(s):
"""
Small function to check if a value is numeric
"""
try:
float(s) # for int, long and float - not complex as complex also allows 'J' as number or unit
except ValueError:
return False
return True | 6198e5b3a7b755fb427e905fe7d7a98068d52c46 | 590,341 |
def trim_doi(path):
"""Trim doi link.
e.g. https://doi.org/10.1093/hmg/ddy327
-> 10.1093/hmg/ddy327
"""
path = path.replace('https://doi.org/', '')
return path | e2a5265a8ee07499950fd497e68e4ee9facb0a56 | 590,345 |
from typing import Tuple
def text_reader(path: str) -> Tuple[list, list]:
"""Read a text file, and return data
data should follow this format:
I O
want O
to O
New B-City
York I-City
"""
with open(path, 'r', encoding='utf-8') as fobj:
parts = fobj.read().split('\n\n')
... | c13140bb2d2f4743091279df820707d7440da6bb | 590,354 |
import imghdr
def validate_image_file(filename, image_format):
""" Determine if an image file is valid
Args:
filename (:obj:`str`): path to image file
image_format (:obj:`ImageFormat`): image format
Returns:
:obj:`tuple`:
* nested :obj:`list` of :obj:`str`: nested li... | a22f61476daf79f05c8d0322b26cdabca310fc56 | 590,357 |
def differential_frequency(a, C, e, eref=1):
"""
Differential frequency of events with energies (or other metric) greater than e for a power-law of the form
f = C*e**-a
to the flare energy distribution, where f is the cumulative frequency of flares with energies greater than e.
"""
return a*C*... | 0c830ae564e25ba265ea4dca5ad2b783c77ffec6 | 590,362 |
def remove_last_entry_from_path(
path: str):
"""
- Use this to remove the last entry from a path.
:param path: Initial path.
:return: New path with the last entry removed.
"""
splitted = path.split('/')
new_path = ''
for index in range(len(splitted) - 1):
new_path += ... | c443076ba804a6f8b79dffaec36382ab398376db | 590,364 |
def _grade_level(total_sentences, total_words, total_syllables):
"""
Flesch-Kincaid Grade Level Score.
Parameters
----------
total_sentences: int, number of sentences.
total_words: int, number of words.
total_syllables: int, number of syllables.
Returns
-------
... | 1c2c78f35be0691b7c54debf9a6e4d80f7643317 | 590,365 |
def transpose_pairs(tuple_list):
"""
For each tuple pair in the list, transpose. i.e. (a,b) => (b,a)
"""
a,b = [list(x) for x in zip(*tuple_list)]
return list(zip(b,a)) | e7dd1dbfa8e1c73e84a88dbec44b08e86ff6c538 | 590,369 |
def idx2sign(idx: int, dim: int, neg: bool = True):
"""
Unify idx to be negative or positive, that helps in cases of broadcasting.
Parameters
----------
idx : int
current index
dim : int
maximum dimension
neg : bool
indicate we need negative index
Returns
--... | f9169834649091d10828f3e81857bc5c7e02b9e9 | 590,370 |
def _range_normalize(vector, lower=None, upper=None):
"""Normalizes values to a range (eg [0, 1]).
Used to range normalize a subset of a larger set of data (where the total
range exceeds the [min, max] of the values in vector).
Note that this can return values outside of [0, 1] if lower or upper are
within ... | 7f5cfa25f43bcf6307b9f2bb81f76823661906da | 590,373 |
def is_a_palindrome(string: str) -> bool:
"""Return True if string is a palindrome, False otherwise.
A palindrome is a string who can be read the same both
ways.
"""
return string == ''.join(reversed(string)) | 238f677dc732d4a3d2760771434a64b75f7d8c64 | 590,375 |
from typing import List
def _get_characters(sentence: str, whitespace: bool) -> List[str]:
"""Split sentence into individual characters.
Args:
sentence: An input sentence to split.
whitespace: An indication whether to keep whitespaces during character n-gram extraction.
Return:
A... | 63d5c6b5a75529b58cd97cad118ce9cd8b8cf88a | 590,376 |
def S(r, rc1, rc2, derivative=False):
"""
Calculate the switching function S(r) which decays continuously
between 1 and 0 in the range from rc1 to rc2 (rc2>rc1):
S(r) = (rc2^2 - r^2)^2 * (rc2^2 + 2*r^2 - 3*rc1^2) / (rc2^2-rc1^2)^3
I'm using the same smoothing/switching cutoff function used by the... | 1161c938e98ed959e11f55750100d0c4a8aff86f | 590,377 |
def indent_block(s, amt=1):
"""
Intend the lines of a string.
:param s: The string
:param amt: The amount, how deep the string block should be intended (default 1)
:return: The indented string
"""
indent_string = " "
res = s
for i in range(0, amt):
res = indent_string + ind... | adf74c9dc11baee6902ea148ef10c9eb6a65c7d4 | 590,378 |
def is_session_name(parameter):
"""Whether the parameter is a session name parameter."""
return parameter.get("is_session_name", False) | 9c482dfd454108d394c479822f18fd4eec6b2d2b | 590,380 |
def keltner_channels(data, period=20, atr_period=10, kc_mult=2, take_last=50):
"""
calculate keltner channels mid, up and low values
"""
ema = data.close.ema(period).select('ema')
atr = data.atr(atr_period).select('atr')
high = ema[-take_last:] + (kc_mult * atr[-take_last:])
low = ema[-take_... | e7eb9982689197db7f8a7f2b09de640b16c148f6 | 590,381 |
def is_file_key(path):
"""Returns True if the given S3 key is a file."""
return not path.endswith('/') | f5c7e0d96ba6581e6a8ec62d5765716d25424d6e | 590,387 |
def compute_max_saturation(a: float, b: float) -> float:
"""
Finds the maximum saturation possible for a given hue that fits in sRGB.
Saturation here is defined as `S = C/L`.
`a` and `b` must be normalized so `a^2 + b^2 == 1`.
"""
# Max saturation will be when one of r, g or b goes below zero.... | bc2fdafa3e02d4ff2479fe66efda8a093e2b91b6 | 590,390 |
def split_tag(image_name):
"""Split docker image by image name and tag"""
image = image_name.split(":", maxsplit=1)
if len(image) > 1:
image_repo = image[0]
image_tag = image[1]
else:
image_repo = image[0]
image_tag = None
return image_repo, image_tag | 576dbf7a1dd156dcb80d910e58aa6a76df1ce990 | 590,395 |
def humanize_name(name):
"""
"Humanize" camel case or Python variable name.
Usage:
>>> humanize_name('SomeName')
'some name'
"""
name = name.replace("_", " ")
parts = []
buffer = []
is_last_lower = False
for chr in name:
if chr.isupper():
if is_la... | 0325b45a2fae1efb3566b591fafe03b3bf2b5a87 | 590,398 |
def format_float_or_int_string(text: str) -> str:
"""Formats a float string like "1.0"."""
if "." not in text:
return text
before, after = text.split(".")
return f"{before or 0}.{after or 0}" | 47deb1b085a21efa48868043631099ec415fbdf3 | 590,400 |
def get_fname(config):
"""
Parameters
----------
config : dict
A dictionary with all the arguments and flags.
Returns
-------
fname : str
The filename for the saved model.
"""
hidden_dims_str = '_'.join([str(x) for x in config['hidden_dims']])
num_heads_str = '_'... | 51ba0e3fdeda03e9e8b7d13fd9806ab629c547f1 | 590,402 |
def jacobi(f, rho, h):
""" A Jacobi stepper for the Poisson equation in any number of dimensions.
Parameters
----------
f: numpy.ndarray
Initial guess for the solution satisfying the boundary conditions
rho: numpy.ndarray
The RHS of the Poisson equation. Must have same shape as ... | 9e800b8d67db0c05053c10e55b1ed623ae8a1cc0 | 590,404 |
def es_primo(numero):
"""
Determina si un numero es o no primo. Asume que es un numero entero
positivo.
"""
if numero <= 3:
return True
elif numero % 2 == 0 or numero % 3 == 0:
return False
divisor = 5
while divisor**2 <= numero:
if numero % divisor == 0 or numer... | 8db67e55693a8be3667bff00debce96377bc6bc8 | 590,405 |
def classname(class_object):
"""Returns the class name of the given object"""
return class_object.__class__.__name__ | f08c8bf90b0e5243c83d9d213ca208f50e27ab96 | 590,412 |
def _subsequence(s, c):
"""
Takes as parameter list like object s and returns the length of the longest
subsequence of s constituted only by consecutive character 'c's.
Example: If the string passed as parameter is "001000111100", and c is '0',
then the longest subsequence of only '0's has length 3.... | 265189094a2f31b73eefacd5524f75ebb8a9421b | 590,416 |
def _MergeDeps(dest, update):
"""Merge the dependencies specified in two dictionaries.
Arguments:
dest: The dictionary that will be merged into.
update: The dictionary whose elements will be merged into dest.
"""
assert(not set(dest.keys()).intersection(set(update.keys())))
dest.update(update)
retu... | 46447cc179b206e78cb7eb1b5d8208d5c3e5acd4 | 590,418 |
from typing import List
import glob
def get_html(module: str) -> List[str]:
"""Return all html files on the html/module folder"""
files = glob.glob(f"./html/{module}/*.html")
# remove ./html/module
return [f.replace(f"./html/{module}/texthero.", "") for f in files] | 6cd95d0f0fea509e81902d0afd5e7f4414c19a1d | 590,423 |
def add_toffoli_to_line(local_qasm_line, qubit_1, qubit_2, target_qubit):
"""
Add a single Toffoli gate application to the given line of qasm.
Args:
local_qasm_line: The line of qasm
qubit_1: The first control qubit
qubit_2: The second control qubit
target_qubit: The target ... | db1f2288c9d41125be705bb292cf6470388e3bad | 590,426 |
def normalize_z(df, feature):
"""Takes DataFrame with measurements and feature name and adds a column with normalized values of the feature.
"""
mean = df[df.Status == 'Sample'][[feature]].mean()
std = df[df.Status == 'Sample'][[feature]].std()
df[feature + '_norm'] = df[feature].apply(lambda x:(x ... | 202b9e6628cc1cb3095f2d84e19ececcda315e44 | 590,427 |
from typing import List
def get_image_descriptions(images_scans: List[dict]) -> List[dict]:
"""
Get the image descriptions
Args:
images_scans (list[dict]): images scans information.
Returns:
List[dict]: images descriptions.
"""
return [
{
"Image": image_sc... | 955759c620eb284efd77cc47be953adb188e5289 | 590,431 |
def humanize_speed(speed):
"""
Humanize speeds given in Kbps. Examples:
1544 => "1.544 Mbps"
100000 => "100 Mbps"
10000000 => "10 Gbps"
"""
if not speed:
return ''
if speed >= 1000000000 and speed % 1000000000 == 0:
return '{} Tbps'.format(int(speed / 1000000... | c0d387ed06ce4d42badf6ede4455af0954023604 | 590,438 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.