content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def _metatile_contents_equal(zip_1, zip_2):
"""
Given two open zip files as arguments, this returns True if the zips
both contain the same set of files, having the same names, and each
file within the zip is byte-wise identical to the one with the same
name in the other zip.
"""
names_1 = set(zip_1.namelist())
names_2 = set(zip_2.namelist())
if names_1 != names_2:
return False
for n in names_1:
bytes_1 = zip_1.read(n)
bytes_2 = zip_2.read(n)
if bytes_1 != bytes_2:
return False
return True
|
3b5ec1cfbea5cef52a24450ca4b22bc382c2d6be
| 571,920 |
def _broadcast_strides(X_shape, X_strides, res_ndim):
"""
Broadcasts strides to match the given dimensions;
returns tuple type strides.
"""
out_strides = [0] * res_ndim
X_shape_len = len(X_shape)
str_dim = -X_shape_len
for i in range(X_shape_len):
shape_value = X_shape[i]
if not shape_value == 1:
out_strides[str_dim] = X_strides[i]
str_dim += 1
return tuple(out_strides)
|
04e25a196a80e957eb84cba176aac26614894bb9
| 512,598 |
def solution2array(solution):
""" rewrites an solution of the form {(1,1): [4], (1,2): [5] , .... (9,9) : [1]} to an 2dimensional array.
this is useful if we want to output it in a human readable form.
this is also used as intermediate step for rewriting the sudoku back to the original format.
"""
sudoku_array = []
for i in range(9):
sudoku_array.append([])
for j in range(9):
sudoku_array[i].append(0)
for variable, assignment in solution.iteritems():
if len(assignment) == 1:
sudoku_array[variable[0] -1][variable[1] - 1] = assignment[0]
return sudoku_array
|
507b9dfe7b4c2e1296670c2d1a948c40098d7a3c
| 691,857 |
def dimensions(mesh):
"""
Returns the extent of the mesh in [x, y, z] directions, i.e. of the axis aligned bbox.
:param mesh: open3d.geometry.TriangleMesh
:return: (3) np array
"""
return mesh.get_max_bound().flatten() - mesh.get_min_bound().flatten()
|
d4a9ffecdaa84eec63887f784fec70ce4cb3214c
| 189,629 |
import re
def expand_ios_ifname(ifname: str) -> str:
"""Get expanded interface name for IOSXR/XE given its short form
:param ifname: str, short form of IOSXR interface name
:returns: Expanded version of short form interface name
:rtype: str
"""
ifmap = {'BE': 'Bundle-Ether',
'BV': 'BVI',
'Fi': 'FiftyGigE',
'Fo': 'FortyGigE',
'FH': 'FourHundredGigE',
'Gi': 'GigabitEthernet',
'Gig': 'GigabitEthernet',
'Hu': 'HundredGigE',
'Lo': 'Loopback',
'Mg': 'MgmtEth',
'Nu': 'Null',
'TE': 'TenGigE',
'TF': 'TwentyFiveGigE',
'TH': 'TwoHundredGigE',
'tsec': 'tunnel-ipsec',
'tmte': 'tunnel-mte',
'tt': 'tunnel-te',
'tp': 'tunnel-tp',
'Vl': 'Vlan',
'CPU': 'cpu',
}
pfx = re.match(r'[a-zA-Z]+', ifname)
if pfx:
pfxstr = pfx.group(0)
if pfxstr in ifmap:
return ifname.replace(pfxstr, ifmap[pfxstr])
return ifname
|
9cd8f6f5dc858b94436cbce60c9eb0e755a2fccf
| 623,060 |
def read_text_file_to_lines(text_file_path):
""" Read a text file and return all the lines """
# read the file and return all the lines
with open(text_file_path) as file:
return file.readlines()
|
32d7f2ea159c37a577985dcad28e326831563a6c
| 360,380 |
import re
def shorten(CSTAG: str) -> str:
"""Convert long format of cs tag into short format
Args:
CSTAG (str): cs tag in the **long** format
Return:
str: cs tag in the **short** format
Example:
>>> import cstag
>>> cs = "cs:Z:=ACGT*ag=CGT"
>>> cstag.shorten(cs)
cs:Z::4*ag:3
"""
cstags = re.split(r"([-+*~=])", CSTAG.replace("cs:Z:", ""))[1:]
cstags = [i + j for i, j in zip(cstags[0::2], cstags[1::2])]
csshort = []
for cs in cstags:
if cs[0] == "=":
csshort.append(":" + str(len(cs) - 1))
continue
csshort.append(cs)
return "cs:Z:" + "".join(csshort)
|
653de1947a3cdf06103b01c1a7efc3dbc16ea4ab
| 14,250 |
from unittest.mock import call
import re
def is_release() -> bool:
"""Return if current branch is a release branch."""
tag_name = call("git describe --tags").replace("\n", "")
return re.match(r"^v\d+\.\d+\.\d+$", tag_name) is not None
|
f3eb14cdf279ff0b974b7ae16b4f430364fd50d5
| 641,328 |
def summation(num):
"""Return sum of 0 to num."""
x = [i for i in range(num + 1)]
return sum(x)
|
f2ff68b73a924011dad05dcc3270e1c87f36e214
| 562,847 |
from typing import Optional
from typing import List
from typing import Tuple
def is_valid_atom_index(index: int,
coordinates: Optional[dict] = None,
existing_indices: Optional[List[int]] = None,
) -> Tuple[bool, str]:
"""
Check whether an atom index is valid:
1. it is not 0
2. it is not in the existing indices list (if ``existing_indices`` is not ``None``)
2. it is not higher than the total number of atoms
Args:
index (int): The atom index to be checked.
existing_indices (list, optional): Entries are pre-checked atom indices.
coordinates (dict, optional): The 3d coordinates from which the total number of atoms is deduced.
Returns:
Tuple[bool, str]:
- Whether the atom index is valid.
- A reason for invalidating the argument.
"""
if index == 0:
return False, 'A 1-indexed atom index cannot be zero.'
if coordinates is not None and index > len(coordinates['symbols']):
return False, f'An atom index {index} cannot be greater than the number of atoms {len(coordinates["symbols"])}.'
if existing_indices is not None and index in existing_indices:
return False, f'Atom index {index} appears more than once in this argument.'
return True, ''
|
311b106f00994f617b953d6b630f8f3515f8dd8b
| 666,099 |
def matrix_equals(a, b, tolerance=1e-10):
"""
Compares two matrices with an imperfection tolerance
Args:
a (list, tuple): the matrix to check
b (list, tuple): the matrix to check against
tolerance (float): the precision of the differences
Returns:
bool : True or False
"""
if not all(abs(x - y) < tolerance for x, y in zip(a, b)):
return False
return True
|
ff330b834ec5cb448f39b4d918c263ba2f75edd5
| 428,507 |
def find_contiguous_sum_to(num_list, target_sum):
"""Find range of numbers in list that sums to target_sum"""
total = 0
range_start = 0
for i, curr_num in enumerate(num_list):
total += curr_num
while total > target_sum:
total -= num_list[range_start]
range_start += 1
if total == target_sum:
return num_list[range_start : i + 1]
|
28e829fda1e54957ec6c66ab705808ac99240520
| 374,586 |
def relative_levels(levels, station):
"""Converts a list of level data to a list of relative level data for a given station"""
if not station.typical_range_consistent():
return None
else:
min, max = station.typical_range
return [(i - min)/(max - min) for i in levels]
|
84250d7748cc4ed76a411e203ddd7dc071eee2ae
| 282,494 |
def transfer_function_Rec1886_to_linear(v):
"""
The Rec.1886 transfer function.
Parameters
----------
v : float
The normalized value to pass through the function.
Returns
-------
float
A converted value.
"""
g = 2.4
Lw = 1
Lb = 0
# Ignoring legal to full scaling for now.
# v = (1023.0*v - 64.0)/876.0
t = pow(Lw, 1.0 / g) - pow(Lb, 1.0 / g)
a = pow(t, g)
b = pow(Lb, 1.0 / g) / t
return a * pow(max((v + b), 0.0), g)
|
7a2a2a2348d701e7fd7dd90c5d016dbf8a2e0c56
| 17,484 |
def get_traitset_map(pop):
"""
Utility method which returns a map of culture ID's (hashes) and the trait set
corresponding to a random individual of that culture (actually, the first one
we encounter).
"""
traitsets = {}
graph = pop.agentgraph
for nodename in graph.nodes():
traits = graph.node[nodename]['traits']
culture = pop.get_traits_packed(traits)
if culture not in traitsets:
traitsets[culture] = traits
return traitsets
|
c80f1f05e0dd5268990e62e6b87726d5349b53f7
| 699,911 |
import math
import cmath
def dirN(c):
"""Given a complex number, return its phase as a compass heading"""
if c is None:
value = None
else:
value = (450 - math.degrees(cmath.phase(c))) % 360.0
return value
|
2f6ddce35f0bdd62c31dc2cfb27ec3665dc6607b
| 347,222 |
def is_valid_field(field, allow_quote=False, minimum=None, maximum=None):
"""
Validates a generic user inputted field, such as a "name" for an
object. For now, it basically only validates whether single quote
characters should be allowed in the string.
:type field: str
:param field: The data to be validated.
:type allow_quote: bool
:param allow_quote: If True, a single quote character (') will be allowed
to pass validation.
:type minimum: int
:param minimum: If defined, values with fewer characters than this value
will be rejected.
:type maximum: int
:param maximum: If defined, values with more characters than this value
will be rejected.
:rtype: bool
:return: True or False depending on whether field passes validation.
"""
if field is None:
return False
if not allow_quote and "'" in field:
return False
if minimum:
if len(field) < minimum:
return False
if maximum:
if len(field) > maximum:
return False
return True
|
375b96d891a37115d8a367bc228e020f719da946
| 43,085 |
from typing import List
from typing import Dict
from pathlib import Path
def collect_file_pathes_by_ext(
target_dir: str, ext_list: List[str]
) -> Dict[str, List[Path]]:
"""Return the list of Path objects of the files in the target_dir that have the specified extensions.
Args:
target_dir (str): Directory to search for files.
ext_list (List[srt]): List of file extensions to search for.
Returns:
List[List[Path]]: List of lists of Path objects. The first list contains the files having the first extension
in the ext_list. The second list contains the files having the second extension in the ext_list and so on.
"""
target = Path(target_dir)
rtn = {}
for ext in ext_list:
if ext[0] == ".":
ext = ext.strip(".")
rtn[ext] = list(target.glob(f"**/*.{ext}"))
return rtn
|
18b6287d12a301b7cff98e37a4122474ae3a7958
| 30,162 |
from typing import Optional
def to_field_element(val: int, prime: Optional[int]) -> int:
"""
Converts val to an integer in the range (-prime/2, prime/2) which is
equivalent to val modulo prime.
"""
if prime is None:
return val
half_prime = prime // 2
return ((val + half_prime) % prime) - half_prime
|
0f7318d67bc8a3c257d43a4fc403fc1675c78361
| 185,720 |
def upto_sum(n):
"""Sum 1...n with built-in sum and range"""
return sum(range(n))
|
9fb4fb7d4590dee1726406866dbebae891310402
| 389,483 |
def get_ip_port_kwargs(ipString):
""" Parse IP and port into kwargs suitable for reactor.listenTCP """
ip, port = ipString.split(':')
ip, port = ( '' if ip == '*' else ip ), int(port)
return dict(interface=ip, port=port)
|
311ab5fcb0e70e685cf94149b8aa08fce745ed37
| 336,539 |
def read_codelines(filepath):
""" Reads a source code file and returns all lines. """
with open(filepath) as f:
lines = f.readlines()
return lines
|
c4136e260486f78aff76be3714edd1e8ea4a9885
| 398,936 |
def cubrt(x):
"""Returns the cubed root of x"""
return round(x ** (1/3), 12)
|
41e500d1ee6ccc61c4442ea618c17daebea76c4e
| 644,007 |
import ast
def empty_list(lineno=None, col=None):
"""Creates the AST node for an empty list."""
return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col)
|
2def486baf5537d2754312c6234a7908c4aa46dd
| 23,612 |
import re
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('Byte', 'KiB', 'MiB', 'GiB', 'T', 'P', 'E', 'Z', 'Y')
num = re.findall(r"[0-9\.]+", s)
assert (len(num) == 1)
num = num[0]
num = float(num)
for i, n in enumerate(symbols):
if n in s:
multiplier = 1 << (i)*10
return int(num * multiplier)
raise Exception('human number not parsable')
|
8ed56b6ea327cdc12b58c662268e54719e568f1d
| 678,466 |
import typing
import inspect
def tidy_fn_call(fn: typing.Callable, args: typing.Iterable, kwargs: dict):
"""
Put args to kwargs if they matches.
This works like a function call parser.
Parameters
----------
fn : typing.Callable
The function to be called (it won't be called).
args : typing.Iterable
The positional arguments.
kwargs : dict
The keyword arguments.
Returns
-------
tuple
args, kwargs
"""
# we have to assign the stuff in `args` to `kwargs`
args = list(args)
params = inspect.signature(fn).parameters
for name, param in params.items():
if not any(args):
break # no more pos args to process
if name in kwargs:
continue # already specified in kws
# confirmed
kwargs[name] = args.pop()
# 1. no one wants None stuff
# 2. cvt obj to dict
kwargs = {
k: v # if isinstance(v, (str, list, dict)) else to_dict(v)
for k, v in kwargs.items()
if v
}
return args, kwargs
|
6acedf601f3d19b84d49c48b65b0ba2b0cd1d9b4
| 113,324 |
from typing import Sequence
from typing import Callable
from typing import List
from typing import Any
def join(processors: Sequence[Callable[[List[Any]], List[Any]]])-> Callable[[List[Any]], List[Any]]:
"""
Creates a processor from a list of processor.
The processor created is equivalent to applying each of the passed processor
in sequence over the result of the previous processor (after the result is
flattened)
* **processors**: a list of processors
* **return** : a join processor
>>> def double( elms):
... result = []
... for elm in elms:
... result += [elm, elm]
... return result
...
>>> def add_one( elms):
... result = []
... for elm in elms:
... result.append(elm + 1)
... return result
...
>>> pr = join([add_one, double])
>>> pr( [1,100])
[2, 2, 101, 101]
>>> pr = join([double, add_one])
>>> pr([1, 100])
[2, 2, 101, 101]
>>> pr = join([double, add_one, double])
>>> pr([1, 100])
[2, 2, 2, 2, 101, 101, 101, 101]
"""
def inner(elms):
result = elms
for processor in processors:
result = processor(result)
return result
return inner
|
f38cf67b5bab7e44849685f22c88e82d0be117db
| 338,862 |
def get_map_class_signature(deploy_annotations):
"""
Returns for every class its signature as defined in the cost annotations
"""
class_to_signature = {}
for i in deploy_annotations:
class_name = i["class"]
for j in i["scenarios"]:
if j["name"]:
class_to_signature[(class_name,j["name"])] = j["sig"]
return class_to_signature
|
5259e041d084c670ffc63e2f8bcaf09d9cc4986c
| 523,817 |
def trip_mode_type(roundSpeed, vehicle_speed_cutoff, bicycle_speed_cutoff, walk_speed_cutoff):
"""
Estimate trip transportation mode.
:param roundSpeed:
fix speed value (in km/h)
:param vehicle_speed_cutoff:
speed greater than this value (in Km/h) will be marked as vehicle
:param bicycle_speed_cutoff:
speed greater than this value (in Km/h) will be marked as bicycle
:param walk_speed_cutoff:
speeds greater than this value (in Km/h) will be marked as pedestrian
:return:
integer number classifying trip mode
"""
# round the speed to the nearest integer
speed_ = roundSpeed
try:
if speed_ < 0:
value = -1 # unknown trip mode
# elif speed_ >=0 and speed_ < walk_speed_cutoff:
# value = 0 # stationary (not in a trip)
# elif speed_ >= walk_speed_cutoff and speed_ < bicycle_speed_cutoff:
elif speed_ >= 0 and speed_ < bicycle_speed_cutoff:
value = 1 # pedestrian trip
elif speed_ >= bicycle_speed_cutoff and speed_ < vehicle_speed_cutoff:
value = 2 # bicycle trip
elif speed_ >= vehicle_speed_cutoff:
value = 3 # vehicle trip
else:
value = 0
except:
value = None
return value
|
67db1ac87f41874f3d1583940f6b10573b7dc4c1
| 283,506 |
def get_container_name(framework):
"""Translate the framework into the docker container name."""
return 'baseline-{}'.format({
'tensorflow': 'tf',
'pytorch': 'pyt',
'dynet': 'dy'
}[framework])
|
172dfb49d25646aa1253bc257db5bc712c1229e9
| 681,340 |
from typing import List
from typing import Dict
def confusion_matrix_binary(
y_true: List[int],
y_pred: List[int]
) -> Dict[str, int]:
"""
Compute tp, tn, fp, fn
Parameters
----------
y_true : list of ints
True labels
y_pred : list os ints
Predicted labels
Returns
-------
Dict[str, int]
Dictionary with number of samples of tp, tn, fp, fn
Examples
--------
>>> from evaluations.classification import confusion_matrix_binary
>>> confusion_matrix_binary([1, 1, 0, 0], [1, 0, 0, 1])
{'tp': 1, 'tn': 1, 'fp': 1, 'fn': 1}
"""
true_pos, true_neg, false_pos, false_neg = 0, 0, 0, 0
for el_true, el_pred in zip(y_true, y_pred):
if el_true and el_pred:
true_pos += 1
elif not el_true and not el_pred:
true_neg += 1
elif el_true and not el_pred:
false_neg += 1
elif not el_true and el_pred:
false_pos += 1
return {'tp': true_pos, 'tn': true_neg, 'fp': false_pos, 'fn': false_neg}
|
6297ae5f736c349cf482f36429d6ca1eb4461d1f
| 117,583 |
from typing import Mapping
def subdict(d: Mapping, keys=None):
"""Gets a sub-dict from a Mapping ``d``, extracting only those keys that are both in
``keys`` and ``d``.
Note that the dict will be ordered as ``keys`` are, so can be used for reordering
a Mapping.
>>> subdict({'a': 1, 'b': 2, 'c': 3, 'd': 4}, keys=['b', 'a', 'd'])
{'b': 2, 'a': 1, 'd': 4}
"""
return {k: d[k] for k in (keys or ()) if k in d}
|
ffd0578fa0ad642f6573ae392cb17e8c9220569f
| 666,546 |
def get_iteration_prefix(i, total):
""" Return a String prefix for itarative task phases.
:param i int current step.
:param total int total steps.
"""
return " [{0}/{1}]".format(i, total)
|
a1131b8ad931aaa07ccd8fb714ec91ddd985f0f3
| 673,917 |
def firstlemma(lemmastring):
"""selects the first lemma from a string denoting a "set" of lemmas,
e.g. |bla|blub|"""
lemmastring = lemmastring.strip("|")
lemmalist = lemmastring.split("|")
return(lemmalist[0])
|
93a5f9752dfdac4beb78f49fe8e88ac4d1f2f241
| 342,065 |
def has_group(user, group_name):
"""Check if user is member of a group"""
return user.groups.filter(name=group_name).exists()
|
63f56cc4d1cebc40345a453cabeb72892173a7dc
| 562,104 |
def _get(elements, index):
"""Return element at the given index or None."""
return None if index is None else elements[index]
|
9d105f64e7416bc8f33593653f1235a4ea544f42
| 219,531 |
def exception_to_dict(error):
"""Takes in an exception and outputs its details, excluding the stacktrace, to a dict
Args:
error (Exception): The exception to serialize
Returns:
dict: The serialized exception
"""
return {"type": str(type(error).__name__), "message": str(error)}
|
a677e151079a7b0005a7da1065f08b49cbf559be
| 29,891 |
def flatten_dict(input_dict: dict, separator: str = '_', prefix: str = ''):
""" Flatten a (possibly nested) dictionary
Args:
input_dict: the input dictionary to flatten
separator: string used to merge nested keys. It defaults to "_"
prefix: used in the recursive calls. Do not set manually
"""
return {prefix + separator + k if prefix else k: v
for kk, vv in input_dict.items()
for k, v in flatten_dict(vv, separator, kk).items()
} if isinstance(input_dict, dict) else {prefix: input_dict}
|
5a1a6a5bfbaa30af639df1ee7bd2c9a6c0ef4034
| 504,444 |
def colour_column_volc(df, xcol, ycol):
"""Generates red/blue/gray colour column for volcano plot data according to the value in x and y cols for each protein."""
df['colours'] = 'gray'
df.loc[(df[xcol] > 1) & (df[ycol] > 1.3), ['colours']] = 'red'
df.loc[(df[xcol] < -1) & (df[ycol] > 1.3), ['colours']] = 'blue'
return df
|
bc1f6df807b1076e5dfd126f404496bc6194d10a
| 364,149 |
import re
def GetVersion(native_heap):
"""Get the version of the native heap dump."""
re_line = re.compile("Android\s+Native\s+Heap\s+Dump\s+(?P<version>v\d+\.\d+)\s*$")
matched = 0
with open(native_heap, "r") as f:
for line in f:
m = re_line.match(line)
if m:
return m.group('version')
return None
|
fc90392cc009e154c5fa043becf92cb0a611a30f
| 557,442 |
def winphone(alert, title=None, _open_page=None, extras=None):
"""MPNS specific platform override payload.
Must include exactly one of ``alert``, ``title``, ``_open_page``, or ``extras``.
"""
if len(list(filter(None, (alert, _open_page, title)))) != 1:
raise ValueError("MPNS payload must have one notification type.")
payload = {}
if alert is not None:
payload['alert'] = alert
if title is not None:
payload['title'] = title
if _open_page is not None:
payload['_open_page'] = _open_page
if extras is not None:
payload['extras'] = extras
return payload
|
6cedbb59c7a12a01c9832173d6020ce4732fae86
| 555,856 |
import csv
def read_csv(file):
""" Reads a csv file and returns all rows (including field names) """
with open(file, newline='') as csv_file:
reader = csv.DictReader(csv_file, delimiter=',')
rows = [row for row in reader]
return rows
|
4ec479b87272cbd60fcda6df671ef37f5702adf9
| 425,645 |
def tweet_with_accident_veichle_and_person(text):
"""
check if tweet contains words indicating an accident between person and veichle
:param text: tweet text
:return: boolean, true if tweet contains words, false for others
"""
if ((u'הולך רגל' in text or u'הולכת רגל' in text or u'נהג' in text
or u'אדם' in text)
and (u'רכב' in text or u'מכונית' in text or u'אופנוע' in text
or u"ג'יפ" in text or u'טרקטור' in text or u'משאית' in text
or u'אופניים' in text or u'קורקינט' in text)):
return True
return False
|
d7a478e9d6f7ec9ef44562aac00a6d2b9d0b85c6
| 317,692 |
def retrieve_cnv_data(store, solution, chromosome=''):
""" Retrieve copy number data for a specific solution
"""
cnv = store['solutions/solution_{0}/cn'.format(solution)]
if chromosome != '':
cnv = cnv[cnv['chromosome'] == chromosome].copy()
cnv['segment_idx'] = cnv.index
return cnv
|
2c77415909ff27a3b3fd00e7abb8d25b67b6ea8f
| 701,920 |
def valid_cmd(cmd: str):
"""
Returns true if the given command is valid.
Valid commads are of the form:
ACTION TICKER AMOUNT
"""
if cmd in ("q" or "quit"):
return False
tokens = cmd.split(" ")
if len(tokens) != 3:
print("Incorrect format: require ACTION TICKER AMOUNT")
return False
if tokens[0] not in ("buy", "sell"):
print("ACTION is not either 'buy' or 'sell'")
return False
try:
int(tokens[2])
except:
print("AMOUNT not an integer")
return False
if int(tokens[2]) <= 0:
print("AMOUNT is not positive")
return False
return True
|
5edc4b4646ef0264cd4831ab10de02dab5d72bbd
| 280,095 |
def limit_data(data_dict: dict, limit: int = -1) -> dict:
"""apply limitation to data set
Args:
data_dict (dict): set with source and target
limit (int, optional): limit of data to process.
Defaults to -1.
Returns:
[dict]: dict with limited source and target
"""
if limit == -1:
return data_dict
new_dict = dict()
for item in ["source", "target"]:
new_dict[item] = {
"input_ids": data_dict[item]['input_ids'][:limit],
"attention_mask": data_dict[item]['attention_mask'][:limit]
}
return new_dict
|
7ec0990659092ae98882dca90d5a288e5b23d2dc
| 614,550 |
import re
def to_mb(s):
"""Simple function to convert `disk_quota` or `memory` attribute string
values into MB integer values.
"""
if s is None:
return s
if s.endswith('M'):
return int(re.sub('M$', '', s))
elif s.endswith('G'):
return int(re.sub('G$', '', s)) * 1000
return 512
|
870f276552ef90bbd5034551ea8ade0f5160491b
| 7,145 |
import warnings
def deprecate(version, msg=None):
"""Decorator to deprecate Python classes and functions
Parameters
----------
version : str
A string containing the version with which the callable is removed
msg : str, optional
An additional message that will be displayed alongside the default message
"""
def deprecate_decorator(callable_):
def warn(*args, **kwargs):
message = "%s has been deprecated and will be removed in version %s!" % (callable_.__name__, version)
if msg:
message += " - %s" % msg
warnings.warn(message, DeprecationWarning)
return callable_(*args, **kwargs)
return warn
return deprecate_decorator
|
0ea05fde9547886afd225f9b143bf71bc2aa985d
| 374,472 |
def split_version(version):
"""
Separate a string including digits separated by periods into a
tuple of integers.
"""
return tuple(int(ver) for ver in version.split('.'))
|
f39f23d7e14a2b38ae50df479e05f5d76d5be6f8
| 562,874 |
def mock_return_false(*args):
"""A mock function to return False"""
return False
|
d903b188e94774c4b286e4dc83bb4ff90c27030d
| 497,018 |
def make_checkout_web3modal_url(
currency_type, amount_in_ether_or_token, wallet_address, chainId=1
):
"""
Build a checkout.web3modal.com link that uses web3modal
to create a tx to pay in ETH/DAI on a chain to a certain address.
Note: amount_in_ether_or_token is in decimals.
"""
if currency_type not in {"ETH", "DAI"}:
raise ValueError("currency_type should be either ETH or DAI")
return f"https://checkout.web3modal.com/?currency={currency_type}&amount={amount_in_ether_or_token}&to={wallet_address}&chainId={chainId}"
|
c1c5622af89afa73920d0dbb9ff331f632897fd2
| 409,674 |
import torch as th
def _topk_torch(keys, k, descending, x):
"""Internal function to take graph-wise top-k node/edge features according to
the rank given by keys, this function is PyTorch only.
Parameters
----------
keys : Tensor
The key for ranking.
k : int
The :math:`k` in "top-:math:`k`".
descending : bool
Indicates whether to return the feature corresponding to largest or
smallest elements.
x : Tensor
The padded feature with shape (batch, max_len, *)
Returns
-------
sorted_feat : Tensor
A tensor with shape :math:`(batch, k, *)`.
sorted_idx : Tensor
A tensor with shape :math:`(batch, k)`.
"""
batch_size, max_len = x.shape[0], x.shape[1]
topk_indices = keys.topk(k, -1, largest=descending)[1] # (batch_size, k)
x = x.view((batch_size * max_len), -1)
shift = th.arange(0, batch_size, device=x.device).view(batch_size, 1) * max_len
topk_indices_ = topk_indices + shift
x = x[topk_indices_].view(batch_size, k, -1)
return th.masked_fill(x, th.isinf(x), 0), topk_indices
|
f23a681dbb22d422d659edcd4ccbb4b202473d68
| 88,965 |
import re
def find_startend_time(s):
"""
Find starttime and endtime from a given string
"""
starttime, endtime = '', ''
ts = re.findall(r'(\d+\:\d+\s?(?:AM|PM|am|pm|A.M.|P.M.|a.m.|p.m.))', s)
if len(ts) == 1:
starttime = ts[0]
endtime = ''
elif len(ts) == 2:
starttime = ts[0]
endtime = ts[1]
return starttime, endtime
|
be0781fe2a723bf545ce32ed903e7c3eae6e7f7b
| 314,125 |
def merge_tweets(labels_tweets):
"""
Merge tweets for each cluster.
labels_tweets: DataFrame
return: a dict of lables and their text
"""
pass
labels = set(labels_tweets['label'])
labels_text = dict()
for label in labels:
qry = "label == {}".format(label)
res = labels_tweets.query(qry)
tweets = list(res['tweet'])
text = " ".join(tweets)
labels_text[label] = text
return labels_text
|
5a7737de089d622f0dc8e444b3243f8575b95ab2
| 184,098 |
def process(container_):
"""
Testing pythons default sorting operations
:param container_: container of array (vector) of scalars
:return: sorted container
"""
return sorted(container_)
|
581768a493e56789ae4340f5e3940881fe28250e
| 273,471 |
def reconstruct_path(current):
"""
Uses the cameFrom members to follow the chain of moves backwards
and then reverses the list to get the path in the correct order.
"""
total_path = [current]
while current.cameFrom != None:
current = current.cameFrom
total_path.append(current)
total_path.reverse()
return total_path
|
85000ca0d9ed4150afc536ff8ac8a500586df5fb
| 660,778 |
def get_highest_priority_reachable(Sr):
"""
Sr: The remaining unconsidered part of the original solution
Return: the highest priority rule which is also reachable,
i.e. that is to say it is in table 1. Or None if no
rules are reachable.
"""
reachable = [r for r in Sr if r.table == 0]
# Sort decreasing so we get the highest priority
reachable.sort(key=lambda x: -x.priority)
if reachable:
return reachable[0]
return None
|
0db461c71b79f10f0e239fd6c48658c0d1fdfc2e
| 629,411 |
def readbinary(filename):
"""Given a filename, read a file in binary mode. It returns a single string."""
filehandle = open(filename, 'rb')
thisfile = filehandle.read()
filehandle.close()
return thisfile
|
1fb214aa355e3a3b8b2b5674e73aa28807b7023d
| 580,920 |
import torch
def stable_softmax(scores, mask=None, epsilon=1e-9):
"""
:param scores: tensor of shape (batch_size, sequence_length)
:param mask: (optional) binary tensor in case of padded sequences, shape: (batch_size, sequence_length)
:param epsilon: epsilon to be added to the normalization factor
:return: probability tensor of shape (batch_size, sequence_length)
"""
batch, seq = scores.size()
# Numerically stable masked-softmax
maxvec, _ = scores.max(dim=1, keepdim=True)
scores = torch.exp(scores - maxvec) # greatest exp value is up to 1.0 to avoid overflow
if mask is not None:
scores = scores * mask.view(batch, seq).float()
sums = torch.sum(scores, dim=1, keepdim=True) + epsilon # add epsilon to avoid div by zero in case of underflow
prob = scores / sums
return prob
|
2a5a036307853318d2c576dbbdd4d7c60745182f
| 471,354 |
def r(line):
"""
Selects rho from a given line.
"""
r, _ = line
return r
|
555f4fecc67f895ddf69f568b856ab7a8bdad3dd
| 681,037 |
def col(red, green, blue):
"""Convert the given colours [0, 255] to HTML hex colours."""
return "#%02x%02x%02x" % (red, green, blue)
|
8ae52c0f16fb65e90e2017efc8076ea64b738f6d
| 426,191 |
def extract_entities(input_data_tokens, entity_dict):
"""Extracts valid entities present in the input query.
Parses the tokenized input list to find valid entity values, based
on the given entity dataset.
Args:
input_data_tokens: A list of string tokens, without any punctuation,
based on the input string.
entity_dict: A dictionary of dictionary, of entity values for a
particular entity type.
Returns:
A list of valid entity values and their start, stop token index
locations in the tokenized input query.
[(['comedy', 'action'], 5, 7), (['suspense'], 9, 10)]
Always returns a list. If no valid entities are detected, returns
an empty list.
"""
detected_entities = []
length = len(input_data_tokens)
for i, word in enumerate(input_data_tokens):
if word in entity_dict:
start = i
stop = -1
loc = i # keeps track of the current cursor posiiton
current_dict = entity_dict
# keeps track of the current dictionary data
while(loc <= length and current_dict):
if 1 in current_dict:
# tag index of a potential entity value if a
# longer entity is not present
stop = loc
if len(current_dict) == 1:
detected_entities.append(
(input_data_tokens[start:stop], start, stop)
)
stop = -1 # reset
# if end of query reached or mismatch in entity values,
# discard and move on to the next word
if loc == length or input_data_tokens[loc] not in current_dict:
# save a shorter entity, if it exists in the already \
# parsed query
if stop != -1:
detected_entities.append(
(input_data_tokens[start:stop], start, stop)
)
break
else:
# entity matches up until current word, continue
current_dict = current_dict[input_data_tokens[loc]]
loc += 1
return detected_entities
|
516d0d9ae0df4a318808125b7e44bc327ecb8cff
| 25,434 |
import re
def clean_val(val):
"""
Returns cleaned value after replacing underscores (`'_'`) and asterisks (`'*'`) with
an empty whitespace.
:param val: Raw parsed string
:type val: str
:return:
A :py:class:`str` object after removing underscores and asterisks
"""
return re.sub(r'[_*]', ' ', val).strip()
|
8289cee081989cb5d6bed712c9b3d7c497298d9c
| 212,655 |
def node_to_GeoJSON(node, graph, color="#F5A207"):
"""Convert node to GeoJSON string."""
data = graph.nodes[node]
lat = data['lat']
lon = data['lon']
node_string = ''
node_string += '{ "type" : "Feature",\n'
node_string += '"geometry" : {"type": "Point", "coordinates": [%f,%f]},\n'%(lon, lat)
node_string += '"properties": {"marker-color": "%s"}\n'%(color)
node_string += '}\n'
return node_string
|
5efb1f477904ce24b232ccdb03cab8e1537fe65b
| 474,029 |
def dVdc_calc(Vdc,Ppv,S,C):
"""Calculate derivative of Vdc"""
dVdc = (Ppv - S.real)/(Vdc*C)
return dVdc
|
59d2708726e078efb74efce0bac2e397ba846d89
| 9,004 |
def short_bucket_name(bucket_name):
"""Returns bucket name without "luci.<project_id>." prefix."""
parts = bucket_name.split('.', 2)
if len(parts) == 3 and parts[0] == 'luci':
return parts[2]
return bucket_name
|
b182955198c927f4fe2ab470a34fe002e5634041
| 390,363 |
def true_positives(T, X, margin=5):
"""Compute true positives without double counting
>>> true_positives({1, 10, 20, 23}, {3, 8, 20})
{1, 10, 20}
>>> true_positives({1, 10, 20, 23}, {1, 3, 8, 20})
{1, 10, 20}
>>> true_positives({1, 10, 20, 23}, {1, 3, 5, 8, 20})
{1, 10, 20}
>>> true_positives(set(), {1, 2, 3})
set()
>>> true_positives({1, 2, 3}, set())
set()
"""
# make a copy so we don't affect the caller
X = set(list(X))
TP = set()
for tau in T:
close = [(abs(tau - x), x) for x in X if abs(tau - x) <= margin]
close.sort()
if not close:
continue
dist, xstar = close[0]
TP.add(tau)
X.remove(xstar)
return TP
|
58bf0edb83d8d2f823fc3c6e10e827109f401c3e
| 581,604 |
def normalize(msg):
"""
Normalizes the plain text removing all invalid characters and spaces
:param msg: Plain text to be normalized
:return: the normalized message without invalid chars
"""
return "".join([let.lower() for let in msg if let.isalpha() or let.isdigit()])
|
d0bea7e7a813196d49cda8873d756849ec61b36d
| 646,550 |
def _neighbors(text: str, pos: list[int]) -> dict[str, str]:
"""Finds the characters neighboring a position
Args:
text (str): The text to use when finding neighbors
pos (list[int]): The location in the form [row, column]
Returns:
dict[str, str]: A dictionary of neighbors of the form
{"N": `chr`, "S": `chr`, "E": `chr`, "W": `chr`}.
If there is no neighboring character in a cardinal direction,
then that `chr` will be \0.
"""
r, c = pos
chars = [[*line] for line in text.splitlines()]
near = {}
find = {
"E": lambda: chars[r][c + 1],
"W": lambda: chars[r][c - 1],
"S": lambda: chars[r + 1][c],
"N": lambda: chars[r - 1][c],
}
for direction in find:
try:
near[direction] = find[direction]()
except IndexError:
near[direction] = "\0"
return near
|
f1faa6f032479d631a7f5f4a4aeb214153565017
| 412,834 |
def get_number_of_usable_hosts_from_raw_address(raw_address: str) -> int:
"""
Return number of usable host ip addresses.
>>> get_number_of_usable_hosts_from_raw_address("192.168.1.15/24")
254
>>> get_number_of_usable_hosts_from_raw_address("91.124.230.205/30")
2
"""
slash_ind = raw_address.index('/')
prefix = int(raw_address[slash_ind + 1:])
return pow(2, 32-prefix) - 2
|
be06cb197dd3aad98974ee006a93738f085a5c05
| 100,570 |
import collections
def merge_dicts(dict1: dict, dict2: dict) -> dict:
"""
Merges two dicts adding up the values.
:param dict1: The first dict.
:param dict2: The second dict.
:return: A dict with the added values of first and second dicts.
"""
return dict(collections.Counter(dict1) + collections.Counter(dict2))
|
d3a46f01a201fe97c69e93bc9c571f6b03c99bec
| 357,338 |
def fillna_value(df, value=0.0):
"""Set NaN to zero."""
return df.mask(df.isnull(), value)
|
dbce52b67c31f947d57440d358767815a7cb0439
| 412,872 |
import re
def matchall(text, patterns):
"""Scans through a string for substrings matched some patterns.
Args:
text: A string to be scanned.
patterns: a list of regex pattern.
Returns:
a list if matched. empty if not.
"""
ret = []
for pattern in patterns:
try:
match = re.findall(pattern, text)
except(TypeError):
match = re.findall(pattern, str(text))
ret += match
return ret
|
06e2003780b0d8bf22b138bd92161b1c1cb7d367
| 512,249 |
def binary_search_recursive(array, elem, offset=0):
"""
Binary search algorithm.
Complexity of algorithm is log(n).
:param array: should be sorted list of elements
:param elem: element to find in array
:param offset: default is 0, used for recursive call
:return: index of element in array if it's in array, otherwise -1
"""
ind = len(array) % 2
if elem == array[ind]:
return ind + offset
elif elem > array[ind]:
return binary_search_recursive(array[ind + 1:], elem, offset + ind + 1)
else:
return binary_search_recursive(array[:ind - 1], elem, offset)
|
1b1dff1bcd7ea4cd42e75a2a3bfc881ccb3b282b
| 464,447 |
import requests
def get_node(name, api_url, headers, validate_certs=True):
"""Returns a dict containing API results for the node if found.
Returns None if not just one node is found
"""
url = "{}/v3/nodes?name={}".format(api_url, name)
node_search = requests.get(url, headers=headers, verify=validate_certs)
if node_search.json()['pagination']['total'] > 1 or node_search.json()['pagination']['total'] == 0:
return None
return node_search.json()['data'][0]
|
d6df2228d3a49cf82f2f38caff3204a738ea5547
| 664,642 |
def negation(f):
"""Negate a filter.
Args:
f: filter function to invert
Returns:
A filter function that returns the negation of f.
"""
def keep(paths):
l = set(paths)
r = set(f(paths))
return sorted(list(l-r))
return keep
|
b732a7ebab22b8647f8e0d957b77258fff95e52b
| 611,601 |
def get_next_super_layer(layer_dependency_graph, super_nodes, current_layer):
"""
Return the immediate next super layer of current layer.
:param layer_dependency_graph: dependency graph of the model
:param super_nodes: list of all super nodes
:param current_layer: the layer whose next super layer need to compute
:return: immediate next super layer
"""
current_layer = layer_dependency_graph[current_layer].get_output_layers()[0]
while True:
if current_layer in super_nodes:
return current_layer
current_layer = layer_dependency_graph[current_layer].get_output_layers()[0]
|
d7a0e606c10974510d0d250d15d26537f8440494
| 660,396 |
def filter_objlist(olist, fieldname, fieldval):
"""
Returns a list with of the objetcts in olist that have a fieldname valued as fieldval
@param olist: list of objects
@param fieldname: string
@param fieldval: anything
@return: list of objets
"""
return [x for x in olist if getattr(x, fieldname) == fieldval]
|
f39c90261ac259c04e7daa70fa951156818719bc
| 291,077 |
def file_get_contents(path_to_file):
""" Function get content of file (analog of php file_get_contents()) """
fh = open(path_to_file, 'r')
content = fh.read()
fh.close()
return content
|
35ce52bdf33aa22c4359fe3aab8085e24780071b
| 584,411 |
from typing import Union
def hex256(x: Union[int, str]) -> str:
"""Hex encodes values up to 256 bits into a fixed length
By including this amount of leading zeros in the hex string, lexicographic
and numeric ordering are identical. This facilitates working with these
numbers in the database without native uint256 support.
"""
if isinstance(x, str):
x = int(x)
return "0x{:064x}".format(x)
|
1bc19b38c46114e15fc62305d58e62b1e9fcbe8f
| 213,726 |
def get_vcf_column_headers(line, sample_ids, sample_indices):
"""Get VCF column headers, including only relevant samples
Parameters
----------
line : str
A line from a vcf file (e.g. from an open file descriptor)
sample_ids : list, tuple
All sample IDs in the input VCF file
sample_indices : container
Indices indicating which samples from sample_ids should be kept
Returns
-------
list
Column headers for the output VCF file
"""
return line.split()[:9] + [sample_ids[i] for i in sample_indices]
|
496616202b820224c54b91111678c54554bca771
| 580,019 |
import math
def get_cosine(question_vector, sentence_vector):
""" Implementation of Cosine Similarity (https://en.wikipedia.org/wiki/Cosine_similarity).
Formula = [SUM(1,n) of Ai * Bi] / {[Square root of (SUM(1,n) Ai^2)] * [Square root of (SUM(1,n) Bi^2)]}
:param question_vector: The question's vector.
:type question_vector: collections.Counter
:param sentence_vector: The sentence's vector.
:type sentence_vector: collections.Counter
:return: The similarity score of question & sentence vectors(from -1 to 1)
:rtype: float
"""
# Create intersection ('tomi').
intersection = set(question_vector.keys()) & set(sentence_vector.keys())
# Create numerator ('arithmitis').
# [SUM(1,n) of Ai * Bi]
numerator = sum([question_vector[x] * sentence_vector[x] for x in intersection])
# Create denominator ('paronomastis').
question_vector_sum = sum([question_vector[x]**2 for x in question_vector.keys()]) # (SUM(1,n) of Ai^2)
sentence_vector_sum = sum([sentence_vector[x]**2 for x in sentence_vector.keys()]) # (SUM(1,n) of Bi^2)
denominator = math.sqrt(question_vector_sum) * math.sqrt(sentence_vector_sum) # [Square root of (question_vector_sum)] * [Square root of (sentence_vector_sum)]
# Calculate similarity score.
if not denominator:
return 0.0
else:
return float(numerator) / denominator
|
17c44f1946b42071df2cd47960ce660c5c1cd048
| 413,843 |
from typing import Dict
from typing import Any
def get_role_dependency_link(metadata: Dict[str, Any]) -> str:
"""
Returns role dependency link
Args:
metadata (Dict[str, Any]): role metadata
Returns:
str: role dependency link
"""
role_name = metadata.get("role_name", None)
namespace = metadata.get("namespace", None)
if not namespace or not role_name:
raise ValueError(
f"Can not generate dependency link for {namespace}.{role_name}"
)
return (
f"<b>"
f'<a href="https://galaxy.ansible.com/{namespace}/{role_name}" '
f'title="{namespace}.{role_name} on Ansible Galaxy" target="_'
f'blank">{namespace}.{role_name}</a></b>'
)
|
c7018ccfa49c6ff7a7cc483fce6af64c27d6bc94
| 499,299 |
def derive_table_from(source):
"""Ease the typical use case /somewhere/TAB.txt -> TAB.json."""
table = source.stem.upper()
return table, f'{table}.json'
|
08f364d70750c887915ca8464fe76fb09e7687d8
| 654,903 |
import inspect
def get_args(frame):
"""Gets dictionary of arguments and their values for a function
Frame should be assigned as follows in the function itself: frame = inspect.currentframe()
"""
args, _, _, values = inspect.getargvalues(frame)
return dict((key, value) for key, value in values.items() if key in args)
|
87bb968522657c762962e58a9c90023e97bc118e
| 667,640 |
def _ensure_cr(text):
""" Remove trailing whitespace and add carriage return
Ensures that `text` always ends with a carriage return
"""
return text.rstrip() + '\n'
|
1f70b470070f0d3640af0739d3320684d2116141
| 457,978 |
def _is_decoy_suffix(pg, suffix='_DECOY'):
"""Determine if a protein group should be considered decoy.
This function checks that all protein names in a group end with `suffix`.
You may need to provide your own function for correct filtering and FDR estimation.
Parameters
----------
pg : dict
A protein group dict produced by the :py:class:`ProtXML` parser.
suffix : str, optional
A suffix used to mark decoy proteins. Default is `'_DECOY'`.
Returns
-------
out : bool
"""
return all(p['protein_name'].endswith(suffix) for p in pg['protein'])
|
77da0255f7fe9672f502817bd5ab07f0bd6e3159
| 689,370 |
def _rgb2hex(c_rgb):
"""RGB to Hex.
Parameters
----------
c_rgb : tuple (255, 255, 255)
rgb colors in range 0-255.
Returns
-------
str.
Hex color.
Examples
--------
hexcolor = _rgb2hex([255,255,255])
"""
# Components need to be integers for hex to make sense
c_rgb = [int(x) for x in c_rgb]
return "#"+"".join(["0{0:x}".format(v) if v < 16 else
"{0:x}".format(v) for v in c_rgb])
|
e64f11cc599c88670c16f439afb6553113dad879
| 150,038 |
def sample_image(imgGray, sampleRect, maxVal):
""" Sample image in a given rectangle, represented as [x0,y0,w,h], where x0,y0 is the top-left coordinates of the sampling region """
y0, x0, w, h = sampleRect
sampleSum = 0
for y in range(h):
for x in range(w):
sampleSum += imgGray[y0+y][x0+x]
sample = float(sampleSum) / (w * h * maxVal)
return sample
|
c6e7bde238b0f7fe5ff0b9cc2224e33dada410bc
| 557,645 |
import time
import hmac
import hashlib
def create_auth_headers(url, access_key, secret, body=None):
"""
get HTTP headers for API authentication
:param url: API url. (e.g. https://coincheck.com/api/accounts/balance )
:param access_key: Access Key string for API authentication
:param secret: Secret Access Key string for API authentication
:return: HTTP header dictionary
"""
current_millis = str(int(round(time.time() * 1000)))
message = current_millis + url + body
signature = hmac.new(secret.encode("utf-8"), message.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
"ACCESS-KEY": access_key,
"ACCESS-NONCE": current_millis,
"ACCESS-SIGNATURE": signature
}
return headers
|
7f34aecf72a4fef230b7b081cfed9ecba6d9dd2a
| 204,412 |
def get_event_abi(abi, event_name):
"""Helper function that extracts the event abi from the given abi.
Args:
abi (list): the contract abi
event_name (str): the event name
Returns:
dict: the event specific abi
"""
for entry in abi:
if 'name' in entry.keys() and entry['name'] == event_name and \
entry['type'] == "event":
return entry
raise ValueError(
'Event `{0}` not found in the contract abi'.format(event_name))
|
fe8c7e6c16991d7b44439b70adfbad7b87fb57c3
| 505,954 |
def move1(state,b1,dest):
"""
Generate subtasks to get b1 and put it at dest.
"""
return [('get', b1), ('put', b1,dest)]
|
c84a2d8246017fa94a73dd2e3408f7f05cf3573d
| 696,739 |
import inspect
def getPublicTypeMembers(type_, onlyValues=False):
"""
Useful for getting members from types (e.g. in enums)
>>> [_ for _ in getPublicTypeMembers(OS, True)]
['Linux', 'Windows']
"""
retVal = []
for name, value in inspect.getmembers(type_):
if not name.startswith("__"):
if not onlyValues:
retVal.append((name, value))
else:
retVal.append(value)
return retVal
|
859dcce8245e6eac372fc8db5e4559366600b309
| 664,964 |
import hashlib
def proof_of_work(unique_trxn_data, nonce):
"""[CHANGING DIFFICULTY: Look for the 'difficulty = X' row, and change X to another integer]
The Bitcoin SHA256 proof-of-work. Takes transaction data, and requires the miner to find a nonce (number only
used once) that will result in a SHA256 hash containing X zero bits in front of it.
Because SHA256 is a cryptographic hash function, there is no better way to figure out the nonce than to brute
force guess it. Computers do it really fast. In this demonstration, the program just guesses random numbers until
a number somehow works.
Feel free to change the number of zero bits required; you'll notice that the time taken to brute-force guess it
increases exponentially with the number of zero bits. In my experience, the computer takes more than 10 minutes
once there are 8 zero bits, at least under my really inefficient program. Bitcoin miners are expected to spend
10 minutes doing their proof of work, and this is modulated by changing the number of zero bits required."""
mine_attempt = unique_trxn_data * nonce # This represents one brute force guess of the nonce.
sha = hashlib.new("sha256")
sha.update(str(mine_attempt).encode("ascii")) # Converts the guess into bits and runs it through SHA256
# Calibrates number of zero bits required at the front of the SHA256 hash
difficulty = 5 # Change this to any integer you'd like, to see how the time taken changes!
solution = "".join(["0" for i in range(difficulty)])
if sha.hexdigest()[:difficulty] == solution:
print(f"\nNonce for difficulty of {difficulty} zero bits found.\n"
f"SHA256 hash is {sha.hexdigest()}")
return True
else:
return False
|
bc6370639cb4cbd2e625b7cf0eb2d1bc89b91b61
| 543,240 |
def _string_from_cmd_list(cmd_list):
"""Takes a list of command line arguments and returns a pretty
representation for printing."""
cl = []
for arg in map(str, cmd_list):
if ' ' in arg or '\t' in arg:
arg = '"' + arg + '"'
cl.append(arg)
return ' '.join(cl)
|
773fcc8b93b4ff31fdb18c1939f396d0b19b1d96
| 537,460 |
from typing import Dict
from pathlib import Path
def read_image_to_bytes(filename: str) -> Dict:
"""
Function that reads in a video file as a bytes array
Parameters
----------
filename : str
Path to image file
Returns
-------
JSON
Object containing "filename" and bytes array
"""
with open(filename, "rb") as file:
bytes_array = file.read()
file_info = {}
file_info["filename"] = Path(filename).stem
file_info["data"] = bytes_array
return file_info
|
d90721ff1231e7f1e0d2f7ea4bcf81facd2b1686
| 72,735 |
import string
def letterDensity(authors):
""" Calculate the empirical distribution of first letters.
"""
authors['firstLetter'] = authors.firstLetter.apply(lambda x: x.lower())
authors = authors[authors['firstLetter'].isin([i for i in string.ascii_lowercase])]
byLetter = authors.groupby('firstLetter').name.agg('count')
total = byLetter.sum()
return byLetter / total
|
d5b1533a66293b06e1035d1bf1a353c0a267106c
| 218,388 |
from datetime import datetime
def _iso8601_date(time: datetime) -> str:
"""Formats the timestamp in ISO-8601 format, e.g. '2020-06-01T00:00:00.000Z'."""
return f"{time.replace(tzinfo=None).isoformat(sep='T', timespec='milliseconds')}Z"
|
17a9363f7ba7f7c45f0a5dedf838cfc003ac58d8
| 562,657 |
from typing import List
def txt_python_func(func_list: List[str], func_type: str) -> str:
"""This method creates strings from which the python file in which the simulation functions are defined is created.
func_list contains the names of all process functions for which a string representation should be generated.
func_type contains the type of function to be created, possible cases are:
'p' -> process functions
's' -> sources and sinks
'g' -> global functions
"""
# Make a list of unique elements
func_list = list(set(func_list))
# Create functions signature based on the function type
signature: str = ''
if func_type == 'p':
signature = 'env, item, machine, factory'
elif func_type == 's':
signature = 'env, factory'
elif func_type == 'g':
signature = 'env, factory'
txt_func: str = ''
for func in func_list:
txt_func += 'def ' + func + '(' + signature + '):\n\n\tpass\n\n'
return txt_func
|
443aadda78530493ec9a8007912f1925f517a0d1
| 112,713 |
import logging
def get_logger(log_file=None):# {{{
"""Set logger and return it.
If the log_file is not None, log will be written into log_file.
Else, log will be shown in the screen.
Args:
log_file (str): If log_file is not None, log will be written
into the log_file.
Return:
~Logger
* **logger**: An Logger object with customed config.
"""
# Basic config
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO,
)
logger = logging.getLogger(__name__)
# Add filehandler
if log_file is not None:
file_handler = logging.FileHandler(log_file, mode='w')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(
logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
)
logger.addHandler(file_handler)
return logger
|
25cbf7d9cd9150ee5b86929c9ab56d748ae0fdc3
| 19,318 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.