content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def eletype(eletype):
"""Assigns number to degrees of freedom
According to iet assigns number of degrees of freedom, number of
nodes and minimum required number of integration points.
Parameters
----------
eletype : int
Type of element. These are:
1. 4 node bilinear quadrilatera... | a1f520429f23ac53835bf0fd1279abecb378b737 | 58,368 |
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
"""
Convert moles to pressure.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_l... | 43c7f5346da68db758dfae6e256260054cfd5d39 | 685,976 |
import math
def lat_lon_to_tile(lat,lon,z):
"""convert a Point to tuple (x,y,z) representing a tile in Mercator projection
information about converting coordinates to a tile in Mercator projection may be found at:
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
http://mapki.com/wiki/Lat/Lo... | 5dee0876f3bb7988b3b536d78a438a96a1702bda | 140,386 |
def _half_window(window):
"""Computes half window sizes
"""
return tuple((w[0] / 2, w[1] / 2) for w in window) | 664727d518ce1899d69c1cd3907d3e03aafba88d | 179,350 |
def test_get_track_count(monkeypatch, albumdata):
"""Test track count getting with a fake cdparanoia output."""
testdata = """\
cdparanoia III release 10.2 (September 11, 2008)
Table of contents (audio tracks only):
track length begin copy pre ch
===================================... | 8242026be59e3dd7bc7b78e1d11d2a5f5033060a | 136,527 |
def s_time_offset_from_secs(secs):
"""
Return a string with offset from UTC in RFC3339 format, from secs.
"""
if secs > 0:
sign = "+"
else:
sign = "-"
secs = abs(secs)
offset_hour = secs // (60 * 60)
offset_min = (secs // 60) % 60
return "%s%02d:%02d" % (sign, ... | a3f6ca131474928b6ffff3338d66a3f183444c4e | 345,943 |
from pathlib import Path
import _hashlib
def get_hash(file: Path, first_chunk_only=False, hash_algo=_hashlib.sha1):
"""Returns a hash of the provided Path_Obj.
Can return full hash or only first 1024 bytes of file.
Args:
file (Path_Obj): File to be hashed.
first_chunk_only (bool, optional... | cd6d7dc87a1b25cf9111105ed49508dc91155a0e | 119,812 |
def cm2inches(centimeters):
"""Convert cm to inches"""
return centimeters / 2.54 | bf6ce213135bf013c40f28098bacbf1de826642e | 403,049 |
import unicodedata
def remove_accents(string):
"""
Removes unicode accents from a string, downgrading to the base character
"""
nfkd = unicodedata.normalize('NFKD', string)
return u"".join([c for c in nfkd if not unicodedata.combining(c)]) | 41c8e05aa8982c85cf5cf2135276cdb5e26fefec | 704,740 |
import re
def sympy2bnet(rule):
"""Converts a sympy string expression to a BNET string expression.
Parameters
----------
rule : str
Boolean expression in sympy format.
Returns
-------
str
Expression in BNET format.
"""
crule = re.sub("~","!",rule)
crule = re.... | d69a7c3bdb496588c2867142f3c6b5c235db04af | 449,389 |
def di(i, a, dt, tau):
"""
Computes the change of concentration given an initial concentration `i`,
a time increment `dt` and a constant `k`.
Args:
a (float): the initial concentration value
of the activator
i (float): the initial concentration value
... | 2d932a3c0be2c950e5ed6c6a380995b37a1f351b | 417,205 |
def clamp(a, low, high):
""" Clamp a number between a range. """
if a > high:
return high
elif a < low:
return low
else:
return a | f1f0e1860e55fa3b8a47a5727b263889c5bf339e | 447,881 |
import json
def parse_config_file(config_path):
""" Loads config file like this:
{'bit_str': '0110100000100000',
'freq': 315000000,
'baud': 410,
'sample_rate': 2000000,
'amp_map': {'LOW': 0.28, 'HIGH': 1.4},
'header_len': 3.85,
'space_len': 3.78
}
"""
with open(config... | 262408e401a351f03cd3e838866fc93f203da22e | 118,731 |
import requests
def get_access_token(api_key):
"""Retrieve an access token from the IAM token service."""
token_response = requests.post(
"https://iam.cloud.ibm.com/identity/token",
data={
"grant_type": "urn:ibm:params:oauth:grant-type:apikey",
"response_type": "cloud_i... | b51c59ec76ec784f8c4d9c88c0f07926e4466565 | 69,652 |
def split_part_numbers(row):
"""Split part number string into main and alternates."""
part_no = ''
part_no_alt = ''
if row['manuf part'] != '':
tmp = row['manuf part'].split(None, 1)
part_no = tmp[0]
if len(tmp) > 1:
part_no_alt = tmp[1]
row['manuf part'] = ... | 2d53c15a91e4c4cbfe853d8716de2db794014cfc | 196,219 |
def cartesian_product(set1, set2):
"""
Desc: In set theory a Cartesian product is a mathematical operation that
returns a set (or product set or simply product) from multiple sets. That
is, for sets A and B, the Cartesian product A × B is the set of all ordered
pairs (a, b) where a ∈ A and b ∈ B.
... | dfa89c6c5e3218868d168ca001a9782e2f5f6b45 | 392,637 |
import itertools
def get_spiro_atoms(mol):
"""Get atoms that are part of a spiro fusion
:param mol: input RDKit molecule
:return: a list of atom numbers for atoms that are the centers of spiro fusions
"""
info = mol.GetRingInfo()
ring_sets = [set(x) for x in info.AtomRings()]
spiro_atoms ... | ec6c82a90604c23cba0a628b1dfd4ab805db8e7d | 232,721 |
def yes_no_to_bool(s):
"""Converts yes or y to True. false or f to False. Case-insensitive."""
return {"yes": True, "y": True, "no": False, "n": False}[s.casefold()] | fc7c580736209f650c6b1651affde7e3ab33148f | 97,444 |
import re
def parse_cnn_logs(filename):
"""Given a cnn log, return the number of true positives, and total test cases"""
with open(filename, 'r') as handle:
lines = [l.rstrip() for l in handle]
summary_line = lines[-1]
fraction = re.findall(r"[0-9]. \/ [0-9].$", summary_line).pop()
tp, tot... | f01001e177dcb1b8e9ab6c927fc88bd86c008afa | 128,284 |
def standardize_subject_id(sub_id):
"""Standardize subject ID to start with the prefix 'sub-'.
Parameters
----------
sub_id : str
subject ID.
Returns
-------
str
Standardized subject IDs.
"""
return sub_id if str(sub_id).startswith("sub-") else "sub-" + str(sub_id) | e9bc78a051c75a2633be1f231cfffb9274a0c954 | 497,104 |
def is_hydrogen(line):
"""Check if (pdb)-line is Hydrogen-Record.
If it's a proper-pdb line (77+ characters, extract element)
If it's a Qprep-pdb line (<54 chars, take from atomname)
"""
if len(line) >= 78:
return bool(line[77] == 'H')
line = line.strip()
if len(line) < 54:
... | 2f92629c18be9a58b2490cbd44bbe41612867987 | 439,401 |
from typing import Any
import types
import functools
def is_callable(func: Any) -> bool:
"""
Return ``True`` if ``func`` is callable.
:param func: Function object
:return: ``True`` if function
"""
# noinspection PyTypeChecker
return isinstance(func, (types.FunctionType, types.BuiltinFunct... | 7eaa9f439c3464df44cd82d63a4f0f9e9d6ad928 | 104,345 |
def memoprop(f):
"""
Memoized property.
When the property is accessed for the first time, the return value
is stored and that value is given on subsequent calls. The memoized
value can be cleared by calling 'del prop', where prop is the name
of the property.
"""
fname = f.__name__
... | 31249af7040cb1a05cf8f644d74ea3153b1ca1d6 | 667,704 |
def part_sum2(x_table):
"""All subsetsums from a list x
:param x_table: list of values
:complexity: :math:`O(2^{len(x)})`
"""
answer = set([0]) # 0 = value of empty set
for xi in x_table:
answer |= set(value + xi for value in answer)
return answer | 848b1ff3510d83c9e8ada5078c85ae4ca7408b4b | 243,702 |
def image_size(data):
"""
Parameters
----------
data : numpy.ndarray
Image data.
Returns
-------
tuple (int, int)
Image width and height.
"""
image_shape = data.shape
return (image_shape[0], image_shape[1]) | 011c8a3385fc04c407f8b76b48cc7833f58d7df6 | 104,217 |
import base64
def unwrap(data):
"""
Decode a formatted base64 keystring or an encrypted string.
Arguments:
data: Bytes to decode.
Returns:
The decoded input.
"""
data = bytes([b for b in data if b not in b" \r\n"])
return base64.b64decode(data) | 004550c9940371d2413b6ab4628c4af5b431d350 | 550,595 |
def _VerifyDirectoryIterables(existing, expected):
"""Compare two iterables representing contents of a directory.
Paths in |existing| and |expected| will be compared for exact match.
Arguments:
existing: An iterable containing paths that exist.
expected: An iterable of paths that are expected.
Raises... | 40daa32a2ad239a2fc6f309b41ca7f4d64bb7b25 | 648,798 |
def sleep_stage_dict(mode="decode"):
"""
Get dictionary to encode/decode sleep stage
Parameters
----------
mode : {"decode", "encode"}, default "decode"
If "decode", return dict num -> str
If "encode", return dict str -> num
Returns
-------
dict
Dictionary f... | d03a6bd9f1691d97dfbe9bf9d290b2d71897d5f3 | 391,687 |
def from_size(n):
"""
Constructs a zeroed, *n* sized vector clock.
"""
return (0,) * n | 64de5493f441c077f63d5416108dd8962e932a9b | 56,769 |
def read_title_and_seq(filename):
"""Crude parser that gets the first record from a FASTA file."""
with open(filename) as handle:
title = handle.readline().rstrip()
assert title.startswith(">")
seq = ""
for line in handle:
if line.startswith(">"):
brea... | e5b0be843dc96c77593ed00ad4924d1b5fb1b15c | 386,231 |
import torch
def get_node_features(omega, theta, phi, sc=False):
"""
Extract node features
Parameters:
-----------
omega : torch.Tensor, (L, L) or (2, L, L)
omega angles or sines and cosines
theta : torch.Tensor, (L, L) or (2, L, L)
theta angles or sines and cosines
... | 5c08df44e26135487c74368d92858f283cef6669 | 238,951 |
def playagain() -> bool:
"""ask user to play again"""
return input("Would you like to play again (Yes/No)? ").lower().startswith("y") | 84d24db06be40540784ba8648e43ea0275223fa8 | 86,077 |
def ConstructEnsembleBV(bv, bitsToKeep):
"""
>>> from rdkit import DataStructs
>>> bv = DataStructs.ExplicitBitVect(128)
>>> bv.SetBitsFromList((1,5,47,99,120))
>>> r = ConstructEnsembleBV(bv,(0,1,2,3,45,46,47,48,49))
>>> r.GetNumBits()
9
>>> r.GetBit(0)
0
>>> r.GetBit(1)
1
>>> r.GetBit(5)
0
... | 39ce7f781c1b7d1752a52c7d36f28be7b3d60312 | 492,874 |
def convert_temperature(temp_in, units_in, units_out):
"""Converts temperature from F to C or C to F.
Parameters
==========
temp_in: np.array
temperature in units_in
units_in: str
C for Celcius or F for Fahrenheit
units_out: str
C for Celcius or F for Fahrenheit
Ret... | ccf7141b4d0caa414f8957c0db720e413a2fb23c | 539,354 |
import logging
def find_log_path(lg):
"""
Find the file paths of the FileHandlers.
"""
out = []
for h in lg.handlers:
if isinstance(h, logging.FileHandler):
out.append(h.baseFilename)
return out | efab0cb7eafd0491e1365224dc83f816c7bb1b51 | 15,836 |
def no_filtering(
dat: str,
thresh_sam: int,
thresh_feat: int) -> bool:
"""Checks whether to skip filtering or not.
Parameters
----------
dat : str
Dataset name
thresh_sam : int
Samples threshold
thresh_feat : int
Features threshold
Returns
... | 49867e2597180ffad0bbd7a80ebd04d338b4cc91 | 126,901 |
def split_host_port(host_port):
"""Return a tuple containing (host, port) of a string possibly
containing both. If there is no port in host_port, the port
will be None.
Supports the following:
- hostnames
- ipv4 addresses
- ipv6 addresses
with or without ports. There is no validation ... | 89fd98aee3a07406c478eca82922bdecf5cb7078 | 22,982 |
def compatibility_in_test(a, b):
"""Return True when a is contained in b."""
return a in b | c55bc1cf46de5cfe2f7b63e811d316845af14545 | 70,139 |
def apply_caching(response):
"""
This method applies a cookie to each response, which avoids an error in Chrome, which looks like:
"A cookie associated with a cross-site resource at <URL> was set without the `SameSite`attribute. A f..."
:param response:
:return: response with cookie set to avoid i... | 5c36518f44a7d6952eb964a5c5f0b6ab990d9b0e | 173,332 |
def ssh_preamble(address, key_path):
""" Common options to SSH into a conversion host. """
return [
'ssh',
'-i', key_path,
'-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=no',
'-o', 'ConnectTimeout=10',
'cloud-user@' + address
] | deb2de03ac18218cb32387c6f0e4c5fe84eb0005 | 342,280 |
import torch
def smooth(x, span):
"""
Moving average smoothing with a filter of size `span`.
"""
x = torch.nn.functional.pad(x, (span//2, span//2))
x = torch.stack([torch.roll(x, k, -1) for k in range(-span//2, span//2+1)]).sum(dim=0) / span
return x | 494590de72e78fcbeb11bacf9214bee4ba6efcf3 | 64,972 |
from datetime import datetime
def ts_to_camli_iso(ts):
""" Convert timestamp to UTC iso datetime compatible with camlistore. """
return datetime.utcfromtimestamp(ts).isoformat() + 'Z' | 3bf0e1a09764e604d24810e31a5263518f264fac | 503,197 |
def get_indexable_filter_columns(predicate):
"""
Returns all of the columns in a filter which the operation benefits
from an index
This creates an list of tuples of (field,value) that we can feed to the
index search.
"""
INDEXABLE_OPS = {"=", "==", "is", "in", "contains"}
if predicate i... | 61ca254c7ca1372be39868363c2e77c2140e577e | 549,003 |
def get_comparable_location_types(query_metadata_table):
"""Return the dict of location -> GraphQL type name for each location in the query."""
return {
location: location_info.type.name
for location, location_info in query_metadata_table.registered_locations
} | 531ce97731f5d8fc48df9491d8129f244aff2433 | 248,070 |
def validate_capacity(vrp, **kwargs):
"""
Validates vehicle capacities of given individual's solution.
:param vrp: An individual subject to validation.
:param kwargs: Keyword arguments. The following are expected
from it:
- (int) 'capacity': Vehicle capacity.
- (list<int>) 'demand': List of... | 51ba57ac17b28d5ffc8e02abf8bc6a6925960c2a | 393,055 |
def linear_function(m, x, b):
""" A linear function of one variable x
with slope m and and intercept b.
"""
return m * x + b | f61b62d36314483029a3f668a8aaa2b98b1a765c | 686,692 |
import requests
from bs4 import BeautifulSoup
def soupify(url):
"""
Takes a url and returns parsed html via BeautifulSoup and requests. Used by the scrapers.
"""
r = requests.get(url)
soup = BeautifulSoup(r.text)
return soup | 39985dc857fc344497589649a6f7aec3443bc7de | 76,846 |
def get_subclasses(cls):
"""
Get all the (direct and indirect) subclasses of ``cls``.
"""
subcls_set = {cls}
for subcls in cls.__subclasses__():
subcls_set.update(get_subclasses(subcls))
return subcls_set | 687f3c4a44f4f22d93454f5243c19f0e3ca84921 | 153,778 |
def get_unit_string_from_comment(comment_string):
"""return unit string from FITS comment"""
bstart = comment_string.find("[")
bstopp = comment_string.find("]")
if bstart != -1 and bstopp != -1:
return comment_string[bstart + 1: bstopp]
return None | 232c1a6446d955be172fb08c1fe0c9e7847f87da | 680,739 |
import re
def format_name(name):
"""
Generate a stack name from class name by converting camel case to dash case.
Adapted from https://stackoverflow.com/questions/1175208/.
This function is our best effort to provide a good stack name in Cloudformation.
However, if you want to have fine-grained c... | 70938572ad3bed19eb8f6c4db2e7ac828f43c763 | 479,763 |
async def uploadHastebin(ctx, text: str) -> str:
"""Uploads some text to hastebin and returns the URL."""
async with ctx.bot.session.post("https://hastebin.com/documents", data=text.encode("utf-8")) as post:
json = await post.json()
return f"https://hastebin.com/{json['key']}" | da1c4628d54a568fe7951f4765a870c917b3077a | 248,474 |
def _gp_int(tok):
"""Get a int from a token, if it fails, returns the string (PRIVATE)."""
try:
return int(tok)
except ValueError:
return str(tok) | bfc36405324b8b74a40aec78fce1d795341ce7fe | 176,815 |
import re
def get_type_area_parts(type_area):
"""
Returns a tuple like (type_area_number, type_area_suffix)
"""
type_area = str(type_area)
try:
type_area[-1].isalpha()
except IndexError:
print(type_area)
if type_area[-1].isalpha():
suf = type_area[-1]
else:
... | ffa0a3e2d9186e80051978d5fe9ca8305830ee7e | 344,625 |
def trim_data(raw_data) -> bytes:
"""Removes head and tail from byte string.
Args:
raw_data: Input bytes to be trimmed.
Returns:
Trimmed data string.
"""
return raw_data[5:-2] | 926050a519c0d17ee26128c8198b9aa4025d92d2 | 551,892 |
def get_string_value(value_format, vo):
"""Return a string from a value or object dictionary based on the value format."""
if "value" in vo:
return vo["value"]
elif value_format == "label":
# Label or CURIE (when no label)
return vo.get("label") or vo["id"]
elif value_format == "... | 0efaa0850a63076dd0334bc54f2c96e4f352d6ae | 698,546 |
def get_uncovered_character(number_of_mines : int) -> str:
"""Gets the correct character for a number tile.
Args:
number_of_mines (int): The number of mines surrounding the tile.
Returns:
str: The character representation of the tile.
"""
if number_of_mines == 0:
return "."... | 937cde550b1960c4490af6ed18fa6c4645aa0b36 | 156,028 |
def score_bridge(bridge):
"""Score bridge by adding ports in all components."""
return sum(sum(component) for component in bridge) | 064e2b71df48f05fd21a79ec1309fb5b446b36d2 | 160,889 |
def map_with_obj(f, dct):
"""
Implementation of Ramda's mapObjIndexed without the final argument.
This returns the original key with the mapped value. Use map_key_values to modify the keys too
:param f: Called with a key and value
:param dct:
:return {dict}: Keyed by the original key, va... | 414b5f92acabe8621e2865e975b966b3c3bc6879 | 345,477 |
def assert_keys_in_form_exist(form, keys):
"""
Check all the keys exist in the form.
:param form: object form
:param keys: required keys
:return: True if all the keys exist. Otherwise return false.
"""
if form is None:
return False
if type(form) is not dict:
return False... | 536ba684669ea58d1342d6478f8d62df419f8231 | 61,706 |
import pickle
def get_data_or_compute(fname, comp_func, recompute=False, *args, **kwargs):
"""
A simple pickle_cache for computing stuff.
Parameters
----------
fname : str
path to where store the data
comp_func : callable
the function for which to compute values
recompute :... | b420c91392ec4481ff2c0b59d9794e5713f03e8b | 495,058 |
def _inc_average(count, average, value):
"""Computes the incremental average, `a_n = ((n - 1)a_{n-1} + v_n) / n`."""
count += 1
average = ((count - 1) * average + value) / count
return (count, average) | 35d7bc274623031314522631b4039bba0804b383 | 385,415 |
def iou(box_a, box_b):
""" Calculates Intersection over Union (IoU) metric.
:param box_a: First bbox
:param box_b: Second bbox
:return: Scalar value of metric
"""
intersect_top_left_x = max(box_a.xmin, box_b.xmin)
intersect_top_left_y = max(box_a.ymin, box_b.ymin)
intersect_width = max... | 08e330c1b059f01761cbb0b58650a7bc4f4b3e4c | 391,124 |
def GetNegativeCachingPolicy(client, args, backend_bucket):
"""Returns the negative caching policy.
Args:
client: The client used by gcloud.
args: The arguments passed to the gcloud command.
backend_bucket: The backend bucket object. If the backend bucket object
contains a negative caching policy... | a7112b71a641a0bf9e2c071aa943604465f6e7ed | 214,391 |
def get_word(word):
"""Return word text from word/syllable tuple"""
return word[0] | 9d6630cf1b535f23f360d41df2e830a4f57331ad | 115,470 |
def find_tabs(line: str, start: int = 0) -> int:
"""return the position of the next non tabs character in the string"""
while line[start] == "\t":
start += 1
return start | b3e88988534f380c5cec1844e6095325a0131f3e | 300,244 |
def _compute_expected_collisions(keyspace, trials):
"""Compute the expected number of collisions
Uses formula from Wikipedia:
https://en.wikipedia.org/wiki/Birthday_problem#Collision_counting
:param keyspace: keyspace size
:param trials: number of trials
:rtype float: Number of expected collis... | 8634f38aca0bae22d27bdad5e571d99e9ad26ac0 | 447,414 |
def line_split_to_str_list(line):
"""E.g: 1 2 3 -> [1, 2, 3] Useful to convert numbers into a python list."""
return "[" + ", ".join(line.split()) + "]" | 3f06e0f03b22d4dd92939afe7a18d49a1bc236dc | 690,299 |
def calc_percent(per, cent):
"""Takes the parameters "per" and "cent"
and returns the calculated percent."""
return (per / cent) * 100 | aeb7cf4a5ba243847ccd638bd8c89dbfa3b5195f | 677,944 |
def map_value(value, min_, max_):
"""
Map a value from 0-1 range to min_-max_ range.
"""
return value * (max_ - min_) + min_ | 9b5e083304d4476b223b156a32105b3bfb776cb5 | 639,665 |
import csv
import ast
def get_paths(path_csv):
""" Gets the path coordinates from an output.csv file.
"""
with open(path_csv, mode='r') as f:
reader = csv.reader(f)
paths = []
for row in reader:
if 'True' in row:
paths.append(ast.literal_eval(row[2]))
... | c2cdfa1f7b3b13a5b962b3840faffc305132548d | 178,963 |
def sorted_cols(orig_df):
"""
sort columns by name and return df
"""
cols = sorted(orig_df.columns)
return orig_df[cols] | 04e8e47c23e81f578387b198903f82ca5f2ee88b | 386,394 |
def verlet(atom_coord,forces,dtstep,old_atom_coord,mass):
"""
This function gets as input parameters:
- `atom_coord`, a vector containing the x and y position and the charge of the i atoms
- `old_atom_coord`, a vector containing the x and y positions from the previous MD step
- `forces`, a vector co... | 514fe59f4fa9b8b236ccd3780d6c4a8e4c07e1db | 208,360 |
def get_workflows_in_pipeline(scripts_dict, pipeline):
"""
IF pipeline == "all":
return a dictionary with keys=pipeline names, values=list of workflows in that pipeline
ELSE:
return a list of workflows in a given pipeline
input:
scripts_dict: scripts dictionary described in ge... | e0503cc535074a42e5f0975d1a89e2af85a5e600 | 297,102 |
def make_iter_method(method_name, *model_names):
"""Make a page-concatenating iterator method from a find method
:param method_name: The name of the find method to decorate
:param model_names: The names of the possible models as they appear in the JSON response. The first found is used.
"""
def ite... | 67623ab63930a899a1e6ce91c80e49ec41779079 | 685,640 |
def delta_t(delta_v, f):
"""Compute required increment of velocity."""
return delta_v / f | 2a4a42226c472163fb529fcc8182b9cf90924f39 | 286,518 |
def get_failure_results(error_repository):
""" Returns the appropriate values based on the onError actions for failing steps.
Arguments:
1. error_repository = (dict) dictionary containing the onError action, values
"""
if error_repository['action'] == 'NEXT':
return False
elif error_... | 65d7661c48efe164c89cbdf73ed0d6fb29b5cd8b | 228,086 |
def is_admin(user):
"""Check if the given user is admin"""
return user.userprofile.is_admin | 9798f72981b7eaa68904cbea2915a003a01ae74e | 492,045 |
import re
def ckan_legal_name(s: str) -> str:
"""
CKAN names must be between 2 and 100 characters long and contain only lowercase alphanumeric characters,
'-' and '_'. This function makes a reasonable best effort to convert an arbitrary input string. Strings
below 2 characters long will raise a ValueE... | 5d17c08755d5b626b438ccdb0cb9699888d35f7a | 365,739 |
def cross_product(vec1, vec2):
"""Cross product of two 2d vectors is a vector
perpendicular to both these vectors. Return value is a
scalar representing the magnitude and direction(towards
positive/negative z-axis) of the cross product.
"""
(px1, py1), (px2, py2) = vec1, vec2
retur... | 1b112989d7271bc9a56ad3651573a685b3b4dbfc | 417,051 |
def precip_36(code: str, unit: str = 'in') -> str:
"""
Translates a 5-digit 3 and 6-hour precipitation code
"""
return ('Precipitation in the last 3 hours: '
f'{int(code[1:3])} {unit}. - 6 hours: {int(code[3:])} {unit}.') | dc8004f41782d936ab9b09feb7db2f9c30b5e5de | 159,351 |
def strip_control(in_bytes: bytes) -> str:
"""Strip control characters from byte string"""
return in_bytes.strip(b"\x00").decode() | 4cefa25b58e8ba68a20aca3c10ecc8aebb2697a0 | 23,209 |
def _determine_levels(index):
"""Determine the correct levels argument to groupby."""
if isinstance(index, (tuple, list)) and len(index) > 1:
return list(range(len(index)))
else:
return 0 | 2eaed820eb45ff17eb4911fe48670d2e3412fb41 | 7,855 |
import json
def read_template(template):
"""
Read and return template file as JSON
Parameters
------------
template: string
template name
returns: dictionary
JSON parsed as dictionary
"""
data = None
with open(template) as data_file:
data = json.load(data... | 9708b1947998301ae2426bf30d375feb915bba3e | 651,724 |
def _return_gene_body_bounds(df):
"""
Get start/end locations of a gene
Parameters:
-----------
df
df that is subset from reading a GTF file using the GTFparse library.
Returns:
--------
start, end
Notes:
------
(1) This function could be extended to o... | fd4ba665a609111e9253f20ef30059bf628bed39 | 120,723 |
def _get_issue_info_by_issue_id(issue_id, assessment_issues):
"""Get Issue information by issue id.
Args:
- issue_id: id of Issue object
- assessment_issues: Dictionary with Issue information
Returns:
- issue_id: id of Issue object convert to string.
- issue_info: information by current issu... | 2e859b9e864f64034e4ceb0369eefe7628161a1f | 517,354 |
def _get_docstring_type_name(var_doc: str) -> str:
"""
Get the string of argument or return value type's description
from docstring.
Parameters
----------
var_doc : str
Docstring's part of argument or return value.
Returns
-------
type_name : str
Argument or return ... | fe07d6bb9869b4fcac404a3da6cdb0480880076b | 62,345 |
def evlmap(accdfid):
"""Return ``evlmap`` argument for ``.IterStatsConfig`` initialiser.
"""
if accdfid:
evl = {'ObjFun': 'ObjFun', 'DFid': 'DFid', 'RegL1': 'RegL1'}
else:
evl = {}
return evl | 41174fe9f18a5361fb2f1846acb0f4dbeb0146c5 | 371,801 |
def convert_degrees(deg, tidal_mode=True):
"""
Converts between the 'cartesian angle' (counter-clockwise from East) and
the 'polar angle' in (degrees clockwise from North)
Parameters
----------
deg: float or array-like
Number or array in 'degrees CCW from East' or 'degrees CW from North'
... | 6b8f21342271ffbc2e897d45119762a31090f746 | 267,156 |
def nrrcus_stnid(stnid):
"""
Number of RCUs from station ID
Parameters
---------
stnid: str
Station ID
Returns
-------
nrrcus: int
Number of RCUs
"""
location_id = stnid[:2]
if location_id == 'CS' or location_id == 'RS':
nrrcus = 96
else:
... | f3c57afaca5d4e85237c4030d69263e3249999c0 | 379,024 |
def has_findings(resource, resource_attributes_with_findings):
"""
Return True if this resource has findings.
"""
attribs = (getattr(resource, key, None) for key in resource_attributes_with_findings)
return bool(any(attribs)) | 49221eeacc4c627e85432e216f1368cefeb09f3f | 508,595 |
import re
def replaceThreeOrMore(word):
"""
look for 3 or more repetitions of letters and replace with this letter itself only once
"""
pattern = re.compile(r"(.)\1{3,}", re.DOTALL)
return pattern.sub(r"\1", word) | c052a082d74873da1a4c64dc035aeff429b29efd | 698,140 |
def fiscal_to_academic(fiscal):
"""Converts fiscal year to academic year.
Args:
fiscal (str): Fiscal year value.
Returns:
str: Academic year value.
"""
fiscal_int = int(fiscal)
fiscal_str = str(fiscal)
return f'{fiscal_int - 1}/{fiscal_str[-2:]}' | 03e5376f1d94f214183d02a5a932a64796c370c3 | 57,468 |
def autocomplete_getarg(line):
"""
autocomplete passes in a line like: get_memory arg1, arg2
the arg2 is what is being autocompleted on so return that
"""
# find last argument or first one is seperated by a space from the command
before_arg = line.rfind(',')
if(before_arg == -1):
bef... | 91f4773de94259a1026e09ac32d2cb798b6ac5b4 | 121,788 |
from typing import List
def buy_sell(arr: List[int]) -> int:
"""
Solution:
We traverse the array and keep a record of the index of the highest
and lowest value.
The curveball being that if we encounter a new lowest value, we need to
reset our highest value as well. This is because we must buy... | 177f243d7cbc031f164e0e4a344eee803384266e | 484,186 |
def get_snap_statuses(r):
"""
Description: Helper function for pandas apply() function. Retrieves the associatedInterpretationSnapshots
from the provisionalVariant column and parses out the statuses in a format expected in the vciStatus
column.
Args:
r (pandas row): A row in a panda... | 63d7bcb50e9244f56ab6cbbf73e6f748af8ef52e | 542,601 |
def nbytes(frame, _bytes_like=(bytes, bytearray)):
"""Number of bytes of a frame or memoryview"""
if isinstance(frame, _bytes_like):
return len(frame)
else:
try:
return frame.nbytes
except AttributeError:
return len(frame) | 3ab4b752c2c5c48f0842d876a7bcd6764cebd410 | 503,569 |
def bin_bucket_sort(arr):
"""
Binary bucket sort / 2-Radix sort
Time: O(NLog2N)
Space: O(N)
input: 1D-list array
output: 1D-list sorted array
"""
bucket = [[], []]
aux = list(arr)
flgkey = 1
while True:
for ele in aux:
bucket[int(bool(ele & flgke... | 8945ef31d5705d1462ce71ed6447bcc8d76e4665 | 702,437 |
import requests
def get_histohour(fsym = 'BTC', tsym = 'USD', e = 'CCCAGG', limit = 1920, optional_params = {}):
"""Gets hourly pricing info for given exchange
Args:
Required:
fsym (str): From symbol
tsym (str): To symbol
e (str): Name of exchange
Optio... | 0a40d62685d438d0f2bd896a2b905e8e66d56a87 | 33,936 |
def str_to_bool(bool_as_string: str) -> bool:
"""
A converter that converts a string representation of ``True`` into a boolean.
The following (case insensitive) strings will be return a ``True`` result:
'true', 't', '1', 'yes', 'y', everything else will return a ``False``.
:param bool_as_string: Th... | 62fef04039d66d3530e4cac42bf3c152d8f891e6 | 19,056 |
def evaluate_g1( l, s1 ):
"""
Evaluate the first constraint equation and also return the jacobians
:param float l: The value of the modulus lambda
:param float s1: The constraint value
"""
return l - s1**2, {'lambda':1., 's1':- 2 * s1 } | f270b803cacc3eb02c94f68d3a326750362b607e | 132,448 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.