content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def factorial_recursive(n):
"""
Return the factorial of the given int
"""
# base case
if n < 2:
return 1
else:
return n * factorial_recursive(n-1) | 380ede9b10871ba8ccfc7855d260af145e2df66d | 490,791 |
def build_histogram(text):
"""Builds a distribution of the word types and numbers of word tokens."""
histogram = {}
words = text.split()
# make a distribution of word types and count of tokens
for word in words:
word = word.lower()
if word not in histogram:
histogram[word] = 1
else: # word type already seen before in histogram
histogram[word] += 1
return histogram | 32a9c6a53536104ca2bfed12bf0faedbd60b5731 | 554,654 |
def slice2limits(slices):
"""
Create a tuple of minimum, maximum limits from a set of slices.
Parameters
----------
slices : list
List of slice objects which return points between limits
Returns
-------
limits: tuple, (ndarray, ndarray)
Two tuple consisting of array of the minimum and maximum indices.
See Also
--------
limits2slice : Find a list of slices given minimum and maximum limits.
"""
mins = [s.start for s in slices]
maxs = [s.stop - 1 for s in slices]
return mins, maxs | 052eedc7edf181fa29e14c50bb07f3e673170b93 | 501,549 |
def get_8kfilings(df):
"""Extract 8-K filings only from documents."""
return df.loc[df.seq == 1].copy() | 5295b4427175284dfd4cb3fae8a539cd92352938 | 418,145 |
import math
def distance(point1, point2):
""" Calculates distance between two points.
:param point1: tuple (x, y) with coordinates of the first point
:param point2: tuple (x, y) with coordinates of the second point
:return: distance between two points in pixels
"""
return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2)) | e38be3e5cc3418ab8c5edefb560e95e583dede21 | 691,082 |
def largeur_image(image):
"""
Retourne la largeur de l'image ``image`` (en pixels).
Arguments :
img : nom de la variable Python contenant l'image
"""
return image.size[0] | e16f9a5927b11d8b752eb53fba39691997b6e764 | 596,262 |
import mimetypes
def is_video(file_path):
"""
Checks whether the file is a video.
"""
type = mimetypes.guess_type(file_path)[0]
return type and type.startswith('video') | 93c44492816f3156d1b899750ec1551379ae4bef | 125,591 |
def de_itemparser(line):
"""return a dict of {OfficalName: str, Synonyms: [str,]} from a de_item
The description item is a str, always starts with the proposed official
name of the protein. Synonyms are indicated between brackets. Examples
below
'Annexin A5 (Annexin V) (Lipocortin V) (Endonexin II)'
"""
fieldnames = ["OfficalName", "Synonyms"]
fields = [e.strip(") ") for e in line.split("(")]
# if no '(', fields[1:] will be []
return dict(list(zip(fieldnames, [fields[0], fields[1:]]))) | b5417b7d047d16462051c889117bf0b0177157a8 | 63,407 |
def min_by(f, x, y):
"""Takes a function and two values, and returns whichever value produces the
smaller result when passed to the provided function"""
return x if f(x) < f(y) else y | 95aca87a35cf5795a4586a4162728fd3c5907ef9 | 390,157 |
def get_group_size_and_start(total_items, total_groups, group_id):
"""
Calculate group size and start index.
"""
base_size = total_items // total_groups
rem = total_items % total_groups
start = base_size * (group_id - 1) + min(group_id - 1, rem)
size = base_size + 1 if group_id <= rem else base_size
return (start, size) | 841b82db970bca60e34a72587c016e721a2b4bad | 273,311 |
def find_columns_by_key(df, keys):
"""
Find all Dataframe column names containing any of the keys
Parameters
----------
df : Dataframe
Dataframe
keys : array_like
List of keys of `str` type
Returns
-------
list
List of column names
"""
col = [c for c in df.columns if any([k.lower() in c.lower() for k in keys])]
return col | 38765c14e8ea7be43623314192924971ee3f9906 | 406,387 |
import math
def compute_shannon(data):
"""
Calculate Shannon entropy value for a given byte array.
Keyword arguments:
data -- data bytes
"""
entropy = 0
for x in range(256):
it = float(data.count(x))/len(data)
if it > 0:
entropy += - it * math.log(it, 2)
return entropy | 3be2cdd3a3f7bea43cdcd4175b3d1717859379af | 594,984 |
import random
def null_boolean_field_data(field, **kwargs):
"""
Return random value for NullBooleanField
>>> result = any_form_field(forms.NullBooleanField())
>>> type(result)
<type 'unicode'>
>>> result in [u'1', u'2', u'3']
True
"""
return random.choice(['None', 'True', 'False']) | 5e36b2ac7a6a30a849f618162216f463d9e08a61 | 201,958 |
def curried(func):
"""curried(func) takes function with signature:
func(self, *args)
and makes it:
curried_func(*args) --> func(self, *args)
That is, it makes the self implicit
"""
def curried_func(self, *args):
return func(self, *args)
curried_func.__doc__ = """Curried version of:\n%s""" % func.__doc__
return curried_func | 95d19e92747bbae18b3795fd79518cdae70906b1 | 160,508 |
import torch
def masked_precision(pred: torch.Tensor, target: torch.Tensor, eps: float=1e-6) -> torch.Tensor:
"""
Function to calculate the masked precision. Like precision,
but with usability mask in channel in the first channel
of the target, i.e. target should have one more channel
than prediction.
:param pred: (torch.Tensor) predictions, logits or binary
:param target: (torch.Tensor) target, logits or binary
:param eps: (eps) epsilon for numerical stability
:returns precision: (torch.Tensor)
"""
mask = (target[:, 0] > 0.).float()
mask = mask[:, None]
pred = mask*(pred > 0).float()
target = mask*(target[:, 1:] > 0).float()
tp = ((pred == 1) * (target == 1)).float()
return tp.sum() / (pred.sum() + eps) | f5951e1afc822ff82e39ed1d4ad9ef02643b2d93 | 359,813 |
import re
def contains_domain(address, domain):
"""Returns True if the email address contains the given,domain,in the domain position, false if not."""
domain = r'[\w\.-]+@'+domain+'$'
if re.match(domain,address):
return True
return False | 8ca7352995fe9b25e6c7e0094a4af89b65d10147 | 612,599 |
import re
def normalize(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
:param value: string.
String.
:return: string.
Cleaned string.
"""
value = re.sub('[^\w\s-]', '', value).strip()
value = re.sub('[-\s]+', '-', value)
return value | 629245ceb18fdf3b93adc20d434fc072c26e259d | 338,174 |
def readPhraseIndexFromFiles (filenames):
"""Takes a list of files; reads phrases from them, with one phrase per line, ignoring blank lines
and lines starting with '#'. Returns a map from words to the list of phrases they are the first word of."""
phraseIndex = dict()
for filename in filenames:
with open(filename,"r") as instream:
for line in instream:
line = line.strip()
if (line != "" and not line.startswith("#")):
line = line.lower()
phrase = line.split()
firstWord = phrase[0]
phraseList = phraseIndex.get(firstWord)
if (phraseList == None):
phraseList = []
phraseIndex[firstWord] = phraseList
phraseList.append(phrase)
# Sort each list of phrases in decreasing order of phrase length
for phrases in phraseIndex.values():
phrases.sort(key=lambda p: len(p),reverse=True)
return phraseIndex | c2968c8d7613c501c7c6bd37ead7017ded57be09 | 663,845 |
def bool_to_yes_no(value, color_enabled=False, color_no=None, color_yes=None):
"""Convert a boolean (or ``None``) to a yes/no string.
:param value: The value to be converted.
:type value: bool
:param color_enabled: Whether to enable color callbacks. Useful for controlling color at run time.
:type color_enabled: bool
:param color_no: Color the word "no".
:type color_no: callable
:param color_yes: Color the word "yes".
:type color_yes: callable
:rtype: str
.. versionadded:: 0.27.0-d
"""
if value is True:
if callable(color_yes) and color_enabled:
return color_yes("yes")
else:
return "yes"
else:
if callable(color_no) and color_enabled:
return color_no("no")
else:
return "no" | 4a4432fc62c7fcd42d82fadd60d76dd79567a829 | 393,412 |
import torch
def _create_1d_regression_dataset(n: int = 100, seed: int = 0) -> torch.Tensor:
"""Creates a simple 1-D dataset of a noisy linear function.
:param n: The number of datapoints to generate, defaults to 100
:param seed: Random number generator seed, defaults to 0
:return: A tensor that contains X values in [:, 0] and Y values in [:, 1]
"""
torch.manual_seed(seed)
x = torch.rand((n, 1)) * 10
y = 0.2 * x + 0.1 * torch.randn(x.size())
xy = torch.cat((x, y), dim=1)
return xy | 1534c7a968dfb3663c1f4d953e3088225af54b5f | 690,702 |
def format_tags(tags):
"""Formats tags as comma-separated list of urls to tags index."""
return ", ".join([f'<a href="tags.html#{tag}">{tag}</a>' for tag in tags]) | 5371cc166650eb51bc94a23fcb4b2e2709c7d9d8 | 605,435 |
def time_to_str(time):
"""Convert time into 4 char string"""
time_str = str(time)
return "0"*(4-len(time_str))+time_str | 04049ff7eb263a0179b22c2e38aceb1b2a45f01a | 225,846 |
def get_samples(mcmc):
"""Get samples from variables in MCMC."""
return {k: v for k, v in mcmc.get_samples().items()} | d29761ac64cf079d21cee3099f63dd6439577a56 | 490,190 |
import csv
def parse_csv(csv_file):
"""Parses an individual CSV file into a set of data points
Args:
csv_file (File): a csv file
Returns:
List[List[int,int,float]]: A list of data points.
Each data points consist of
0: 1 if is a transmission,
1: 1 if is a retransmission,
2: time in seconds
"""
data_points = []
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
previous_bytes = 0
start_time = None
for row in csv_reader:
if line_count == 0:
pass
else:
if "130.215.28." in row[4]:
if start_time == None:
start_time = sum(x * float(t) for x, t in zip([3600, 60, 1], row[11][12:30].split(":")))
data_points.append([0,0,0])
elif int(row[8]) > previous_bytes:
data_points.append([1,0,sum(x * float(t) for x, t in zip([3600, 60, 1], row[11][12:30].split(":"))) - start_time])
previous_bytes = int(row[8])
elif int(row[8]) <= previous_bytes and int(row[8]) > 10:
data_points.append([0,1,sum(x * float(t) for x, t in zip([3600, 60, 1], row[11][12:30].split(":"))) - start_time])
line_count += 1
return data_points | e2040af9ab9ff2036fb402484450d447f38de310 | 623,180 |
def gettext_getfunc( lang ):
"""
Returns a function used to translate to a specific catalog.
"""
# Note: you would get the gettext catalog here and install it in the
# closure.
def tr( s ):
# Note: we do not really translate here, we just prepend the
# language, but you get the idea.
return '[%s] %s' % (lang, s)
return tr | c303505812581a8101511bc23abfe8be8c390088 | 63,603 |
def convert_detector(old_detector):
"""
Convert an old detector string into a new string.
NOTE: Only exists to support old data formats.
"""
if old_detector:
old_detector = old_detector.strip() # Strip off superfluous white space
if old_detector == 'IM':
return 'MIRIMAGE'
elif old_detector == 'LW':
return 'MIRIFULONG'
elif old_detector == 'SW':
return 'MIRIFUSHORT'
else:
# For any other value, return the same string
return old_detector | b52d2299d411f5cb228b747e62ea8ec357607788 | 388,739 |
import re
def remove_number_from_cols(df):
""" Remove number ahead of column names, e.g. [[1]col1, [2]col2] --> [col1, col2] """
df = df.rename(columns={col:re.sub("\[\d+\]", "", col) for col in df.columns})
return df | 7de2f4495641bf1ee43a0cf1a839af2684c653e1 | 453,547 |
def flatten_voting_method(method):
"""Flatten a voting method data structure.
The incoming ``method`` data structure is as follows. At the time of
writing, all elections have an identical structure. In practice. the None
values could be different scalars. ::
{
"instructions": {
"voting-id": {
"en_US": None,
},
},
"excuse-required": None,
"start": None,
"end": None,
"primary": None,
"type": None,
}
This function flattens the US English voting ID instructions to become a top
level item like all of the others.
Args:
method (dict): A nested voting method data structure.
Returns:
dict: A flat voting method data structure.
"""
flat_method = {k: v for k, v in method.items() if k != "instructions"}
flat_method["instructions"] = method["instructions"]["voting-id"]["en_US"]
return flat_method | 14095dc027ea011d4a28df85cf0f1113d04f88e5 | 654,325 |
import requests
def get_public_key(repo):
""" Get a public key for the repository from travis. """
url = 'https://api.travis-ci.org/repos/%s' % repo
response = requests.get(url)
public_key = response.json().get('public_key', '')
return public_key.replace('RSA PUBLIC', 'PUBLIC') | fe370a08beb8e9b2f6ae84388865f994e45de0fc | 170,997 |
def get_state_dict(model):
"""Return model state dictionary whether or not distributed training was used"""
if hasattr(model, "module"):
return model.module.state_dict()
return model.state_dict() | fe1f22c63dac3b7d96b0f0485c9a010e98bae2f5 | 51,367 |
from pathlib import Path
import shutil
def copy(src: Path, dest: Path):
"""Copy backup from `src` to `dest`.
Args:
src (Path): the source to copy from
dest (Path): the destination to copy to
Returns:
bool: True if successful
"""
shutil.copy(str(src), str(dest))
print(f'Backed up {src.name} to {dest}!')
return True | bb3d4e4dabdb56761d3776d3d67b2653a54a7e7f | 377,695 |
def getNamespace(modelName):
"""Get the name space from rig root
Args:
modelName (str): Rig top node name
Returns:
str: Namespace
"""
if not modelName:
return ""
if len(modelName.split(":")) >= 2:
nameSpace = ":".join(modelName.split(":")[:-1])
else:
nameSpace = ""
return nameSpace | abfb4c54f2dd1b54563f6c7c84e902ed4ee77b01 | 5,018 |
def non_zero_mean(vals):
"""Gives the non-zero mean of the values."""
return vals[vals > 0].mean() | 650f2083812e046f833a1412bb1ced8b9ed94a8c | 124,573 |
def to_tag(name):
"""
Creates a XML tag from a given string.
"""
temp = name.lower().replace(' ', '_')
temp = temp.replace('fir_', 'FIR_')
temp = temp.replace('a0_', 'A0_')
return temp | 3db295e1132467519437243a32eb50754998ee25 | 508,750 |
from typing import List
def to_lines(s: str) -> List[str]:
"""
Like `str.splitlines()`, except that an empty string results in a
one-element list and a trailing newline results in a trailing empty string
(and all without re-implementing Python's changing line-splitting
algorithm).
"""
lines = s.splitlines(True)
if not lines:
return [""]
if lines[-1].splitlines() != [lines[-1]]:
lines.append("")
for i, ln in enumerate(lines):
l2 = ln.splitlines()
assert len(l2) in (0, 1)
lines[i] = l2[0] if l2 else ""
return lines | 90fac21f535537a731a4e3a3573a2f2cf548f161 | 569,316 |
def get_countN(x,n):
"""Count the number of nucleotide n in the string."""
return x.upper().count(n.upper()) | 7e5577dcf2a5666f77a915dd943cd5f59e2bd260 | 25,124 |
def is_unexpected_exception(exc_type: Exception) -> bool:
"""Check if exception type is unexpected (any exception except AssertionError, pytest.block.Exception, pytest.skip.Exception)."""
if exc_type and (isinstance(exc_type, (Exception, BaseException)) or issubclass(exc_type, (Exception, BaseException))):
return exc_type not in (None, FailedAssumption, AssertionError, pytest.block.Exception, pytest.skip.Exception) # type: ignore
return False | d23f6e76ffec26fe7be8bce5e9b9a6dc07532845 | 285,227 |
def roundstr(size):
"""
Perform round-up processing
Round up and return as string
"""
return str(round(size, 1)) | 47f120a919637b5845be6db66f9884a5b1bf4333 | 416,649 |
def get_city_byname(cities, name):
""" Retorna o município cujo o nome foi especificado.
Retorna um objeto do tipo city ou None caso não seja encontrado.
Parâmetros:
- cities : lista de municípios.
- name : nome do município desejado.
"""
for city in cities:
if city.name == name:
return city
return None | ebe6ef1b064ae560dab9e55e977039df912b8ea4 | 306,617 |
def magnify_contents(contents, features):
"""
Create additional features in each entry by replicating some column
of the original data. In order for the colums to differ from the
original data append a suffix different for each new additional
artificial column.
"""
magnified_contents = []
for entry in contents:
magnified_entry = entry[:-1] + [entry[feature]+str(i) for i, feature
in enumerate(features)] + [entry[-1]]
magnified_contents.append(magnified_entry)
return magnified_contents | ec2a43cdb280da74b44a6fec96d0708c90d03f18 | 27,978 |
def traverse_graph(graph, rules, domains, classifiers=None):
"""Traverses a rule graph and classifies a collection of domains.
Each node is a dictionary with the schema:
{
"title": "Rule name",
"children": [
{
"title": Rule name",
"children": [ ... ],
},
...
]
}
Rules are evaluated in order. If a rule is successfully evaluated,
this function will recurse into any child rules, if any exist.
Finally a classification list, containing the path of rules satisfied
by the given domains, is returned.
Args:
graph (list, dict): Rule graph to traverse.
rules (dict): Rule objects to evaluate on domains.
domains (list): Domain objects to classify.
classifiers (list): Current classifiers for a Domain collection.
Returns:
classifiers
"""
if not classifiers:
classifiers = []
for node in graph:
title = node["title"]
rule = rules[title]
if not rule.satisfied_by(domains):
continue
classifiers.append(title)
children = node.get("children")
if children:
classifiers = traverse_graph(children, rules, domains, classifiers)
rule.rename_domains(domains)
return classifiers
return classifiers | 7df0553793f4f8380b6d7af31653c68eeaf16486 | 465,864 |
import inspect
import re
def _getdoc(object):
"""Get the doc string or comments for an object."""
result = inspect.getdoc(object) or inspect.getcomments(object)
return result and re.sub('^ *\n', '', result.rstrip()) or '' | b5a2c526530910ec6f4cb498fa365ddcaec0f429 | 272,692 |
from typing import Tuple
def calc_pad_value(src_value: int,
dst_value: int) -> Tuple[int, int]:
"""
Calculate a padding values for a pair of source and destination numbers.
Parameters:
----------
src_value : int
Source number.
dst_value : int
Destination number.
Returns:
-------
tuple of 2 int
Left and right paddings.
"""
assert (dst_value >= src_value)
if src_value == dst_value:
pad_left = 0
pad_right = 0
else:
pad_value = dst_value - src_value
pad_left = pad_value // 2
pad_right = pad_value - pad_left
return pad_left, pad_right | 6231eae061c3a534f0b2fe4a313987dc3d4eed98 | 626,808 |
def find_last_in_flow_child(children):
"""Find and return the last in-flow child of given ``children``."""
for child in reversed(children):
if child.is_in_normal_flow():
return child | ad141fad32148b7ecb8dfd73f1d53026423e8e74 | 473,795 |
def extract_modified_bs_sequence(sax_sequence):
"""
This functions extracts the modified Behaviour Subsequence (BS) sequence list, which is the original sax word
sequence where every consecutive pairs of sax words are equal are fused into the same sax word.
:param sax_sequence: list of original sax words
:type sax_sequence: list of str
:return:
- bs_sequence (:py:class:`list of str`) - list of modified sax words
- bs_lengths (:py:class:`list of int`) - list of lengths of each modified sax word
"""
bs_sequence = []
bs_lengths = []
curr_len = 1
for i in range(len(sax_sequence)):
curr_bs = sax_sequence[i]
if i < len(sax_sequence)-1:
next_bs = sax_sequence[i+1]
else:
next_bs = ''
if curr_bs == next_bs:
curr_len = curr_len + 1
else:
bs_sequence.append(curr_bs)
bs_lengths.append(curr_len)
curr_len = 1
return bs_sequence, bs_lengths | 3a26278a478789032d35f994902440db3f879c9d | 653,610 |
def render_group(path, prefix):
"""Renders test_groups which represents a set of CI results.
Follows this format:
test_group('test-group-name', 'gcs-path')
"""
return 'test_group(\n \'%s\',\n \'%s/%s\'),' % (
path, prefix, path) | 44ecaa47ec137edfc2a67cbee509a9f912f0fb9a | 68,257 |
def find_category_dc(value):
"""Find the category of a dc value
:param value: Value for which we want the category
:type value: int
:return: Category corresponding to the value
:rtype: int
"""
if value == 0:
return 0
if 1 <= abs(value) <= 5:
return 1
if 6 <= abs(value) <= 17:
return 2
if 18 <= abs(value) <= 82:
return 3
if 83 <= abs(value) <= 375:
return 4
if 376 <= abs(value) <= 1263:
return 5
if 1264 <= abs(value) <= 5262:
return 6
if 5263 <= abs(value) <= 17579:
return 7
if 17580 <= abs(value) <= 72909:
return 8
return -1 | eaa8731658ce5a51eb0b5415fae4a3d0cdd60473 | 357,515 |
def stanardize_numeric_values(df, list_of_clms, ref_df):
"""
Use the median and interquartile range to
standardize the numeric variables
value = (value – median) / (p75 – p25)
"""
for code in list_of_clms:
median = ref_df[code]['50%']
p25 = ref_df[code]['25%']
p75 = ref_df[code]['75%']
df[code] = (df[code] - median) / (p75 - p25)
# Subset relevant columns
columns = ['hadm_id'] + list_of_clms
df = df[columns].copy()
return df | ff15caf1ae438401b5252f7bc5cb6ba784e2f8b1 | 192,268 |
def convert_error_code(error_code):
"""Convert error code from the format returned by pywin32 to the format that Microsoft documents everything in."""
return error_code % 2 ** 32 | 40197987e46fab5082b7ccad308edbefd472b852 | 663,692 |
def result_pks(response, cast=None):
"""
returns ids from wagtail admin search result
:param cast: cast pks to a type, default int
:param response: webtest response
:return: ids list
"""
cast = cast or int
result_rows = response.lxml.xpath('.//tr[@data-object-pk]/@data-object-pk')
return [
cast(r) for r in result_rows
] | c46373733cf1451ccb7dbadd842726445112c9f2 | 33,450 |
def ensure_keys_defined(header, needed_keys=(), define_as="UNDEFINED"):
"""Define any keywords from `needed_keys` which are missing in `header`, or defined as 'UNDEFINED',
as `default`.
Normally this defines missing keys as UNDEFINED.
It can be used to redefine UNDEFINED as something else, like N/A.
"""
header = dict(header)
for key in needed_keys:
if key not in header or header[key] in ["UNDEFINED", None]:
header[key] = define_as
return header | cbb0fb2134745d6aa50af927f00687e0a5949608 | 375,131 |
def _create_ad_schedule_info(client, day_of_week, start_hour, start_minute,
end_hour, end_minute):
"""Create a new ad schedule info with the specified parameters."""
ad_schedule_info = client.get_type('AdScheduleInfo', version='v2')
ad_schedule_info.day_of_week = day_of_week
ad_schedule_info.start_hour.value = start_hour
ad_schedule_info.start_minute = start_minute
ad_schedule_info.end_hour.value = end_hour
ad_schedule_info.end_minute = end_minute
return ad_schedule_info | b4acefa48ea1f3174ec71993dcd3c9e354c042be | 217,851 |
def ensure_bytes(s, encoding):
"""
Ensure *s* is a bytes string. Encode using *encoding* if it isn't.
"""
if isinstance(s, bytes):
return s
return s.encode(encoding) | f82f0ca37bd29c1b856ce9ff79b1bf92d00ea3d5 | 534,160 |
def validate_all(*validators):
"""
returns a validator that evaluates to true only if all validators passed through
the argument validators also evaluate to true
:param validators: validators to be chained
:return: a validator function
"""
def validator(value):
return all(v(value) for v in validators)
return validator | cc025212a5084ac7af41760f86b87b9b74ada54b | 485,829 |
def get_api_title(specs):
"""Fetch the API title
:param: specs: the JSON smartapi specs
"""
return specs['info']['title'] | ef54167d97a6835622aa5e1ce6a34f1e736df202 | 452,899 |
def formatNumber(number, billions="B", spacer=" ", isMoney = False):
"""
Format the number to a string with max 3 sig figs, and appropriate unit multipliers
Args:
number (float or int): The number to format.
billions (str): Default "G". The unit multiplier to use for billions. "B" is also common.
spacer (str): Default " ". A spacer to insert between the number and the unit multiplier. Empty string also common.
isMoney (bool): If True, a number less than 0.005 will always be 0.00, and a number will never be formatted with just one decimal place.
"""
if number == 0:
return "0%s" % spacer
absVal = float(abs(number))
flt = float(number)
if absVal >= 1e12: # >= 1 trillion
return "%.2e" % flt
if absVal >= 10e9: # > 10 billion
return "%.1f%s%s" % (flt/1e9, spacer, billions)
if absVal >= 1e9: # > 1 billion
return "%.2f%s%s" % (flt/1e9, spacer, billions)
if absVal >= 100e6: # > 100 million
return "%i%sM" % (int(round(flt/1e6)), spacer)
if absVal >= 10e6: # > 10 million
return "%.1f%sM" % (flt/1e6, spacer)
if absVal >= 1e6: # > 1 million
return "%.2f%sM" % (flt/1e6, spacer)
if absVal >= 100e3: # > 100 thousand
return "%i%sk" % (int(round(flt/1e3)), spacer)
if absVal >= 10e3: # > 10 thousand
return "%.1f%sk" % (flt/1e3, spacer)
if absVal >= 1e3: # > 1 thousand
return "%.2f%sk" % (flt/1e3, spacer)
if isinstance(number, int):
return "%i" % number
if absVal >= 100:
return "%i%s" % (flt, spacer)
if absVal >= 10:
if isMoney:
return "%.2f%s" % (flt, spacer) # Extra degree of precision here because otherwise money looks funny.
return "%.1f%s" % (flt, spacer) # Extra degree of precision here because otherwise money looks funny.
# if absVal > 1:
# return "%.2f%s" % (absVal, spacer)
if absVal > 0.01:
return "%.2f%s" % (flt, spacer)
if isMoney:
return "0.00%s" % spacer
return ("%.2e%s" % (flt, spacer)).replace("e-0", "e-") | c4d6bfd97df7bb69e451eb9a8a20626f69ed12cb | 343,881 |
from datetime import datetime
from typing import Optional
def get_epoch_time(time_as_str: Optional[str] = None,
fmt: str = '%d-%m-%Y %H:%M:%S.%f') -> int:
"""
>>> get_epoch_time('04-09-2020 17:13:40.162')
1599239620162
"""
fmt_time = datetime.now() if time_as_str is None else datetime.strptime(
time_as_str, fmt)
epoch = datetime.utcfromtimestamp(0)
return int((fmt_time - epoch).total_seconds() * 1000) | ed48c044c4ef3505766f5f669a10a2281fc1589b | 288,998 |
def get_levelized_cost(solution, cost_class='monetary', carrier='power',
group=None, locations=None,
unit_multiplier=1.0):
"""
Get the levelized cost per unit of energy produced for the given
``cost_class`` and ``carrier``, optionally for a subset of technologies
given by ``group`` and a subset of ``locations``.
Parameters
----------
solution : solution container
cost_class : str, default 'monetary'
carrier : str, default 'power'
group : str, default None
Limit the computation to members of the given group (see the
groups table in the solution for valid groups).
locations : str or iterable, default None
Limit the computation to the given location or locations.
unit_multiplier : float or int, default 1.0
Adjust unit of the returned cost value. For example, if model units
are kW and kWh, ``unit_multiplier=1.0`` will return cost per kWh, and
``unit_multiplier=0.001`` will return cost per MWh.
"""
if group is None:
group = 'supply'
members = solution.groups.to_pandas().at[group, 'members'].split('|')
if locations is None:
locations_slice = slice(None)
elif isinstance(locations, (str, float, int)):
# Make sure that locations is a list if it's a single value
locations_slice = [locations]
else:
locations_slice = locations
cost = solution['costs'].loc[dict(k=cost_class, x=locations_slice, y=members)]
ec_prod = solution['ec_prod'].loc[dict(c=carrier, x=locations_slice, y=members)]
if locations is None:
cost = cost.sum(dim='x').to_pandas()
ec_prod = ec_prod.sum(dim='x').to_pandas()
else:
cost = cost.to_pandas()
ec_prod = ec_prod.to_pandas()
return (cost / ec_prod) * unit_multiplier | 96b8f9a9fceaa932bcee72033e73ad8b9551759d | 5,954 |
def getChildren(self):
"""Returns a Python list of the egg node's children."""
result = []
child = self.getFirstChild()
while (child != None):
result.append(child)
child = self.getNextChild()
return result | ae896bc923f62bbe4f06ebcdad748d6c1e628265 | 513,295 |
from pathlib import Path
def this_version() -> str:
"""Read the variable `__version__` from the module itself."""
contents = Path('monoclparse/_version.py').read_text()
*_, version = contents.strip().split()
return version.strip('\'') | fb10b229cca9c1b322d0af833a4ee994643109f4 | 471,040 |
def load_file(uri):
""" Load file from given uri.
"""
with open(uri, encoding='utf-8') as file:
return file.read() | 4c7ddd733f93ab1b491d8c31f2b64d42f29ecbd1 | 533,386 |
def _clean_2007_text(s):
"""Replace special 2007 formatting strings (XML escaped, etc.) with
actual text.
@param s (str) The string to clean.
@return (str) The cleaned string.
"""
s = s.replace("&", "&")\
.replace(">", ">")\
.replace("<", "<")\
.replace("'", "'")\
.replace(""", '"')\
.replace("_x000d_", "\r")
return s | fdd94198a1d1b7562ca388aa316e17324c09bce9 | 485,284 |
def _get_annotations(cls):
"""
Get annotations for *cls*.
"""
anns = getattr(cls, "__annotations__", None)
if anns is None:
return {}
# Verify that the annotations aren't merely inherited.
for base_cls in cls.__mro__[1:]:
if anns is getattr(base_cls, "__annotations__", None):
return {}
return anns | bfa3dde6ac6e3a3d124336cabd1dfe7f74decf28 | 484,483 |
import itertools
def _powerset(iterable, minsize=0):
"""From the itertools recipes."""
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r in range(minsize, len(s) + 1)
) | 41c5576ae031288957d827d82231eab43f1ce70b | 73,679 |
import math
def quadratic_equation(num1, num2, num3):
"""Solve quadratic equation"""
delta = (num2 ** 2) - (4 * num1 * num3)
if delta < 0:
return None
elif delta > 0:
return (-num2 + math.sqrt(delta)) / 2 * num1, (-num2 - math.sqrt(delta)) / 2 * num1
else:
return -num2 / 2 * num1, None | 672c3b4158db58f1975058a8827b1871d52949d2 | 60,657 |
def copy_stimuli(stimuli):
"""
Return a copy of a list of stimuli. The returned copy can be modified
without affecting the original.
"""
new_list = []
for stim in stimuli:
stim_copy = stim.create_copy()
new_list.append(stim_copy)
return new_list | 58a3fc7b8bdb23088ad0bdda83db8d96ebca46f4 | 487,383 |
def sum_digits(num: int) -> int:
"""
Returns the sum of every digit in num.
>>> sum_digits(1)
1
>>> sum_digits(12345)
15
>>> sum_digits(999001)
28
"""
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
return digit_sum | 78680a648dbef0e4220f1628e275e5e84c2b28bb | 437,489 |
def flatten(data):
""" Given a batch of N-D tensors, reshapes them into 1-Dim flat tensor. """
B = data.size(0)
return data.view(B, -1) | dd434241a8f3a491e39094f485e12973e6ef4c4a | 84,126 |
from datetime import datetime
def get_week_from_ts(ts: datetime) -> int:
"""Returns the integer value of the week for the given time slot"""
return ts.isocalendar()[1] | a589e366fa9fa360c4e8e41fae3832d22340900b | 292,065 |
def make_s3_raw_record(bucket, key, size=100):
"""Helper for creating the s3 raw record"""
return {
's3': {
'configurationId': 'testConfigRule',
'object': {
'eTag': '0123456789abcdef0123456789abcdef',
'sequencer': '0A1B2C3D4E5F678901',
'key': key,
'size': size
},
'bucket': {
'arn': 'arn:aws:s3:::mybucket',
'name': bucket,
'ownerIdentity': {
'principalId': 'EXAMPLE'
}
}
},
'awsRegion': 'us-east-1'
} | f6b82c8815da11af1898f1cb2445983220107f7a | 415,835 |
def fasta_name_seq(s):
"""
Interprets a string as a FASTA record. Does not make any
assumptions about wrapping of the sequence string.
"""
DELIMITER = ">"
try:
lines = s.splitlines()
assert len(lines) > 1
assert lines[0][0] == DELIMITER
name = lines[0][1:]
sequence = "".join(lines[1:])
return (name, sequence)
except AssertionError:
raise ValueError("String not recognized as a valid FASTA record") | e450455710a945df25ad2cf4cc3c7f9ad662e7d3 | 9,676 |
import math
def deg2rad(angle):
"""Converts value in degrees to radians."""
return angle * math.pi / 180.0 | 6bc69b7ad8d99d554b4a7854f0a7aa9753addae9 | 509,271 |
import json
import collections
def textToJSON(text, orderedDict=True, showErrors=False):
"""
Turn a JSON object stored as text into a Python object.
Will be forced to a Python collections.OrderedDict if orderedDict argument
is True.
"""
try:
if orderedDict:
return json.loads(text, object_pairs_hook=collections.OrderedDict)
else:
return json.loads(text)
except:
if showErrors:
raise
else:
return None | 4fe816435f47fb445538f5165e742478aaf59273 | 358,526 |
def resolve_relative_name(package, module, relative):
"""Convert a relative import path into an absolute one.
:param str package: The ``__package__`` that we are in.
:param str module: The ``__name__`` of the module we are in.
:param str relative: The module name to resolve.
Absolute names are passed through untouched.
"""
if relative.startswith('.'):
# Add a dummy module onto the end if this is a package. It will be
# pulled off in the loop below.
if package == module:
module += '.dummy'
parts = module.split('.')
while relative.startswith('.'):
relative = relative[1:]
parts.pop(-1)
relative = '.'.join(parts) + ('.' if relative else '') + relative
return relative | 04af75a3d0e8f18d54573af06f5e087e1804db24 | 284,993 |
def token_identity(it, token_payload=None):
""" Echo back what it gets. """
return (it, token_payload) | 6fe367d1e908a8812c8372e5909b54c8bb7b17f5 | 681,096 |
def int32(x):
"""Force conversion of x to 32-bit signed integer"""
x = int(x)
maxint = int(2**31-1)
minint = int(-2**31)
if x > maxint: x = maxint
if x < minint: x = minint
return x | 854338b7fd748ba5ddbbbd8c697288c6331995c4 | 697,941 |
def is_primary(row : dict):
"""
Determines if a row is in the Primary inbox.
These are emails that are in the Inbox,
but aren't in Spam, Promotions, or Trash.
"""
try:
if (
not row.get('Spam') and
not row.get('Category Promotions') and
not row.get('Trash') and
row['Inbox']
):
return 1
except Exception as e:
print(e)
print(row)
return 0 | 7c0b05333edfe734519c18b4732a3ce2b1cffe50 | 307,962 |
def _is_neighbor_ipaddress(config_db, ipaddress):
"""Returns True if a neighbor has the IP address <ipaddress>, False if not
"""
entry = config_db.get_entry('BGP_NEIGHBOR', ipaddress)
return True if entry else False | 8ccd3aad0390bf9a80fe6861d8c1ca3e42242485 | 146,715 |
import torch
def euclidean_distances(X, Y, squared=False):
"""
Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
Parameters
----------
X : {tensor-like}, shape (n_samples_1, n_features)
Y : {tensor-like}, shape (n_samples_2, n_features)
squared : boolean, optional
Return squared Euclidean distances.
Returns
-------
distances : {Tensor}, shape (n_samples_1, n_samples_2)
"""
X_col = X.unsqueeze(1)
Y_lin = Y.unsqueeze(0)
if squared == True:
c = torch.sum((torch.abs(X_col - Y_lin)) ** 2, 2).sqrt_()
else:
c = torch.sum((torch.abs(X_col - Y_lin)) ** 2, 2)
return c | 4f02bc0d1f60fd7916954dab1c07ad57fae7682e | 285,554 |
import math
def mod_one(x):
"""
Reduce a number modulo 1.
INPUT:
- ``x`` - an instance of Integer, int, RealNumber, etc.; the
number to reduce
OUTPUT:
- a float
EXAMPLES::
sage: from sage.plot.colors import mod_one
sage: mod_one(1)
1.0
sage: mod_one(7.0)
0.0
sage: mod_one(-11/7)
0.4285714285714286
sage: mod_one(pi) + mod_one(-pi)
1.0
"""
x = float(x)
if x != 1:
x = math.modf(x)[0]
if x < 0:
x += 1
return x | 2f76d32ffbcda62cae459a45d82139e6b36b8ca4 | 358,161 |
def filter_nuc_variants(nuc_variants):
"""
Transforms nucleotide variants of type SUB longer than 1 in multiple variants of length 1.
Ignore insertions or substitutions of alternative sequence 'n'.
Removes duplicated variant impacts.
"""
new_nuc_variants = []
for n in nuc_variants:
seq_original = n['sequence_original']
seq_alternative = n['sequence_alternative']
start_original = int(n['start_original'])
start_alternative = int(n['start_alternative'])
variant_length = int(n['variant_length'])
variant_type = n['variant_type']
impacts = n['annotations']
impacts_set = set(tuple(values) for values in impacts if not values[0].startswith('GU280'))
# split substituions into single point mutations + ignore SUBs or INS to 'n'
if (variant_type == 'SUB' and variant_length > 1) or seq_alternative.lower() == 'n':
for i in range(variant_length):
if seq_alternative[i].lower() != 'n':
new_nuc_variants.append({
'sequence_original': seq_original[i],
'sequence_alternative': seq_alternative[i],
'start_original': start_original + i,
'start_alternative': start_alternative + i,
'variant_length': 1,
'variant_type': variant_type,
'annotations': impacts_set
})
else:
n['annotations'] = impacts_set
new_nuc_variants.append(n)
return new_nuc_variants | 4bdc507de783ba4d536352fc8144dc3b7ffc2737 | 582,860 |
def uri_scheme_behind_proxy(request, url):
"""
Fix uris with forwarded protocol.
When behind a proxy, django is reached in http, so generated urls are
using http too.
"""
if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https":
url = url.replace("http:", "https:", 1)
return url | 873ac1c70627fc8e8dd0cb2b86dec99246bb9344 | 40,949 |
from typing import Sequence
from typing import Mapping
def normalize_dist(dist, ndim):
"""Return a tuple containing dist-type for each dimension.
Parameters
----------
dist : str, list, tuple, or dict
ndim : int
Returns
-------
tuple of str
Contains string distribution type for each dim.
Examples
--------
>>> normalize_dist({0: 'b', 3: 'c'}, 4)
('b', 'n', 'n', 'c')
"""
if isinstance(dist, Sequence):
return tuple(dist) + ('n',) * (ndim - len(dist))
elif isinstance(dist, Mapping):
return tuple(dist.get(i, 'n') for i in range(ndim))
else:
raise TypeError("Dist must be a string, tuple, list or dict") | 79c48d809d0c509039b93e8ea13a1934c9c04900 | 517,600 |
def convert(color):
"""Get (0-1, 0-1, 0-1) color code and converts it to (0-255, 0-255, 0-255).
Parameters
----------
color : tuple
RGB code in format (0-1, 0-1, 0-1)
Returns
-------
list
a list representing RBG color code in format (0-255, 0-255, 0-255)
"""
return [int(x * 255) for x in color] | 4e57b4c575ad9a8c6fe9cda077d07dc67e41df3b | 643,746 |
def format_seconds(seconds):
"""
Format a floating point representing seconds into
a nice readable string.
Arguments:
seconds The seconds to format.
Returns:
A formatted string as either seconds, minutes, or hours.
"""
output_time = seconds
output_unit = "seconds"
if output_time >= 60.:
output_time /= 60.
output_unit = "minutes"
if output_time >= 60.:
output_time /= 60.
output_unit = "hours"
return "{:.2f} {}".format(output_time, output_unit) | 277279fb3c37ebbe9db1f6c4fb804391c3ab81e9 | 596,772 |
def geo_locate_multiple_ips(
self,
ip_address_list: list,
) -> dict:
"""Get geo-location information on multiple ip addresses from Cloud
Portal
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- POST
- /spPortal/internetDb/geoLocateIp
:param ip_address_list: List of 32-bit integer ip addresses,
e.g. ``[167837953, 167837954, ...]``
:type ip_address_list: list
:return: Dictionary of ip address geo-location information for all
ip's \n
* keyword **<ip_address>** (`int`): Nested dictionary of
attributes \n
* keyword **ip** (`int`): ip address of location calculated
* keyword **rangeIpStart** (`int`): Start of subnet that
geo-located IP falls under
* keyword **rangeIpEnd** (`int`): End of subnet that
geo-located IP falls under
* keyword **isp** (`str`): ISP provider registered to
address
* keyword **org** (`str`): Organization registered to
address
* keyword **country** (`str`): Country
* keyword **countryCode** (`str`): Country code
* keyword **city** (`str`): City
* keyword **postalCode** (`int`): Postal/Zip code
* keyword **latitude** (`int`): Latitude coordinates of ip
address
* keyword **longitude** (`int`): Longitude coordinates of ip
address
:rtype: dict
"""
data = ip_address_list
return self._post("/spPortal/internetDb/geoLocateIp", data=data) | e8b5bec744d3011d90885de79acee855415316d0 | 371,037 |
import json
def is_jsonable(obj):
"""
Checks if obj is JSONable (can be converted to JSON object).
Parameters
----------
obj : any
The object/data-type we want to know if it is JSONable.
Returns
-----
boolean
True if obj is JSONable, or False if it is not.
"""
try:
json.dumps(obj)
return True
except TypeError:
return False | 50a568b898c9609206993372983d40add0be4603 | 693,922 |
def sqr(num):
"""
Computes the square of its argument.
:param num: number
:return: number
"""
return num*num | cb16d5638afeff0061415e45467b5fd4e644951f | 20,935 |
import math
def distance3D(loc3d1=tuple(), loc3d2=tuple()):
"""
get distance from (x1, y1, z1), (x2, y2, z2)
loc3d1 : (x1, y1, z1)
loc3d2 : (x2, y2, z2)
return : distance
"""
return math.sqrt((loc3d1[0] - loc3d2[0])**2 + (loc3d1[1] - loc3d2[1])**2 + (loc3d1[2] - loc3d2[2])**2) | e780a5125a725f3d99a1f730d9ba4b2b9167e059 | 64,290 |
def rows2labels(rows):
"""Given a list of rows, return a map from subject to rdfs:label value."""
labels = {}
for row in rows:
if row["predicate"] == "rdfs:label":
labels[row["subject"]] = row["value"]
return labels | 62637c530bf9fa769e470579496288b26fc0b355 | 322,149 |
from pathlib import Path
def extract_name(
filename: Path,
max_length: int = 100,
prefix: str = "",
suffix: str = "",
long_name: bool = False,
) -> str:
"""Extract the name from a file
Parameters
----------
filename
The input file
max_length
The maximum length of the name, by default 100
prefix
The prefix to be added to the name, by default ""
suffix
The suffix to be added to the name, by default ""
long_name
Whether or not to use the full name, by default False
Returns
-------
The name
"""
name = Path(filename).stem
if not long_name:
name = name.split(".")[0]
if len(name) > max_length:
name = name[:max_length] + "..."
name = prefix + name + suffix
return name | f190ec38b8a5e57512d48b1f3c6a258005f7547f | 440,783 |
from bs4 import BeautifulSoup
def parse_html(html: str) -> BeautifulSoup:
"""Parse the HTML with Beautiful Soup"""
return BeautifulSoup(html, features="html.parser") | 8e10667747f24b9f9790b2b512bc9d5635ec7cd9 | 30,787 |
def cutout_subimage(image2d,
startx=0,
starty=0,
width=100,
height=200):
"""Cutout a subimage ot of a bigger image
:param image2d: the original image
:type image2d: NumPy.Array
:param startx: startx, defaults to 0
:type startx: int, optional
:param starty: starty, defaults to 0
:type starty: int, optional
:param width: width, defaults to 100
:type width: int, optional
:param height: height, defaults to 200
:type height: int, optional
:return: image2d - subimage cutted out from original image2d
:rtype: NumPy.Array
"""
image2d = image2d[starty:starty + height, startx:startx + width]
return image2d | 3e98bda2fc7eae0513a80cf699da60c6a7315e38 | 620,082 |
def _format_datetime_for_js(stamp):
"""Formats time stamp for Javascript."""
if not stamp:
return None
return stamp.strftime("%Y-%m-%d %H:%M:%S %Z") | a305c9c64f1ec9de0bd99181f14dedebae8cf940 | 34,182 |
def remove_angle(mol, a, b, c):
"""
utils.remove_angle
Remove a specific angle in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific angle (int)
Returns:
boolean
"""
if not hasattr(mol, 'angles'):
return False
for i, angle in enumerate(mol.angles):
if ((angle.a == a and angle.b == b and angle.c == c) or
(angle.c == a and angle.b == b and angle.a == c)):
del mol.angles[i]
break
return True | 9e54c283e84b767809d13f9ee807a1a97d0e5503 | 458,010 |
def _convert(value, conversion_function):
""" Convert value using the optional conversion function. """
if conversion_function is not None:
value = conversion_function(value)
return value | ebb28156707d3d973ead5783ad9ee57c90319ee4 | 292,047 |
def matrix_to_board(matrix):
"""
Converts the matrix into a board.
Args:
matrix (np.array): The board in matrix representation.
Returns:
list: The board.
"""
return matrix.reshape(1, -1).tolist()[0] | 8c337e815f1e7e4642086c1a6704cd943bf992ff | 208,649 |
def get_binary_string(string_input):
"""
Generate binary string from input string
:param string_input: user input string
:return: binary_string: binary input string
"""
binary_str = ""
for char in string_input:
binary_str = binary_str + f'{ord(char):08b}'
return binary_str | 1154def212055cbb30c09cc1e4764f614784fb80 | 229,182 |
def _resize_row(array, new_len):
"""Alter the size of a list to match a specified length
If the list is too long, trim it. If it is too short, pad it with Nones
Args:
array (list): The data set to pad or trim
new_len int): The desired length for the data set
Returns:
list: A copy of the input `array` that has been extended or trimmed
"""
current_len = len(array)
if current_len > new_len:
return array[:new_len]
else:
# pad the row with Nones
padding = [None] * (new_len - current_len)
return array + padding | 810be7f94234e428135598dc32eca99dd0d3fcca | 48,738 |
def set_lat_lon_attrs(ds):
""" Set CF latitude and longitude attributes"""
ds["lon"] = ds.lon.assign_attrs({
'axis' : 'X',
'long_name' : 'longitude',
'standard_name' : 'longitude',
'stored_direction' : 'increasing',
'type' : 'double',
'units' : 'degrees_east',
'valid_max' : 360.0,
'valid_min' : -180.0
})
ds["lat"] = ds.lat.assign_attrs({
'axis' : 'Y',
'long_name' : 'latitude',
'standard_name' : 'latitude',
'stored_direction' : 'increasing',
'type' : 'double',
'units' : 'degrees_north',
'valid_max' : 90.0,
'valid_min' : -90.0
})
return ds | fe95bbd7bd698b7cc0d5d1a60713477ab36e909a | 658,940 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.