content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import json
def save_json(input_dict, output_file):
"""save dictionary to file as json. Returns the output file written.
Parameters
==========
content: the dictionary to save
output_file: the output_file to save to
"""
with open(output_file, "w") as filey:
filey.writelines(json.dumps(input_dict, indent=4))
return output_file
|
05d5c8440f5d7e7a021d91136e2277031de53f18
| 644,636 |
def _is_clustal_seq_line(line):
"""Returns True if line starts with a non-blank character but not 'CLUSTAL'
Useful for filtering other lines out of the file.
"""
return line and (not line[0].isspace()) and\
(not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE'))
|
78c9067fa02254409d33fdb9f243c74d549138ce
| 696,588 |
def italic(string):
"""
Surrounds the string with underscores (_) so it will be parsed italic when using markdown
"""
if not isinstance(string, str):
raise TypeError("Must be given a string")
return "_" + string + " _"
|
db93a3e2c529486228b029747eedb770faf1fc3b
| 540,701 |
import json
import hashlib
def hash_dict(nested_dict):
""" Returns hash of nested dict, given that all keys are strings
"""
dict_string = json.dumps(nested_dict, sort_keys=True)
md5_hash = hashlib.md5(dict_string.encode()).hexdigest()
return md5_hash
|
5f518698154b351ca38b8027f047b4a1153f2c83
| 655,496 |
from math import sin, cos, sqrt, atan2, radians
def lat_lon_2_distance(lat1, lon1, lat2, lon2):
"""
return distance (in km) between two locations (lat1, lon1) and (lat2, lon2)
parameter
---------
lat1, lat2: latitude in degrees
lon1, lon2: longitude in degrees
return
------
distance in km
"""
# approximate radius of earth in km
R = 6373.0
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
return distance
|
d0a03ca3c8f2e0574b1677fe271e2bbbef8f7e6c
| 394,438 |
import torch
def convert_half_precision(model):
"""
Converts a torch model to half precision. Keeps the batch normalization layers
at single precision
source: https://github.com/onnx/onnx-tensorrt/issues/235#issuecomment-523948414
"""
def bn_to_float(module):
"""
BatchNorm layers need parameters in single precision. Find all layers and convert
them back to float.
"""
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
module.float()
for child in module.children():
bn_to_float(child)
return module
return bn_to_float(model.half())
|
c899bc0e7f97deb8983794e4ea81ceac2551ec22
| 81,814 |
def decode(value, encoding='utf-8'):
"""Decode given bytes value to unicode with given encoding
:param bytes value: the value to decode
:param str encoding: selected encoding
:return: str; value decoded to unicode string if input is a bytes, original value otherwise
>>> from pyams_utils.unicode import decode
>>> decode(b'Cha\\xc3\\xaene accentu\\xc3\\xa9e')
'Chaîne accentuée'
>>> decode(b'Cha\\xeene accentu\\xe9e', 'latin1')
'Chaîne accentuée'
"""
return value.decode(encoding) if isinstance(value, bytes) else value
|
8cef7b6d0367d5bff48f5c9b9cb2b5d7c4a883d9
| 15,309 |
def normalize(array):
"""Normalize the array.
Set all the values betwwen 0 and 1.
0 corresponds to the min value and 1 the max.
If the normalization cannot occur, will return the array.
"""
min_ = min(array)
max_ = max(array)
return (
(array - min_) / (max_ - min_) # Normalize
if min_ != max_ else
array / (max_ if max_ > 0 else 1) # Avoid divide by 0
)
|
71efcc238a3c2810db9d57e3f32ddad3ef077e56
| 423,759 |
def _adaptive_order_1(q, i, j, recons):
"""
First-order reconstruction.
First-order reconstruction is given by
.. math::
\hat{q}_{i + 1/2} = q_i
"""
recons[2 * i + 1] = q[j]
recons[2 * i + 2] = q[j]
return True
|
1a49bed58094988b6e884427c63d3baf5daf1ae8
| 691,891 |
from typing import Iterable
from typing import Any
from typing import Optional
def get(iterable: Iterable[Any], **kwargs) -> Optional[Any]:
"""
Returns the first object that matches the kwargs arguments.
Used in caching.
:param Iterable iterable: The iterable.
:param kwargs: The key arguments.
:return: The first object that matches the kwargs arguments.
:rtype: Optional[Any]
"""
for elem in iterable:
for key, value in kwargs.items():
if getattr(elem, key) == value:
return elem
|
998cb924b51d10eab86247db7b068c5b50f076ec
| 134,954 |
import re
def replace_chrom_name_in_header(line, name_map):
"""
Replaces the Chrom name from header.
Returns new header.
:param line: line from VCF
:param name_map: name-mapping dict
:return: new header line
"""
old_name = re.split('=|,', line)[2]
return line.replace(old_name, name_map[old_name])
|
3b1b20d09d4ee0ef77a74d902927c715a05415bc
| 181,593 |
def get_job_name(job):
"""Returns job name.
:param Job job: An apscheduler.job.Job instance.
:return: task name
:rtype: str
"""
return job.args[0]
|
50c77c537566c533016075fde113f439ed3999f4
| 491,525 |
def sum(gdf, array: list):
"""Return a sum expression."""
expression = " + ".join(map(str, array))
return gdf.eval(expression)
|
e9a5f3738b8e4925892c424b3505f687f3a8e017
| 132,684 |
def merge(L1: list, L2: list) -> list:
"""Merge sorted lists L1 and L2 into a new list and return that new list.
>>> >>> merge([1, 3, 4, 6], [1, 2, 5, 7])
1, 1, 2, 3, 4, 5, 6, 7]
"""
newL = []
i1 = 0
i2 = 0
# For each pair of items L1[i1] and L2[i2], copy the smaller into newL.
while i1 != len(L1) and i2 != len(L2):
if L1[i1] <= L2[i2]:
newL.append(L1[i1])
i1 += 1
else:
newL.append(L2[i2])
i2 += 1
# Gather any leftover items from the two sections.
# Note that one of them will be empty because of the loop condition.
newL.extend(L1[i1:])
newL.extend(L2[i2:])
return newL
|
9b6423a2ed8ac900668cef3221ca3db7e581500f
| 664,145 |
def get_mapping_pfts(mapping):
"""Get all PFT names from the mapping."""
pft_names = set()
for value in mapping.values():
pft_names.update(value["pfts"])
return sorted(pft_names)
|
40fc5d5cbd537db203a240e44a0ef6c0358a7019
| 688,923 |
def t02_calc_population(base_population) -> int:
"""
Gets a starting population of fish as input and determines their number after an 256 days period.
Each element in the starting population represents a fish and each element's value represents the
reproduction timer.
Also uses a better storage management to overcome O(log(n)) as runtime.
:param base_population: Array with information about the starting population.
:return: The number of fish in the population
"""
arr = [0 for i in range(9)]
for i in base_population:
arr[i] += 1
for i in range(256):
births = arr.pop(0)
arr.append(births)
arr[6] += births
return sum(arr)
|
c9ef1b5d606d30655a8d367237e56668fd159ef3
| 408,130 |
import re
def remove_special_characters(value: str) -> str:
"""Replaces special characters with '_' while keeping instances of '__'."""
normalized_parts = []
for part in value.split("__"):
part = re.sub(r"[^a-zA-Z0-9_]", "_", part) # Remove special characters.
part = re.sub(r"_+", "_", part) # Remove duplicate "_".
part = part.strip("_") # Don't end or start in "_".
normalized_parts.append(part)
return "__".join(normalized_parts)
|
a2896cf92299c3403fea6455bd8257c4bd15a734
| 257,159 |
import time
def strLocalTime(str_format):
"""
.. _strLocalTime :
Return the system local date and time as a string according to the given format.
Parameters
----------
str_format : str
Date/Time code format.
Example: '%Y-%m-%d, %H:%M:%S'
Returns
-------
str_date_time : str
Formatted system local date time string.
"""
str_date_time = time.strftime(str_format, time.localtime())
return str_date_time
|
e9dd98f0b0ac2f03f36f91b432c65dbab6b41533
| 372,419 |
def str2bool(v):
""" Convert string to a boolean value.
References
----------
https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python/715468#715468
"""
return str(v).lower() in ("yes", "true", "t", "1")
|
4e65003e8565536b24c7a47c7983ce1235c8f6c5
| 221,862 |
def downsample_naive(img, downsample_factor):
"""
Naively downsamples image without LPF.
"""
new_img = img.copy()
new_img = new_img[::downsample_factor]
new_img = new_img[:, ::downsample_factor]
return new_img
|
9ccda4d23dfd7816a547d8a968136e0595ba6591
| 480,332 |
def url_replace(request, field, value):
"""URL Replace.
Allows us to quickly and easily swap parameters in the request
object in the case of doing complex queries like filtering
a certain search results, feed, or metadata. Pour exemple:
<a href="?{% url_replace request 'viewing' 'unanswered' %}" class="feedNav-link">Unanswered</a> # noqa
And let's pretend the url currently looks like this:
http://app.dev/feed/?viewing=all&topic=Chronic%20Pain
Clicking on that link would generate a URL like this:
http://app.dev/feed/?viewing=unaswered&topic=Chronic%20Pain
"""
dict_ = request.GET.copy()
dict_[field] = value
return dict_.urlencode()
|
5828680cd207689b31175ab952f34350ac62de82
| 62,659 |
def get_admin_extension_href(href):
"""Returns sys admin version of a given vCD url.
This function is idempotent, which also means that if input href is already
an admin extension href no further action would be taken.
:param str href: the href whose sys admin version we need.
:return: sys admin version of the href.
:rtype: str
"""
if '/api/admin/extension/' in href:
return href
elif '/api/admin/' in href:
return href.replace('/api/admin/', '/api/admin/extension/')
else:
return href.replace('/api/', '/api/admin/extension/')
|
d60d127e3a094e8b5f7ef64da02ab2da6fe45dbc
| 278,099 |
def hash_int_pair(ind1, ind2):
"""Hash an int pair.
Args:
ind1: int1.
ind2: int2.
Returns:
hash_index: the hash index.
"""
assert ind1 <= ind2
return ind1 * 2147483647 + ind2
|
131ccb2b35156716eb7e7ef89f3a5ce6e0e1dfdd
| 498,025 |
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input text
"""
textout = [s.strip() for s in text.split(' ') if s.strip()]
return textout
|
abc45882e8b333a608e65d8e171fc155b9b3e749
| 633,800 |
import itertools
def group_and_create_lookup(things, key_func):
"""
Takes list of things then sorts, groups, and
returns a lookup with result of `key_func`
as the key and list of things grouped on key
as the value
"""
things = things or []
things = sorted(things, key=key_func)
return {k: list(g) for k, g in itertools.groupby(things, key_func)}
|
e85d832dfd908b5055f3165f5271e72a575fd637
| 176,556 |
def _get_coordinate_keys(df):
"""Keys associated to atom coordinate in system's dataframe.
"""
if 'x_coord' in df:
return ['x_coord', 'y_coord', 'z_coord']
else:
return ['r_0', 'r_1', 'r_2']
|
9f8100eb259f207ad83104d65b59f3fd084eb0af
| 301,849 |
def corr_well(text):
"""
>>> corr_well('Я колодец') # I am well
'Я в порядке'
>>> corr_well('Я чувствую колодец') # I am feeling well
'Я чувствую себя хорошо'
"""
text = text.replace('колодец', 'хорошо')
if 'чувствую' in text and 'себя' not in text:
text = text.replace('чувствую', 'чувствую себя')
elif 'делаю хорошо' in text:
text = text.replace('делаю хорошо', 'в порядке')
elif 'был хорошо' in text:
text = text.replace('был хорошо', 'в порядке')
elif 'хорошо' in text:
text = text.replace('хорошо', 'в порядке')
return text
|
f44bc752c6ec0a8d7cf4962d34251669a19a812e
| 464,280 |
def parse_integer_line(line):
"""
Parse a string of integers (with or without a trailing newline).
Returns an iterator object of integers.
This function allows leading and trailing spaces. ValueError is
raised if one of the values does not parse to an integer.
"""
return (int(s) for s in line.split())
|
b1be853e0f1329dfb978c4c0d18c33e2226dcd29
| 174,616 |
def note_onsets(a_list, b_list):
"""
Takes two lists of NoteNode objects. These may be NoteList objects.
Returns a list of tuples, each of the form:
(int: bar #, float: beat #)
Each of these tuples represents a time where a note starts in either
a_list, b_list, or both.
"""
changes = []
for l in [a_list, b_list]:
for note in l:
if note.start not in changes:
changes.append(note.start)
return changes
|
2166c6450916891de1d17071a98ed77893fe6616
| 560,195 |
def get_scale(f_min, f_max, q_min, q_max):
"""Get quantize scaling factor. """
return (q_max - q_min) / (f_max - f_min)
|
0f48cc32c21b2efe9355124e162f2dd2abfa3d58
| 96,312 |
def seq_format_from_suffix(suffix):
"""
Guesses input format from suffix
>>> print(seq_format_from_suffix('gb'))
genbank
"""
suffixes = {'fasta': ['fas','fasta','fa','fna'],
'genbank': ['gb','genbank'],
'embl': ['embl']}
found = False
for key in suffixes.keys():
if suffix in suffixes[key]:
found = True
return key
if not found:
raise RuntimeError(suffix+' is not a recognised suffix of an unaligned sequence file')
|
d7103d3d4bd803d9f55623155c703db3a55683bf
| 513,033 |
def query_int(pregunta, opciones):
"""
Query the user for a number in predefined interval
:param pregunta: Question that will be shown to the user
:param opciones: Available choices
"""
opcion = None
while opcion not in opciones:
opcion = input(pregunta + ' [' + str(opciones[0]) + '-' +
str(opciones[-1]) + ']: ')
try:
opcion = int(opcion)
except:
print('Introduzca un número')
opcion = None
return opcion
|
15f3ddafc47107538d8bbfa46792ee0472e87231
| 83,500 |
def clean_data(df):
"""
Clean the dataset
Args:
df: (pandas.DatFrame) containing data to be cleaned
Returns:
df: (pandas.DataFrame) containing the cleaned dataset
"""
try:
# clean target labels
categories = df.categories.str.split(";", expand=True)
cat_names = categories.applymap(lambda x: x[:-2]).values
categories = categories.applymap(lambda x: x[-1])
categories.columns = cat_names.tolist()[0]
single_cardinality_classes = categories.columns[categories.nunique() == 1]
categories.drop(single_cardinality_classes, axis=1, inplace=True)
# drop original categories column
df.drop(['categories'], axis=1, inplace=True)
# convert categories columns to int
for col in categories.columns:
categories[col] = categories[col].astype(int)
# convert categories.related values (2) to (1)
categories.related = categories.related.replace(2, 1)
# merge categories with df
df = df.merge(categories, left_index=True, right_index=True)
# drop duplicates
df = df.drop_duplicates().reset_index(drop=True)
# remove original columns as it is not needed for modelling
df.drop(['original'], axis=1, inplace=True)
except:
raise Exception("Could not clean dataset.")
finally:
return df
|
676f43ebdb426155ce53d3632626aefca09b3b00
| 670,652 |
def add_to_hof(hof, population):
"""
Iterates over the current population and updates the hall of fame.
The hall of fame is a dictionary that tracks the fitness of every
run of every strategy ever.
Args:
hof (dict): Current hall of fame
population (list): Population list
Returns:
dict: Updated hall of fame
"""
for ind in population:
if str(ind) not in hof:
hof[str(ind)] = []
hof[str(ind)].append(ind.fitness)
return hof
|
5ec67dfd878bc1fcc7abca11cea8f22337935c3f
| 450,271 |
def _spark_calc_values_chunk(points):
"""
Compute some basic information about the chunk points values
The returned information are :
* count : the number of points in chunk
* max : the maximum value in chunk
* min : the minimum value in chunk
* sum : the sum of the values in chunk
* sqr_sum : the sum of the square values in chunk (used for variance calculation)
:param points: list of data values for each point in the chunk
:type points: numpy.array
:return: a dict composed of the basic information computed
:rtype: dict
"""
try:
nb_points = len(points)
except TypeError:
return None
if nb_points > 0:
sum_chunk_value = sum(points)
square_sum_chunk_value = sum([x * x for x in points])
max_chunk_value = max(points)
min_chunk_value = min(points)
else:
# Empty chunk, skip it
return None
return {
"count": nb_points,
"max": max_chunk_value,
"min": min_chunk_value,
"sum": sum_chunk_value,
"sqr_sum": square_sum_chunk_value,
}
|
04dd208038bf1df0172b821943337533f9759291
| 75,114 |
def get_current_temp(soup):
"""Return the current temperature"""
current__temp_find = soup.find_all("span", class_="wxo-metric-hide")[0]
return current__temp_find.get_text()
|
f35d955288d9390ab7f26e51b240a31ae05afe74
| 444,255 |
def calculate_difference(dsm_array, dtm):
"""Calculate the difference between the dsm and dtm"""
dtm_array = dtm.read(1, masked = True)
difference = dsm_array - dtm_array
difference.data[difference < 0] = 0 # We set to 0 anything that might have been negative
return difference
|
962078fe055b27189472fceb4008665aa946b038
| 646,606 |
def homogeneous_to_cartesian(homogeneous_point):
"""
Convert Homogeneous coordinates to Cartesian coordinates
:param homogeneous_point: Homogeneous coordinates
:return: Cartesian coordinates
"""
return homogeneous_point[:, :-1]
|
7a2e3571023d28024d8caf1f3626abb051193a32
| 89,384 |
def limit_es(expected_mb):
"""Protection against creating too small or too large chunks."""
if expected_mb < 1: # < 1 MB
expected_mb = 1
elif expected_mb > 10**7: # > 10 TB
expected_mb = 10**7
return expected_mb
|
9838c10b4af502811a161e0541bf787daeb2680a
| 413,680 |
def traverse(the_module, do_action, traverse_submodules_flag=True):
"""
Traverses ``the_module`` and performs action :func:`do_action` on each of the objects of the structure.
:param the_module: Dictionary ``{'module_obj': module_obj, 'submodules': submodules,
'classes': classes, 'functions': functions}``. The ``submodules`` is the list of
submodules that belong to ``module_obj``. Each submodule has the same structure as ``the_module``.
The ``classes`` is the list of classes that belong to ``module_obj``.
The functions is the list of functions that belong to ``module_obj``.
:param do_action: Function that takes one parameter ``module_obj`` as input. It returns ``True`` if
traversal needs to be stopped.
:param traverse_submodules_flag: True if function must recursively traverse submodules too
:return: Returns tuple ``(the_module, obj)`` where ``obj`` is the object identified by :func:`do_action` and
``the_module`` is the corresponding dictionary structure to which the object belongs. It returns ``None``
if no object has been identified by the :func:`do_action`
"""
if do_action(the_module['module_obj']):
return the_module, the_module['module_obj']
# Traverse classes of the_module
for the_class in the_module['classes']:
if do_action(the_class):
return the_module, the_class
# Traverse functions of the_module
for the_func in the_module['functions']:
if do_action(the_func):
return the_module, the_func
# Recursively traverse submodules of the_module
if traverse_submodules_flag:
for submodule in the_module['submodules']:
the_tuple = traverse(submodule, do_action, traverse_submodules_flag)
if the_tuple is not None:
return the_tuple
return None
|
7eab757b8223d5305db59f3b8e1c4403ccca458e
| 288,579 |
import json
def filter_coverage_file(covfile_handle, cov_functions):
"""Given an input coverage json file and a set of functions that the test
is targeting, filter the coverage file to only include data generated
by running the given functions."""
covdata_out = dict()
covdata = json.load(covfile_handle)
# copy basic info
assert covdata["format_version"] == "1"
covdata_out["format_version"] = covdata["format_version"]
covdata_out["current_working_directory"] = covdata["current_working_directory"]
covdata_out["data_file"] = covdata["data_file"]
covdata_out["gcc_version"] = covdata["gcc_version"]
# handle per proj file data
covdata_out["files"] = list()
for targetfile in covdata["files"]:
cur_file = dict()
cur_file["file"] = targetfile["file"]
cur_functions = list()
for function in targetfile["functions"]:
if function["name"] in cov_functions:
cur_functions.append(function)
cur_file["functions"] = cur_functions
cur_lines = list()
for line in targetfile["lines"]:
if line["function_name"] in cov_functions:
cur_lines.append(line)
cur_file["lines"] = cur_lines
covdata_out["files"].append(cur_file)
return covdata_out
|
12562e355feaeea18fa4d8386c1f77cf44c167b5
| 451,049 |
from typing import Dict
from typing import Optional
def get_collection_for_id(
id_: str, id_map: Dict, replace_underscore: bool = False
) -> Optional[str]:
"""
Returns the name of the collect that contains the document idenfied by the id.
Parameters
----------
id_ : str
The identifier of the document.
id_map : Dict
A dict mapping collection names to document ids.
key: collection name
value: set of document ids
replace_underscore : bool
If true, underscores in the collection name are replaced with spaces.
Returns
-------
Optional[str]
Collection name containing the document.
None if the id was not found.
"""
for collection_name in id_map:
if id_ in id_map[collection_name]:
if replace_underscore is True:
return collection_name.replace("_", " ")
else:
return collection_name
return None
|
0473b4cc14e25bca7d2f4cbf8f77a8bdb60359d8
| 370,033 |
from typing import Dict
from typing import List
from typing import Tuple
from bs4 import BeautifulSoup
from typing import OrderedDict
def load_docs_from_sgml(
file_path: str, encoding='utf-8'
) -> Dict[str, List[Tuple[str, str]]]:
"""
Loads documents from given SGML file.
Returns dict mapping document ids to list of segments [segments].
Each segment is a tuple (segment id, segment text).
"""
soup = None
with open(file_path, encoding=encoding) as _file:
soup = BeautifulSoup(_file, features='lxml')
all_docs: Dict[str, List[Tuple[str, str]]] = OrderedDict()
for curr_doc in soup.find_all('doc'):
curr_doc_id = curr_doc.attrs['docid']
if not curr_doc_id in all_docs:
all_docs[curr_doc_id] = []
for curr_seg in curr_doc.find_all('seg'):
curr_seg_id = curr_seg.attrs['id']
curr_seg_text = curr_seg.get_text()
all_docs[curr_doc_id].append((curr_seg_id, curr_seg_text))
return all_docs
|
99074d183c2f66839db50394528453f4517685c9
| 42,236 |
from typing import List
import logging
import re
def python_result_extractor(raw_test_output: str) -> List[bool]:
"""
Function which extracts the test resutls for an execution
@param raw_test_output: output provided by the submission
@return list of bools, where each element on position i means, that the i-th test passed or not
"""
logging.info("Start extracting result from raw_output")
try:
test_results = raw_test_output.strip().split('\n')[0]
if not re.match("^[\\.F]*$", test_results):
raise ValueError("Submission result is not properly formatted")
return [True if test_res == "." else False for test_res in test_results]
except (ValueError, IndexError) as err:
logging.error(f"Error while extracting results from following raw output: {raw_test_output}")
raise ValueError(f"Invalid raw output format for python err: {str(err)}")
|
c7b487c79db03c7a048301c8f97e89b4692b3b2a
| 408,585 |
def load_file(filename: str) -> list:
"""Read file containing survey responses
:param filename: Location of survey response file
:return: List of survey responses by group
"""
groups = []
gp = []
with open(filename, 'r') as f:
for line in f:
if line == '\n':
groups.append(gp)
gp = []
else:
gp.append(frozenset(line[:-1]))
groups.append(gp)
return groups
|
940f836377e12774fd1e1ec8fba89d4aea496d8e
| 381,851 |
from bs4 import BeautifulSoup
import requests
def get_content(url:str) -> BeautifulSoup:
"""Attempts to make get request to url, raises HTTPError if it fails.
Returns the contents of the page.
Args:
url (str): Valid url example: https://www.rescale.com.
Returns:
BeautifulSoup: The contents of the html page to parse.
"""
resp = requests.get(url)
resp.raise_for_status
return BeautifulSoup(resp.content, "html.parser")
|
dd7ff1a50964ac6a4c51ec0511ba18a3f9035306
| 64,624 |
def get_requirements(rfile):
"""Get list of required Python packages."""
requires = list()
with open(rfile, "r") as reqfile:
for line in reqfile.readlines():
requires.append(line.strip())
return requires
|
ef707cdf35500cb05f86e5c986e9b9c58968d111
| 484,059 |
import itertools
def flatten(l):
"""
Flatten a 2-dimensional list.
"""
return list(itertools.chain.from_iterable(l))
|
bcfe036e44068da0bad1e4024cc767da471d3d4f
| 383,321 |
def take_bet(player: dict) -> float:
"""Prompt the player for how much money to bet."""
while True:
print(f"\nYou currently have ${player['money']:.2f}")
bet = input('How much money would you like to bet on this hand? (min: $20)\n> $')
if not bet.isdigit() or float(bet) < 20:
print('You must bet at least $20\n')
continue
if float(bet) > player['money']:
print(f"You only have {player['money']}. You can't bet more than you've got\n")
continue
rounded_bet = round(float(bet), 2)
player['money'] -= rounded_bet
return rounded_bet
|
b28d48bdd690cd7ec317fbe00da039de86a2423a
| 624,285 |
def make_query_result(query_type):
"""Return a function that creates the result of a query."""
def _result(tokens):
return (query_type, tokens)
return _result
|
14e6f05b8d5197dda48c11ce8f509fb82c4b24ce
| 375,102 |
def get_sig(value):
"""
Extract the signature of a docstring.
"""
return value.__doc__.strip().splitlines()[0]
|
229479bfffd5c97cec76d27e31fbfbc6c5f560aa
| 152,016 |
def split_name_pos(no_chrom_list):
"""
Splits the name and position in no_chrom_list.
Args:
no_chrom_list (list): list with header info not containing chromosome
Returns:
name_pos_split_list: split name and position list
"""
name_pos_split_list = []
for item in no_chrom_list:
new_split = item[0].replace("_", "").split(":")
name_pos_split_list.append([new_split[1]])
return name_pos_split_list
|
6a063908c38bb22e4611ccd17e672e146230a009
| 527,158 |
from typing import List
import re
def split(sentence: str) -> List[str]:
"""
Split a string by groups of letters, groups of digits,
and groups of punctuation. Spaces are not returned.
"""
return re.findall(r"[\d]+|[^\W\d_]+|[^\w\s]+", sentence)
|
d8e8e3ac0a0b00c4346eedef29693a5d66a7f3a4
| 655,252 |
def edge(node1, node2):
"""Create an edge connecting the two nodes, which may be the same."""
return frozenset({node1, node2})
|
160b1d8c5c9d945d25598b585901d1a7f076d2de
| 243,100 |
def getstate(cells, pos, inc):
"""
A helper function to call within a cellular automata's rule function to
access the value of neighbor cells at position pos + inc. See: `states()`.
The new position pos+inc will automatically wrap mod the size of the cells
array so will never go out of bounds.
Parameters
----------
cells : list
An array of cells holding the cellular automata's current states.
pos : tuple
The (*row*, *col*) index of the current cell in the cells array.
Your rule function will receive this position in its pos argument.
To access a neighbor cell, pass the pos value to getstate() along
with a positional increment *inc*.
inc : int | tuple
A positive or negative offset to add to pos to calculate the position of the
neighbor cell. This must be a tuple (*row*, *col*) for 2D automata. For 1D
cases you can specify a positive or negative integer, or a tuple (0, *col*).
Returns
-------
The value of the neighbor cell at pos+inc.
"""
if not isinstance(inc, tuple):
inc = (0, inc)
row = (pos[0] + inc[0]) % len(cells)
col = (pos[1] + inc[1]) % len(cells[0])
return cells[row][col]
|
2328869f9d7e8d1310a9abe6f609ac7f0fa4ba6e
| 371,929 |
import torch
def abs_img_point_to_rel_img_point(abs_img_points,
img_shape,
spatial_scale=1.):
"""Convert image based absolute point coordinates to image based relative
coordinates for sampling.
Args:
abs_img_points (Tensor): Image based absolute point coordinates,
shape (N, P, 2)
img_shape (tuple): (height, width) of image or feature map.
spatial_scale (float): Scale points by this factor. Default: 1.
Returns:
Tensor: Image based relative point coordinates for sampling,
shape (N, P, 2)
"""
assert isinstance(img_shape, tuple) and len(img_shape) == 2
h, w = img_shape
scale = torch.tensor([w, h],
dtype=torch.float,
device=abs_img_points.device)
scale = scale.view(1, 1, 2)
rel_img_points = abs_img_points / scale * spatial_scale
return rel_img_points
|
528ea12f13d6e74ce7433824270702760cba2bf8
| 271,070 |
def _CalcThroughput(samples):
"""Calculates the throughput in MiB/second.
@type samples: sequence
@param samples: List of samples, each consisting of a (timestamp, mbytes)
tuple
@rtype: float or None
@return: Throughput in MiB/second
"""
if len(samples) < 2:
# Can't calculate throughput
return None
(start_time, start_mbytes) = samples[0]
(end_time, end_mbytes) = samples[-1]
return (float(end_mbytes) - start_mbytes) / (float(end_time) - start_time)
|
0f7c973532833ab75ac41fec85c1f7f80983447b
| 589,160 |
from typing import Any
import textwrap
def clean_text(text: Any) -> str:
"""Convert an object to text, dedent it, and strip whitespace."""
return textwrap.dedent(str(text)).strip()
|
85427e3c8ef77d334a92490616c4db2ca8de75bc
| 276,966 |
def strip_ses_recipient_label(address):
"""
Ensure `address` does not contain any +label.
Address is a simple recipient address given by SES, it does not contain a display name.
For example, 'coder+label@vanity.dev' -> 'coder@vanity.dev'.
"""
name, domain = address.split("@")
if '+' in name:
name = name.split("+")[0]
return name + "@" + domain
|
4d6b5503b303b9ea5abf44f3189e04b424abc66f
| 122,287 |
import struct
def little_endian_uint32(i):
"""Return the 32 bit unsigned integer little-endian representation of i"""
s = struct.pack('<I', i)
return struct.unpack('=I', s)[0]
|
07f72baaf8f7143c732fd5b9e56b0b7d02d531bd
| 706,808 |
def adjust_displacement(n_trials, n_accept, max_displacement):
"""Adjusts the maximum value allowed for a displacement move.
This function adjusts the maximum displacement to obtain a suitable acceptance \
of trial moves. That is, when the acceptance is too high, the maximum \
displacement is increased and when the acceptance is too low, the \
maximum displacement is decreased.
Parameters
----------
n_trials : integer
Number of trials that have been performed when the funtction is called.
n_accept: integer
Number of current accepted trials when the function is called.
max_displacement: float
Maximum displacement allowed for any step in the simulation.
Returns
-------
n_trials: int
Number of trials. Updated to zero if maximum displacement is updated.
n_accept: int
Number of trials. Updated to zero if maximum displacement is updated.
max_displacemnt: float
Maximum displacement allowed for any step in the simulation.
"""
acc_rate = float(n_accept)/float(n_trials)
if (acc_rate < 0.38):
max_displacement *= 0.8
elif (acc_rate > 0.42):
max_displacement *= 1.2
n_trials = 0
n_accept = 0
return max_displacement, n_trials, n_accept
|
cc513be27481d239cf8c937bd260e1db8f182775
| 650,283 |
def sanitize(s, strict=True):
"""
Sanitize a string.
Spaces are converted to underscore; if strict=True they are then removed.
Parameters
----------
s : str
String to sanitize
strict : bool
If True, only alphanumeric characters are allowed. If False, a limited
set of additional characters (-._) will be allowed.
"""
allowed = ''.join(
[
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz',
'0123456789',
]
)
if not strict:
allowed += '-_.'
s = str(s).replace(' ', '_')
return ''.join([i for i in s if i in allowed])
|
3150b7d118443224630dcfd2925799bf8daea602
| 87,606 |
from pathlib import Path
def get_directory(base_path, vin):
"""Generate directory where data files go."""
path = Path(base_path) / Path(str(vin))
path.mkdir(parents=True, exist_ok=True)
return path
|
ef3fbda689b7feba527bb014896a170b873f5665
| 578,537 |
def _hbc_P(P):
"""Define the boundary between Region 2b and 2c, h=f(P)
Parameters
----------
P : float
Pressure [MPa]
Returns
-------
h : float
Specific enthalpy [kJ/kg]
References
----------
IAPWS, Revised Release on the IAPWS Industrial Formulation 1997 for the
Thermodynamic Properties of Water and Steam August 2007,
http://www.iapws.org/relguide/IF97-Rev.html, Eq 21
Examples
--------
>>> _hbc_P(100)
3516.004323
"""
return 0.26526571908428e4+((P-0.45257578905948e1)/1.2809002730136e-4)**0.5
|
86757a8285960c1805babe61574e160bccdfb891
| 403,732 |
def get_neighbors(x, y):
"""Returns the eight neighbors of a point upon a grid."""
return [
[x - 1, y - 1], [x, y - 1], [x + 1, y - 1],
[x - 1, y ], [x + 1, y ],
[x - 1, y + 1], [x, y + 1], [x + 1, y + 1],
]
|
21ec6d4f4143f717388ff20def80fd53127bc1ed
| 682,159 |
import struct
import re
import io
def get_size(data: bytes):
"""
Returns size of given image fragment, if possible.
Based on image_size script by Paulo Scardine: https://github.com/scardine/image_size
"""
size = len(data)
if size >= 10 and data[:6] in (b'GIF87a', b'GIF89a'):
# GIFs
w, h = struct.unpack("<HH", data[6:10])
return int(w), int(h)
if size >= 24 and data.startswith(b'\211PNG\r\n\032\n') and data[12:16] == b'IHDR':
# PNGs
w, h = struct.unpack(">LL", data[16:24])
return int(w), int(h)
if size >= 16 and data.startswith(b'\211PNG\r\n\032\n'):
# older PNGs
w, h = struct.unpack(">LL", data[8:16])
return int(w), int(h)
if size >= 30 and data[:4] == b'RIFF' and data[8:12] == b'WEBP':
# WebP
webp_type = data[12:16]
if webp_type == b'VP8 ': # Lossy WebP (old)
w, h = struct.unpack("<HH", data[26:30])
elif webp_type == b'VP8L': # Lossless WebP
bits = struct.unpack("<I", data[21:25])[0]
w = int(bits & 0x3FFF) + 1
h = int((bits >> 14) & 0x3FFF) + 1
elif webp_type == b'VP8X': # Extended WebP
w = int((data[26] << 16) | (data[25] << 8) | data[24]) + 1
h = int((data[29] << 16) | (data[28] << 8) | data[27]) + 1
else:
w = 0
h = 0
return w, h
if b'<svg' in data:
# SVG
start = data.index(b'<svg')
end = data.index(b'>', start)
svg = str(data[start:end + 1], 'utf8')
w = re.search(r'width=["\'](\d+)', svg)
h = re.search(r'height=["\'](\d+)', svg)
return int(w.group(1) if w else 0), int(h.group(1) if h else 0)
if size >= 2 and data.startswith(b'\377\330'):
# JPEG
with io.BytesIO(data) as inp:
inp.seek(0)
inp.read(2)
b = inp.read(1)
while (b and ord(b) != 0xDA):
while ord(b) != 0xFF:
b = inp.read(1)
while ord(b) == 0xFF:
b = inp.read(1)
if 0xC0 <= ord(b) <= 0xC3:
inp.read(3)
h, w = struct.unpack(">HH", inp.read(4))
return int(w), int(h)
inp.read(int(struct.unpack(">H", inp.read(2))[0]) - 2)
b = inp.read(1)
return 0, 0
|
1b45563b0f59f5670638d554821406389b5333a6
| 15,612 |
def QuadraticLimbDarkening(Impact, limb1, limb2):
"""Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1"""
return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2
|
1b271c7afec301331b978e015c085ffaaa335240
| 677,194 |
def trusted_division(a, b):
"""
Returns the quotient of a and b
Used for testing as 'trusted' implemntation of division.
"""
return a * 1.0 / b
|
e544c5b617cd559e207aa1d8c2440b4f88dc056a
| 102,167 |
def substitute(message, substitutions=[[], {}], depth=1):
"""
Substitute `{%x%}` items values provided by substitutions
:param message: message to be substituted
:param substitutions: list of list and dictionary.
List is used for {%number%} substitutions and dictionary for
{%name%} substitutions
:param depth: defines number of pass
:return: substituted message
"""
if not isinstance(message, str):
raise Exception('StringExpected!')
if depth <1 :
return message
new_message = message
# substitute numbered substitutions
i = 0
for value in substitutions[0]:
new_message = new_message.replace("{%%%d%%}" % i, value)
i += 1
# processing named substitutions
for (k, value) in substitutions[1].items():
new_message = new_message.replace("{%%%s%%}" % k, value)
return substitute(new_message, substitutions, depth-1)
|
4a46c46faf1848f1c7e437fed956e21cfdd3a813
| 652,579 |
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 bit_len(i):
"""
Calculate the bit length of an int
:param int i: Int
:return: Length of *i*
:rtype: int
"""
length = 0
while i:
i >>= 1
length += 1
return length
|
f0e35e6d89870cc05c9ae0a6fe22a6cba896b6ad
| 474,861 |
from pathlib import Path
def parse_taxid_names(file_path):
"""
Parse the names.dmp file and output a dictionary mapping names to taxids
(multiple different keys) and taxids to scientific names.
Parameters
----------
file_path : str
The path to the names.dmp file.
Returns
-------
name2taxid : dict
Keys are all possible names and values are taxids.
taxid2name : dict
Keys are taxids and values are scientific names.
"""
names = Path(file_path)
with names.open() as f:
lines_processed = 0
name2taxid = {}
taxid2name = {}
for line in f:
lines_processed += 1
if lines_processed % 1000000 == 0:
print('processing line', str(lines_processed))
entries = [entry.strip() for entry in line.split('|')]
name2taxid[entries[1]] = entries[0]
if 'scientific name' in line:
taxid2name[entries[0]] = entries[1]
return name2taxid, taxid2name
|
1d136f73a56ac8d3c02fd53c6e7928a39440e27a
| 5,451 |
def num_vertices(G):
"""Counts the number of vertices in the graph."""
return max(v for e in G for v in e)
|
ef9b396159681d4a379c2c3c727043f8384db8f6
| 365,238 |
def camel_case_split(str):
"""Split up camel case string."""
words = [[str[0]]]
for c in str[1:]:
if words[-1][-1].islower() and c.isupper():
words.append(list(c))
else:
words[-1].append(c)
return [''.join(word) for word in words]
|
64e075978aedacdae83845fa26bcf80ab75ef230
| 223,251 |
def clean_col_names(df):
"""
cleans up the column names in the mta dataframe
:param df: mta dataframe
:return: mta dataframe with cleaned columns
"""
df = df.copy()
before = 'EXITS '
df.rename(columns={before: 'EXITS', "C/A": "CA"}, inplace=True)
return df
|
62ee58e79095823c69d18a81bb7845bb6224d1ae
| 58,113 |
def minidom_get_text(nodelist):
"""
gets the text in a minidom nodelist for something like
<tag>this text</tag>
nodelist: the childNodes field of the minidom node
"""
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return "".join(rc)
|
2f9a781cdd6c675fb0ec0ef5268a824144e8838d
| 67,478 |
import re
def extract_top_level_domain_from_uri(uri):
"""
Extract host's top level domain from URIs like 'https://amy.carpentries.org/api/v1/organizations/earlham.ac.uk/' to 'earlham.ac.uk'.
When subdomains are used, as in 'https://amy.carpentries.org/api/v1/organizations/cmist.manchester.ac.uk/' we are only interested in
top level domain 'manchester.ac.uk'.
:param uri: URI like 'https://amy.carpentries.org/api/v1/organizations/earlham.ac.uk/'
:return: top level domain like 'earlham.ac.uk'
"""
host = list(filter(None, re.split("(.+?)/", uri)))[-1] # Get the host from the URI first
# Now just get the top level domain of the host
domain_parts = list(filter(None, re.split("(.+?)\.", host)))
if len(domain_parts) >= 3:
domain_parts = domain_parts[-3:] # Get the past 3 elements of the list only
top_level_domain = ''.join((x + '.') for x in domain_parts) # join parts with '.' in between
top_level_domain = top_level_domain[:-1] # remove the extra '.' at the end after joining
return top_level_domain
|
22d965028116d1faaae6de6bc7d7dd877c50b9a2
| 587,600 |
def tokens(_s, _separator=' '):
"""Returns all the tokens from a string, separated by a given separator, default ' '"""
return _s.strip().split(_separator)
|
cb07414580b7d7a1bfe0917cc220b3951741bc7e
| 191,444 |
def get_restaurants(restaurants, category=None):
"""
This function takes a list of dictionaries as an argument and returns a list of strings that includes restaurants' names
Parameters:
restaurants (list): A list of dictionaries, each representing a restaurant
category (list): A list of strings containing different categories of restaurants
Returns:
restaurants_names (list): A list containing the restaurants' names
"""
restaurants_names = []
for restaurant in restaurants:
if category:
if restaurant['Category'] in category:
restaurants_names.append(restaurant['Name'])
else:
restaurants_names.append(restaurant['Name'])
return restaurants_names
|
af61eaec4a0bc632921f030eb6779e5b8f4caac1
| 92,538 |
def email_context(request, application, message=None):
"""
Return a dictionary with the context to be used when constructing
email messages about this application from a template.
"""
fa_app_url = request.build_absolute_uri(application.fa_app_url())
context = {
'user': request.user,
'message': message,
'application': application,
'applicant': application.user,
'fa_app_url': fa_app_url,
}
return context
|
554d32861217b4c3c90c23d410bdbe94b1fb034c
| 403,043 |
from typing import List
from typing import Any
def _flatten_non_tensor_optim_state(
state_name: str,
non_tensors: List[Any],
unflat_param_names: List[str],
) -> Any:
"""
Flattens the non-tensor optimizer state given by the values ``non_tensors``
for the state ``state_name`` for a single flattened parameter corresponding
to the unflattened parameter names ``unflat_param_names`` by enforcing that
all values are the same and using that common value.
See the note in :func:`_flatten_zero_dim_tensor_optim_state`.
Args:
state_name (str): Optimizer state name.
non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
parameters corresponding to the single flattened parameter.
unflat_param_names (List[str]): A :class:`list` of unflattened
parameter names corresponding to the single flattened parameter.
Returns:
Any: A non-tensor giving the value of the state ``state_name`` for all
unflattened parameters corresponding to the names
``unflat_param_names``.
"""
non_none_non_tensors = [nt for nt in non_tensors if nt is not None]
# Enforce that all have the same value (same type already checked)
non_tensor_set = set(non_tensors)
if len(non_none_non_tensors) != len(non_tensors) or \
len(non_tensor_set) != 1:
raise ValueError(
"All unflattened parameters comprising a single flattened "
"parameter must have scalar state with the same value and dtype "
f"but got values {non_tensor_set} for state {state_name} and "
f"unflattened parameter names {unflat_param_names}"
)
non_tensor = next(iter(non_tensor_set))
return non_tensor
|
68199447dc6d3443a0df05f3660893fa0f000697
| 167,123 |
def render_tile(tile):
"""
For a given tile, render its character
:param tile:
:returns str value of tile
"""
# each tile list has the meaning: [Visible (bool), Mine (bool), Adjacent Mines (int)]
# visible, mine, adjacent_mines = tile
if tile[0]:
# if the tile is visible
if tile[1]:
# if the tile is a mine
return "X"
elif tile[2]:
# if the tile has neighboring mines
return str(tile[2])
else:
return " "
else:
return "+"
|
95e28284d7a8d38b3a850dd81449c405a6528f93
| 302,979 |
def vals_to_array(offset, *content):
"""
Slice all the values at an offset from the content arrays into an array.
:param offset: The offset into the content arrays to slice.
:param content: The content arrays.
:return: An array of all the values of content[*][offset].
"""
slice = []
for arr in content:
slice.append(arr[offset])
return slice
|
3a6dcb84f6ee8ecebc57ffc8e42ca18f6d56e9c7
| 120,594 |
from typing import Dict
def get_short_namespace(full_ns: str, xml_namespaces: Dict[str, str]) -> str:
"""
Inverse search of a short namespace by its full namespace value.
:param full_ns: The full namespace of which the abbreviated namespace is to be found.
:param xml_namespaces: A dictionary containing the mapping between short namespace (keys) and
long namespace (values).
:return: If the full namespace is found in the dictionary, returns the short namespace.
:raise KeyError: If the full namespace is not found in the dictionary.
"""
for key, value in xml_namespaces.items():
if full_ns == value:
return key
raise KeyError('The namespace is not found in "xml_namespaces".', full_ns)
|
5a431defce47dc2e3594c3a1da8c44d2f00c9c38
| 389,773 |
def get_accumulated_value(n: int, P: float, i: float) -> float:
""" "
Повертає нарощену суму на певну кількість років
Parameters
----------
P : float
Початкова величина боргу(позики, кредиту)
i : float
Річна ставка складних відсотків
n : int
Кількість років нарощення
Returns
-------
S : float
Нарощена сума
"""
return P * (1 + i) ** n
|
0b38575447f3fb97d03f23607e675c2f92aa7ad3
| 548,089 |
def bool_to_string(boolean: bool) -> str:
"""
boolを小文字にして文字列として返します
Parameters
----------
boolean : bool
変更したいbool値
Returns
-------
true or false: str
小文字になったbool文字列
"""
return "true" if boolean else "false"
|
74c1c9a8c4b92ae9b41e73c50331c14ed6d9c259
| 152,272 |
import hashlib
def _convert_to_id(name):
"""Convert a string to a suitable form for html attributes and ids."""
hasher = hashlib.md5()
hasher.update(name.encode('utf-8'))
return hasher.hexdigest()
|
85ee402cdec9793ef00406f4d06eb6fdd41b5e06
| 561,486 |
def save(sizes: list, hd: int) -> int:
"""
Your task is to determine how many files of the
copy queue you will be able to save into your
Hard Disk Drive.
Input:
Array of file sizes (0 <= s <= 100)
Capacity of the HD (0 <= c <= 500)
Output:
Number of files that can be fully saved in the HD
:param sizes:
:param hd:
:return:
"""
counter = 0
total = 0
for size in sizes:
total += size
counter += 1
if total > hd:
counter -= 1
break
return counter
|
361d05b6145c9eee837bd98bae0c232329cb60d9
| 133,827 |
import functools
import time
def time_method(function_name=None):
"""Times the execution of a function as a decorator.
Parameters
__________
function_name : str
The name of the function to time.
(default is None)
Returns
-------
A decorator function.
"""
def real_decorator(func):
@functools.wraps(func)
def wrapper_time_method(*args, **kwargs):
t_start = time.time()
result = func(*args, **kwargs)
t_end = time.time()
if function_name is None:
name = func.__name__.upper()
else:
name = function_name
elapsed_t = (t_end - t_start)
print(f'TIMING: {name}'.ljust(40) + f'{elapsed_t:>39.4f}s')
return result
return wrapper_time_method
return real_decorator
|
56d4f75c6ef9ff9e14e79edad1629f3e515884a8
| 536,351 |
import re
def is_base64(text: str) -> bool:
"""Guess whether text is base64-encoded."""
return bool(
re.match(
r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$",
text.replace("\n", ""),
)
)
|
f3be6a0e77e84715317d7233523b01ff5de92ce5
| 634,407 |
from bs4 import BeautifulSoup
import re
def get_text(connection_or_html) -> str:
"""
Uses BeautifulSoup to get text from HTML
"""
# https://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text/1983219#1983219
if isinstance(connection_or_html, BeautifulSoup):
soup = connection_or_html
else:
soup = BeautifulSoup(connection_or_html, "html5lib")
[s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title'])]
[s.extract() for s in soup.find_all(attrs={"style": re.compile("display: ?none|visibility: ?hidden")})]
split = [re.sub(r"\s+", " ", s) for s in soup.stripped_strings]
split = [s for s in split if s]
return "\t".join(split)
|
3a87fa000732f04cf64d46431e753abc57262ddb
| 231,902 |
def count_matches(list, item):
"""
Return the number of occurrences of the given item in the given
list.
"""
if list == ():
return 0
else:
head, tail = list
if head == item:
return 1 + count_matches(tail, item)
else:
return count_matches(tail, item)
|
beaf23ee6d915a32fcb18326ac23fd705e10f94d
| 582,181 |
def all_jobs_completed(jobs):
"""Returns jobs if they are all completed, otherwise False."""
if all(j.get('status') == 'completed' for j in jobs):
return jobs
else:
return False
|
b3e7f4dbfbb89080f34eb98673c8d5c469a9e35b
| 563,799 |
import shutil
def disk_usage(pathname):
"""Return disk usage statistics for the given path"""
### Return tuple with the attributes total,used,free in bytes.
### usage(total=118013599744, used=63686647808, free=48352747520)
return shutil.disk_usage(pathname)
|
c7a36e2f3200e26a67c38d50f0a97dd015f7ccfa
| 625 |
def pretty_print(params, offset=0, printer=repr):
"""Pretty print the dictionary 'params'
Parameters
----------
params : dict
The dictionary to pretty print
offset : int
The offset in characters to add at the begin of each line.
printer : callable
The function to convert entries to strings, typically
the builtin str or repr
Notes
-----
Implementation is taken from ``sklearn.base._pprint`` with minor modifications
to avoid additional dependencies.
"""
# Do a multi-line justified repr:
param_names = [p for p in params.keys() if p is not "cost"]
param_names.sort()
params_list = list()
this_line_length = offset
line_offset = " " * offset
for i, name in enumerate(param_names):
value = params[name]
if isinstance(value, float):
this_repr = '%s=%s' % (name, str(value))
else:
this_repr = '%s=%s' % (name, printer(value))
if len(this_repr) > 500:
this_repr = this_repr[:300] + '...' + this_repr[-100:]
this_repr = f"\n{line_offset}{this_repr},"
params_list.append(this_repr)
this_line_length += len(this_repr)
lines = ''.join(params_list)
# Strip trailing space to avoid nightmare in doctests
lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n'))
return lines
|
8386626542752a67faf089d71a5ffa1f4b4a20e8
| 238,136 |
def pretty_timer(seconds: float) -> str:
"""Formats an elapsed time in a human friendly way.
Args:
seconds (float): a duration of time in seconds
Returns:
str: human friendly string representing the duration
"""
if seconds < 1:
return f'{round(seconds * 1.0e3, 0)} milliseconds'
elif seconds < 60:
return f'{round(seconds, 3)} seconds'
elif seconds < 3600:
return f'{int(round(seconds) // 60)} minutes and {int(round(seconds) % 60)} seconds'
elif seconds < 86400:
return f'{int(round(seconds) // 3600)} hours, {int((round(seconds) % 3600) // 60)} minutes, and {int(round(seconds) % 60)} seconds'
else:
return f'{int(round(seconds) // 86400)} days, {int((round(seconds) % 86400) // 3600)} hours, and {int((round(seconds) % 3600) // 60)} minutes'
|
de49d27f57ce45d3ad967f58377b361b9eda63ef
| 315,962 |
import re
def _is_dns_label(name):
""" Check that name is DNS label: An alphanumeric (a-z, and 0-9) string,
with a maximum length of 63 characters, with the '-' character allowed
anywhere except the first or last character, suitable for use as a hostname
or segment in a domain name """
dns_label = re.compile(r"""^[a-z0-9][a-z0-9\.-]{1,62}$""")
if dns_label.match(name):
return True
else:
return False
|
513e1eb08c87891e99398509d6fc9d04f8141f47
| 529,973 |
def tocreset(I, Ipickup, TD, curve="U1", CTR=1):
"""
Time OverCurrent Reset Time Function.
Function to calculate the time to reset for a TOC
(Time-OverCurrent, 51) element.
Parameters
----------
I: float
Measured Current in Amps
Ipickup: float
Fault Current Pickup Setting (in Amps)
TD: float
Time Dial Setting
curve: string, optional
Name of specified TOC curve, may be entry from set:
{U1,U2,U3,U4,U5,C1,C2,C3,C4,C5}, default=U1
CTR: float, optional
Current Transformer Ratio, default=1
Returns
-------
tr: float
Time-to-Reset for characterized element.
"""
# Condition Inputs
curve = curve.upper()
# Define Dictionary of Constants
C = {"U1": 1.08, "U2": 5.95, "U3": 3.88,
"U4": 5.67, "U5": 0.323, "C1": 13.5,
"C2": 47.3, "C3": 80.0, "C4": 120.0,
"C5": 4.85}
# Evaluate M
M = I / (CTR * Ipickup)
# Evaluate Reset Time
tr = TD * (C[curve] / (1 - M ** 2))
return tr
|
8c26a3aebcb5f51fe884724e4d9460f44454b3d1
| 657,381 |
from typing import Dict
from typing import Any
from typing import List
def process_properties(schema: Dict[str, Any]) -> Dict[str, Any]:
"""Processes a Pydantic generated schema to a confluent compliant schema
:param schema: a valid pydantic schema
:type schema: Dict[str, Any]
:return: schema with `fields` and `names` keys
:rtype: Dict[str, Any]
"""
fields: List[Dict[str, Any]] = []
json2avro_types = {
'number': 'double',
'integer': 'int'
}
python2avro_defaults = {
False: 'false',
True: 'true'
}
for name, value in schema['properties'].items():
try:
value.pop('title')
value['name'] = name
json_type = value['type']
value['type'] = json2avro_types.get(json_type, json_type)
if value.get('default') is not None:
default = value['default']
value['default'] = python2avro_defaults.get(default, default)
finally:
fields.append(value)
schema['fields'] = fields
return schema
|
e647ba12f25d2440b6c987f2098995ef6e6280cb
| 203,810 |
def construct_api_params(
business_unit=None,
event_type=None,
limit=None,
page_token=None
):
"""
Constructs the parameters object for the API call. Note that startDateUtc and
endDateUtc are not listed here (although they are parameters); this is because
they are included already in the URL
Args:
business_unit (str): Comma separated list of business unit IDs
event_type (str): Comma separated list of event types.
Allowed event types are: ON_PREM_EXPOSURE_APPEARANCE,ON_PREM_EXPOSURE_DISAPPEARANCE,
ON_PREM_EXPOSURE_REAPPEARANCE. Beta event types are: CLOUD_EXPOSURE_APPEARANCE,
CLOUD_EXPOSURE_DISAPPEARANCE,CLOUD_EXPOSURE_REAPPEARANCE
limit (int): Number of events to be fetched per page of results. Max and default value is 10,000
page_token (str): Page token of page
Returns:
dict: the params object to be sent to the API
"""
tokens = {
'businessUnit': business_unit,
'eventType': event_type,
'limit': limit,
'pageToken': page_token
}
params = {}
for token_key, token_value in tokens.items():
if token_value is not None:
params.update({token_key: token_value})
return params
|
36f4de8a30d6cbf6aff72b08130553843b7eec7d
| 623,096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.