content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def pollutants_from_summary(summary):
"""
Get the list of unique pollutants from the summary.
:param list[dict] summary: The E1a summary.
:return dict: The available pollutants, with name ("pl") as key
and pollutant number ("shortpl") as value.
"""
return {d["pl"]: d["shortpl"] for d i... | d880a1f693139786a3ee799594ed1bd664d4b93e | 30,015 |
def _dest_path(path):
"""Returns the path, stripped of parent directories of .dSYM."""
components = path.split("/")
res_components = []
found = False
for c in components:
# Find .dSYM directory and make it be at the root path
if c.endswith(".dSYM"):
found = True
i... | 869efc4265e09c182a948f6580075846a6af7c9f | 30,016 |
def get_max(num_list):
"""Recursively returns the largest number from the list"""
if len(num_list) == 1:
return num_list[0]
else:
return max(num_list[0], get_max(num_list[1:])) | a1ba81d12e1a9f7aa7cfa1c9846a790a5789485d | 30,019 |
import json
def get_device(token):
"""
Read the device configuration from device.json file.
:return: dict - the device configuration
"""
try:
with open("/tmp/{}/device.json".format(token), "r") as f:
return json.load(f)
except:
pass | 5675113a87ee2d4abf8ce630cd167113c25e3626 | 30,020 |
def unique(valuelist):
"""Return all values found from a list, but each once only and sorted."""
return sorted(list(set(valuelist))) | 1218bb7c353a898b2815c5cd95b8ef71e386b91f | 30,023 |
from typing import List
from typing import Any
def get_list_elements_containing(l_elements: List[Any], s_search_string: str) -> List[str]:
"""get list elements of type str which contain the searchstring
>>> get_list_elements_containing([], 'bc')
[]
>>> get_list_elements_containing(['abcd', 'def', 1, ... | 7a9ea19fcf94ca0493487c3a343f49cd45e85d08 | 30,024 |
def floatformatter(*args, sig: int=6, **kwargs) -> str:
"""
Returns a formatter, which essantially a string temapate
ready to be formatted.
Parameters
----------
sig : int, Optional
Number of significant digits. Default is 6.
Returns
-------
string
The s... | aead01fd8a2b1f97d20091af4326a7f248ea43a7 | 30,026 |
def comp_active_surface(self):
"""Compute the active surface of the conductor
Parameters
----------
self : CondType11
A CondType11 object
Returns
-------
Sact: float
Surface without insulation [m**2]
"""
Sact = self.Hwire * self.Wwire * self.Nwppc_tan * self.Nwppc... | 302bb23c4ed94084603c02437c67ef4ea8046b4b | 30,028 |
import hashlib
def get_checksum(address_bytes: bytes) -> bytes:
""" Calculate double sha256 of address and gets first 4 bytes
:param address_bytes: address before checksum
:param address_bytes: bytes
:return: checksum of the address
:rtype: bytes
"""
return hashlib.sha256... | 40e515603223ec68ce2b07208de47f63905dafd2 | 30,029 |
def isHeteroplasmy(variant, depth_min = 40, depth_strand = 0, depth_ratio_min = 0.0, freq_min = 0.01):
"""
determine whether a variant is a heteroplasmy according to the filers specified
Attributes
----------
variant: MTVariant
depth_min: the minimum depth
depth_strand: the minimum depth on either the forward... | 0f36082b2d545a3f4ceec9474f3dfd63feda36d0 | 30,045 |
import hashlib
def hash_ecfp(ecfp, size):
"""
Returns an int < size representing given ECFP fragment.
Input must be a string. This utility function is used for various
ECFP based fingerprints.
Parameters
----------
ecfp: str
String to hash. Usually an ECFP fragment.
size: int, optional (default ... | 4850ee88735ae172216a5ae5cbd08505d8a2f42e | 30,050 |
def dict_union(a, b):
"""
Return the union of two dictionaries without editing either.
If a key exists in both dictionaries, the second value is used.
"""
if not a:
return b if b else {}
if not b:
return a
ret = a.copy()
ret.update(b)
return ret | 5f228221a4a0fc5f322c29b8500add4ac4523e04 | 30,055 |
def gef_pybytes(x: str) -> bytes:
"""Returns an immutable bytes list from the string given as input."""
return bytes(str(x), encoding="utf-8") | aa349940a72129329b850363e8cb807566d8d4b8 | 30,058 |
def parse_STATS_header(header):
"""
Extract the header from a binary STATS data file.
This extracts the STATS binary file header information
into variables with meaningful names. It also converts year
and day_of_year to seconds at midnight since the epoch used by
UNIX systems.
@param header : string of... | 87ee5bd8971f62304c7e48f7b573a1a89c604c65 | 30,061 |
import decimal
def recall(qtd_true_positives, list_of_true_positive_documents, ref=0):
"""
TP / (TP + FN)
TP - True Positive
FN - False Negative - a document is positive but was classified as negative
"""
fn = 0
for d in list_of_true_positive_documents:
if d.predicted_polarity < ref:
fn = fn + 1
qtd_tru... | 7656a565a9ef42d06d8d7deeb3f14966e1fcf138 | 30,066 |
from datetime import datetime
def fromisoformat(isoformat):
"""
Return a datetime from a string in ISO 8601 date time format
>>> fromisoformat("2019-12-31 23:59:59")
datetime.datetime(2019, 12, 31, 23, 59, 59)
"""
try:
return datetime.fromisoformat(isoformat) # Python >= 3.7
exc... | bcb7e277e907a5c05ca74fd3fbd7d6922c0d7a36 | 30,073 |
def _generator_to_list(subnets_generator):
"""Returns list of string representations
of each yielded item from the generator.
"""
subnets = []
for subnet in subnets_generator:
subnets.append(str(subnet))
return subnets | f72c1f735d692a820d20eb14cd13e88abe21b2bb | 30,076 |
def is_selected_branch(branch: str) -> bool:
"""Determine whether a branch is the current branch."""
return branch.startswith("* ") | f7569964a3aee08a7995f66332a890ec03cee096 | 30,080 |
def getFile(file):
"""
Read out a file and return a list of string representing each line
"""
with open (file, "r") as out:
return out.readlines() | b869a7252fc45fdc6877f22975ee5281650877b9 | 30,083 |
def format_chores(chores):
"""
Formats the chores to properly utilize the Oxford comma
:param list chores: list of chores
"""
if len(chores) == 1:
return f'{chores[0]}'
elif len(chores) == 2:
return f'{chores[0]} and {chores[1]}'
else:
chores[-1] = 'and ' + chores[-1... | 38b7115520867e2545f7be7364e6147ca12dc8e1 | 30,085 |
import math
def get_line_size(l):
""" Return the size of the given line
"""
return math.sqrt(
math.pow(l[0] - l[2], 2) +
math.pow(l[1] - l[3], 2)) | 07a1d92e19e2b6104bf8d63459e588449d45912e | 30,086 |
def centercrop(pic, size):
""" Center-crops a picture in a square shape of given size. """
x = pic.shape[1]/2 - size/2
y = pic.shape[0]/2 - size/2
return pic[int(y):int(y+size), int(x):int(x+size)] | fa89253af6be414ef242ee0ba4b626ab676980a0 | 30,091 |
def early_stopping(val_bleus, patience=3):
"""Check if the validation Bleu-4 scores no longer improve for 3
(or a specified number of) consecutive epochs."""
# The number of epochs should be at least patience before checking
# for convergence
if patience > len(val_bleus):
return False
l... | dafc48f674673736e5a129aab8ce4c40fdbcbbeb | 30,096 |
def indent_code(input_string):
"""
Split code by newline character, and prepend 4 spaces to each line.
"""
lines = input_string.strip().split("\n")
output_string = ""
for line in lines:
output_string += " {}\n".format(line)
## one last newline for luck
output_string += "\n"
... | 5b110ed9bb1a4bbf471c5c4126c7460b6eb6ba1c | 30,097 |
import torch
def set_devices(model, loss, evaluator, device):
"""
:param: model, loss, evaluation_loss : torch.nn.Module objects
:param: device: torch.device,compatible string, or tuple/list of devices.
If tuple, wrap the model using torch.nn.DataParallel and use the first
specified device... | d15de114b4e5099c9c33edf5e82d95d2babed3cd | 30,100 |
def btod(binary):
"""
Converts a binary string to a decimal integer.
"""
return int(binary, 2) | 202ce460bf9fa5675e195ca2714d8f5f0576020c | 30,107 |
def set_progress_percentage(iteration, total):
"""
Counts the progress percentage.
:param iteration: Order number of browser or version
:param total: Total number of browsers or versions
:return: Percentage number
"""
return float((iteration + 1) / total * 100) | 1881cd84e2af051379dc293b0e71067fc7be92a0 | 30,111 |
def has_loop(page_list):
"""
Check if a list of page hits contains an adjacent page loop (A >> A >> B) == True.
:param page_list: list of page hits derived from BQ user journey
:return: True if there is a loop
"""
return any(i == j for i, j in zip(page_list, page_list[1:])) | 461691e62a900e84f779ed96bdf480ce8a5367af | 30,117 |
def linear(a, b, x, min_x, max_x):
"""
b ___________
/|
/ |
a _______/ |
| |
min_x max_x
"""
return a + min(max((x - min_x) / (max_x - min_x), 0), 1) * (b - a) | d6bbac95a0a53663395cd4d25beeadbaa5f9f497 | 30,118 |
def form_message(sublines, message_divider):
"""Form the message portion of speech bubble.
Param: sublines(list): a list of the chars to go on each line in message
Return: bubble(str): formaatted to fit inside of a bubble
"""
bubble = ""
bubble += message_divider
bubble += "".join(subl... | c3ca1c2a684d25b439a594cfc5ade187f272a2c1 | 30,123 |
from typing import BinaryIO
from typing import Optional
from io import StringIO
def decode_object(
handle: BinaryIO,
num_lines: Optional[float] = None,
) -> StringIO:
""" Converts a binary file-like object into a String one.
Files transferred over http arrive as binary objects.
If I want to check... | 5c08438727290ea797ee93261ccd6f03763b7f36 | 30,125 |
import torch
def get_grad_norm_from_optimizer(optimizer, norm_type=2):
"""
Get the gradient norm for some parameters contained in an optimizer.
Arguments:
optimizer (torch.optim.Optimizer)
norm_type (int): Type of norm. Default value is 2.
Returns:
norm (float)
"""
tota... | c8987953f23d6023d3b4f3abf894b98d720662fb | 30,128 |
def count_days_between(dt1, dt2):
"""Function will return an integer of day numbers between two dates."""
dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0)
dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0)
return (dt2 - dt1).days | 94fb2cf51af9007ab0c47229d485524af1f18656 | 30,132 |
import string
import random
def generate_random_alphanumeric_string(str_length=12):
"""
Generates a random string of length: str_length
:param str_length: Character count of the output string
:return: Randomly generated string
:rtype: str
"""
letters_and_digits = string.ascii_letters + str... | 5f0cbd817e3d9dcb5a0b5e785a634bfa2e166968 | 30,135 |
def _buffer_list_equal(a, b):
"""Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal
"""
if len(a) != len(b):
return False
... | c88d9d87684d27007a73c196f5aaa12e963a8656 | 30,136 |
def delete_line_breaks(text, joiner):
""" Deletes line breaks and joins split strings in one line
:param text: string
:param joiner: string used to join items [" " for abs or "" for title]
:return: joined text
"""
text = text.split('\n')
text = joiner.join(text)
return text | b05a701d4828d57060af55389ec785a64e094392 | 30,142 |
def get_adm_fields(adm_level, field_name="name"):
"""Get list of adm-fields from `adm_level` up to the adm1 level"""
return [f"adm{i}_" + field_name for i in range(1, adm_level + 1)] | 75a216ab7448f53417c5b8f5e951a5c96312b1e3 | 30,145 |
def prepare_actions(actions, enabled_analyzers):
"""
Set the analyzer type for each buildaction.
Multiple actions if multiple source analyzers are set.
"""
res = []
for ea in enabled_analyzers:
for action in actions:
res.append(action.with_attr('analyzer_type', ea))
retu... | a8a8624c5921f9addaef9c9e532f333726e35618 | 30,149 |
import click
def style_bold(txt, fg):
"""Style text with a bold color."""
return click.style(txt, fg=fg, bold=True) | adecdf207ecb27d202f298a56f8de54576e72ecd | 30,150 |
from typing import Optional
from typing import Tuple
import re
def find_github_owner_repo(url: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
"""Find the owner's name and repository name from the URL representing the GitHub
repository.
Parameters
----------
url : Optional[str]
Any... | 81ba5533546efde91a7c6ef5f48e65d1cdd2c6c4 | 30,151 |
from typing import Union
def celsius_to_kelvin(temperature_in_celsius: Union[int, float]) -> float:
"""
>>> celsius_to_kelvin(0)
273.15
>>> celsius_to_kelvin(1)
274.15
>>> celsius_to_kelvin(-1)
272.15
>>> celsius_to_kelvin(-273.15)
0.0
>>> celsius_to_kelvin(-274.15)
Tra... | 1aa5b214e20c0d47a3ab50388132f174cd33dbde | 30,152 |
def union(x, y=None):
"""
Return the union of x and y, as a list. The resulting list need not
be sorted and can change from call to call.
INPUT:
- ``x`` - iterable
- ``y`` - iterable (may optionally omitted)
OUTPUT: list
EXAMPLES::
sage: answer = union([1,2,3,4], [5,6])... | 67b20db26081c05a8c706d5529897bc753726f6a | 30,153 |
from typing import List
def define_frontal_base_direction(robot: str) -> List:
"""Define the robot-specific frontal base direction in the base frame."""
if robot != "iCubV2_5":
raise Exception("Frontal base direction only defined for iCubV2_5.")
# For iCubV2_5, the reversed x axis of the base fr... | eac7536aca5e8cd1ba06160a4dd4f5f6332fb5ed | 30,158 |
from typing import List
from typing import Dict
from pathlib import Path
def collect_file_pathes_by_ext(
target_dir: str, ext_list: List[str]
) -> Dict[str, List[Path]]:
"""Return the list of Path objects of the files in the target_dir that have the specified extensions.
Args:
target_dir (str): D... | 18b6287d12a301b7cff98e37a4122474ae3a7958 | 30,162 |
def node_is_empty(node):
"""Handle different ways the regulation represents no content"""
return node.text.strip() == '' | 64c80be5ad40ab388664e6f391fb729b6fc9ebb6 | 30,165 |
def find_dict_in_list_from_key_val(dicts, key, value):
""" lookup within a list of dicts. Look for the dict within the list which has the correct key, value pair
Parameters
----------
dicts: (list) list of dictionnaries
key: (str) specific key to look for in each dict
value: value to match
... | 02c98b64086266a21c2effdb72d1b681f77cbc26 | 30,167 |
from typing import List
from typing import Any
def get_combinations(*args: List[Any]) -> List[List]:
"""Takes K lists as arguments and returns Cartesian product of them.
Cartesian product means all possible lists of K items where the first
element is from the first list, the second is from the second and... | db3d2f48e650e647cec79d7bab0b6e555238cb3a | 30,169 |
def unique_from_list_field(records, list_field=None):
"""
Return a list of unique values contained within a list of dicts containing
a list.
"""
values = []
for record in records:
if record.get(list_field):
values = values + record[list_field]
return list(set(values)) | 9b30a2afb80e95479aba9bbf4c44ecdc0afaed34 | 30,170 |
def human_size(qbytes, qunit=2, units=None):
""" Returns a human readable string reprentation of bytes"""
if units is None:
units = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'][qunit:]
return str(qbytes) + units[0] if qbytes < 1024 else human_size(qbytes >> 10, 1, units[1:]) | 2d573c61ae5241383054936e99adcc38260fc9ae | 30,175 |
def flesch(df):
"""
Calculates the Flesch formula for each text.
The formula and its interpretation is given in this wiki page: https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
Needed features:
Avg_words_per_sentence
Avg_syllables_per_word
Adds column:
Fle... | 8bf6efa9e9c2ddd8795688ed0d11b687c20a4c36 | 30,178 |
def state_size_dataset(sz):
"""Get dataset key part for state size.
Parameters
----------
sz : `int`
State size.
Returns
-------
`str`
Dataset key part.
"""
return '_ss%d' % sz | 2ab9b2247309b3441437baddd9f258f1772cd5ae | 30,179 |
def trunc(number, n_digits=None, *, is_round=False):
"""
Function to truncate float numbers
>>> from snakypy import helpers
>>> helpers.calcs.trunc(1.9989, 2)
1.99
>>> helpers.calcs.trunc(1.9989, 2, is_round=True)
2.0
Args:
number (float): Must receive a... | 41f1e84271795fb0972e17a9c3a9208d1db8b816 | 30,182 |
import re
def comment_modules(modules, content):
"""
Disable modules in file content by commenting them.
"""
for module in modules:
content = re.sub(
r'^([ \t]*[^#\s]+.*{0}\.so.*)$'.format(module),
r'#\1',
content,
flags=re.MULTILINE
)
... | ba1c1a6a9e5fd9a655e7c6c00975843196b4c1db | 30,183 |
import logging
def get_logger(logger_name):
"""
Get the dev or prod logger (avoids having to import 'logging' in calling code).
Parameters:
logger_name - 'dev' or 'prod'
Returns:
Logger to use for logging statements.
"""
valid_logger_names = ['dev','prod']... | 2e4c41ef0eb226e11d9627090d80bcbbf9bfc475 | 30,186 |
def get_out_path(config):
"""
Returns path where summary output is copied after d-blink finishes running
:param config: ConfigTree
:return: path if it exists, otherwise None
"""
steps = config.get_list('dblink.steps')
copy_steps = [a for a in steps if a.get_string('name') == 'copy-files'] #... | 330e32fe84f473b5e46a3d033fe94653ed33e551 | 30,187 |
def _clean(item):
"""Return a stripped, uppercase string."""
return str(item).upper().strip() | 92e3319345149b5b645b21250389ddf3ce04e636 | 30,191 |
def validation_email_context(notification):
"""Email context to verify a user email."""
return {
'protocol': 'https',
'token': notification.user.generate_validation_token(),
'site': notification.site,
} | 0475223827d57f93aba25f49080f02cf164628d6 | 30,194 |
def parse_path(path):
"""Parse a path of /hash/action/my/path returning a tuple of
('hash', 'action', '/my/path') or None values if a shorter path is
given.
:param path: :py:class:`string`: the path
:rtype: :py:func:`tuple`
"""
if path == '/':
return None, None, None
paths =... | d6b9ea79104503888c862e8c42c8815e91a885fb | 30,196 |
import six
def _contains(values, splitter):
"""Check presence of marker in values.
Parameters
----------
values: str, iterable
Either a single value or a list of values.
splitter: str
The target to be searched for.
Return
------
boolean
"""
if isinstance(val... | 1f41e366309e7160d66a54115e1f20d4c3fe5f52 | 30,197 |
def get_top_namespace(node):
"""Return the top namespace of the given node
If the node has not namespace (only root), ":" is returned.
Else the top namespace (after root) is returned
:param node: the node to query
:type node: str
:returns: The top level namespace.
:rtype: str
:raises: ... | c7314b4b2dea934da4ab5710ee8cd1c1e7c87035 | 30,200 |
def football_points(win: int, draw: int, loss:int):
"""Calculate the number of points for a football team."""
return (win * 3 + draw) | 692d115e3955847e2a2e9ede2995fedbc752a00c | 30,201 |
def perc_diff(bigger, smaller):
""" Calculates the percentual difference between two int or float numbers
:param bigger: greater value
:param smaller: smaller value
:return: dif_perc """
dif_perc = round(((bigger - smaller) / smaller * 100), 2)
return dif_perc | 3e4a19e907afed549c598cd03d78454c2e140db1 | 30,202 |
def uploads_to_list(environment, uploads_list):
""" return list of upload url """
return [upload.get("url") for upload in uploads_list] | 7771dfb0190b76ad3de55168720640170e72f26c | 30,203 |
def _element_fill_join(elements, width):
"""Create a multiline string with a maximum width from a list of strings,
without breaking lines within the elements"""
s = ''
if(elements):
L = 0
for i in range(len(elements) - 1):
s += str(elements[i]) + ', '
L += len(el... | 2cb08a9be5dfc5a6af99f9fbd95487fbaebf11ca | 30,204 |
def hmsToHour(s, h, m, sec):
"""Convert signed RA/HA hours, minutes, seconds to floating point hours."""
return s * (h + m/60.0 + sec/3600.0) | 900f6a942d126eb9af0f4f0ccfc57daac73e0e53 | 30,205 |
def convert_to_indices(vert_list):
"""
Convert given flattened components list to vertices index list
:param vert_list: list<str>, list of flattened vertices to convert
# NOTE: Vertices list must follow Maya vertices list convention: ['{object_name}.v[0]', '{object_name}.v[1]' ...]
:return: list<str... | b98f79fc8e6c5f8126698ef0ce0b1fb77e29250d | 30,206 |
def guess_feature_group(feature):
"""Given a feature name, returns a best-guess group name."""
prefix_list = (
('Sha', 'Shadow'),
('miRNA', 'miRNA'),
('chr', 'mRNA'),
('Fir', 'Firmicutes'),
('Act', 'Actinobacteria'),
('Bac', 'Bacterodetes'),
('Pro', 'Prote... | f25d5c368cf832b48f8f154d525c96999fae39fb | 30,209 |
def add_lane_lines(img, lane_line_img):
"""
Colors lane lines in an image
"""
ret_img = img.copy()
ret_img[(lane_line_img[:, :, 0] > 0)] = (255, 0, 0)
ret_img[(lane_line_img[:, :, 2] > 0)] = (0, 0, 255)
return ret_img | 2cab2fe7615f9072d998afc3c28a31ff82a7e8fd | 30,212 |
import re
def parse(instruction):
"""
Take an instruction as a string and return a tuple (output wire, input specification).
Example input specifications:
* ("ID", "6") for constant input
* ("ID", "a") for direct wire input "a"
* ("NOT", "ab") for negated wire "ab"
* ("AND", "76", "xy") for bitwise-AND... | 8a17605b4a4a93a2ca01e32bee083ece6d75627b | 30,213 |
import math
def _ms_to_us(time_ms, interval_us=1e3, nearest_up=True):
"""Convert [ms] into the (not smaller/greater) nearest [us]
Translate a time expressed in [ms] to the nearest time in [us]
which is a integer multiple of the specified interval_us and it is not
smaller than the original time_s.
... | fcc6c03ba55451dccfce42b30579298d963ef696 | 30,215 |
def generate_dmenu_options(optlist: list) -> str:
"""
Generates a string from list seperated by newlines.
"""
return "\n".join(optlist) | 6bcb1e601973d12d66c1d28f86a8eb4743408a4d | 30,216 |
import time
def _is_active(log_stream: dict, cut_off: int) -> bool:
"""
Determine if the given stream is still active and worth tailing.
:param log_stream:
A dictionary returned by `describe_log_streams` describing the
log_stream under consideration.
:param cut_off:
The number... | 210dcd5a965dcf2535e55af694e11f17918666e6 | 30,217 |
import re
def mountpoint_dataset(mountpoint: str):
"""
Check if dataset is a 'zfs' mount.
return dataset, or None if not found
"""
target = re.compile(r'^.*\s+' + mountpoint + r'\s+zfs\b')
with open("/proc/mounts") as f:
mount = next((ds for ds in f.read().splitlines() if target.sear... | b549a94915b0089fcb3267b6273bde6f3243bd65 | 30,223 |
def _add_necessary_columns(args, custom_columns):
"""
Convenience function to tack on columns that are necessary for
the functionality of the tool but yet have not been specifically
requested by the user.
"""
# we need to add the variant's chrom, start and gene if
# not already there.
i... | 931b7ed9b181462220e665e6fb895bb7a1a835dc | 30,224 |
def get_part_of_speech(s):
"""
Detect part-of-speech encoding from an entity string, if present.
:param s: Entity string
:return: part-of-speech encoding
"""
tokens = s.split("/")
if len(tokens) <= 4:
return ""
pos_enc = tokens[4]
if pos_enc == "n" or pos_enc == "a" or pos_e... | 8498e4ff112bad0946b1f66b466007d9049b5e2f | 30,228 |
def get_pam_and_tool_from_filename(score_filename):
"""Extracts pam/tool info from a score filename
Args:
score_filename: specific score file name (including .txt)
Returns:
list of pam, pam_tool
Example:
Example score file: 'aggt_Chimera.txt'
output: ['aggt', 'Chimera']
... | 319c211d98591ab1702689e08d15cb5025ca7a6c | 30,229 |
from typing import Dict
from typing import Union
def parse_websocket_action(data: Dict[str, str]) -> Union[str, None]:
"""
Returns the websocket action from a given decoded websocket message or None if the action
doesn't exist or isn't a valid string.
"""
if isinstance(data, Dict):
websoc... | 7a7a2136c0f5809e51641ba10839070152b2df98 | 30,230 |
def get_object(conn, key, error='object not found', version_id=None):
""" Gets an object from s3 """
def helper():
try:
if version_id is None: return conn['client'].get_object(Bucket=conn['bucket'], Key=key)
else: return conn['client'].get_object(Bucket=conn['bucket'], Key=key, ... | 506dfdf11c98d9cd6cf6d7d6938c71b4b6d4ae5c | 30,231 |
import fnmatch
def filter_repos(config, repo_dir=None, vcs_url=None, name=None):
"""Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
Parameters
----------
config : dist
the expanded repo config in :py:class:`dict` format.
... | 587d81e0292f785fd8a4a4511487752a1d5ebfe7 | 30,234 |
def extend_smallest_list(a, b, extension_val=None):
"""Extend the smallest list to match the length of the longest list.
If extension_val is None, the extension is done by repeating the last element of the list. Otherwise, use
extension_val.
Arg(s):
a - A list.
b - A list.
exte... | 2d80690073cbf258ac918b1677b6cd0b7313d17d | 30,235 |
def to_celsius(temp):
"""Convert temperature measured on the Fahrenheit scale to Celsius.
Parameters:
temp (int): temperature value to convert
Returns
float: temperature value converted to Celsius
"""
return round((int(temp) - 32) * .5556, 3) | da86d46794ef1e8d4d34ae2b23a48488b75643a0 | 30,240 |
def readable_bool(b):
"""Takes a boolean variable and returns "yes" for true and "no" for false
as a string object.
:param b: boolean variable to use
"""
if b:
return "yes"
else:
return "no" | dc30a0dda31943538283b1f18dd6351ca0613614 | 30,243 |
import re
def is_url(_str):
"""return true if the str input is a URL."""
ur = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', _str)
return len(ur) > 0 | 7a298424c2f39f62a9d4197a7f822806e68e424f | 30,244 |
from typing import Union
from typing import List
def common_missing_fills(variable_type: str) -> Union[List[int], List[str]]:
"""Return a list of common missing stand-ins.
Returns
-------
List[int]
Parameters
----------
variable_type : str
What type of variable to return the miss... | 1e3e189c7d2fd2895028ca5be59e3ada3a90a688 | 30,246 |
def obtain_ECG(tensec_data):
""" obtain ECG values of ten second data
:param tensec_data: 10 seconds worth of heart rate data points
:return ECGData: ECG unmultiplexed data
"""
ECGData = tensec_data[1::2]
return ECGData | ce63b58435b67b6995d19e04a64bcc24d9687cd5 | 30,252 |
import ast
def str2dict(d_s):
"""Convert string to dictionary
:d_s: Dictionary string
:returns: Evaluated dictionary
"""
return ast.literal_eval(d_s) | 959da3c3197b5f8338cc33a7d9998303c50dd424 | 30,260 |
def project_08_largest_product(count):
""" Problem 8: Find the largest product of n numbers in a hardcoded series..
Args:
count (int): The number of adjacent numbers to determine product for.
"""
def product(sequence):
if 0 in sequence:
return 0
else:
pro... | 49d7e5d5d2b90bc22b07d9af7863b8367d16501d | 30,262 |
def load_input_segs(cand_segs, ref_segs, src_segs=None):
"""
Load input files specified in the CL arguments into memory.
Returns a list of 5-tuples: (segment_id, origin, src_segment,
candidate_segment, reference_segment)
"origin" is always None (present for compatibilit... | e6d8f6b92d00603dc7c06ca1484bf86ebea84273 | 30,263 |
from typing import Union
def fibonacci_k_n_term(n: int, k: int) -> Union[int, NotImplementedError]:
"""
Returns the nth fibonacci_k number.
Where F_{k,n+1} = k*F_{k,n} + F_{k,n−1} for n ≥ 1
"""
if n < 0:
return NotImplementedError('negative n is not implemented')
if n in [0, 1]:
... | 135e130f63e0ab9317eb145f21e55268412973da | 30,264 |
from typing import Sequence
def chg_modelqa(models: Sequence, ordinal: int, **kwargs) -> int:
"""
Information on the quality of the curve fit the intercept the ordinal date.
Args:
models: sorted sequence of CCDC namedtuples that represent the pixel history
ordinal: standard python ordinal... | 9d370dcecccd67204d2c88edf5d8d426f72ef2dd | 30,265 |
import yaml
def yaml_read(path):
"""
Reads yaml from disk
"""
with open(path, "r") as fp:
return yaml.load(fp, Loader=yaml.FullLoader) | 838b286792dfa0a38a385fe38aafdef92945e263 | 30,278 |
def chunks(obj, size, start=0):
"""Convert `obj` container to list of chunks of `size`."""
return [obj[i : i + size] for i in range(start, len(obj), size)] | c523a346906b85c121bf67a56a806d51f639eeb3 | 30,282 |
def http_verb(dirty: str) -> str:
"""
Given a 'dirty' HTTP verb (uppercased, with trailing whitespaces), strips
it and returns it lowercased.
"""
return dirty.strip().lower() | 74601bb0d5e22f632612fbf63924e27777ce8bf3 | 30,283 |
import copy
def trim_audio(A, start, stop):
"""Trim copy of MultiSignal audio to start and stop in seconds."""
B = copy.deepcopy(A)
assert start < len(B) / B.fs, 'Trim start exceeds signal.'
for c in range(B.channel_count):
B.channel[c].signal = B.channel[c].signal[
int(start * B.f... | 722a6b40bed4b6e441cddc5e0a0c5ca75207f701 | 30,288 |
def all_values_unique(d):
"""Return whether no value appears more than once across all value sets of multi-valued mapping `d`."""
seen = set()
for multivalue in d.values():
if any(v in seen for v in multivalue):
return False
seen.update(multivalue)
return True | a4663130a72e88b77dc47878165149fc35b50cec | 30,295 |
def calculate_future_value(present_value, interest_rate, compounding_periods, years):
"""
Calculates the future value of money given the present_value, interest rate, compounding period, and number of years.
Args:
present_value (float): The present value
interest_rate (float): The interest ... | 80578a52a7339e647846b342ff44e0593351a204 | 30,296 |
def align(value, m):
""" Increase value to a multiple of m """
while ((value % m) != 0):
value = value + 1
return value | 9171b62c71ae21b51b2f6cffe9e9e2a6d4778446 | 30,300 |
def get_ip(request):
"""
Attempts to extract the IP number from the HTTP request headers.
"""
key = "REMOTE_ADDR"
meta = request.META
# Lowercase keys
simple_meta = {k.lower(): v for k, v in request.META.items()}
ip = meta.get(key, simple_meta.get(key, "0.0.0.0"))
return ip | 2ccb542312257a955b0e2a34c2f63693c818955d | 30,303 |
import re
def sanitize_title(title):
"""Generate a usable anchor from a title string"""
return re.sub("[\W+]","-",title.lower()) | bb6b1cf9a5e0e9b9e896d35e6c7b77beb631ac64 | 30,305 |
def IsGoodTag(prefixes, tag):
"""Decide if a string is a tag
@param prefixes: set of prefixes that would indicate
the tag being suitable
@param tag: the tag in question
"""
for prefix in prefixes:
if tag.startswith(prefix):
return True
return False | 7c772b24c0b17257654fca0fb1e5d6c41ffbf9a9 | 30,311 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.