content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import ast
def is_name_in_ptree(name, ptree):
"""
Return True if an ast.Name node with the given name as its id
appears anywhere in the ptree, False otherwise
"""
if not ptree:
return False
for node in ast.walk(ptree):
if isinstance(node, ast.Name) and (node.id == name):
... | c2d6d0001c3baf14c110ff351c8a1c5e97b256d8 | 690,251 |
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str:
"""Return the updated view based on whether the guess matches position in puzzle
>>> update_letter_view('apple', 'a^^le', 2, 'p')
p
>>> update_letter_view('banana', 'ba^a^a', 0, 'b')
b
>>> update_letter_view('bitt... | b7c534acdbc57c04e1f7ee6a83fc94ff2734948a | 698,438 |
def remove_unnecessary(string):
"""Removes unnecessary symbols from a string and returns the string."""
string = string.replace('@?', '')
string = string.replace('?@', '')
return string | 56965ef4b60d302e659bafd4874b8c72790c5ec3 | 59,827 |
import json
def load_json(filename):
"""
json loader to load Nematus vocabularies
Note that we use unicode representations (not str)
:param filename:
:return:
"""
with open(filename, mode='rb') as f:
return json.load(f) | 6df9c234c37a7ed01cf00d24ed49578bc447e38e | 599,445 |
def _compute_error(node, x, y=None):
"""Error between target and prediction."""
prediction = node.state()
error = prediction - y
return error, x.T | 2d675073cf994864f8557fd3e401c1e543755e9c | 163,307 |
from typing import Callable
from typing import Any
from typing import Iterable
from typing import Tuple
from typing import List
def group_by_pred(
pred: Callable[[Any], bool], iterable: Iterable[Any]
) -> Tuple[List[Any], List[Any]]:
"""Splits items in a sequence into two lists, one containing
items match... | 07af56c4e40bbef2055b2675353be14e04f991aa | 289,629 |
def new_line(string: str):
"""
Append a new line at the end of the string
Args:
string: String to make a new line on
Returns: Same string with a new line character
"""
return string + "\n" | f4deeaa94a6980f95a3020fa54570fbe1f0a6e9e | 701,112 |
import typing
import yaml
def get_targets(filename: str) -> typing.List[str]:
"""Load the configuration file.
The configuration file is expected to be a YAML file listing
the target urls as a list.
For more information, refer to the README.md or the example configuration.
"""
with open(filena... | 66cc4be3d17040562e321bf5e3fb7e564aa77335 | 420,156 |
from typing import Tuple
import math
def euler_to_quaternion(roll: float = 0, pitch: float = 0, yaw: float = 0) -> Tuple[float, float, float, float]:
"""
Convert Euler to Quaternion
Args:
roll (float): roll angle in radian (x-axis)
pitch (float): pitch angle in radian (y-axis)
yaw... | e8346172f07510c377e14827842eb18f1631402e | 707,128 |
def get_network(network_arg, task_idx):
""" Get network file from list of arguments.
Parameters
----------
network_arg: list of space-separated network filenames
as parsed by argparse (--networks)
task_idx: int
index of the task/network
Returns
------
Path to the netwo... | eac76c0c70e5dec1dccf8e3c3adea8a199997c10 | 113,661 |
def single_line(value):
"""Returns the given string joined to a single line and trimmed."""
return " ".join(filter(None, map(str.strip, value.splitlines()))) | 2f51425a02f64d9b64be74ad8b78ecaba8d6b300 | 206,907 |
from typing import List
from typing import Set
def _extract_target_labels(targets_in_order: List[dict], target_name: str) -> Set[str]:
"""Collect a set of all the board names from the inherits field in each target in the hierarchy.
Args:
targets_in_order: list of targets in order of inheritance, star... | f47dcd90427efd70b0ac965ea017852db68381e4 | 674,322 |
import hashlib
def convert_to_SHA256(x):
"""Convert a given string to SHA256-encoded string.
:param x: arbitrary string.
:type x: str
:return: SHA256 encoded string
:rtype: str
"""
result = hashlib.sha256(x.encode())
result = result.hexdigest()
return result | b199155459a7d36b9614678190d72aff167da13c | 272,896 |
def get_index_groups(time_list):
"""Get index groups corresponding to the different time interval
tvals. An index group is a pair consisting of a time interval
time value and a list of indices corresponding to that time value. A
dictionary will map the time interval tvals to their corresponding
in... | bc38858d28e25b45ed4ee6753a88638a847a810b | 248,345 |
def latex_float(f, precision=0.2, delimiter=r'\times'):
""" Convert a float value into a pretty printable latex format
makes 1.3123e-11 transformed into $1.31 x 10 ^ {-11}$
Parameters
----------
f: float
value to convert
precision: float, optional (default: 0.2)
the precision w... | b3d31afcfbf8a564d85f5f5b099b0d63bc8d89f8 | 77,753 |
def celsius_to_fahrenheit(temp):
"""
Convert degrees Celsius to degrees Fahrenheit
:param float temp: The temperature in Celsius
:return: The temperature in Fahrenheit
:rtype: float
"""
return (temp * 1.8) + 32.0 | ebb420e14c0b01b8ed91cd603b2e3bf34388f917 | 563,487 |
def FormatResources(resources):
"""Formats a list of resources for printing.
Args:
resources: a list of resources, given as (type, name) tuples.
"""
return '\n'.join(['%-12s %s' % (t, n) for t, n in sorted(resources)]) | f88604a186115a7333de02d6c0ad31315ea22f12 | 486,397 |
def binary_search(input_array, value):
""" Algorithm: Here is how it could be done:
1. Get middle index of array with range (0...array-size)
2. Compare value of mid-element at that index with given value
2.1 If (value == mid-element)
then return the middle index [DONE]
2.2 E... | 6723316e9460efb5ce41ad8e94152deb13af0d94 | 192,086 |
def format_iter(body: list) -> str:
"""
Formats an iterable into a multi-line bulleted string of its values.
"""
return "\n".join(sorted([f" - {getattr(v, 'value', v)}" for v in body])) | 0f55b06276c45ef652e89df3dfd24d1fe9a4e844 | 11,724 |
def classify_list_f(a_list, *filters):
"""Classfy a list like object. Multiple filters in one loop.
- collection: list like object
- filters: the filter functions to return True/False
Return multiple filter results.
Example:
data = [1, 2, 3]
m1 = lambda x: x > 1
m2 = lambda x: x > 2
... | 4bafa7a6b714387cfa2a6c896eece909e4171cdf | 288,981 |
def _convert_from_F(temp: float) -> float:
"""
Convert F temp to C
param temp: temp in F to convert
return: float
"""
return round((temp - 32) * 5/9, 1) | 0bff2139405161193b6212ab46ddf34d8ef984f2 | 255,295 |
def detector_substr(detector):
"""
change detector string to match file format
(e.g., "SCA01" -> "SCA_1")
"""
return f"{detector[:3]}_{str(int((detector[3:])))}" | 878a75146b5bf03d020acfa2b6363c166a3b0e4d | 93,165 |
def get_neighbours_from_grid(row, column, grid):
"""Get from the grid neighbours of square on given row and column."""
coordinates = []
if row > 0:
coordinates.append(('up', row - 1, column))
if row + 1 < len(grid):
coordinates.append(('down', row + 1, column))
if column > 0:
... | b6df05d66d26af30de9f0ac7c2544bd8f5e9643f | 365,638 |
from typing import Dict
from typing import Any
async def provider() -> Dict[str, Any]:
"""Define a basic example data provider function."""
return {
"title": "Example",
"link": "https://example.com",
"description": "An example rsserpent plugin.",
"items": [{"title": "Example Ti... | e952f40d360bf31e4a8710c3b5d531c1467ef660 | 422,373 |
def get_sequence_name(image_file):
"""Returns a sequence name like '20180227_185324'."""
return image_file.split('/')[-3] | 8456faf80320f2f4fe85413c537edf79ec6d5afa | 357,289 |
from bs4 import BeautifulSoup
import re
def get_links(html_page, base_url):
"""gets all links from html
Parameters
------
html_page (str): document html
base_url (str): the original URL supplied
Returns
------
list: list of all the links in the html document
these could be fi... | f2e97ce2934e994787f3ef79d43558f3380c6722 | 665,409 |
import errno
def is_eintr(exc):
"""Returns True if an exception is an EINTR, False otherwise."""
if hasattr(exc, 'errno'):
return exc.errno == errno.EINTR
elif getattr(exc, 'args', None) and hasattr(exc, 'message'):
return exc.args[0] == errno.EINTR
return False | b6a7c280f87757492f3a4c1ee166577691ef8622 | 123,313 |
import collections
def build_dicts(reviewText):
"""
Build dictionaries mapping words to unique integer values.
"""
counts = collections.Counter(reviewText).most_common()
dictionary = {}
for word, _ in counts:
dictionary[word] = len(dictionary)
return dictionary | 5a20752a044d63f1be433494c4c2ca83953bbe67 | 119,082 |
def simplify_person_name( name ):
"""
Simpify a name to a last name only. Titles such as Ph. D. will be removed first.
Arguments:
name -- The name to shorten
"""
if name is not None:
new_name = name.replace("Ph.D.", "").replace("Ph. D.", "").replace("M.A.", "").replace("LL.D.",... | c8e26c84f4c8e2ef0107ed14a13980259b1b306b | 208,868 |
import re
import json
def get_interfaces_counters(module):
"""
@summary: Parse output of "show interfaces counters" command and convert it to the dictionary.
@param module: The AnsibleModule object
@return: Return dictionary of parsed counters
"""
cli_cmd = "portstat -j"
rc, stdout, stderr... | 5f68b977c2a934a84e37d059349f60261e151055 | 443,116 |
def wow_gen(length: int):
"""Generates a wow at a given length"""
if (length <= 1984 and length >= 0):
wow_thing = "***__~~w"
for _ in range(length):
wow_thing += "o"
wow_thing += "w~~__***"
return wow_thing
elif (length >= -1984 and length < 0):
new_lengt... | 8057befdc1f5513340e659c3bcd92bd86c13875f | 525,529 |
from typing import Any
import gc
def _object_for_id(id_: int) -> Any:
""" Return an object, given its id. """
# Do a complete garbage collect, to avoid false positives in case the
# object was still in use recently. In the context of AppSingleLaunch,
# this would happen if an app was closed, then lau... | 6a334eb9dd7cffbc95fd4671fe9883bd4238d064 | 143,003 |
def get_file_name(conanfile, find_module_mode=False):
"""Get the name of the file for the find_package(XXX)"""
# This is used by the CMakeToolchain to adjust the XXX_DIR variables and the CMakeDeps. Both
# to know the file name that will have the XXX-config.cmake files.
if find_module_mode:
ret ... | db8afd149df6efd8dc01c120ab85d77ca229d3e8 | 480,555 |
def default_inverse_transform_targets(current_state, delta):
"""
This is the default inverse transform targets function used, which reverses the preprocessing of the targets of
the dynamics function to obtain the real current_state not the relative one,
The default one is (current_state = target + curr... | 9d7031dded17a69e195017384b5bdc71751aeb27 | 475,991 |
def confirmable_div(confirm_field_id: str | None, prefix: str = 'form-group-') -> str:
"""Return an opening div tag linking this error div to a confirm field.
See `confirmable-error.ts`.
"""
attrs = ['', 'data-role="confirmable-error"',
f'data-confirmed-by-checkbox-id="{confirm_field_id}"'... | f6c773bb04bed63d387c61616ff437be727244f9 | 503,233 |
def fixup_setup(setup):
"""Fill in any missing pieces from setup."""
if not hasattr(setup, 'PY_NAME'):
setup.PY_NAME = setup.NAME
if not hasattr(setup, 'PY_SRC'):
setup.PY_SRC = '%s.py' % setup.PY_NAME
if not hasattr(setup, 'DEB_NAME'):
setup.DEB_NAME = setup.NAME
if not hasattr(setup, 'AUTHOR_NAM... | de49f99d09f6c683392ea2f006970bfe48ad01da | 234,364 |
import string
import torch
def translate(sentence, inp_word2id, trg_word2id, trg_id2word, encoder, decoder, trg_max_len, device='cpu'):
"""
Generate translation for input sentence.
Inputs:
- sentence: a sentence in string format
- inp_word2id: word2id from input training set
- trg_word2id... | 7c66d1ce73600443da2326c1c61b337cb6388d32 | 511,872 |
def make_valid_mapping(package_leaflets):
"""
Make sure to have valid mappings from NER (input) to section_content (output)
In case either input or output - None or empty, make sure the corresponding pair is None
:param package_leaflets: list, collection of package leaflets
:return: package_leafle... | fee328e4d207cf0a4510f190ac47b9f7fa6736b0 | 425,946 |
def nextIter(it, default=None):
"""
Returns the next element of the iterator,
returning the default value if it's empty,
rather than throwing an error.
"""
try:
return next(iter(it))
except StopIteration:
return default | f7be7cf6fdf6cd77459453858f20121207220ec9 | 534,219 |
def plurality(l):
"""
Take the most common label from all labels with the same rev_id.
"""
s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0])
s.name = 'y'
return s | 4e363648e79b5e9049aca2de56fd343c1efe1b93 | 8,513 |
def unique_append(old_list, new_list):
"""
Add items from new_list to end of old_list if those items are not
already in old list -- returned list will have unique entries.
Preserve order (which is why we can't do this quicker with dicts).
"""
combined = old_list
for item in new_list:
... | 96ecc3350300ef0b6ed3ff54b370fbc9189ec96f | 532,965 |
def fuel_burn_by_ll_rule(mod, prj, tmp, s):
"""
If no fuel_burn_by_ll_rule is specified in an operational type module, the
default fuel burn needs to be greater than or equal to 0.
"""
return 0 | 7e5e2861b7d5114060b66a6c988896e476063da2 | 478,799 |
def get_packagetype(name: str) -> str:
"""Get package type out of a filename"""
if name.endswith(".tar.gz"):
return "sdist"
elif name.endswith(".egg"):
return "bdist_egg"
elif name.endswith(".whl"):
return "bdist_wheel"
else:
return "" | 34ad89c3c118ee7da1a07396da0dd39a63ea7a8b | 385,152 |
def binary_search(arr, val):
"""Takes in a sorted list and a value. Preforms the Binary Search algorythem to see if the value is in the lsit."""
# Set the values to the end of the list
left,right = 0,len(arr)
while not right <= left:
mid = (right + left) // 2
if val > arr[mid]:
left = mid+1
... | 49e25dd5ba4e9e92d6b1225141efa74f48ee19b1 | 95,118 |
def percent_diff(value1: float, value2: float, frac: bool = False) -> float:
""" Return the percentage difference between two values. The denominator
is the average of value1 and value2.
value1: float, first value
value2: float, second value
frac: bool, Default is ... | cffe298fb4218adc60bf75ff659090c41ae86922 | 37,999 |
def getdifflist(inputlist):
"""returns a list of length-1 relative to the input list
list values are the differential of the inputlist [n+1]-[n]"""
difflist=[inputlist[i+1]-inputlist[i]
for i in range(len(inputlist)-1)]
return difflist | 145f11f1f6af87a222f91a2b2cd2ee4c6a039df7 | 604,190 |
def _modname_to_cliname(parser_mod_name):
"""Return module's cli name (underscores converted to dashes)"""
return parser_mod_name.replace('_', '-') | a8dea162a38744c4eeb13f68acdf88a03338c3ef | 384,162 |
def calc4travel(fuelprice: float, averagecons: float, km: float) -> float:
"""
Função para calcular o valor gasto em combustivel para uma viagem de X Km (ida e volta).
fuelprice: representa o preço do combustivel;
averagecons: consumo médio do veiculo;
km: distância em km.
Retorna o valor em rea... | c1a7f0e7c6d669463ec40e290a7bc60036df9fbf | 488,672 |
import yaml
def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.safe_dump(data, stream, **kwds) | 02e8cba070e19842fc669d20a83837b9c5ff19b6 | 255,519 |
import math
def get_3rd_side(a, b):
"""
Returns hypotenuse of a right-angled triangle, given its other sides
"""
# return np.sqrt(np.sum(np.square(mags)))
return math.sqrt(a**2 + b**2) | 5f5f6606e3a18f567bef157b43fe54771ffe90f4 | 206,719 |
def calc_3d_bbox(xs, ys, zs):
"""Calculates 3D bounding box of the given set of 3D points.
:param xs: 1D ndarray with x-coordinates of 3D points.
:param ys: 1D ndarray with y-coordinates of 3D points.
:param zs: 1D ndarray with z-coordinates of 3D points.
:return: 3D bounding box (x, y, z, w, h, d)... | 5e4f2c6197addae67816844f6764b16c031d3d29 | 625,506 |
def filter_deleted_items(items, flag):
"""Filter deleted items
:param items: target
:param flag: deleted flag name, always True means deleted
:return: list does not contain deleted items
"""
# just return if parameter is not a list
if not isinstance(items, list):
return items
... | 0f494d3515f7bd78661b3e5bed00055eeea6f7d3 | 662,339 |
def snake_to_camel_case(value):
"""
Converts a string from snake_case to camelCase
"""
words = value.strip("_").split("_")
return words[0].lower() + "".join([word.capitalize() for word in words[1:]]) | b78419dbdbe0cd88f6dd79e9174f4a26ae9640b5 | 607,712 |
def get_all_ann_index(self):
""" Retrieves all annotation ids """
return list(self.ann_infos.keys()) | 4375c9dbc14bf50575c8a5e42ce0ae8749820dfb | 706,589 |
def get_clean_fips(fips):
"""
Given a FIPS code, ensure it is returned as a properly formatted FIPS code of length 5
Example:
get_clean_fips(123) = "00123"
get_clean_fips("0002") = "00002"
get_clean_fips("00001") = "00001
:param fips: The FIPS code to clean
:return: The 5-digit FIPS co... | e41c846a7db4f34329e8d2d6a9f960f4b3da99a5 | 408,341 |
import math
def deg2rad(deg):
"""
Convert unit from deg to rad.
"""
return deg * math.pi / 180.0 | 3b0b206519f8725a81e5f97b236eb04b9caa94c8 | 402,897 |
def calculate_progress(total_count, count, start_progress = 0.0):
"""Calculates the progress in a way that is guaranteed to be safe
from divizion by zero exceptions or any other exceptions. If there
is any problem with the calculation or incoming arguments, this
function will return 0.0"""
default =... | 9219e7b6657fbc405c478ae3294dd422f5b7d618 | 145,419 |
def _popanykey(dct, *keys, strict=False):
"""
Returns the first of the listed keys to be found in the dict
:param dct: a dict
:param keys:
:param strict: [False] if True, raise KeyError if we get to the end of the list and nothing was found
:return:
"""
for key in keys:
if key.lo... | dc895b8a2f7b4c42b8f46557a48a0f1fb048eb96 | 492,293 |
def remove_xml(rid):
"""
Removes the .xml from a resource or spec id.
"""
if '.xml' in rid[-4:]:
return rid[:-4]
else:
return rid | e57c7ccfdfb130092ef0f2fd8412d4771fd716aa | 47,855 |
def intseq(words, w2i, unk='.unk'):
"""
Convert a word sequence to an integer sequence based on the given codebook.
:param words:
:param w2i:
:param unk:
:return:
"""
res = [None] * len(words)
for j, word in enumerate(words):
if word in w2i:
res[j] = w2i[w... | 9716cbc3fad228802ba954e50df4d2f109eff3e6 | 87,079 |
def feature_normalization(X):
"""
Mean/standard deviation normalization.
:param np.ndarray X: Feature matrix to be normalized.
:return: np.ndarray of normalized feature matrix, np.ndarray of means and np.ndarray of standard deviation.
"""
mu = X.mean(axis=0)
sigma = X.std(axis=0, ddof=1... | b9d8b45db8c05e7dd55e3b6339543401219262ce | 493,445 |
def parse_job_line(line):
"""
>>> parse_job_line("* * * *,myquery,mycredentials\\n")
('* * * *', 'myquery', 'mycredentials', 'collect.py')
>>> parse_job_line("* * * *,myquery,mycredentials,scripts/foo.py\\n")
('* * * *', 'myquery', 'mycredentials', 'scripts/foo.py')
"""
parts = line.strip().... | 8a83a3a5721e9e9b15cae7cd438bf505e776b38f | 125,629 |
def hamming_distance(str1, str2):
"""calculate the hamming distance of two strings."""
# ensure length of str1 >= str2
if len(str2) > len(str1):
str1, str2 = str2, str1
# distance is difference in length + differing chars
distance = len(str1) - len(str2)
for index, value in enumerate(str... | 6ac874c65fec012c74866bb10713195586c90294 | 535,228 |
def hist_range(array, bins):
""" Compute the histogram range of the values in the array.*
Parameters
----------
array: array
the input data.
bins: int
the number of histogram bins.
Returns
-------
range: 2-uplet
the histogram range.
"""
s = 0.5 * (array.... | 937df240f2e2c91aa8eb4f4fe6d5075a30f0ff76 | 87,904 |
import yaml
def trun_from_file(fpath):
"""Returns trun from the given fpath"""
with open(fpath, 'r') as yml_file:
return yaml.safe_load(yml_file) | 4cc2ea61f61607edd79f25c93e01f55fc7b5dbbd | 435,604 |
def count_distinct_occurence(calls, texts):
"""Return the count of distinct occurence of number
Args:
calls: list of calls
texts: list of texts
Returns:
number of distinct number
"""
number_set = set()
for record in calls+texts:
number_set.add(record[0])
n... | 4acf40c50bbd32b23735aaad2c581559829bb664 | 21,923 |
def extract_ingredient_counts(ingredients_dict, ingredient_labels):
"""
Extract ingredient counts from dict for plotting in chart.
:param ingredients_dict: dict mapping ingredient names to counts
:param ingredient_labels: list of strings containing ingredient names
:return: list of counts of ingredi... | 852b299d31e8896ec047db9bbf296cdbc7a0a2b0 | 574,037 |
from typing import Optional
def filter_106_sum_lines(obj: dict) -> Optional[bool]:
"""Filter our unneeded lines in Form 106Sum
:param obj: Pdf line
:return: Whether to keep filtered lines
"""
if obj["width"] < 20:
return False
if obj["top"] < 60:
return False
if obj["x0"] ... | fc63f005bcdc8d057fdec74dca4b572767296be8 | 196,222 |
def readDictionary(input):
"""
Read file to a dictionary data structure:
Input file is a lexicon consisting lines of the word and the most frequent associated tag
"""
dictionary = {}
lines = open(input, "r").readlines()
for line in lines:
wordtag = line.strip().split()
... | 543261fe7cbff53b4dc3082d56687aa3d2cef336 | 627,535 |
def http_ok_status() -> dict:
"""
Return an HTTP 200 ok status
"""
return {"statusCode":200, "body":""} | e88f3f4f2c7a4ac900d52f58f5601d3782ff4867 | 580,552 |
def _dash_escape(args):
"""Escape all elements of 'args' that need escaping.
'args' may be any sequence and is not modified by this function.
Return a new list where every element that needs escaping has
been escaped.
An element needs escaping when it starts with two ASCII hyphens
('--'). Esca... | 94f1f19cf02c3b640480052f1f586d24dee135ec | 347,996 |
import sympy
def field_linear(theta):
"""Jones vector for linear polarized light at angle theta from horizontal plane."""
return sympy.Matrix([sympy.cos(theta), sympy.sin(theta)]) | 4ae21f61e0263f5e51ef6a390004bcdf4b9d763d | 590,084 |
import logging
def get_logger(name):
"""
Create new logger with the given name
:param name: Name of the logger
:return: Logger
"""
logger = logging.getLogger(name)
return logger | 80a7e545be7badd71277d38dbb202e70643f6ecb | 629,815 |
def function() -> str:
"""Return a value."""
return "value" | 00e8446e17cd3b2fa436a429780a500abdfe1286 | 504,049 |
def is_trunk(output, port):
"""
Returns True port is trunk, False otherwise
:param output: String - Output of 'show int trunk'
:param port: String - The port e.g. Gi0/1
:return: Bool
"""
for lines in output.strip().splitlines():
if port in lines:
return True
return F... | dd687f7a2c6536b634baa9594f0e9835176a8716 | 463,093 |
def str_to_pair_of_lists(_str1, _str2, _sep=','):
"""
Attempts to convert 2 strings containing tokens separated by some _sep to a pair of lists, e.g. "a1,a2,a3", "b1,b2,b3" -> [['a1','a2','a3'],['b1','b2','b3']]
:param _str1: input string #1
:param _str2: input string #2
:param _sep: token separator... | 704d322ca9ab55fcb67683402c057a39d9386dd2 | 500,063 |
import re
def clen(string):
"""Return the length of a string, excluding ansi color sequences."""
return len(re.sub(r'\033[^m]*m', '', string)) | 042873da51a583cfa30fda0b999e7a2cba0d5ada | 450,571 |
def hex_8bit(value):
"""Converts 8bit value into bytearray.
args:
8bit value
returns:
bytearray of size 1
"""
if value > 0xff or value < 0:
raise Exception('Sar file 8bit value %s out of range' % value)
return value.to_bytes(1, 'little') | 597ecb6c9a499c7a5959f1f8ddd7300b78b06e9a | 694,649 |
def clamp(value: float, lower: float, upper: float) -> float:
"""
Basic clamp function: if below the floor, return floor; if above the ceiling, return ceiling; else return unchanged.
:param value: float input
:param lower: float floor
:param upper: float ceiling
:return: float within range [lower-upper]
"""
r... | e9dbe198776dafe743bbea4d4959e6e857112509 | 198,447 |
async def leave_comment(gh, issue_comment_url: str, message: str, token: str):
"""
Leave comment in issue or pull request
:param gh: object with actions
:param issue_comment_url: api string
:param message: comment
:param token: GitHub token
:return: response
"""
data = {'body': messa... | cdcddeaef04cf3667cc861d44bd69180a8e49b34 | 628,004 |
def fatorial(num, show=False):
"""
-> Função para calcular fatorial.
-> Paramêtros:
* num: Número a ser calculado o fatorial.
* show: True para mostrar calculo, False para mostrar apenas resultado.
* return: Resultado da somatória.
"""
soma = 1
for cont in range (num, 0, -1):
... | e6f50f63af36e79ed952010c917090cd4cbc930b | 151,212 |
def module_tracker(fwd_hook_func):
"""
Wrapper for tracking the layers throughout the forward pass.
Arguments
---------
fwd_hook_func : function
Forward hook function to be wrapped.
Returns
-------
function :
Wrapped hook function
"""
... | d0835227ba1f7dde27bcc0d0af22bef8d50b90c6 | 380,123 |
def last_consecutives(vals, step=1):
"""
Find the last consecutive group of numbers
:param vals: Array, store numbers
:param step: Step size for consecutive numberes, default 1
:return: The last group of consecutive numbers of the input vals
"""
group = []
expected = None
for ... | 7e12990eb8ee1f44fd81d2dd66c24bf952316053 | 520,789 |
import hashlib
def get_md5(path):
"""
Utility function for generating the md5sum of a file
:param path: Path to file
"""
md5 = hashlib.md5()
block_size = 8192
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
return in... | 6ac19b40154d5a2acfd6ff251a2d63cbc5908e96 | 421,588 |
def _massage_groups_out(appstruct):
"""Opposite of '_massage_groups_in': remove 'groups:' prefix and
split 'groups' into 'roles' and 'groups'.
"""
d = appstruct
groups = [
g.split("group:")[1]
for g in d.get("groups", "")
if g and g.startswith("group:")
]
roles = [r f... | a447e50c551e16319c53101d646d93d8868cd3f0 | 444,332 |
def scale_bounding_boxes(bounding_boxes, orig_width, new_width):
"""
Scale a list of bounding boxes to reflect a change in image size.
Args:
bounding_boxes: List of lists of [x1, y1, x2, y2], where
(x1, y1) is the upper left corner of the box, x2 is the width
of the box, and... | f670e9d37853075f169e933ff5128edbd300aa9f | 67,649 |
def get_collection_sizes(net, bus_size=1.0, ext_grid_size=1.0,
trafo_size=1.0, load_size=1.0, sgen_size=1.0,
switch_size=2.0, switch_distance=1.0):
"""
Calculates the size for most collection types according to the distance between min and max geocoord so that
... | c032eeb22e4aed9acb2c519b2b0bcb548bba576f | 502,461 |
def merge_dicts(dict_a, dict_b):
"""Performs a recursive merge of two dicts dict_a and dict_b, wheras dict_b always overwrites the values of dict_a
:param dict_a: the first dictionary. This is the weak dictionary which will always be overwritten by dict_b (dict_a
therefore is a default dicti... | 32e2823a7491f916fcdab8a28b94d5027c1f0306 | 656,141 |
def getLaggedReturns_fromReturns(x, lag):
"""
Get lagged log returns for an x pandas Serie.
Parameters
----------
x : pd.Series
Data serie
lag : int
Number of periods to be lagged
"""
weekly_price = x.rolling(lag).sum()
weekly_returns = weekly_price.diff(lag)
r... | 12e2f8ba1cdf7316d8003dc030c7f181e2c7b17c | 489,925 |
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 suffix(d: int) -> str:
"""Convert an input date integer to a string with a suffix.
Example:
>>> suffix(10)
'th'
>>> suffix(2)
'nd'
>>> suffix(23)
'rd'
>>> suffix(4)
'th'
"""
return "th" if 11 <= d <= 13 else {1: "st", 2: "nd", 3: "rd"... | 96c41def9519d08e37a72a0fb7bbc39ae309cbbb | 332,656 |
def areaCuadrado(lado):
"""Esta función sirve para calcular el área de un cuadrado del lado especificado como parámetro."""
return "El área del cuadrado de lado {} es: ".format(lado) + str(lado*lado) | 827bfaac1644f8d56e64d207fbf5da896884c2be | 472,933 |
def isascii(s):
"""Returns True if str s is entirely ASCII characters.
(Compare to Python 3.7 `str.isascii()`.)
"""
try:
s.encode("ascii")
except UnicodeEncodeError:
return False
return True | ab0969a89ebdf23b8c6ec2d34ecd3f67b616b30a | 73,812 |
def get_recommendations(mid, conn):
"""
Grab recommendations for a single mid.
Returns multiple recommendation types as a dictionary.
Example Return
--------------
{
'l2r': [mid1, mid2, mid3],
'wrmf': [mid5, mid6, mid7
}
"""
c = conn.cursor()
sql = """
S... | 5794810f907eae4cc778b15611efa19e49f1b05d | 184,157 |
from bs4 import BeautifulSoup
def get_tag_by_field(text_or_soup, tag_name, field, expr):
"""Returns HTML tag in text if expr is in its field.
If not found, returns None.
"""
if isinstance(text_or_soup, BeautifulSoup):
soup = text_or_soup
else:
soup = BeautifulSoup(text_or_soup)
for tag in soup.fi... | 4d792c5da4bf4621142c5efa04a4e437a7d70619 | 94,586 |
def oracle_id(account_id):
"""
Compute the oracle id of a oracle registration
:parm account_id: the account registering the oracle
"""
return f"ok_{account_id[3:]}" | 6589b0cde6ab7bfc25b40e9e78e08d6c324a781b | 140,980 |
def deserialize_utf8(value, partition_key):
"""A deserializer accepting bytes arguments and returning utf-8 strings
Can be used as `pykafka.simpleconsumer.SimpleConsumer(deserializer=deserialize_utf8)`,
or similarly in other consumer classes
"""
# allow UnicodeError to be raised here if the decodin... | 21cc61d6048b5f7d9333ceadb86d03666719f05f | 25,860 |
def ReserveHospRsrvEnd(t):
"""Hospitalization reserve: End of period"""
return 0 | adc01e22aee1bc14a114fb37f27b40abd73810d7 | 64,145 |
def add_load_data_args(parser):
"""Adds common data loader arguments to arg parser"""
platforms = ['telegram', 'whatsapp', 'messenger', 'hangouts']
parser.add_argument('-p', '--platforms', default=platforms, choices=platforms, nargs='+', help='Use data only from certain platforms')
parser.add_argument('... | 5a1bc118a06199222a9940f095fa0471b7f20c33 | 541,607 |
def str_to_color(s):
"""Convert hex string to color value."""
if len(s) == 3:
s = ''.join(c + c for c in s)
values = bytes.fromhex(s)
# Scale from [0-255] to [0-1]
return [c / 255.0 for c in values] | cedcad67ee8de5d5470bb60ae106eb52b459c7ff | 223,212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.