content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
|---|---|---|
import collections
def comp_initial(tags, treebank):
"""Compute initial probability for the given set of tags and training corpus
Args:
tags (list): list of unique tags from the corpus
treebank (object): File object with train corpora loaded. nltk.corpus.reader.tagged.TaggedCorpusReader
Returns:
list: list of tuples containing POS tag and its initial probability. Size: 1 X K
"""
parsed_sents = treebank.paras()
f_tags = [line[0][1] for line in parsed_sents]
freq_f_tags = collections.Counter(f_tags)
init_p = [freq_f_tags[item]/len(f_tags) for item in list(tags)]
return list(zip(list(tags), init_p))
|
51dc836e33d301524064897eee89a77bba1e2797
| 81,587
|
def get_num_fft(sample_rate, window_len):
"""
Function get_num_fft calculates optimal number of FFT points based on frame length.
Less number of FFT points than length of frame
will lose precision by droppping many of the samples.
Therefore, we want num_fft as a power of 2, greater than frame length.
@param sample_rate: The sample rate of audio signal we working with.
@param window_len: Time interval we are taking within frames.
@returns: Optimal number of FFT points.
"""
frame_length = sample_rate * window_len
num_fft = 1
while num_fft < frame_length:
num_fft *= 2
return num_fft
|
bbab1ec96fb78b2facba181cf9eba3b6bc1e9129
| 81,595
|
def label(field):
"""Return a label for a data field suitable for use on a graph axis.
This returns the attribute 'long_name' if it exists, or the field name,
followed by the units attribute if it exists.
Parameters
----------
field : NXfield
NeXus field used to construct the label.
Returns
-------
str
Axis label.
"""
if 'long_name' in field.attrs:
return field.long_name
elif 'units' in field.attrs:
return f"{field.nxname} ({field.units})"
else:
return field.nxname
|
c087a57a597ea4feef1d293d371fb6175042644c
| 81,597
|
def filter_features(features, key, include=None, exclude=None):
"""Filter an iterable of GeoJSON-like features based on
one of their attributes.
Parameters
----------
features : iterable of dict
Source GeoJSON-like features.
key : str
Property key.
include : tuple of str, optional
Property values to include.
exclude : tuple of str, optional
Property values to exclude.
Returns
-------
out_features : list of dict
Filtered GeoJSON-like features.
"""
if not include and not exclude:
raise ValueError('No value to include or exclude.')
out_features = []
for feature in features:
if include:
if feature['properties'][key] in include:
out_features.append(feature)
if exclude:
if not feature['properties'][key] in exclude:
out_features.append(feature)
return out_features
|
b2bfea17bae33ece7f37bb35d08569fa8fd061b0
| 81,602
|
def bucket_from_url(url):
""" Extracts a bucket name from an S3 URL.
url: an S3 URL, or what should be one
Return value: bucket name from S3 URL
"""
if url[:6] == 's3n://':
start_index = 6
elif url[:5] == 's3://':
start_index = 5
elif url[0] == '/':
start_index = 1
else:
start_index = 0
while url[start_index] == '/':
start_index += 1
return url[start_index:start_index+url[start_index:].index('/')]
|
82c98e613948d8369c3a74a7d87b9a374c54928d
| 81,608
|
def calculate_management_strategy(fef, mtbfa, mtbfgp):
"""
Function to calculate the minimum required management strategy for the
entire program or a test phase.
:param float fef: the average fix effectiveness factor over the period to
calculate the management strategy.
:param float mtbfa: the average MTBF over the first test phase.
:param float mtbfgp: the growth protential MTBF.
:return: _avg_ms
:rtype: float
"""
try:
_avg_ms = (1.0 - (mtbfa / mtbfgp)) / fef
except ZeroDivisionError:
_avg_ms = 1.0
return _avg_ms
|
2d72a733af36f6e3f724f52699c377cf04e4e8c7
| 81,609
|
import re
def getAlignmentLength(cigar):
"""
Computes the alignment length given a cigar string. Needed for Start + End calculation.
@type cigar: string
@param cigar: Cigar string (SAM)
@rtype: int
@return: alignmentlength
"""
# I - insertions do not extend the alignment
# S - does not extend...
# P - does not extend...
# H - does not extend...
match = re.findall("(\d+)[MDN]", cigar)
sumOfMatches = 0
for item in match:
sumOfMatches += int(item)
return (sumOfMatches)
|
6a8e99cb6250d26ed1c9771ada9694a316ee917c
| 81,610
|
def val_and_std(token):
"""check the validity of a token; standard it if needed
Args:
token (string): a token
Returns:
string: an standardized token if the token is valid
otherwise return None
"""
token = token.strip("\"\'-")
tran_t = token.replace("-", "").replace("'", "")
if tran_t.isascii() and tran_t.isalpha():
return token.lower()
return None
|
754f6f520fd12ebf688bc7bd801d39fae16a68fc
| 81,617
|
def market_clock ( self ):
"""Receive information about the state of the exchange
"""
url_suffix = 'market/clock.json'
results = self.call_api (
method = 'GET',
url_suffix = url_suffix,
use_auth = False
)
x = { k:v
for k,v in results.items()
if k in ( 'message','status')
}
return x
|
c290f527e5151dfcf47fe29b5e739903623180bd
| 81,620
|
import re
def _parse_bonds_from_svg(bond_elements, mol):
"""Extract bonding information from SVG elements
Args:
bond_elements (list[xml.etree.ElementTree.Element]):
List of SVG path elements.
mol (rdkit.Chem.rdchem.Mol): RDKit mol object]
Returns:
list[dict]: JSON-style formated bond informations
"""
result = []
re_bond_regex = r"bond-\d+"
for bond_svg in bond_elements:
try:
if not re.search(re_bond_regex, bond_svg.attrib["class"]):
continue
atoms = re.findall(r"atom-\d+", bond_svg.attrib["class"])
atom_id_a = int(atoms[0][5:]) # to get int part of "atom-0"
atom_id_b = int(atoms[1][5:])
temp = {
"bgn": mol.GetAtomWithIdx(atom_id_a).GetProp("name"),
"end": mol.GetAtomWithIdx(atom_id_b).GetProp("name"),
"coords": bond_svg.attrib["d"],
"style": bond_svg.attrib["style"],
}
result.append(temp)
except (RuntimeError, KeyError):
pass # we do not care about bonded Hydrogens
return result
|
f78462ac81f29ca7300c0d269f963df0a1b72feb
| 81,630
|
def ask(question: str) -> str:
"""Ask the user to provide a value for something."""
print(question)
response = input()
return response
|
de420095822a16aacee571fc114de65cb7380d3e
| 81,632
|
from pathlib import Path
def generate_csv(
symmetric_corr_table, rna_info, data_load_sources, stringency, out_dir
):
"""
Given a correlation table of RBPs binding to an RNA molecule of interest,
generates and saves a CSV file containing the correlation values.
:param symmetric_corr_table: A nested dictionary such that
symmetric_corr_table[rbp1][rbp2] returns the binding correlation value
between rbp1 and rbp2.
:param rna_info: A dictionary containing 'official_name' as key, with a
corresponding value that indicates the name of the RNA under
investigation.
:param data_load_sources: A list of data sources that were used, such as
'postar', 'rbpdb', etc.
:param stringency: numerical value representing the base stingency that was
used in analyzing the correlation coefficient.
:returns: a filepath to the saved CSV file.
"""
rna = rna_info["official_name"]
path_to_save = (
Path(out_dir)
/ "csv"
/ f"{rna.lower()}-{'-'.join(data_load_sources)}-{stringency}.csv"
)
path_to_save.parent.mkdir(parents=True, exist_ok=True)
path_to_save = str(path_to_save)
with open(path_to_save, "w+") as csv_file:
rbps = list(symmetric_corr_table.keys())
csv_file.write("," + ",".join(rbps))
csv_file.write("\n")
for rbp1 in rbps:
csv_file.write(rbp1 + ",")
for rbp2 in rbps:
csv_file.write(str(symmetric_corr_table[rbp1][rbp2]))
csv_file.write(",")
csv_file.write("\n")
return path_to_save
|
b6d2a7e668371af0b601e88243ea2308d32196bc
| 81,633
|
def get_auto_name(name: str, rnn_layers: int, rnn_size: int, rnn_bidirectional=False, rnn_type='lstm') -> str:
"""Generate unique name from parameters"""
model_name = f"{name}_{rnn_layers}l{rnn_size}"
if rnn_bidirectional:
model_name += 'bi'
if rnn_type == 'gru':
model_name += '_gru'
return model_name
|
841e801319fee1a4dce56cf760ea6c2081e48177
| 81,635
|
def get_column_unit(column_name):
"""Return the unit name of a .mpt column, i.e the part of the name after the '/'"""
if "/" in column_name:
unit_name = column_name.split("/")[-1]
else:
unit_name = None
return unit_name
|
b7cbc268aebadf3dfed541b5e246ad46295826c8
| 81,637
|
def resolve_dependencies(func_name, dependencies):
"""Given a function name and a mapping of function dependencies,
returns a list of *all* the dependencies for this function."""
def _resolve_deps(func_name, func_deps):
""" Append dependencies recursively to func_deps (accumulator) """
if func_name in func_deps:
return
func_deps.append(func_name)
for dep in dependencies.get(func_name, []):
_resolve_deps(dep, func_deps)
func_deps = []
_resolve_deps(func_name, func_deps)
return sorted(func_deps)
|
af8d4eec403ea40f52514d8af53bf1020941b5fb
| 81,638
|
def getJunitTestRunnerClass(version):
""" Get the correct junit test running class for the given junit version
Parameters
----------
version : int
The major version for junit
Returns
-------
str or None
Returns str if `version` is either 3 or 4
Returns None otherwise
"""
if version == 4:
return "org.junit.runner.JUnitCore"
elif version == 3:
# Use the JUnit 3 test batch runner
# info here: http://www.geog.leeds.ac.uk/people/a.turner/src/andyt/java/grids/lib/junit-3.8.1/doc/cookbook/cookbook.htm
# Does anyone actually use this version of junit?????
return "junit.textui.TestRunner"
return None
|
2020c1b9b128595048521bcee7bbd4ccf04c36bc
| 81,643
|
def quaternion_to_xaxis_yaxis(q):
"""Return the (xaxis, yaxis) unit vectors representing the orientation specified by a quaternion in x,y,z,w format."""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
xaxis = [ w*w + x*x - y*y - z*z, 2*(x*y + w*z), 2*(x*z - w*y) ]
yaxis = [ 2*(x*y - w*z), w*w - x*x + y*y - z*z, 2*(y*z + w*x) ]
return xaxis, yaxis
|
b98f5a59b7fb5f741d388b2eab22726acf6e2ac5
| 81,644
|
def getHeaderResponse(station, type='FixedStation'):
""" Get header response
:param station: station name id
:param type: station type (FixedStation or MobileStation)
:return: header response
"""
response = {'id': station}
response['station_name'] = station
response['scientificName'] = 'CanAirIO Air quality Station'
response['ownerInstitutionCodeProperty'] = 'CanAirIO'
response['type'] = type
response['license'] = 'CC BY-NC-SA'
return response
|
ed16dca9ed3187f038fb70828dc2c9632eb045a7
| 81,650
|
def _nonetypeclass(*args, **kwargs):
"""Initializer function that returns Nonetype no matter what."""
return None
|
438fb33596a02d474edafde375a661508514c6cd
| 81,651
|
def _get_username(acs_info):
"""
Gets the admin user name from the Linux profile of the ContainerService object.
:param acs_info: ContainerService object from Azure REST API
:type acs_info: ContainerService
"""
if acs_info.linux_profile is not None:
return acs_info.linux_profile.admin_username
return None
|
02258432845599c7e198f4069f25123e2be14535
| 81,654
|
def list_len(x):
"""Implement `list_len`."""
return len(x)
|
81b49aa40c74d14ded61d26de8d3fb71b6c8a3e1
| 81,655
|
def verify_input(json_data):
"""
Verifies the validity of an API request content
:param json_data: Parsed JSON accepted from API call
:type json_data: dict
:return: Data for the the process function
"""
# callback_uri is needed to sent the responses to
if 'callback_uri' not in json_data:
raise ValueError('callback_uri not supplied')
return json_data
|
ad84c15d89fc060575f2dc84acf96dd10f7721e9
| 81,656
|
def normalize_greek_accents(text):
"""Sanitize text for analysis. Includes making turning grave accents
into acutes, making the whole text lowercase and removing
punctuation (.,·)
"""
# Switch graves to acutes
text = text.replace(u'ὰ', u'ά')
text = text.replace(u'ὲ', u'έ')
text = text.replace(u'ὶ', u'ί')
text = text.replace(u'ὸ', u'ό')
text = text.replace(u'ὺ', u'ύ')
text = text.replace(u'ὴ', u'ή')
text = text.replace(u'ὼ', u'ώ')
text = text.replace(u'ἃ', u'ἅ')
text = text.replace(u'ἓ', u'ἕ')
text = text.replace(u'ὃ', u'ὅ')
text = text.replace(u'ἳ', u'ἵ')
text = text.replace(u'ὓ', u'ὕ')
text = text.replace(u'ἣ', u'ἥ')
text = text.replace(u'ὣ', u'ὥ')
text = text.replace(u'ἂ', u'ἄ')
text = text.replace(u'ἒ', u'ἔ')
text = text.replace(u'ὂ', u'ὄ')
text = text.replace(u'ἲ', u'ἴ')
text = text.replace(u'ὒ', u'ὔ')
text = text.replace(u'ἢ', u'ἤ')
text = text.replace(u'ὢ', u'ὤ')
# Make lowercase
text = text.lower()
# Remove punctuation
text = text.replace(u',', u'')
text = text.replace(u'·', u'')
return(text)
|
b60cd80b54fabff73ef460e6ba51685a7ae7367e
| 81,661
|
def _to_num(src_string):
"""Convert string to int or float if possible.
Original value is returned if conversion failed.
"""
if not isinstance(src_string, str):
return src_string
src_string = src_string.strip()
try:
return int(src_string)
except ValueError:
try:
return float(src_string)
except ValueError:
return src_string
|
2904b44a12073bfe466869e965473e932c79d164
| 81,662
|
def reformatStripList(stripList):
"""\brief Converts a list of channels into a string for being included in the .xml file.
The string contains all the strip numbers, separated by a space.
"""
String = ''
for channel in stripList:
String = String + str(channel) + ' '
# Remove the last space.
String = String[:-1]
return String
|
d8d33bfc6e69d9b94a63ac1ff310d989cf5f8b16
| 81,666
|
def is_nearest_multiple(m, a, b):
"""
Replacement for m % b == 0 operator when variable is incremented by value other than one at each iteration.
m is assumed to be increased by a at each iteration. If not exactly divisible, this function returns True the first
iteration returns True the first iteration m surpasses b.
"""
return (a > b) or (m - m // b * b < a)
|
78ecf301ad0b6d9d0daca08ea17ef204d511f10b
| 81,669
|
def is_y_or_n(string):
"""Return true if the string is either 'Y' or 'N'."""
return string in ['Y', 'N']
|
47bf100bc1b687211513b58e8330ca6904c80bb8
| 81,677
|
from typing import Tuple
def _calculate_fold_number(length: int, max_length: int, folding: bool) -> Tuple[int, int]:
"""Calculate the number of the folded and unfolded items.
Arguments:
length: The object length.
max_length: The configured max length.
folding: Whether fold the "repr" of the object.
Returns:
The number of the folded items & the number of the unfolded items.
"""
if folding and length > max_length:
return length - max_length + 1, max_length - 2
return 0, length
|
5cf1f9173b826c78b87e50cf7b360c71732962cb
| 81,680
|
def clean_data(data):
"""
This function takes in data and returns a mutated version that converts string versions of numbers
to their integer or float form depending on the type of value.
Parameters:
data (list): A list of dictionaries.
Returns:
(list): A list of dictionaries with the numerical values appropriately converted.
"""
for row in data:
for key in row.keys():
if key == 'points':
row[key] = float(row[key])
elif key == 'position':
row[key] = int(row[key])
return data
|
756ce5805022b0779a575d7f6c83e7740fed135b
| 81,693
|
def mask2list(bitmask, number=1):
"""
Convert an integer bitmask into a list of integers.
>>> mask2list((1 << 14) | (1 << 0))
[1, 15]
"""
if not bitmask:
return []
this = []
if bitmask & 1:
this = [number]
return this + mask2list(bitmask >> 1, number + 1)
|
da5f4076f9bec3353c365f4da939dfb92bd14f96
| 81,694
|
def removeDuplicateObservations(
linkages,
linkage_members,
min_obs=5,
linkage_id_col="orbit_id",
filter_cols=["num_obs", "arc_length"],
ascending=[False, False]
):
"""
Removes duplicate observations using the filter columns. The filter columns are used to sort the linkages
as desired by the user. The first instance of the observation is kept and all other instances are removed.
If any linkage's number of observations drops below min_obs, that linkage is removed.
Parameters
----------
linkages : `~pandas.DataFrame`
DataFrame containing at least the linkage ID.
linkage_members : `~pandas.DataFrame`
Dataframe containing the linkage ID and the observation ID for each of the linkage's
constituent observations. Each observation ID should be in a single row.
min_obs : int, optional
Minimum number of observations for a linkage to be viable.
linkage_id_col : str, optional
Linkage ID column name (must be the same in both DataFrames).
filter_cols : list, optional
List of column names to use to sort the linkages.
ascending : list, optional
Sort the filter_cols in ascending or descending order.
Returns
-------
linkages : `~pandas.DataFrame`
DataFrame with duplicate observations removed.
linkage_members : `~pandas.DataFrame`
DataFrame with duplicate observations removed.
"""
linkages_ = linkages.copy()
linkage_members_ = linkage_members.copy()
linkages_.sort_values(
by=filter_cols,
ascending=ascending,
inplace=True,
ignore_index=True
)
linkages_.set_index(linkage_id_col, inplace=True)
linkage_members_.set_index(linkage_id_col, inplace=True)
linkage_members_ = linkage_members_.loc[linkages_.index.values]
linkage_members_.reset_index(inplace=True)
linkage_members_ = linkage_members_.drop_duplicates(subset=["obs_id"], keep="first")
linkage_occurences = linkage_members_[linkage_id_col].value_counts()
linkages_to_keep = linkage_occurences.index.values[linkage_occurences.values >= min_obs]
linkages_ = linkages_[linkages_.index.isin(linkages_to_keep)]
linkage_members_ = linkage_members_[linkage_members_[linkage_id_col].isin(linkages_to_keep)]
linkages_.reset_index(inplace=True)
linkage_members_.reset_index(
inplace=True,
drop=True
)
return linkages_, linkage_members_
|
e878416adbb380a84f9e4a4941228f065486c570
| 81,695
|
def human_format(num: int) -> str:
"""Returns num in human-redabale format
from https://stackoverflow.com/a/579376
Args:
num (int): number.
Returns:
str: Human-readable number.
"""
# f
if num < 10000:
return str(num)
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0 # type: ignore
if num == int(num):
formatter = "%.1d%s"
else:
formatter = "%.1f%s"
return formatter % (num, ["", "K", "M", "G", "T", "P"][magnitude])
|
6331d7c8d57ca3b93be80af882ccfdf6047a16ab
| 81,696
|
import json
def load_output(results):
"""Load json result from broker.
"""
if results['Code'] == '0':
try:
var = json.loads(results['Stdout'])
except Exception as e:
raise Exception('JSON load failed: {}'.format(e))
else:
raise Exception('Operation failed: {}'.format(results['Stderr']))
return var
|
94959ed37ab58384b21ade5f0e188beff669358e
| 81,697
|
from typing import List
from typing import Tuple
def boundingbox_intersection(
box1: List[int],
box2: List[int]
) -> Tuple[int, List[int]]:
"""
Compute the intersection of two bounding boxes.
The bounding boxes have the notation [xmin, ymin, XMAX, YMAX].
Args
----
box1: the first bounding box.
box2: the second bounding box.
Returns
-------
area: the area of intersection.
bounding_box: the resulting intersection bounding_box
Note
----
The area is expressed in terms of geometric area!
The area intended as number of pixels, can be computed by the geometric features
that can be obtained from the bounding box:
PIXELS = area + perimeter/2 + 1
"""
xmin_b1 = int(box1[0])
xMAX_b1 = int(box1[2])
ymin_b1 = int(box1[1])
yMAX_b1 = int(box1[3])
xmin_b2 = int(box2[0])
xMAX_b2 = int(box2[2])
ymin_b2 = int(box2[1])
yMAX_b2 = int(box2[3])
if (xmin_b2 > xMAX_b1) or (ymin_b2 > yMAX_b1) or (xMAX_b2 < xmin_b1) or (yMAX_b2 < ymin_b1):
# No intersection
area = 0
bounding_box = []
else:
# There is intersection
xmin = max(xmin_b1, xmin_b2)
ymin = max(ymin_b1, ymin_b2)
xMAX = min(xMAX_b1, xMAX_b2)
yMAX = min(yMAX_b1, yMAX_b2)
bounding_box = [xmin, ymin, xMAX, yMAX]
# geometric area is width*height
area = (xMAX - xmin)*(yMAX - ymin)
return area, bounding_box
|
a42b30ef8fcb32500867fa7c6e92cea2d601c1dd
| 81,698
|
from typing import List
def find_the_runner_up_score(arr: List[int]) -> int:
"""
>>> find_the_runner_up_score([2, 3, 6, 6, 5])
5
"""
return sorted(set(arr))[-2]
|
b1004d86a9e07d5dd55cb683676790fed0957503
| 81,700
|
def preconvert_preinstanced_type(value, name, type_):
"""
Converts the given `value` to an acceptable value by the wrapper.
Parameters
----------
value : `Any`
The value to convert.
name : `str`
The name of the value.
type_ : ``PreinstancedBase`` instance
The preinstanced type.
Returns
-------
value : ``PreinstancedBase`` instance
Raises
------
TypeError
If `value` was not given as `type_` instance, neither as `type_.value`'s type's instance.
ValueError
If there is no preinstanced object for the given `value`.
"""
value_type = value.__class__
if (value_type is not type_):
value_expected_type = type_.VALUE_TYPE
if value_type is value_expected_type:
pass
elif issubclass(value_type, value_expected_type):
value = value_expected_type(value)
else:
raise TypeError(f'`{name}` can be passed as {type_.__name__} or as {value_expected_type.__name__} '
f'instance, got {value_type.__name__}.')
try:
value = type_.INSTANCES[value]
except LookupError:
raise ValueError(f'There is no predefined `{name}` for the following value: {value!r}.') from None
return value
|
257948a0ebed93dcb8772d74c8378b9f5a42af36
| 81,701
|
import logging
def run_flushdb(redis_con):
"""
Purpose:
Run Redis FlushDB Command. Will clear all
keys and values from the Redis Database (good
for clearing cache when redis is used as
a caching solution)
Args:
redis_con (Redis StrictRedis): Connection
to Redis database
Return
was_successful (bool): whether or not the
command was successful running
"""
logging.info("Flushing Redis DB")
try:
redis_con.flushdb()
except Exception as err:
logging.error("Error Flushing DB: {0}".format(err))
return False
return True
|
7e65b420a827a2204d0f40cb8534ce35c1427ce0
| 81,704
|
def storage_method(meth):
"""
Decorator to mark the decorated method as being a storage method,
to be copied to the storage instance.
"""
meth.storage_method = True
return meth
|
7cb277fd0dca7aa2348e0ca6d173c2e97d1cb589
| 81,710
|
def openhand(config,hand,amount):
"""Opens the hand of the given Hubo configuration config by the given amount.
hand is either 'l','r', 'left', or 'right' and amount is in the range [0,1]
ranging from closed to open.
"""
if hand!='left' and hand!='right' and hand!='l' and hand != 'r':
raise ValueError("Invalid hand specified, must be l or r")
leftdofs = range(14,29)
rightdofs = range(35,50)
leftopen = [0.0]*15
rightopen = [0.0]*15
leftclose = [-1.0,0.7,0.7]*5
rightclose = [-1.0,0.7,0.7]*5
output = config[:]
dofs = None
if hand[0]=='l':
dofs = leftdofs
vals = [a+amount*(b-a) for (a,b) in zip(leftclose,leftopen)]
else:
dofs = rightdofs
vals = [a+amount*(b-a) for (a,b) in zip(rightclose,rightopen)]
for (d,v) in zip(dofs,vals):
assert d < len(config),"Config does not have enough entries"
output[d] = v
return output
|
8b5f1fc930ff37d8626fcceb3a63d73d3fe966c5
| 81,711
|
import uuid
def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of values (properties) for the MoleculeObject
"""
m = {"uuid": str(uuid.uuid4()), "source": source, "format": format}
if values:
m["values"] = values
return m
|
4a917521a2fd5d4f5f5180aa7d5da60aec2cd00a
| 81,712
|
def get_all_rpi_info(self):
"""
Returns dictionary with all available RPI information
"""
return {
'ip': self.get_rpi_ip(),
'hostname': self.get_rpi_hostname(),
'cpu_temp': self.get_rpi_cpu_temp(),
'usb_devices': self.get_rpi_usb_devices(),
'version': self.get_rpi_version(),
'free_memory': self.get_rpi_free_memory(),
'total_memory': self.get_rpi_total_memory(),
'date': self.get_rpi_date()
}
|
cbfbdbcfe66bcd64222c5853968a35aed71292af
| 81,714
|
def num_leading_spaces(text: str, space_char: str = " ") -> int:
"""Count number of leading spaces in a string
Args:
text: String to count.
space_char: Which characters count as spaces.
Returns:
Number of leading spaces.
"""
return len(text) - len(text.lstrip(space_char))
|
1483b8a7fe3905fef354bb71ea25bf741bcc8a5f
| 81,715
|
def coerce_enum(value, cls):
"""Attempt to coerce a given string or int value into an Enum instance."""
if isinstance(value, int):
value = cls(value)
elif isinstance(value, str):
value = cls[value]
return value
|
4eaf7f7a2624d940002c2946cb36d8f92d968ed9
| 81,727
|
def drop_columns_by_regex(df, column_regex):
"""Returns dataframe with columns matching the regex dropped."""
return df[df.columns.drop(list(df.filter(regex=column_regex)))]
|
ac0fd5f21176fedf6c1c15226173541ba43e0f28
| 81,732
|
def attr_val_bool(elem, attr_name):
"""Returns the boolean value of attribute *attr_name* on element *elem* or None if no such attribute does not exists."""
attr = elem.find_attribute(attr_name)
return attr.normalized_value.strip() in ('1', 'true') if attr else None
|
ce32a9c35939167f52c821dbf752cc285bc468c5
| 81,735
|
def clean_accessions(records):
"""Extract accession keys from SeqRecords.
The id of the given records is processed to remove domain location info
added by HMMer. Most other records won't have a '/' character in the FASTA
header key.
"""
return (rec.id.rsplit('/', 1)[0] for rec in records)
|
117c9bbad8278e8aa9ab978439da908648a9c2d2
| 81,742
|
import pathlib
def get_relative_path_view(file_path: pathlib.Path) -> str:
"""
make relative path from current path to `file_path`
:param file_path: absolute file path
:type file_path: pathlib.Path
:return: string that represents relative path to `file_path`
:rtype: str
"""
current_path = pathlib.Path().absolute()
relative_path = file_path.relative_to(current_path)
return str(relative_path)
|
76119de54839ebd3d28910bdf1f74bf0609c2572
| 81,743
|
import importlib
def _load(name: str):
"""Load a python object from string.
Args:
name: of the form `path.to.module:object`
"""
mod_name, attr_name = name.split(":")
mod = importlib.import_module(mod_name)
fn = getattr(mod, attr_name)
return fn
|
7a9f615961726b75fe33049881029727b1994dc4
| 81,746
|
def select(lstbox, multiple):
"""Returns the user's selection a Listbox
Keyword arguments:
lstbox -- Tkinter Listbox Widget
multiple -- indicates whether to return a string or a list"""
reslist = list()
selection = lstbox.curselection()
for i in selection:
entrada = lstbox.get(i)
reslist.append(entrada)
if (multiple == 1):
return reslist
else:
return reslist[0]
|
8bec60a43138785b7cb4d6795d264723ed9ffde0
| 81,747
|
def split_into_lines(text,char_limit,delimiters=' \t\n',
sympathetic=False):
"""Split a string into multiple lines with maximum length
Splits a string into multiple lines on one or more delimiters
(defaults to the whitespace characters i.e. ' ',tab and newline),
such that each line is no longer than a specified length.
For example:
>>> split_into_lines("This is some text to split",10)
['This is','some text','to split']
If it's not possible to split part of the text to a suitable
length then the line is split "unsympathetically" at the
line length, e.g.
>>> split_into_lines("This is supercalifragilicous text",10)
['This is','supercalif','ragilicous','text']
Set the 'sympathetic' flag to True to include a hyphen to
indicate that a word has been broken, e.g.
>>> split_into_lines("This is supercalifragilicous text",10,
... sympathetic=True)
['This is','supercali-','fragilico-','us text']
To use an alternative set of delimiter characters, set the
'delimiters' argument, e.g.
>>> split_into_lines("This: is some text",10,delimiters=':')
['This',' is some t','ext']
Arguments:
text: string of text to be split into lines
char_limit: maximum length for any given line
delimiters: optional, specify a set of non-default
delimiter characters (defaults to whitespace)
sympathetic: optional, if True then add hyphen to
indicate when a word has been broken
Returns:
List of lines (i.e. strings).
"""
lines = []
hyphen = '-'
while len(text) > char_limit:
# Locate nearest delimiter before the character limit
i = None
splitting_word = False
try:
# Check if delimiter occurs at the line boundary
if text[char_limit] in delimiters:
i = char_limit
except IndexError:
pass
if i is None:
# Look for delimiter within the line
for delim in delimiters:
try:
j = text[:char_limit].rindex(delim)
i = max([x for x in [i,j] if x is not None])
except ValueError:
pass
if i is None:
# Unable to locate delimiter within character
# limit so set to the limit
i = char_limit
# Are we splitting a word?
try:
if text[i] not in delimiters and sympathetic:
splitting_word = True
i = i - 1
except IndexError:
pass
lines.append("%s%s" % (text[:i].rstrip(delimiters),
hyphen if splitting_word else ''))
text = text[i:].lstrip(delimiters)
# Append remainder
lines.append(text)
return lines
|
29d48d0c836528643ac5a3e10f277a0231c2916f
| 81,749
|
def is_in(obj, iterable):
"""
Determine if an obj instance is in a list. Needed to prevent Python from
using __eq__ method which throws errors for ndarrays.
"""
for element in iterable:
if element is obj:
return True
return False
|
5cd11086ff6e40fb15a6392f4ef5ee6b4822cb2e
| 81,751
|
import collections
import itertools
def part2(lines):
"""
Analyzing all the possible numbers we get:
a b c d e f g
-----------------------------------
0: x x x x x x
1: x x
2: x x x x x
3: x x x x x
4: x x x x
5: x x x x x
6: x x x x x x
7: x x x
8: x x x x x x x
9: x x x x x x
-----------------------------------
r: 8 6 8 7 4 9 7 <- how many times each character is present
If we assign each character to the value of r above, we find that each number
can be uniquely represented by the sum of those values:
0: abcefg = 8+6+8+4+9+7 = 42
1: cf = 8+9 = 17
... and so on
"""
def decode(wires, output):
counter = collections.Counter(itertools.chain(*wires))
number = 0
for digits in output:
number = number * 10 + mapping[sum(counter[c] for c in digits)]
return number
correct = {
0: "abcefg",
1: "cf",
2: "acdeg",
3: "acdfg",
4: "bcdf",
5: "abdfg",
6: "abdefg",
7: "acf",
8: "abcdefg",
9: "abcdfg",
}
counter = collections.Counter(itertools.chain(*correct.values()))
mapping = {sum(counter[d] for d in digits): num for num, digits in correct.items()}
return sum(decode(*l) for l in lines)
|
7eb8a5f67558ebf9514bb9909be67ead5b63f5a5
| 81,757
|
from typing import Dict
import requests
def read_number_from_es(es_host) -> Dict[str, int]:
"""
Get numbers of records
:param es_host: the address where the elastic search is hosted
:return: numbers of records in all indices found at the given address
"""
counts = {}
url = f"{es_host}/_cat/indices?v"
"""
example of response
health status index uuid pri rep docs.count docs.deleted store.size
pri.store.size
green open faang_build_2_specimen bo3YAiLmSUWqlgtzVElzKQ 5 1 9388 0 18.4mb
9mb
green open faang_build_4_specimen _jSFP7MRS6qVrkiqcQ9f4Q 5 1 9388 0 19mb
9.6mb
"""
response = requests.get(url).text
# removes the header of returned value
lines = response.split("\n")[1:]
for line in lines:
elmts = line.split()
if elmts:
# 3rd column is the index name and 7th column is docs.count
counts[elmts[2]] = elmts[6]
return counts
|
7b1c0259403c398cad527497e988d4f737856eba
| 81,758
|
import copy
def clean(data):
"""
This function takes a list of lists as an argument, makes a deep copy of the list, and, within the deep copy,
strips strings of trailing whitespece converted and converts numbers to integers.
Parameters:
data (list): A list of lists, each representing a party's election results
Returns:
clean_data (list): a list of lists with clean data, each representing a party's election results
"""
new_data = copy.deepcopy(data)
for line in new_data[1:]:
line[0] = line[0].strip()
line[1] = int(line[1])
line[2] = line[2].lower().strip()
return new_data
|
cd9cae4400097195adb1f618ebb4739c2496e970
| 81,761
|
import re
def headers_to_strings(headers, titled_key=False):
"""Convert HTTP headers to multi-line string."""
return "\n".join(
[
"{0}: {1}".format(
key.title() if titled_key else key,
re.sub(
r"Credential=([^/]+)",
"Credential=*REDACTED*",
re.sub(
r"Signature=([0-9a-f]+)",
"Signature=*REDACTED*",
value,
),
) if titled_key else value,
) for key, value in headers.items()
]
)
|
8dd64c582c4c6abcb13525406455caf5c4e38547
| 81,769
|
def loop_zip(strA, strB):
"""(str, str) => zip()
Return a zip object containing each letters of strA, paired with letters of strB.
If strA is longer than strB, then its letters will be paired recursively.
Example:
>>> list(loop_zip('ABCDEF', '123'))
[('A', '1'), ('B', '2'), ('C', '3'), ('D', '1'), ('E', '2'), ('F', '3')]
"""
assert len(strA) >= len(strB)
s = ""
n = 0
for l in strA:
try:
s += strB[n]
except IndexError:
n = 0
s += strB[n]
n += 1
return zip(list(strA), list(s))
|
748fb794778d99a2beae644b93e2ee96d2a169a7
| 81,771
|
def get_enabled_bodies(env):
"""
Returns a C{set} with the names of the bodies enabled in the given environment
@type env: orpy.Environment
@param env: The OpenRAVE environment
@rtype: set
@return: The names of the enabled bodies
"""
enabled_bodies = []
with env:
for body in env.GetBodies():
if body.IsEnabled():
enabled_bodies.append(body.GetName())
return set(enabled_bodies)
|
ea5a86538edefaacf5b47ea22b9abc3ee87bba81
| 81,774
|
def has_loops(path):
"""Returns True if this path has a loop in it, i.e. if it
visits a node more than once. Returns False otherwise."""
for node in path:
count = 0
for n in path:
if node == n:
count +=1
if count > 1:
return True
return False
|
2cce551bbc8ffc2de0ac08359ae110a707cb62d3
| 81,775
|
from typing import List
def lines_to_list_int(lines: str) -> List[int]:
""" Transform multi-line integer input to a list. """
return list(map(int, lines.splitlines(keepends=False)))
|
2436ade0416e89915795abde56462aa58ff1620c
| 81,776
|
import csv
def parse_mlst_result(path_to_mlst_result):
"""
Args:
path_to_mlst_result (str): Path to the mlst report file.
Returns:
list of dict: Parsed mlst report.
For example:
[
{
'contig_file': 'SAMPLE-ID.fa',
'scheme_id': 'ecoli',
'sequence_type': '405',
'multi_locus_alleles': {
'adk': '35',
'fumc': '37',
'gyrB': '29',
'icd': '25',
'mdh': '4',
'purA': '5',
'recA': '73'
}
}
]
"""
mlst_results = []
#read in the mlst result
with open(path_to_mlst_result) as mlst_result_file:
reader = csv.reader(mlst_result_file, delimiter='\t')
for row in reader:
mlst_result = {}
mlst_result['contig_file'] = row[0]
mlst_result['scheme_id'] = row[1]
mlst_result['sequence_type'] = row[2]
mlst_result['multi_locus_alleles'] = {}
for field in row[3:]:
(locus, allele) = tuple(field.replace(')', '').split('('))
mlst_result['multi_locus_alleles'][locus] = allele
mlst_results.append(mlst_result)
return mlst_results
|
ca7f3972c00da4da4d09494baa3e189742e420ef
| 81,780
|
def test_suites(*suite_names):
"""Decorator that adds the test to the set of suites.
Note that the decorator takes in Test instances, so this decorator should be
used *above* the @checkers.test decorator (so that the @checkers.test
decorator will have already been applied and returned a Test instance.)
Args:
*suite_names: (strings) Names of suites the test should be added to.
Returns:
function: Decorator that will apply suites to the test.
"""
def test_suites_decorator(checkers_test):
for suite_name in suite_names:
checkers_test.test_suite_names.add(suite_name)
return checkers_test
return test_suites_decorator
|
56748f5c0f2b9eb1e16ed3ca53036d293d67c733
| 81,782
|
def any_non_int_numbers(collection):
"""Returns true if any numbers in the collection are not integers"""
return any(map(lambda n: not isinstance(n, int), collection))
|
a263dbfb0c7bea528ca3ef2c271e10495bc1acda
| 81,785
|
def sort_ipv4_addresses_without_mask(ip_address_iterable):
"""
Sort IPv4 addresses only
| :param iter ip_address_iterable: An iterable container of IPv4 addresses
| :return list : A sorted list of IPv4 addresses
"""
return sorted(
ip_address_iterable,
key=lambda addr: (
int(addr.split('.')[0]),
int(addr.split('.')[1]),
int(addr.split('.')[2]),
int(addr.split('.')[3]),
)
)
|
5aac315ee06e0da0eb0e17704ee623a8ca9f199e
| 81,786
|
def remove_from(index, element):
"""
A wrapper around del element[index].
params:
index: the index at which we should delete
element: an element that implements __delitem__
"""
del element[index]
return element
|
00f7a12867489682129af8ef71236f09957e44cc
| 81,789
|
def get_empty_cells(grid):
"""Return a list of coordinate pairs corresponding to empty cells."""
empty = []
for j,row in enumerate(grid):
for i,val in enumerate(row):
if not val:
empty.append((j,i))
return empty
|
b853f7f2f8017db0c1d37426b21785b4fa958350
| 81,793
|
from pathlib import Path
def check_and_create(directory: Path) -> Path:
"""Create directory if it doesn't exist and return it."""
if not directory.is_dir():
directory.mkdir(parents=True, exist_ok=True)
return directory
|
3fc5dc5476387a2ce37ec6021668d993b9bd667a
| 81,798
|
def get_value_of_scoring_none_condition(sc, ml_task):
"""Updates sc value, if sc is None.
Args:
sc: str or None. Scoring. The selection criteria for the best model.
ml_task: str. Machine learning task.
Returns:
sc: str. Scoring. The selection criteria for the best model.
"""
if ml_task in ["binary", "multiclass"]:
if sc is None:
sc = "f1"
else:
if sc is None:
sc = "adjusted_r2"
return sc
|
e55d557056f6c078af9ea7d99d502360469d4272
| 81,802
|
def _length_of_axis_dimension(root, axis_name):
"""Get the size of an axis by axis name.
Parameters
----------
root : netcdf_file
A NetCDF object.
axis_name : str
Name of the axis in the NetCDF file.
Returns
-------
int
Size of the dimension.
"""
try:
return len(root.dimensions[axis_name])
except TypeError:
return root.dimensions[axis_name]
|
11e0af90d6cd1c9603b14b03fb7df81f10bf25d7
| 81,804
|
def lower_rep(text):
"""Lower the text and return it after removing all underscores
Args:
text (str): text to treat
Returns:
updated text (with removed underscores and lower-cased)
"""
return text.replace("_", "").lower()
|
a9e6c507146ba1b0c9bcd924867b330edc8e6d0f
| 81,805
|
from typing import OrderedDict
import json
def dump_json(obj, separators=(', ', ': '), sort_keys=False):
"""Dump object into a JSON string."""
if sort_keys is None:
sort_keys = not isinstance(obj, OrderedDict) # Let it sort itself.
return json.dumps(obj, separators=separators, sort_keys=sort_keys)
|
9c800ceee12cbe5b3cf4eda9530b018ecdf22dc8
| 81,806
|
import re
def fetchthumb(item):
"""
Get the thumbnail image for an item if possible
"""
text = item.summary
if 'content' in item:
text = item.content[0].value
# regex to get an image if available
thumb_search = re.search('(https?:\/\/[\S]+\.(jpg|png|jpeg))', text, re.IGNORECASE)
if thumb_search:
return thumb_search.group(1)
else:
return None
|
d2bbb9793500b49238e40b583df54816587c1884
| 81,811
|
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 _isIPv6Addr(strIPv6Addr):
"""Confirm whether the specified address is an IPv6 address.
:param str strIPv6Addr: IPv6 address string that adopted the full
represented.
:return: True when the specified address is an IPv6 address.
:rtype: bool
Example::
strIPv6Addr Return
---------------------------------------------------
'2001:0dB8:0000:0000:0000:0000:0000:0001' -> True
'2001:0dB8:0000:0000:0000:0000:0001' -> False
'2001:0dB8:0000:0000:0000:0000:0000:001' -> False
'2001:0dB8:0000:0000:0000:0000:0000:000g' -> False
Test:
>>> _isIPv6Addr('2001:0dB8:0000:0000:0000:0000:0000:0001')
True
>>> _isIPv6Addr('2001:0dB8:0000:0000:0000:0000:0001')
False
>>> _isIPv6Addr('2001:0dB8:0000:0000:0000:0000:0000:001')
False
>>> _isIPv6Addr('2001:0dB8:0000:0000:0000:0000:0000:000g')
False
"""
listStrIPv6Hextet = strIPv6Addr.split(':')
if (len(listStrIPv6Hextet) != 8):
return False
for i in range(8):
strHextet = listStrIPv6Hextet[i]
if (len(strHextet) != 4):
return False
c1 = strHextet[0:1]
c2 = strHextet[1:2]
c3 = strHextet[2:3]
c4 = strHextet[3:4]
if (((c1 >= '0' and c1 <= '9') or (c1 >= 'a' and c1 <= 'f') or (c1 >= 'A' and c1 <= 'F')) and
((c2 >= '0' and c2 <= '9') or (c2 >= 'a' and c2 <= 'f') or (c2 >= 'A' and c2 <= 'F')) and
((c3 >= '0' and c3 <= '9') or (c3 >= 'a' and c3 <= 'f') or (c3 >= 'A' and c3 <= 'F')) and
((c4 >= '0' and c4 <= '9') or (c4 >= 'a' and c4 <= 'f') or (c4 >= 'A' and c4 <= 'F'))):
pass
else:
return False
return True
|
45b330bbd74cc22be467f50f1c8a78c2fb7bdec5
| 81,815
|
def get_teams(email_subject):
"""
Returns the visiting, home teams from email subject line.
:param str email_subject: subject line from iScore email
:returns: visiting_team, home_team
:rtype: str, str
"""
subject_parts = email_subject.split()
return subject_parts[6], subject_parts[8]
|
c2132841259a154194b9c29e0b11546fb37cf61a
| 81,819
|
def _name_to_desc(name):
"""Convert a name (e.g.: 'NoteOn') to a description (e.g.: 'Note On')."""
if len(name) < 1:
return ''
desc = list()
desc.append(name[0])
for index in range(1, len(name)):
if name[index].isupper():
desc.append(' ')
desc.append(name[index])
return ''.join(desc)
|
af673982a4d790cfa0007da3012ec772b4800806
| 81,827
|
import re
def re_lines(pat, text, match=True):
"""Return a list of lines selected by `pat` in the string `text`.
If `match` is false, the selection is inverted: only the non-matching
lines are included.
Returns a list, the selected lines, without line endings.
"""
assert len(pat) < 200, "It's super-easy to swap the arguments to re_lines"
return [l for l in text.splitlines() if bool(re.search(pat, l)) == match]
|
aa04cfdbf5dfa2c3aed6d22e3f3671f69ab4481f
| 81,829
|
def _trimmed(array, border_size):
"""Return a view on the array in the border removed"""
return array[border_size:-border_size, border_size:-border_size]
|
63d38e0af7112abe15b5e76b3526b37ee3055c39
| 81,830
|
def login(client, username, password):
"""Simulate a log-in from a user.
After the log-in request, the client will be redirect to the expected page.
Parameters
----------
client : :class:`flask.testing.FlaskClient`
The testing client used for unit testing.
username : str
The user's name.
password : str
The user's password.
Returns
-------
response : :class:`flask.wrappers.Response`
The response of the client.
"""
return client.post('/login', data=dict(
user_name=username,
password=password
), follow_redirects=True)
|
6a595c1d31b0cc331b40bd25d6c6c827ea10fa66
| 81,838
|
import random
import string
def random_hex(length):
""" Generate random string from HEX digits """
return ''.join(random.choice(string.hexdigits) for i in range(length))
|
080145444b30f02578c3b1dbab671aff5141def0
| 81,839
|
def is_upside_down_text_angle(angle: float, tol: float = 3.) -> bool:
"""Returns ``True`` if the given text `angle` in degrees causes an upside
down text in the :ref:`WCS`. The strict flip range is 90° < `angle` < 270°,
the tolerance angle `tol` extends this range to: 90+tol < `angle` < 270-tol.
The angle is normalized to [0, 360).
Args:
angle: text angle in degrees
tol: tolerance range in which text flipping will be avoided
"""
angle %= 360.
return 90. + tol < angle < 270. - tol
|
9a964dbfed0fe341b9ccb99a783e8262c0af6ca3
| 81,849
|
import ipaddress
def get_all_hosts(ipnet):
"""
Generate the list of all possible hosts within a network
Arguments:
ipnet -- an IP network address in the form
<ip>/subnet such as 192.168.1.0/24
or 69f6:a34:2efb:19ca:d40::/74
Returns:
all hosts -- a generator for all IP address objects
that represent all the possible hosts
that can exist within the specified network
"""
return ipaddress.ip_network(ipnet).hosts()
|
c4d78463ed8c3094663d1b4df412fe89a794eee1
| 81,851
|
import re
def FuzzyFilter(collection, searchInput):
"""
Fuzzy Filters a defined collection
:collection: The collection to filter
:searchInput: The input string to fuzzy match
:returns: A list of suggestions
"""
suggestions = []
pattern = '.*?'.join(searchInput) # Converts 'djm' to 'd.*?j.*?m'
regex = re.compile(pattern, re.IGNORECASE) # Compiles a regex.
for item in collection:
# Current item matches the regex?
match = regex.search(item, re.IGNORECASE)
if match:
suggestions.append((len(match.group()), match.start(), item))
return sorted([x for _, _, x in suggestions])
|
48f280bf175f45fc9b1c853f8341c431241786ab
| 81,857
|
from pathlib import Path
def find_package_top(file: Path):
"""Find package top directory."""
while True:
if len(file.parts) == 1:
raise ValueError('Package top was not found!')
if not file.with_name('__init__.py').exists():
break
file = file.parent
return file
|
1a065d6b7c68acb93188b187dd91fc6f9a57eeaf
| 81,859
|
from datetime import datetime
def parse_generalized_datetime(ts):
"""Parse an ASN.1 generalized datetime string.
Currently, only fractionless strings are supported. The result is returned
as a datetime object.
"""
result = None
if ts[-1] == "Z":
result = datetime.strptime(ts, "%Y%m%d%H%M%SZ")
elif ts[-5] == "+" or ts[-5] == "-":
result = datetime.strptime(ts, "%Y%m%d%H%M%S%z")
else:
result = datetime.strptime(ts, "%Y%m%d%H%M%S")
return result
|
917b4a67de18f9080bee038b94de6f393d2c84cc
| 81,864
|
import unicodedata
def normalize_unicodedata(text: str) -> str:
""" Applies unicodedata normalization of the form 'NFC'. """
return unicodedata.normalize('NFC', text)
|
e7f69616d9f5dee067acfb22077cdfdf9e0860d0
| 81,867
|
def labeled_point_to_row_col_period(labeled_point):
"""Helper function to reconstruct period, row, and column of labeled point
Used in .map call for predictions
Args:
labeled_point (LabeledPoint): cell with label and features
Returns:
tuple (int, int, str): row, col, period
"""
features = labeled_point.features
row, col = features[0], features[1]
month, day, hour = features[2], features[3], features[4]
period = '2013{:02d}{:02d}{:02d}'.format(int(month), int(day), int(hour))
return row, col, period
|
e18bd88a8d4a341bec000e0fa250fd7ade69b32b
| 81,872
|
def to_slice(idxs):
"""Convert an index array to a slice if possible. Otherwise,
return the index array. Indices are assumed to be sorted in
ascending order.
"""
if len(idxs) == 1:
return slice(idxs[0], idxs[0]+1)
elif len(idxs) == 0:
return idxs
stride = idxs[1]-idxs[0]
if stride <= 0:
return idxs
#make sure stride is consistent throughout the array
if any(idxs[1:]-idxs[:-1] != stride):
return idxs
# set the upper bound to idxs[-1]+stride instead of idxs[-1]+1 because
# later, we compare upper and lower bounds when collapsing slices
return slice(idxs[0], idxs[-1]+stride, stride)
|
408cd4d0e21abdfb32ef21360cf30af7d973c166
| 81,878
|
def GetDescription(key_list, key_count):
"""Generates a description from readings.
We simply add 1) the most general reading and 2) the most specific reading.
1) and 2) are simply approximated by checking the frequency of the readings.
Args:
key_list: a list of key strings.
key_count: a dictionary of key to the number of key's occurence in the data
file.
Returns:
the description string.
"""
if len(key_list) == 1:
return key_list[0]
sorted_key_list = sorted(key_list, key=lambda key: (key_count[key], key))
return '%s %s' % (sorted_key_list[-1], sorted_key_list[0])
|
c91da52d7b76169ca37df23f3ccda409f4453dad
| 81,879
|
def hr_time(seconds):
"""Formats a given time interval for human readability."""
s = ''
if seconds >= 86400:
d = seconds // 86400
seconds -= d * 86400
s += f'{int(d)}d'
if seconds >= 3600:
h = seconds // 3600
seconds -= h * 3600
s += f'{int(h)}h'
if seconds >= 60:
m = seconds // 60
seconds -= m * 60
if 'd' not in s:
s += f'{int(m)}m'
if 'h' not in s and 'd' not in s:
s += f'{int(seconds)}s'
return s
|
5e852331df6db8b9aaa43fa49d709d2f93b68907
| 81,880
|
def round_down(dt, timeframe):
"""Round a datetime object down based on the given timeframe."""
day = 1 if timeframe == "year" else dt.day
hour = 0 if timeframe in ["year", "month", "week"] else dt.hour
return dt.replace(day=day, hour=hour, minute=0, second=0, microsecond=0)
|
06f5310a8150a16c6d6b0dbf61190ee31ee4272b
| 81,881
|
def warshall(graph):
"""
Warshall's Algorithm for Shortest Path
Complexity: O(V^3)
It produces the shortest paths between all the vertices.
"""
for k in range(len(graph)):
for i in range(len(graph)):
for j in range(len(graph)):
graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])
return graph
|
c3bff1fa525ee677b9a2c184215832843d4d9ad0
| 81,885
|
def sgn(x):
""" Return the sign of *x*. """
return 1 if x.real > 0 else -1 if x.real < 0 else 0
|
d0b937d417d5edcbade7b7e64555d944fcd6c631
| 81,887
|
def is_factor_term(obj):
""" Is obj a FactorTerm?
"""
return hasattr(obj, "_factor_term_flag")
|
7148f0536a4ed0bd5ed724bf18c1228405f0ac3a
| 81,888
|
def required_child_amount_rule(model, cr, ca):
"""
In order for a child resource to select a child activity, a certain amount of child budget is required.
A child activity is selected if and only if the provided amount is sufficient.
:param ConcreteModel model:
:param int cr: child resource
:param int ca: child activity
:return: boolean indicating whether the needed amount is allocated from cr to ca
"""
return model.CHILD_AMT[cr, ca] == model.req_child_amt[cr, ca] * model.CHILD_ALLOCATED[cr, ca]
|
0a582e4d76cc3a1768de2ba9990c8410ae2ed514
| 81,890
|
def _str_len_check(text, min_len, max_len):
"""
Validate string type, max and min length.
"""
if not isinstance(text, str):
raise ValueError("expected string type")
if not (min_len <= len(text) <= max_len):
raise ValueError(f"length should be between {min_len} and {max_len} characters")
return text
|
691f3f0083e892fdb3ee8fbe614cc5d8edafa4be
| 81,891
|
def convert_voxels_padding(voxels, pad_width):
"""
Convert the voxels gained before padding
to the voxels after padding.
(i.e. position at small image -> position at large image).
"""
dim = voxels.shape[1]
new_voxels = voxels.copy()
if type(pad_width) == int:
pad_width = tuple([pad_width] * dim)
for axis in range(dim):
new_voxels[:, axis] += pad_width[axis]
return new_voxels
|
182724d7967009de9f7d9a6e6c0c4790d0f73fdb
| 81,892
|
def get_drop_path_keep_prob(keep_prob_for_last_stage, schedule,
current_stage, num_stages):
"""Gets drop path keep probability for current stage.
Args:
keep_prob_for_last_stage: A float, the drop path keep probability for
last stage. This flag is used in conjunction with the flag `schedule`, as
they together determine drop path keep probability for the other stages.
schedule: A string, the drop path schedule. Currently, we support
'constant': use the same drop path keep probability for all stages, and
'linear': linearly decrease the drop path keep probability from 1.0 at
0-th stage (or STEM) to `keep_prob_for_last_stage` at last stage.
current_stage: An integer, current stage number.
num_stages: An integer, the number of stages.
Returns:
The drop path keep probability for the current stage.
Raises:
ValueError: If schedule is not supported.
"""
if schedule == 'constant':
return keep_prob_for_last_stage
elif schedule == 'linear':
return 1.0 - (1.0 - keep_prob_for_last_stage) * current_stage / num_stages
else:
raise ValueError('Unexpected schedule %s.' % schedule)
|
293a827f6657b86d8099b68c8b26b4a08a7a31dc
| 81,893
|
from typing import Dict
from typing import Any
def validate_result(result: Dict[str, Any]) -> bool:
"""Validates the result.json file generated by prosecoPlanner.cpp
Parameters
----------
results: Dict[str, Any]
Loaded result.json file.
Returns
-------
bool
Validity of the result dictionary.
"""
keys = (
"carsCollided",
"carsInvalid",
"desiresFulfilled",
"finalstep",
"maxSimTimeReached",
"normalizedCoopRewardSum",
"normalizedEgoRewardSum",
"scenario",
)
for key in keys:
if key in result.keys():
if result[key] is None:
print("key: '{}' is None in result".format(key))
return False
else:
print("key: '{}' is missing in result".format(key))
return False
return True
|
98cc89046e2bb567705705aef3e713cb50dbac2d
| 81,894
|
def _collapse_conformers(molecules):
"""
Collapse conformers of isomorphic molecules into single Molecule objects.
This is useful when reading in multi-conformer SDF files because the SDF
reader does not automatically collapse conformers. This function should
not modify lists of Molecule objects whose conformers are already collapsed.
Parameters
----------
molecules : list of Molecule
List of Molecule objects
Returns
-------
collapsed_molecules : list of Molecule
List of Molecule objects with only one object per isomorphic molecule
and conformers of isomorphic molecules stored in each
"""
collapsed_molecules = [molecules[0]]
for molecule in molecules[1:]:
if molecule == collapsed_molecules[-1]:
for conformer in molecule.conformers:
collapsed_molecules[-1].add_conformer(conformer)
else:
collapsed_molecules.append(molecule)
return collapsed_molecules
|
d9340cca58a9688c4c68d2d36342c1fc4561e8dc
| 81,900
|
def _FormatLogContent(name, content):
"""Helper function for printing out complete log content."""
return '\n'.join((
'----------- Start of %s log -----------\n' % name,
content,
'----------- End of %s log -----------\n' % name,
))
|
23b0f7808f2af63d6aebaa2055fc009d36ff100d
| 81,901
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.