content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import math
def get_overall_score(r1_score, bond_score, missing_elements_score, stoich_score, anisotropy_penalty, score_weighting):
"""
Get the overall score for an optimizer result
:param r1_score:
:param bond_score:
:param missing_elements_score:
:param stoich_score:
:param anisotropy_penalty:
:param score_weighting:
:return:
"""
bond_score_basis = 0.1
missing_elements_basis = 0.05
stoich_score_basis = 0.1
anisotropy_penalty_basis = 0.1
# return math.pow(self.r1, self.score_weighting) + math.pow(self.bond_score, 1 - self.score_weighting)
# return (1.0 + math.pow(self.r1 / r1_basis, self.score_weighting)) \
# * (1.0 + math.pow(self.bond_score / bond_score_basis, 1 - self.score_weighting))
# try:
return math.pow(r1_score, score_weighting) * \
math.pow(bond_score + bond_score_basis, 1 - score_weighting) + \
missing_elements_basis * missing_elements_score ** 2 + \
stoich_score_basis * stoich_score + \
anisotropy_penalty_basis * anisotropy_penalty
# except TypeError:
# print(self.r1, self.score_weighting, self.bond_score, self.n_missing_elements)
# quit()
# return self.r1 * self.bond_score
# return (self.r1, len(self.res_file.mixed_site_numbers))
|
2f8174ed7e08644156d5a5287dcbabba759f3e9a
| 601,741 |
def bslice(high, low=None):
"""
Represents: the bits range [high : low] of some value. If low is not given,
represents just [high] (only 1 bit), which is the same as [high : high].
"""
if low is None:
low = high
return slice(low, high + 1)
|
d3a3085f8da638ef63c7d0f65605543f6f3605b7
| 20,046 |
def firesim_tags_to_description(buildtriplet, deploytriplet, commit):
""" Serialize the tags we want to set for storage in the AGFI description """
return """firesim-buildtriplet:{},firesim-deploytriplet:{},firesim-commit:{}""".format(buildtriplet,deploytriplet,commit)
|
20c17da1c8620f14cd7849f4687e759645462809
| 399,174 |
def update_text(s,**kws):
"""
Replace arbitrary placeholders in string
Placeholder names should be supplied as keywords
with the corresponding values being the text to
replace them with in the supplied string.
When placeholders appear in the string they
should be contained within '<...>'.
For example:
>>> text = "Hello my name is <NAME>"
>>> update_text(text,NAME="Joe")
... "Hello my is name is Joe"
Arguments:
s (str): text to be updated
kws (mapping): keywords mapping placeholder
names to new values
Returns:
String: the original text updated by
substituting
"""
for kw in kws:
placeholder = "<%s>" % kw
new_text = kws[kw]
if new_text is None:
continue
s = s.replace(placeholder,new_text)
return s
|
b4ef41689b21093ee3823d341e162d5526110d74
| 283,686 |
def as_scalar(val):
"""
If val is iterable, this function returns the first entry
else returns val. Handles strings as scalars
:param val: A scalar or iterable
:return:
"""
# Check string
if val == str(val):
return val
try: # Check iterable
it = iter(val)
# Get first iterable
return next(it)
except TypeError:
# Fallback, val is scalar
return val
|
b43a730180f85c4fb227aebaad98ca0ec5f7314f
| 465,276 |
def vf_stokes(r,g,eta,drho,Nkn=0.):
"""terminal velocity of Stokes flow (Reynolds number < 2, Davies number < 42)
Args:
r: particle size (cm)
g: gravity (cm/s2)
eta: dynamic viscosity (g/s/cm)
drho: density difference between condensates and atmosphere (g/cm3)
Nkn: Knudsen number
Return:
terminal velocity (cm/s)
Note:
(1.0+1.255*Nkn) is the Cunningham factor
Note:
See also (10-138) p415 in Hans R Pruppacher and James D Klett. Microstructure of atmospheric clouds and precipitation. In Microphysics of clouds and precipitation, pages 10–73. Springer, 2010. Equation (B1) in Appendix B of Ackerman and Marley 2001.
"""
return 2.0*g*r*r*drho*(1.0+1.255*Nkn)/(9.0*eta)
|
c8234fa729b08696d2db22b7d2a69ae4ae23c1ed
| 505,190 |
import aiohttp
async def text_callback(resp: aiohttp.ClientResponse) -> str:
"""Returns the response result as text.
Mostly useful for endpoints that returns just text on its output. Some
examples::
$ curl ifconfig.me/ip
123.123.123.123
$ curl 'wttr.in/?format=%t'
+31°C
"""
return await resp.text()
|
2cf7e0d88654f62e3ab33ed8a8dde9495fbe453b
| 620,473 |
from io import StringIO
def readFromFile(fileName: str) -> str:
"""Returns the complete content of the given file."""
sio = StringIO()
with open(fileName) as f:
return f.read()
|
568893f751fc401165e3c6e81e56c44441975820
| 396,700 |
def getNumberFromId(obj_id):
"""Returns the long decimal number (as a string) from the end of a wsadmin object id string.
For example, returns 1157676511879 from the following id:
PAP_1(cells/ding6Cell01|coregroupbridge.xml#PeerAccessPoint_1157676511879)
Returns the original id string if the ID string can not be parsed.
"""
longnum = obj_id
if longnum.endswith(')'):
# Strip off the trailing parenthesis
len_orig = len(longnum)
longnum = longnum[:len_orig-1]
# Find the index of the last underscore.
ix = longnum.rfind('_')
if -1 != ix:
# Extract the number.
longnum = longnum[ix+1:]
return longnum
|
bcefc9a82ade614600db38e603607f76019016f0
| 529,498 |
def register_global_step(mr):
"""
Add global step to ModelRegistry.
Parameters
----------
mr : ModelRegistry
"""
def callback(**kwargs):
mr.global_step_ = kwargs["global_step"]
return callback
|
a362aa51e9e6aba68aad908982d6e683587a8c10
| 264,291 |
def _get_name(dist):
"""Attempts to get a distribution's short name, excluding the name scope."""
return getattr(dist, 'parameters', {}).get('name', dist.name)
|
fd57e523c1a84a36f9ed56236e4b8db1e887575c
| 709,709 |
def split_files(files, split_train, split_val, use_test):
"""Splits the files along the provided indices
"""
files_train = files[:split_train]
files_val = files[split_train:split_val] if use_test else files[split_train:]
li = [(files_train, 'train'), (files_val, 'val')]
# optional test folder
if use_test:
files_test = files[split_val:]
li.append((files_test, 'test'))
return li
|
908cf517abe1201a62678af9ba8323f78d3769ad
| 435,421 |
def isiterable(x):
"""Determines if an object is iterable and not a string."""
return hasattr(x, "__iter__") and not hasattr(x, "upper")
|
7f82e3e3c21235b7270f6f1106e5ba49d698e353
| 454,951 |
def python_sum(num_list):
"""Calculate the sum using standart 'sum' function of python."""
return sum(num_list)
|
07d6b35ff5dae23b017e568e4cd91ca65df15b96
| 522,596 |
def set_device_orientation_override(alpha: float, beta: float, gamma: float) -> dict:
"""Overrides the Device Orientation.
Parameters
----------
alpha: float
Mock alpha
beta: float
Mock beta
gamma: float
Mock gamma
**Experimental**
"""
return {
"method": "Page.setDeviceOrientationOverride",
"params": {"alpha": alpha, "beta": beta, "gamma": gamma},
}
|
2113001cc29327fbadcb053c3270e32a6384ea82
| 652,060 |
def bfs_shortest_path_distance(graph: dict, start, target) -> int:
"""Find shortest path distance between `start` and `target` nodes.
Args:
graph: node/list of neighboring nodes key/value pairs.
start: node to start search from.
target: node to search for.
Returns:
Number of edges in shortest path between `start` and `target` nodes.
-1 if no path exists.
Example:
>>> bfs_shortest_path_distance(graph, "G", "D")
4
>>> bfs_shortest_path_distance(graph, "A", "A")
0
>>> bfs_shortest_path_distance(graph, "A", "H")
-1
"""
if not graph or start not in graph or target not in graph:
return -1
if start == target:
return 0
queue = [start]
visited = [start]
# Keep tab on distances from `start` node.
dist = {start: 0, target: -1}
while queue:
node = queue.pop(0)
if node == target:
dist[target] = (
dist[node] if dist[target] == -1 else min(dist[target], dist[node])
)
for adjacent in graph[node]:
if adjacent not in visited:
visited.append(adjacent)
queue.append(adjacent)
dist[adjacent] = dist[node] + 1
return dist[target]
|
9eb28d7c854bdc8adc49b208169d68fb9ad15901
| 249,372 |
def cut_string(string, limit=30):
"""Shorten the length of longer strings."""
if len(string) <= limit:
return string
else:
return string[:limit-3] + '...'
|
842cfefcff84c4f146cc85a4e86dff1486e9a434
| 702,116 |
import torch
def gradient_detailed_overlap(grad, V, num_classes):
"""Similar to `gradient_overlap`, but here, we compute the overlap of the gradient
with the individual eigenvectors. The gradiejt overlap can be written as
overlap(grad, S_V) = ||P_V grad||^2 / ||grad||^2
= (sum_{c=1}^C (v_c.T grad)^2) / (grad.T grad)
Here, we consider the individual projections (v_c.T grad)^2.
"""
# Check that grad, V have the correct shape
D, C = V.shape
assert C == num_classes, "V doesn't have `num_classes` columns"
assert grad.numel() == D, f"grad does not have {D} entries"
proj_coeffs = torch.square(torch.matmul(V.T, grad))
return proj_coeffs / (grad.T @ grad)
|
cd3889ccb1fac23bb4888901b3b87dff0dbd26c2
| 412,475 |
def string_to_list(line, sep=','):
"""convert a comma (or sep) separated string to list.
If line is None (or any falsy value), return [].
"""
return line.split(sep) if line else []
|
179e9f5c67dfa6b9a3b3902bed44f5ce497dd4b7
| 458,607 |
def inc(x):
"""
Increments the value of x
>>> inc(4)
5
"""
return x + 1
|
79159342dd7ab241e7f513192fc29d14b5bcd314
| 600,617 |
def find_boolean_function(lib_json_data, port_name):
"""
Search for a boolean function for a certain port in a .lib.json file.
:param lib_json_data: json data of a .lib.json file
:param port_name: The port name
:returns: The boolean function as a string. Empty string if no boolean function was found.
"""
if lib_json_data is None:
return ""
if ("pin,"+port_name) in lib_json_data:
if "function" in lib_json_data[("pin,"+port_name)]:
return lib_json_data[("pin,"+port_name)]["function"]
return ""
|
fac223dcc68bba04858018d190ea82e91ae79f66
| 605,176 |
def get_display_name_from_arn(record):
"""Get the display name for a version from its ARN.
Args:
record
A record returned by AWS.
Returns:
A display name for the task definition version.
"""
arn_parts = record.split(":")
name = arn_parts[5]
version = arn_parts[6]
name_parts = name.split("/")
family = name_parts[1]
return str(family) + ":" + str(version)
|
be00a08c88b07a9134a3625a83912422bb29a05a
| 479,586 |
def weekday_name(day_of_week):
"""Return name of weekday.
>>> weekday_name(1)
'Sunday'
>>> weekday_name(7)
'Saturday'
For days not between 1 and 7, return None
>>> weekday_name(9)
>>> weekday_name(0)
"""
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
if day_of_week < 1 or day_of_week > 7:
return None
return days[day_of_week - 1]
|
7a7e80f3afcf20d66c4b2a595d3756c871414c33
| 565,562 |
def _choice_evaluator(choice_array, choice_condition):
"""
Determines which rows in `choice_array` meet the given `choice_condition`,
where `choice_condition` is in the set `{0.0, 1.0}`.
Parameters
----------
choice_array : 1D ndarray of ints that are either 0 or 1.
choice_condition : int in `{0, 1}`.
Returns
-------
bool_mask : 1D ndarray of bools.
Equal to `choice_array == choice_condition`
"""
if choice_condition in [0.0, 1.0]:
return choice_array == choice_condition
else:
msg = "choice_condition MUST be either a 0 or a 1"
raise ValueError(msg)
|
82e1ae37884b486342c375e630c567387766d5fd
| 573,150 |
import operator
def sortedby2(item_list, *args, **kwargs):
"""sorts ``item_list`` using key_list
Args:
item_list (list): list to sort
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
Returns:
list : ``list_`` sorted by the values of another ``list``. defaults to
ascending order
CommandLine:
python -m utool.util_list --exec-sortedby2 --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5]
>>> key_list1 = [1, 1, 2, 3, 4]
>>> key_list2 = [2, 1, 4, 1, 1]
>>> args = (key_list1, key_list2)
>>> kwargs = dict(reverse=False)
>>> result = ut.sortedby2(item_list, *args, **kwargs)
>>> print(result)
[2, 1, 3, 4, 5]
Example:
>>> # ENABLE_DOCTEST
>>> # Python 3 Compatibility Test
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5]
>>> key_list1 = ['a', 'a', 2, 3, 4]
>>> key_list2 = ['b', 'a', 4, 1, 1]
>>> args = (key_list1, key_list2)
>>> kwargs = dict(reverse=False)
>>> result = ut.sortedby2(item_list, *args, **kwargs)
>>> print(result)
[3, 4, 5, 2, 1]
"""
assert all([len(item_list) == len_ for len_ in map(len, args)])
reverse = kwargs.get('reverse', False)
key = operator.itemgetter(*range(1, len(args) + 1))
tup_list = list(zip(item_list, *args))
# print(tup_list)
try:
sorted_tups = sorted(tup_list, key=key, reverse=reverse)
except TypeError:
# Python 3 does not allow sorting mixed types
def keyfunc(tup):
return tuple(map(str, tup[1:]))
sorted_tups = sorted(tup_list, key=keyfunc, reverse=reverse)
sorted_list = [tup[0] for tup in sorted_tups]
return sorted_list
|
e0e721734b0d3b9c6c63b3ee7f8f8f2285163a4a
| 190,536 |
def generate_seeds(rng, size):
"""
Generate list of random seeds
:param rng: random number generator
:param size: length of the returned list
"""
seeds = [rng.randint(0, 2**32 - 1) for _ in range(size)]
return seeds
|
f264ccaac3f59d33261f35b2eb0c04a43eed3fc6
| 452,089 |
def min(self, parameter_min):
"""
It returns the minimum value of a parameter and the value's indexes.
Parameters
----------
parameter_min: str
Name of the parameter.
Returns
-------
min_dict: dict
Dictionary with the following format:
{
'<name of index 1>': <value of index 1>,
'<name of index n>': <value of index n>,
'name of parameter': < min value of parameter>
}
If min_dict is None, all the values of the parameter are NaN.
"""
df = self.data[parameter_min]
df = df.reset_index()
try:
min_dict = df.loc[df[parameter_min] == df[parameter_min].min(skipna=True)].to_dict('records')[0]
except IndexError:
min_dict = None
return min_dict
|
5f71e69bc1525ce94a626b742c2df7ef45b5e85a
| 639,846 |
def log_gaussian_kernel(dist, h):
"""log of the gaussian kernel for bandwidth h (unnormalized)"""
return -0.5 * (dist * dist) / (h * h)
|
d897d671d12c0bb273c05f9d000614668173336b
| 540,117 |
import re
def get_words(text):
"""
A method to separate the words in a string.
Args:
text (str): input text string.
Return:
words (list): a list of words in the string.
"""
return re.compile('\w+').findall(text)
|
0fc217640c2e7d1ee6ac8dcd836c6cdfdc8ef269
| 251,599 |
def yices_logic(pysmt_logic):
"""Return a Yices String representing the given pySMT logic."""
ylogic = str(pysmt_logic)
if ylogic == "QF_BOOL":
ylogic = "NONE"
return ylogic
|
cdbec0f413d58e8de8eaefd1f2e62998fb02fda6
| 413,830 |
def get_params_string(param_values: dict) -> str:
"""Generate the string from the dict with parameters
Args:
param_values (dict): dict of "param_name" -> "param_value"
"""
params_string = ", ".join(
[k + "=" + str(param_values[k]) for k in param_values.keys()]
)
return params_string
|
3f4a8019da68a67b5da90917524eaf6ee1f5c69e
| 354,877 |
def monomer_from_anisotropy(a, Am, Ad, b):
"""
Calculate monomer fraction from anisotropy, monomer and dimer anisotropy
and brightness relation.
"""
return (b * a - Ad*b) / ((Am - b * Ad) - (1-b) * a)
|
a106af8efed1be5aa3377a04c74e8d704d8eaa19
| 487,392 |
def _corners(d):
"""Return corner coordinates.
@param d: `dict` with keys
`'x', 'y', 'w', 'h'`
@return: quadruple
@rtype: `tuple`
"""
x = d['x']
y = d['y']
w = d['w']
h = d['h']
xmax = x + w
ymax = y + h
return x, xmax, y, ymax
|
c466f3c09c1cdb828bf6570b0200cf757edfe13a
| 402,540 |
def square(x):
"""
Return the square of the single parameter.
:param x: A numeric value
:return: The squre of x
"""
return x*x
|
dae9cd5e6bf610a71c7bdde08c7365b9363fb0a8
| 563,747 |
def triangular(n):
"""Gives the n-th triangle number."""
return n*(n+1)/2
|
17b5cbd0f690dbf0043ea84da3fef56c82812599
| 689,599 |
def selection_sort(list_: list) -> list:
"""Returns a sorted list, by selection sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by selection sort method
"""
def find_smallest_index(list_: list) -> int:
"""Returns the index of the smallest element
:param list_: The list to be sorted
:type list_: list
:rtype: int
:return: Index of the smallest element
"""
smallest = list_[0]
smallest_index = 0
for i in range(1, len(list_)):
if list_[i] < smallest:
smallest = list_[i]
smallest_index = i
return smallest_index
new_list = []
for _ in range(len(list_)):
new_list.append(list_.pop(find_smallest_index(list_)))
return new_list
|
54158ca1346fcfc67602282a5458d0d0f8bc77c5
| 322,698 |
import yaml
def compare_markdown_content(file1, file2, compare='both'):
"""Compare Markdown file metadata
Args:
file1 (str): first file contents
file2 (str): second file contents
compare (str): compare 'meta', 'body' or 'both'
Returns:
True if metadata are logically the same, False otherwise
"""
if '...' in file1:
meta1, _, body1 = file1.partition('...\n')
else:
return False
if '...' in file2:
meta2, _, body2 = file2.partition('...\n')
else:
return False
if compare in ['meta', 'both']:
try:
meta1 = yaml.safe_load(meta1)
except yaml.YAMLError:
print(f'Error in metadata for file 1')
return False
try:
meta2 = yaml.safe_load(meta2)
except yaml.YAMLError:
print(f'Error in metadata for file 2')
return False
if meta1 != meta2:
return False
if compare in ['body', 'both']:
if body1 != body2:
return False
return True
|
7e17416bddc820df56f94caa3d601a6b2a9c0fda
| 546,409 |
import calendar
def toUnixSeconds(timestruct):
"""Convert a datetime struct to a Unix timestamp in seconds.
:param timestruct: A ``datetime.datetime`` object to convert into a
timestamp in Unix Era seconds.
:rtype: int
"""
return calendar.timegm(timestruct)
|
6df27af852cc388beb98489072bbd69d37ca1c18
| 288,715 |
def get_atom_order_from_xyz(xyz):
"""
Get the order in which atoms should be added to the zmat from the 3D geometry.
Args:
xyz (dict): The 3D coordinates.
Returns:
list: The atom order, 0-indexed.
Returns:
None: Not used, but important for returning the same number of parameters as ``get_atom_order_from_mol``.
"""
atom_order, hydrogens = list(), list()
for i, symbol in enumerate(xyz['symbols']):
if symbol == 'H':
hydrogens.append(i)
else:
atom_order.append(i)
atom_order.extend(hydrogens)
return atom_order, None
|
8687531bfbec590970f31831f10169e38a87e122
| 151,723 |
def split_overlapping(signal, freq=257, time=2, shift=0.5):
"""
Splits the signal data into segments. Expects signal with dim-0 samples, dim-1 leads (12)
:param signal: the signal
:param freq: frequency rate of the signal
:param time: time length of the segments
:param shift: time shift in taking different section
:return: list of signal segments and list of starting sample of segment
"""
seglen = int(freq*time)
shiftlen = int(shift*time)
siglen = signal.shape[0]
times = range(0, siglen-seglen, shiftlen)
segments = [signal[i:i+seglen, :] for i in times]
return segments, times
|
ba72e6315f1bf9dec12655f459bcd3d6e4b42a7e
| 574,606 |
def _toArchitectureDir(architecture):
"""Re-map 'x64' to 'amd64' to match MSVC directory names.
"""
return {'x64':'amd64'}.get(architecture, architecture)
|
53f630829ea4c91c032401ba16f28d900c16e98a
| 122,452 |
import csv
def readcsv(filename, delimiter=',', quotechar='"'):
"""Read CSV file data into a list.
Args:
filename (str): Full path of file.
delimiter (str, optional): Delimiter
quotechar (str, optional): Quote character
Returns:
list: List of lines from CSV file
"""
data = []
with open(filename, newline='') as csvfile:
lines = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar)
for line in lines:
data.append(line)
return data
|
e80b09d27339561b4d3bdb12979ece8fd2bd83dc
| 585,223 |
def sparseFeature(feat, feat_num, embed_dim=4):
"""
create dictionary for sparse feature
:param feat: feature name
:param feat_num: the total number of sparse features that do not repeat
:param embed_dim: embedding dimension
:return:
"""
return {'feat': feat, 'feat_num': feat_num, 'embed_dim': embed_dim}
|
ffe53e988e20a2f23db1c63f3a471ff04650f592
| 600,552 |
def lennard_jones(r, sig, eps):
"""
Calculate Lennard Jones potential for given distance, sigma, and epsilon values.
Energy unit: (kB)
"""
return 4 * eps * ((sig / r)**12 - (sig / r)**6)
|
643ee902f5f5845dcca62fa315886f6a438f48dd
| 342,868 |
from typing import Optional
def normalize_string(s: str, *, suffix: Optional[str] = None) -> str:
"""Normalize a string for lookup."""
s = s.lower().replace('-', '').replace('_', '').replace(' ', '')
if suffix is not None and s.endswith(suffix.lower()):
return s[:-len(suffix)]
return s
|
b8104ef22b1ecda3bcddc092bfbdf02956780e79
| 152,779 |
def generate_timestamp_format(date_mapper: dict) -> str:
"""
Description
-----------
Generates a the time format for day,month,year dates based on each's
specified time_format.
Parameters
----------
date_mapper: dict
a dictionary for the schema mapping (JSON) for the dataframe filtered
for "date_type" equal to Day, Month, or Year.
Output
------
e.g. "%m/%d/%Y"
"""
day = "%d"
month = "%m"
year = "%y"
for kk, vv in date_mapper.items():
if vv["date_type"] == "day":
day = vv["time_format"]
elif vv["date_type"] == "month":
month = vv["time_format"]
elif vv["date_type"] == "year":
year = vv["time_format"]
return str.format("{}/{}/{}", month, day, year)
|
cd535a4fb35917517711cf149430c128e2c46b6d
| 16,085 |
def fib_n(n):
"""Efficient way to compute Fibonacci's numbers. Complexity = O(n)"""
fibs = [0, 1] # we don't need to store all along the way, but the memory is still as good as in the naive alg
for i in range(2, n + 1):
fibs.append(fibs[-2] + fibs[-1])
print(fibs[-1])
return fibs[-1]
|
684fecfd5d65bc91cea45f1767c4ae4bae4a73a9
| 531,312 |
def points_bounds(points):
"""Return bounding rect of 2D point list (as 4-tuple of min X, min Y,
max X, max Y)."""
min_x, min_y, max_x, max_y = (
points[0][0],
points[0][1],
points[0][0],
points[0][1],
)
for point in points[1:]:
min_x = min(min_x, point[0])
min_y = min(min_y, point[1])
max_x = max(max_x, point[0])
max_y = max(max_y, point[1])
return (min_x, min_y, max_x, max_y)
|
4c0cbd47bef32fe5d3c1787789d806016d0db4ff
| 78,291 |
def getPrecedence(operator):
"""
Returns the precedence for operators for use in toReversePolish(), where high numbers represent greater precedence
:param operator: operator token data
:return: number representing the precedence of the given operator
"""
if operator == "^":
return 3
elif operator in ["*","/"]:
return 2
elif operator in ["+","-"]:
return 1
|
44532c6bec002aea1596219b78ec029955db0694
| 47,367 |
def ppo_learn(agent, env, env_state, history, args):
"""Learning loop for PPOAgent."""
eval_next = False
# Act
rollout = agent.gather_rollout(env, env_state, history, args)
# Learn
history = agent.learn(*rollout, history, args)
# Sync old and current policy
agent.sync()
# Check for evaluating next
if history["episode"] % args.eval_every == 0 and history["episode"] > 0:
eval_next = True
return env_state, history, eval_next
|
b327352eca31e8247cb1278be769cdc934d344e1
| 520,974 |
def _get_field_ix(line, field):
"""Get position of field ('GT' or 'DS') in FORMAT"""
fmt = line[8].split(':')
if field not in fmt:
raise ValueError('FORMAT field does not contain {}'.format(field))
return fmt.index(field)
|
3eaae31d7a8cb2113b7b2b5423376e92c644f7b5
| 485,157 |
import string
def is_printable(s):
"""
Return True if the string is ASCII (with punctuation) and printable
:param s:
:return:
"""
for c in s:
if c not in string.printable:
return False
return True
|
83303b689d6885c94aad129f195c80460a771ea5
| 382,232 |
def selected_data(accu, selector):
"""
Returns the selected data.
If the selector function is not None, returns the results of
applying the selector function to accu.
Otherwise returns accu.
:param accu: The data accumulator
:param selector: Optional iterable returning function that has the items to be saved
:return:
"""
if selector is None:
return accu
return selector(accu)
|
0904f5a4db41aff4d8e6a5c9c6a9185a8ca9e393
| 163,428 |
def _get_unique(node_list, key, mode=None):
"""
Returns number or names of unique nodes in a list.
:param node_list: List of dictionaries returned by Neo4j transactions.
:param key: Key accessing specific node in dictionary.
:param mode: If 'num', the number of unique nodes is returned.
:return: Unique nodes (list of nodes) or node number
"""
unique_samples = list()
for item in node_list:
unique_samples.append(item[key].get('name'))
unique_samples = set(unique_samples)
if mode == 'num':
unique_samples = len(unique_samples)
return unique_samples
|
26e99c75e30692936781833bf3cd2addf1efd391
| 542,226 |
def isfile(line):
"""
Files are wrapped in FHS / FTS
FHS = file header segment
FTS = file trailer segment
"""
return line and (line.strip()[:3] in ["FHS"]) or False
|
2e33c98f18e44913d18dbbbbed7ec6bd7887f8ba
| 82,462 |
from typing import Union
from typing import Dict
import torch
def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int:
"""
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise.
"""
if isinstance(batch, torch.Tensor):
return batch.size(0) # type: ignore
elif isinstance(batch, Dict):
return get_batch_size(next(iter(batch.values())))
else:
return 0
|
bfdf7c141a6791648a342e0a253cfaaa75b6a61a
| 522,146 |
def relative_to(path, target):
"""Return the relative path of the input to the target path.
For example:
path = /a/b/d/c/Y
target = /a/b/c/X
Then this function will return:
'../../c/X'
Args:
path (pathlib.Path):
target (pathlib.Path):
Returns:
str: the path of 'path' relative to 'target'.
"""
# we step back through 'path' until the parent directory matches a
# parent directory of 'target'. We then construct the return by
# adding N (../) paths for the N steps back and then appending the
# path in 'target' that was not matched in the comparison.
for n, p in enumerate(path.parents):
try:
q = target.relative_to(p)
except ValueError:
continue
return "../" * n + str(q)
return str(target)
|
b6b6a71b0372e6b6bf6bf4d7acfbafe0ad73f77d
| 515,925 |
from typing import Tuple
def fixture_image_shape() -> Tuple[int, int, int]:
"""
Image shape used for the tests.
:returns: Image shape.
"""
return (64, 128, 3)
|
f67c44028acd880b2cabe64ef3496c28183d3799
| 370,812 |
def clean_kwargs(kwargs, keys=None):
"""Removes each key from kwargs dict if found
Parameters
----------
kwargs : dict
* dict of keyword args
keys : list of str, optional
* default: ['obj', 'pytan_help', 'objtype']
* list of strs of keys to remove from kwargs
Returns
-------
clean_kwargs : dict
* the new dict of kwargs with keys removed
"""
if keys is None:
keys = ['obj', 'pytan_help', 'objtype']
clean_kwargs = dict(kwargs)
[clean_kwargs.pop(x) for x in keys if x in kwargs]
return clean_kwargs
|
fad1c665666f49c6b01cc6f1a442c2ae207e7b21
| 291,239 |
def purelin(n):
"""
Linear Transfer Function
:param int n:Net Input of Neuron
:return: Compute purelin(n)=n
:rtype: int
"""
return n
|
79115d62260775d8be3aef5bbffd33b9e3526848
| 537,182 |
def flatten_list(nest_list):
"""
嵌套列表压扁成一个列表
:param nest_list: 嵌套列表
:return: list
"""
result = []
for item in nest_list:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result
|
00d6eed3772f6bfc43bc4f3915a3351dfebe65b6
| 303,775 |
def is_functioncall(reg):
"""Returns whether a Pozyx register is a Pozyx function."""
if (0xB0 <= reg <= 0xBC) or (0xC0 <= reg < 0xC9):
return True
return False
|
0361199ad60446224741948c2af25e24a53ac362
| 346,910 |
def nodes(G):
"""Returns an iterator over the graph nodes."""
return G.nodes()
|
3a1a543f1af4d43c79fd0083eb77fedd696547ec
| 2,821 |
from typing import Iterable
from typing import List
def indent(level: int, lines: Iterable[str]) -> List[str]:
"""
Indent the lines by the specified level.
"""
return [' ' * level + line for line in lines]
|
9fea8a60c3dfa9f91b49c39167cd3dadf1b21604
| 646,305 |
import re
def regex_capture(pattern, list_of_strings, take_index=0):
"""Apply regex `pattern` to each string and return a captured group.
pattern : string, regex pattern
list_of_strings : list of strings to apply the pattern to
Strings that do not match the pattern are ignored.
take_index : The index of the captured group to return
Returns: a list of strings. Each element is the captured group from
one of the input strings.
"""
res_l = []
for s in list_of_strings:
m = re.match(pattern, s)
# Append the capture, if any
if m is not None:
res_l.append(m.groups()[take_index])
return res_l
|
ec5f08ec9885ad2f6bca54f34923716c2e04c0a5
| 404,339 |
def format_datetime(value, format='short'):
"""Filtro que transforma un datetime en str con formato.
El filtro es para ser usado en plantillas JINJA2.
Los formatos posibles son los siguientes:
* short: dd/mm/aaaa
* full: dd de mm de aaaa
:param datetime value: Fecha a ser transformada.
:param format: Formato con el que mostrar la fecha. Valores posibles: short y full.
:return: Un string con formato de la fecha.
"""
value_str = None
if not value:
value_str = ''
if format == 'short':
value_str = value.strftime('%d/%m/%Y')
elif format == 'full':
value_str = value.strftime('%d de %m de %Y')
else:
value_str = ''
return value_str
|
61708656a69ca928443d38e59d37935e3e29e4e3
| 348,217 |
def _GetPermissionErrorDetails(error_info):
"""Looks for permission denied details in error message.
Args:
error_info: json containing error information.
Returns:
string containing details on permission issue and suggestions to correct.
"""
try:
if 'details' in error_info:
details = error_info['details'][0]
if 'detail' in details:
return details['detail']
except (ValueError, TypeError):
pass
return None
|
0401e6a9fbc1de0a3ed3515de569b7cd21d70fcc
| 292,785 |
def find_child(parent, child_tag, id=None):
"""
Find an element with *child_tag* in *parent* and return ``(child, index)``
or ``(None, None)`` if not found. If *id* is provided, it will be searched
for, otherwise the first child will be returned.
"""
for i, child in enumerate(list(parent)):
if child.tag == child_tag:
if id is None:
return (child, i)
child_id = child.find(f'{child_tag}ID').text
if child_id == id:
return (child, i)
if child_id.split(',')[-1] == id.split(',')[-1]:
return (child, i)
return (None, None)
|
ebc9b9bb6ba7ed78efc7a094478b22de1769ccb9
| 48,712 |
def split_datetime(a_datetime):
"""Given a datetime.datetime, return a 2-tuple of (datetime.date, datetime.time)."""
return (a_datetime.date(), a_datetime.time())
|
1647fc742e14e8e880b0f2be0e946a4446071b6c
| 61,628 |
def format_option_for_gamess(opt, val, lop_off=True):
"""Reformat `val` for option `opt` from python into GAMESS-speak."""
text = ''
# Transform booleans into Fortran booleans
if str(val) == 'True':
text += '.true.'
elif str(val) == 'False':
text += '.false.'
# No Transform
else:
text += str(val).lower()
if lop_off:
return opt[7:].lower(), text
else:
return opt.lower(), text
|
c295735cae19ef7e687e3d0f2e9770fd6807a694
| 362,155 |
import requests
def is_valid(email, password):
""" Method to Validate SUSI Login Details
:param email: SUSI Sign-in email
:param password: SUSI Sign-in password
:return: boolean to indicate if details are valid
"""
print('Checking the validity of login details ....')
params = {
'login': email,
'password': password
}
sign_in_url = 'http://api.susi.ai/aaa/login.json?type=access-token'
api_response = requests.get(sign_in_url, params)
if api_response.status_code == 200:
return True
else:
return False
|
90cd3ba23d70e61d7af376603391cdc84b8aced8
| 484,802 |
def deep_encode(e, encoding='ascii'):
"""
Encodes all strings using encoding, default ascii.
"""
if isinstance(e, dict):
return dict((i, deep_encode(j, encoding)) for (i, j) in e.items())
elif isinstance(e, list):
return [deep_encode(i, encoding) for i in e]
elif isinstance(e, str):
e = e.encode(encoding)
return e
|
6541695e741cb2f47d7d2fe87a45f1d8d8ca67fe
| 48,742 |
import re
def is_correct_vector_v3(vector):
"""
Checks whether CVSSv3 base vector is valid.
:param vector: base vector of CVSSv3 (string)
:return: True if valid
"""
return vector is not None \
and re.match(r'(CVSS:3\.0/)?AV:[NALP]/AC:[LH]/PR:[NLH]/UI:[NR]/S:[UC]/C:[NLH]/I:[NLH]'
r'/A:[NLH](/E:[XUPFH]/RL:[XOTWU]/RC:[XURC])?', vector)
|
b091826c5f99ca7f41888f950086f983ddbd1f8b
| 582,378 |
import logging
def _getFormatter(verbose=False):
"""Get log formatter.
Args:
verbose: True if a more verbose log format is desired.
Returns:
logging.Formatter object.
"""
base_formatting = '[%(levelname)s] %(message)s'
if verbose:
formatter = logging.Formatter('[%(process)s] (%(asctime)s) {}'.format(base_formatting),
datefmt='%Y-%m-%d %H:%M:%S')
else:
formatter = logging.Formatter(base_formatting)
return formatter
|
79e629938d208c06c996b804b779f9cf6c1928cb
| 308,746 |
def get_rendered(font, text, color, cache):
"""Simple font renderer that caches render."""
if text in cache:
image = cache[text]
else:
image = font.render(text, 0, color)
cache[text] = image
return image
|
13557f705882da5865812a0be86cf8b46b95e202
| 29,849 |
def parser(response):
"""Parses the json response from CourtListener /opinions endpoint."""
results = response.get("results")
if not results:
return []
ids = []
for result in results:
_id = result.get("id", None)
if _id is not None:
ids.append(_id)
return ids
|
9632ba800b5de4978aa1c85615dfdeb389bfe5ca
| 650,076 |
def parseMovie(line):
"""
Parses a movie record in MovieLens format movieId::movieTitle .
"""
fields = line.split("::")
return int(fields[0]), fields[1]
|
adb5d04b59eced65b2ca5e477624401d199499d4
| 621,037 |
def str_ellipsis(string: str, max_length: int = 40) -> str:
"""
Reduces the length of a given string, if it is over a certain length, by inserting str_ellipsis.
Args:
string: The string to be reduced.
max_length: The maximum length of the string.
Returns:
A string with a maximum length of :param:max_length.
"""
if len(string) <= max_length:
return string
n_2 = int(max_length) / 2 - 3
n_1 = max_length - n_2 - 3
return "{0}...{1}".format(string[: int(n_1)], string[-int(n_2) :])
|
dd3db6981703277dcb5a04a2839a638ebba18209
| 343,942 |
import csv
def detect(stream):
"""Returns True if given stream is valid CSV."""
try:
csv.Sniffer().sniff(stream, delimiters=',')
return True
except (csv.Error, TypeError):
return False
|
92dfeb58c4505fd9843ec1463ba6ae88349dd8d9
| 681,834 |
def default_get_new_authority_record_details(model, authority):
"""Return a tuple of id and URL for a new authority record. This
function provides a default implementation.
Arguments:
model -- AuthorityRecord model class
authority -- Authority object
"""
prefix = 'entity-'
try:
last_id = model.objects.filter(authority=authority).order_by(
'-authority_system_id')[0].authority_system_id
except IndexError:
last_id = '%s000000' % prefix
number = int(last_id[-6:]) + 1
id = '%s%06d' % (prefix, number)
# QAZ: add a sanity check that the generated ID does not already
# exist, due to using multiple schemes over time for ID
# generation.
data = {'id': id, 'is_complete_id': True,
'url': '%s.html' % (id), 'is_complete_url': False}
return data
|
33386ca9b14621faaad6982ecab781b834ce905b
| 307,795 |
def with_vars(carry_vars):
"""Generate WITH statement using the input variables to carry."""
return "WITH {} ".format(", ".join(carry_vars))
|
fb98749d74fffad6d9b5218cec7db5ecd8a6da6b
| 379,563 |
import json
def read_json(param, filename='../secret.json'):
"""Return result of a given parameter from a JSON file
param - dictionary key within specified file
filename - path to JSON file
"""
with open(filename, 'r') as json_file:
json_string = json_file.read()
datastore = json.loads(json_string)
if param in datastore:
return datastore[param]
else:
raise ValueError('Error: `{}` not in: {}'.format(param, json_string))
|
5d0a5b10f77109f584c9f788ce3551ed5965bb20
| 165,445 |
def cli(ctx, files):
"""Show file information
Output:
List of files containing info
"""
return ctx.gi.file.describe(files)
|
7e1842289d59d02d8f219ca57990065c3d7d5134
| 542,375 |
import math
def clip_text(text, max_len):
"""
Clip text to max length, adding ellipses.
"""
if len(text) > max_len:
begin_text = ' '.join(text[: math.floor(0.8 * max_len)].split(' ')[:-1])
end_text = ' '.join(
text[(len(text) - math.floor(0.2 * max_len)) :].split(' ')[1:]
)
if len(end_text) > 0:
text = begin_text + ' ...\n' + end_text
else:
text = begin_text + ' ...'
return text
|
5f543b9de53f9069320ac42fb13a9fc53a17037d
| 467,401 |
def get_features_and_target(df):
"""
Takes a full dataset as argument and returns the corresponding X (features)
and y (target) dataframes.
"""
X = df.iloc[:, df.columns != 'hotel_cluster']
# Deals with the case where the dataframe is the test one
y = df['hotel_cluster'] if 'hotel_cluster' in df.columns else None
return X, y
|
e4d2cb66a0dedfbaa6d8e9174aad622ae7b775c2
| 471,170 |
def generate_ordered_sequences(waypoint_lists):
"""
Given an ordered list of lists of possible choices, generate all possible
ordered sequences.
"""
sequences = []
if len(waypoint_lists) == 0:
return []
if len(waypoint_lists) > 1:
for node in waypoint_lists[0]:
for child in generate_ordered_sequences(waypoint_lists[1:]):
if type(child) == list:
sequences.append([node] + child)
else:
sequences.append([node] + [child])
else:
sequences = waypoint_lists[0]
return sequences
|
8bb0fe184b1c98bbfc769b90473b77719e59eec0
| 90,199 |
def calculate_checksum(message: bytes) -> bytes:
"""Calculates the checksum for a message.
The message should not have a checksum appended to it.
Returns:
The checksum, as a byte sequence of length 2.
"""
return sum(message).to_bytes(2, byteorder='big')
|
5816446fc06bb573282fcf53aa01656b183a4ace
| 358,284 |
def attach_ordinal(num):
"""Convert an integer to an ordinal string, e.g. 2 -> '2nd'."""
suffixes = {str(i): v
for i, v in enumerate(['th', 'st', 'nd', 'rd', 'th',
'th', 'th', 'th', 'th', 'th'])}
v = str(num)
# special case early teens
if v in {'11', '12', '13'}:
return v + 'th'
return v + suffixes[v[-1]]
|
dc54c9919af1b64e217ca552ffacd01becec989b
| 609,526 |
def splitwords(line, sep=','):
"""Split a line into words using `sep`. Instances of `sep` within
quotes are ignored as separators.
>>> splitwords('ID=GQ,Number=1,Type=Float,Description="Genotype Quality"')
['ID=GQ', 'Number=1', 'Type=Float', 'Description=Genotype Quality']
>>> splitwords('ID=GQ,Number=1,Type=Float,Description="Genotype, Quality"')
['ID=GQ', 'Number=1', 'Type=Float', 'Description=Genotype, Quality']
"""
words = []
inquote = 0
prevc = w = ''
for c in line:
if c == sep:
if prevc == '\\':
w += c
continue
if not inquote:
words.append(w)
w = ''
else:
w += c
elif c == '"' and prevc != '\\':
if inquote:
words.append(w)
w = ''
inquote = False
else:
inquote = True
else:
w += c
prevc = c
if w:
words.append(w)
return words
|
6fc82d26eccdd10842e3b647597ae74fdbb25e4f
| 313,662 |
def patch_response(response):
"""
returns Http response in the format of
{
'status code': 200,
'body': body,
'headers': {}
}
"""
return {
'statusCode': response.status_code,
'headers': dict(response.headers),
'body': response.content.decode(),
'isBase64Encoded': False,
}
|
4a4f073e8fa242803b83508c4e581e0be2020fff
| 652,846 |
def set_size(width, fraction=1, subplots=(1, 1)):
"""
Set figure dimensions to avoid scaling in LaTeX.
"""
golden_ratio = 1.618
height = (width / golden_ratio) * (subplots[0] / subplots[1])
return width, height
|
109f185ba76081532b2be9c9945625f13da99fc8
| 113,791 |
def _container_exists(blob_service_client, container):
"""Check if container exists"""
return next(blob_service_client.list_containers(container), None) is not None
|
d59f7e517876f093bbba8a580dd3fe31895075e2
| 689,664 |
def isfloat(n):
"""Checks if number is a float."""
num = str(n)
if "." in num:
return True
return False
|
95947e63a7eb0a44b8c5b7a99999267884d8fe1a
| 294,245 |
def get_grid(context, grid_id):
"""
Returns the sprytile_grid with the given id
:param context: Blender tool context
:param grid_id: grid id
:return: sprytile_grid or None
"""
mat_list = context.scene.sprytile_mats
for mat_data in mat_list:
for grid in mat_data.grids:
if grid.id == grid_id:
return grid
return None
|
c29223b2a972dad49446d257ce1b0b619a344d7f
| 133,299 |
def list_users_with_grants(mydb):
"""
Get an array of tuples containing database users and their databases.
Args:
mydb - A connected MySQL connection
Return:
An array of tuples ( user, host, database )
"""
databases = []
cursor = mydb.cursor()
cursor.execute('SELECT User, Host, Db FROM mysql.db WHERE User<>"root";')
while True:
rows = cursor.fetchmany(20)
if not rows:
break
for rowset in rows:
user = rowset[0].decode("utf-8")
host = rowset[1].decode("utf-8")
database = rowset[2].decode("utf-8")
databases.append(( user, host, database ))
return databases
|
8ddaad5d4942af8b952f17330e3d0f11861c3206
| 414,181 |
def int_to_bytes(i):
"""Convert int to bytes
"""
return i.to_bytes(8, "big")
|
3f10c96663bab191dd5f8ccf24a83878985016e7
| 102,988 |
def uppercase(value):
"""
Returns the string with all alpha characters in uppercase
"""
return value.upper()
|
bf2de90f329ae57e6a11c9d64bd178814c316623
| 265,403 |
def hostname(fqdn):
"""Return hostname part of FQDN."""
return fqdn.partition('.')[0]
|
2def763bcc2dc9112314414a9f43621235f100ff
| 693,334 |
import json
def load_json_file(filepath):
"""Load content of json-file from `filepath`"""
with open(filepath, 'r') as json_file:
return json.load(json_file)
|
578575a6398c3e803613b8b4277043bcab08191c
| 101,348 |
def status_button_class(x):
"""A little helper function that takes a status value and returns a
bootstrap button class so that report follow up are displayed
consistently across the site.
Options here reflect status choices in tfat.models:
STATUS_CHOICES = [
# (0, "Not Requested"),
("requested", "Requested"),
("initialized", "Initialized"),
("completed", "Completed"),
]
"""
if x == "requested":
btnClass = "btn-danger"
elif x == "initialized":
btnClass = "btn-warning"
elif x == "completed":
btnClass = "btn-success"
else:
btnClass = "btn-default"
return btnClass
|
937f171c828e2a5339e6f0c974290190e2c49a1a
| 403,173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.