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 quadrilateral.
2. 6 node quadratic triangle.
3. 3 node linear triangle.
5. 2 node spring.
6. 2 node truss element.
7. 2 node beam (3 DOF per node).
8. 2 node beam with axial force (3 DOF per node).
Returns
-------
ndof : int
Number of degrees of freedom for the selected element.
nnodes : int
Number of nodes for the selected element.
ngpts : int
Number of Gauss points for the selected element.
"""
elem_id = {
1: (8, 4, 4),
2: (12, 6, 7),
3: (6, 3, 3),
4: (18, 9, 9),
5: (4, 2, 3),
6: (4, 2, 3),
7: (6, 2, 3),
8: (6, 2, 3)}
try:
return elem_id[eletype]
except:
raise ValueError("You entered an invalid type of element.")
|
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_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> moles_to_pressure(0.82, 3, 300)
90
>>> moles_to_pressure(8.2, 5, 200)
10
"""
return round(float((moles * 0.0821 * temperature) / (volume)))
|
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/Lon_To_Tile
"""
lat_rad = math.radians(lat)
n = 2.0 ** z
x = ((lon + 180.0) / 360.0 * n)
y = ((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
tile_x = int(x)
tile_y = int(y)
pixel_x = int((x-tile_x)*256)
pixel_y = int((y-tile_y)*256)
return dict(
z=z,
tile_x=tile_x,
tile_y=tile_y,
pixel_x=pixel_x,
pixel_y=pixel_y)
|
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
===========================================================
1. 1000 [00:10.00] 150 [00:01.50] no no 2
TOTAL 1150 [00:11.50] (audio only)
"""
class FakeProcess:
def check_returncode(self):
pass
@property
def stdout(self):
return testdata
obj = FakeProcess()
monkeypatch.setattr('subprocess.run', lambda *x, **y: obj)
assert albumdata.Albumdata._get_track_count('') == 1
|
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, offset_hour, offset_min)
|
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): Hash total file?. Defaults to False.
hash_algo (Hash Function, optional): Hash routine to use. Defaults to _hashlib.sha1.
Returns: Hash Value
"""
def chunk_reader(fobj, chunk_size=1024):
""" Generator that reads a file in chunks of bytes """
while True:
chunk = fobj.read(chunk_size)
if not chunk:
return
yield chunk
hashobj = hash_algo()
with open(file, "rb") as f:
if first_chunk_only:
hashobj.update(f.read(1024))
else:
for chunk in chunk_reader(f):
hashobj.update(chunk)
return hashobj.digest()
|
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.sub("True","1",crule)
crule = re.sub("False","0",crule)
return crule
|
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
of the inhibitor
dt (float): the time increment
tau (float): the constant tau
Returns:
(float): the change of concentration
"""
return dt/tau * (a - i)
|
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_path, 'r') as f:
config_dict = json.load(f)
return config_dict
|
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_iam",
"apikey": api_key
},
headers={
"Accept": "application/json"
}
)
if token_response.status_code == 200:
print ("Got access token from IAM")
return token_response.json()['access_token']
else:
# print( token_response.status_code, token_response.json())
return None
|
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'] = part_no
row['manuf part alt'] = part_no_alt
return row
|
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.
For reference you can visit Wikipedia
"""
cartesian_set = []
for i in range(0, len(set1), 1):
for j in range(0, len(set2), 1):
cartesian_set.append([set1[i], set2[j]])
return cartesian_set
|
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 = []
for i, j in itertools.combinations(ring_sets, 2):
i_and_j = (i.intersection(j))
if len(i_and_j) == 1:
spiro_atoms += list(i_and_j)
return 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, total = fraction.split("/")
tp, total = int(tp), int(total)
return tp, total
|
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:
aname = line[13:17].strip()
return bool(aname[0] == 'H')
|
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.BuiltinFunctionType,
types.MethodType, functools.partial))
|
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__
def fget(self):
if fname not in self._memoized:
self._memoized[fname] = f(self)
return self._memoized[fname]
def fdel(self):
del self._memoized[fname]
prop = property(fget=fget, fdel=fdel, doc=f.__doc__)
return prop
|
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:
AssertionError when there is any divergence between |existing| and
|expected|.
"""
def FormatPaths(paths):
return '\n'.join(sorted(paths))
existing = set(existing)
expected = set(expected)
unexpected = existing - expected
if unexpected:
raise AssertionError('Found unexpected paths:\n%s'
% FormatPaths(unexpected))
missing = expected - existing
if missing:
raise AssertionError('These files were expected but not found:\n%s'
% FormatPaths(missing))
|
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 for decoding/encoding sleep stages
"""
assert mode in ["decode", "encode"]
d = {
"no_sleep": 0,
"wake": 1,
"awake": 1,
"no_stage": 2,
"rem": 3,
"restless": 4,
"light": 5,
"asleep": 6,
"deep": 7,
}
if mode == "decode":
d = {val: key for key, val in d.items()}
return d
|
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(">"):
break
seq += line.strip()
return title[1:], seq
|
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
phi : torch.Tensor, (L, L) or (2, L, L)
phi angles or sines and cosines
Returns:
--------
* : torch.Tensor, (L, 10)
{sin, cos}×(ωi, φi, φ_ri, ψi, ψ_ri).
"""
if (omega.sum() == 0.0) and (theta.sum() == 0.0) and (phi.sum() == 0.0):
return torch.zeros(omega.shape[0], 10)
def get_features(omega, theta, phi):
# omega is symmetric, n1 is omega angle relative to prior
device = omega.device
n1 = torch.cat((torch.tensor([0.], device=device), torch.diagonal(omega, offset=1)))
# theta is asymmetric, n2 and n3 relative to prior
n2 = torch.cat((torch.diagonal(theta, offset=1), torch.tensor([0.], device=device)))
n3 = torch.cat((torch.tensor([0.], device=device), torch.diagonal(theta, offset=-1)))
# phi is asymmetric n4 and n5 relative to prior
n4 = torch.cat((torch.diagonal(phi, offset=1), torch.tensor([0.], device=device)))
n5 = torch.cat((torch.tensor([0.], device=device), torch.diagonal(phi, offset=-1)))
ns = torch.stack([n1, n2, n3, n4, n5], dim=1)
return ns
if not sc:
ns = get_features(omega, theta, phi)
s = torch.sin(ns)
c = torch.cos(ns)
else:
s = get_features(omega[0], theta[0], phi[0])
c = get_features(omega[1], theta[1], phi[1])
return torch.cat([s, c], dim=1)
|
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
>>> r.GetBit(6) # old bit 47
1
"""
finalSize = len(bitsToKeep)
res = bv.__class__(finalSize)
for i, bit in enumerate(bitsToKeep):
if bv.GetBit(bit):
res.SetBit(i)
return res
|
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
Returns
=======
temp_out: np.array
temperature in units_out
"""
temp_out = None
if units_in == 'F':
if units_out == 'C':
temp_out = (temp_in - 32) * (5./9.)
else:
temp_out = temp_in
elif units_in == 'C':
if units_out == 'C':
temp_out = temp_in
else:
temp_out = (temp_in * (9./5.)) + 32
return temp_out
|
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
-------
skip : bool
Whether to skip filtering or not
"""
skip = False
if not thresh_sam and not thresh_feat:
print('Filtering threshold(s) of 0 do nothing: skipping...')
skip = True
thresh_sam_is_numeric = isinstance(thresh_sam, (float, int))
thresh_feat_is_numeric = isinstance(thresh_feat, (float, int))
if not thresh_sam_is_numeric or not thresh_feat_is_numeric:
print('Filtering threshold for %s not a '
'integer/float: skipping...' % dat)
skip = True
if thresh_sam < 0 or thresh_feat < 0:
print('Filtering threshold must be positive: skipping...')
skip = True
return skip
|
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 of either the
host or port.
"""
colon_count = host_port.count(':')
if colon_count == 0:
# hostname or ipv4 address without port
return host_port, None
elif colon_count == 1:
# hostname or ipv4 address with port
return host_port.split(':', 1)
elif colon_count >= 2:
# ipv6 address, must be bracketed if it has a port at the end, i.e. [ADDR]:PORT
if ']:' in host_port:
host, port = host_port.split(']:', 1)
if host[0] == '[':
# for valid addresses, should always be true
host = host[1:]
return host, port
else:
# no port; may still be bracketed
host = host_port
if host[0] == '[':
host = host[1:]
if host[-1] == ']':
host = host[:-1]
return host, None
|
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 issues with cross-site resources
"""
response.headers["Set-Cookie"] = "HttpOnly;Secure;SameSite=Strict";
return response
|
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 is None:
return []
if isinstance(predicate, tuple):
key, op, value = predicate
if op in INDEXABLE_OPS:
return [
(
key,
value,
)
]
if isinstance(predicate, list):
if all([isinstance(p, tuple) for p in predicate]):
return [
(
k,
v,
)
for k, o, v in predicate
if o in INDEXABLE_OPS
]
if all([isinstance(p, list) for p in predicate]):
columns = []
for p in predicate:
columns += get_indexable_filter_columns(p)
return columns
return []
|
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 node demands.
:return: True, if solution is capacity-wise valid. False if not.
Second return value is a string that provides details about it.
"""
vehicle_capacity = kwargs["capacity"]
node_demands = kwargs["demand"]
route_list = vrp.get_route_list()
for demand_type in range(node_demands.shape[1]):
capacity_type_list = []
for active_route in route_list:
if len(active_route) <= 1:
continue
current_capacity = 0
recent_depot = active_route[0]
for i in range(1, len(active_route)):
destination_node = active_route[i]
current_capacity += node_demands[:, demand_type][destination_node]
# Check if capacity constraint is violated.
if current_capacity > vehicle_capacity[demand_type]:
return False, "Capacity constraint violation (Route Node {} / {}, situated at {}): {} / {}" \
.format(
i,
len(active_route) + 1,
destination_node,
current_capacity,
vehicle_capacity[demand_type]
)
# Traveling back to the depot node.
current_capacity += node_demands[:, demand_type][recent_depot]
if current_capacity > vehicle_capacity[demand_type]:
return False, "Capacity constraint violation (Return to Depot Node {}): {} / {}" \
.format(recent_depot, current_capacity, vehicle_capacity[demand_type])
# Save route capacity for later inspections.
capacity_type_list.append(current_capacity)
vrp.route_capacities.append(capacity_type_list)
return True, "Capacity constraint not violated"
|
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 control, please specify the name field in
DeployOptions in your Stack class.
example: format_name("TestStack") == "test-stack"
"""
name = re.sub("(.)([A-Z][a-z]+)", r"\1-\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1-\2", name).lower()
|
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:
suf = ''
return re.findall('\d+', type_area)[0], suf
|
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 == "curie":
# Always the CURIE
return vo["id"]
# IRI or CURIE (when no IRI, which shouldn't happen)
return vo.get("iri") or vo["id"]
|
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 "."
return str(number_of_mines)
|
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, valued by the mapped value
"""
f_dict = {}
for k, v in dct.items():
f_dict[k] = f(k, v)
return f_dict
|
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
for key in keys:
if key not in form.keys():
return False
# value = form[key]
# if value == None:
# return False
return True
|
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 : bool
args:
positional arguments to be passed to comp_func
kwargs:
keyword arguments to be passed to comp_func
Returns
-------
data: object
the data object returned by comp_fund
"""
try:
if recompute:
raise RuntimeError("Recompute!")
with open(fname, "rb") as f:
print("Loading data")
data = pickle.load(f)
except (RuntimeError, TypeError, EOFError, IOError) as e:
print("Tried to load data from disk, but failed. This is expected if the data has not been yet computed)")
print("The provided error message was: " + str(e))
with open(fname, "wb") as f:
data = comp_func(*args, **kwargs)
pickle.dump(data, f, -1)
return data
|
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(0.0, min(box_a.xmax, box_b.xmax) - intersect_top_left_x)
intersect_height = max(0.0, min(box_a.ymax, box_b.ymax) - intersect_top_left_y)
box_a_area = (box_a.xmax - box_a.xmin) * (box_a.ymax - box_a.ymin)
box_b_area = (box_b.xmax - box_b.xmin) * (box_b.ymax - box_b.ymin)
intersect_area = float(intersect_width * intersect_height)
union_area = float(box_a_area + box_b_area - intersect_area)
return intersect_area / union_area if union_area > 0.0 else 0.0
|
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 already, it is used as the base to
apply changes based on args.
Returns:
The negative caching policy.
"""
negative_caching_policy = None
if args.negative_caching_policy:
negative_caching_policy = []
for code, ttl in args.negative_caching_policy.items():
negative_caching_policy.append(
client.messages.BackendBucketCdnPolicyNegativeCachingPolicy(
code=code, ttl=ttl))
else:
if (backend_bucket.cdnPolicy is not None and
backend_bucket.cdnPolicy.negativeCachingPolicy is not None):
negative_caching_policy = backend_bucket.cdnPolicy.negativeCachingPolicy
return 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 collisions
"""
return trials - keyspace + keyspace * ((keyspace - 1) / keyspace) ** trials
|
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]))
return paths
|
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 containing the x and y components of the force on the atoms
- `dtstep`, the integration time step
The function returns a list containing the new positions.
Implement in the following loop between the arrows the Verlet MD algorithm.
A few hints:
- Powers in python are given by **, e.g.: x to the square is `x**2`
- Squared root x: `sqrt(x)`
- Indents are important in python
"""
new_positions=[]
for coord,old_coord,force in zip(atom_coord, old_atom_coord, forces):
r0x=coord[0] # Coordinates
r0y=coord[1]
old_r0x=old_coord[0] # Old coordinates
old_r0y=old_coord[1]
# Insert below the lines defining the new x and y positions based on the old ones + forces + mass + dtstep.
#
# Forces are contained in force[0] for the x force component and force[1] for the y force.
# The step size for the move is given by dtstep.
#
# ====>>>>>
new_r0x = 2*r0x - old_r0x + force[0]/mass * dtstep**2
new_r0y = 2*r0y - old_r0y + force[1]/mass * dtstep**2
# <<<<<====
new_positions.append([new_r0x,new_r0y,coord[2]])
return new_positions
|
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 get_scripts_dict function
pipeline: name of a supported target pipeline or "all".
"""
if pipeline == "all":
print()
return {curr_pipeline:[workflow for workflow in scripts_dict[curr_pipeline] if not workflow == "All Workflows"]
for curr_pipeline in scripts_dict if not curr_pipeline == "All Pipelines"}
return [workflow for workflow in scripts_dict[pipeline] if not workflow == "All Workflows"]
|
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 iter_method(self, *args, **kwargs):
result = getattr(self, method_name)(*args, **kwargs)
# Filter the list of model names for those that are a key in the response, then take the first.
# Useful for backwards compatability if response keys might change
model_name = next((model_name for model_name in model_names if model_name in result), None)
# If there are no model names, return None to avoid raising StopIteration
if not model_name:
return
for model in result[model_name]:
yield model
while True:
if 'next' not in result.get('links', {}):
return
result = self._get(result['links']['next'])
for model in result[model_name]:
yield model
return iter_method
|
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_repository['action'] in ['GOTO', 'EXECUTE_AND_RESUME']:
return error_repository['value']
elif error_repository['action'] in ['ABORT', 'ABORT_AS_ERROR']:
return error_repository['action']
return False
|
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 ValueError.
Longer strings are converted to lower case, stripped of all non-alphanumeric, non underscore or dash, characters,
then truncated to 100 characters if necessary.
:param s:
input string
:return:
valid CKAN name, as close as possible to the original
:raises ValueError:
if the string is too short
"""
if s is None or len(s) < 2:
raise ValueError(f'Unable to convert, input string is too short "{s}"')
# Convert to lower case and remove all non-word characters except '_' and '-', then truncate to 100 chars
return re.sub(r'[^\w_-]', '', s.lower())[:100]
|
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
return px1 * py2 - px2 * py1
|
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_file)
return 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 other features though would require an additioanl level
of identifying the max/min of feature sets that have multiple rows in a GTF (as opposed to
the "gene" feature, which has only a single row / set of values.
"""
gene_body = df.loc[df["feature"] == "gene"]
return gene_body.start.values[0], gene_body.end.values[0]
|
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 issue_id
"""
issue_id = str(issue_id)
issue_info = assessment_issues.get(issue_id)
return issue_id, issue_info
|
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 value's type description.
"""
type_name: str = var_doc.split('\n')[0]
colon_exists: bool = ':' in type_name
if not colon_exists:
return ''
type_name = type_name.split(':')[1]
type_name = type_name.split(',')[0]
type_name = type_name.strip()
return type_name
|
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'
tidal_mode : bool
If true, range is set from 0 to +/-180 degrees. If false, range is 0 to
360 degrees
Returns
-------
out : float or array-like
Input data transformed to 'degrees CW from North' or
'degrees CCW from East', respectively (based on `deg`)
Notes
-----
The same algorithm is used to convert back and forth between 'CCW from E'
and 'CW from N'
"""
out = -(deg - 90) % 360
if tidal_mode:
out[out > 180] -= 360
return out
|
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:
# EU station
nrrcus = 192
return nrrcus
|
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):
before_arg = line.find(' ')
assert before_arg >= 0
# assign the arg. it skips the deliminator and any excess whitespace
return line[before_arg+1:].lstrip()
|
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 before we can
sell. Therefore, their is a constraint that `index_low <= index_high`.
Time complexity: O(n). We do a single pass over the array.
Space complexity: O(1). We are only storing in runtime the indices of low
and high.
"""
index_lowest = 0
index_highest = 0
for i in range(len(arr)):
if arr[index_lowest] > arr[i]:
index_lowest = i
index_highest = i
elif arr[index_highest] < arr[i]:
index_highest = i
return arr[index_highest] - arr[index_lowest]
|
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 pandas dataframe of GVC Interpretation item type
Retval:
retval (dict): A summary of snapshot statuses for the interp in a similar format to:
{'i': 0, 'a': 1, 'p': 1}
"""
tmp = []
if 'provisionalVariant' in r:
if 'associatedInterpretationSnapshots' in r['provisionalVariant']:
for snap in r.provisionalVariant.get('associatedInterpretationSnapshots', []):
tmp.append(snap['approvalStatus'])
retval = {}
if len(tmp) == 0:
retval['i'] = 1
if 'Approved' in tmp:
retval['a'] = 1
if 'Provisioned' in tmp:
retval['p'] = 1
return retval
|
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 & flgkey))].append(ele)
if bucket[0] == [] or bucket[1] == []:
return aux
aux = list(bucket[0]) + list(bucket[1])
flgkey <<= 1
bucket = [[], []]
|
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
Optional:
extraParams (str): Name of app
sign (bool): if true, server will sign requests
tryConvention (bool): if false, get values without conversion
aggregate (int):
limit (int): default: 168, max: 2000 (new default: 1920 (80 days))
toTs (timestamp):
Valid exchanges (e):
Cryptsy, BTCChina, Bitstamp, BTER, OKCoin, Coinbase, Poloniex, Cexio, BTCE, BitTrex, Kraken,
Bitfinex, Yacuna, LocalBitcoins, Yunbi, itBit, HitBTC, btcXchange, BTC38, Coinfloor, Huobi,
CCCAGG, LakeBTC, ANXBTC, Bit2C, Coinsetter, CCEX, Coinse, MonetaGo, Gatecoin, Gemini, CCEDK,
Cryptopia, Exmo, Yobit, Korbit, BitBay, BTCMarkets, Coincheck, QuadrigaCX, BitSquare,
Vaultoro, MercadoBitcoin, Bitso, Unocoin, BTCXIndia, Paymium, TheRockTrading, bitFlyer,
Quoine, Luno, EtherDelta, bitFlyerFX, TuxExchange, CryptoX, Liqui, MtGox, BitMarket, LiveCoin,
Coinone, Tidex, Bleutrade, EthexIndia, Bithumb, CHBTC, ViaBTC, Jubi, Zaif, Novaexchange,
WavesDEX, Binance, Lykke, Remitano, Coinroom, Abucoins, BXinth, Gateio, HuobiPro, OKEX
Returns:
history (str) hourly price history from fsym to tsym
"""
url = "https://min-api.cryptocompare.com/data/histohour"
params = {'fsym':fsym, 'tsym':tsym, 'e': e, 'limit': limit}
for k,v in optional_params.items():
params[k] = v
r = requests.get(url = url, params = params)
return r.text
|
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: The string to be converted to a bool.
:type bool_as_string: str
:rtype: bool
:raises TypeError: Raised when any type other than a string is passed.
"""
if not isinstance(bool_as_string, str):
raise TypeError("Only string types supported")
return bool_as_string.lower() in ["true", "t", "1", "yes", "y"]
|
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.