seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def gf_neg(f, p, K):
"""Negate a polynomial in `GF(p)[x]`. """
return [ -coeff % p for coeff in f ] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def tvr_loss(y):
"""Calculate Total Variation Regularization Loss of Generated Image"""
loss = torch.sum(torch.abs(y[:, :, :, :-1] - y[:, :, :, 1:])) + torch.sum(
torch.abs(y[:, :, :-1, :] - y[:, :, 1:, :])
)
return loss | bigcode/self-oss-instruct-sc2-concepts |
def transform_to_factory_kwargs(data, original_kwargs=None, prefix=""):
"""
Transforms factory data into the correct kwargs to pass to the factory
Args:
data (dict): dictionary of data from the factory_data file
original_kwargs (dict): kwargs passed into the factory function from code
prefix (str): argument prefix string
Returns:
dict: the generate kwargs to call the factory with
"""
if original_kwargs is None:
original_kwargs = {}
kwargs = {
key: value for key, value in original_kwargs.items() if key not in data.keys()
}
for key, value in data.items():
prefixed_key = "{}__{}".format(prefix, key) if prefix else key
if original_kwargs is not None and prefixed_key in original_kwargs:
kwargs[prefixed_key] = original_kwargs[prefixed_key]
elif isinstance(value, dict):
kwargs.update(transform_to_factory_kwargs(value, prefix=prefixed_key))
elif isinstance(value, list):
kwargs[prefixed_key] = [
transform_to_factory_kwargs(item, prefix=prefixed_key) for item in value
]
else:
kwargs[prefixed_key] = value
return kwargs | bigcode/self-oss-instruct-sc2-concepts |
def can_user_perform(user, account_id, action):
"""
Utility method for checking arbitrary actions are applicable to a specific account for a user.
:param user: A dict object representing user
:param account: A string representing an AWS account to validate permission for.
:param action: A string representing an action to check for.
:return (bool, str): Bool for whether or not permission exists, String for justification.
"""
if 'accounts' in user and account_id in user['accounts']:
if 'permissions' in user['accounts'][account_id] and action in user['accounts'][account_id]['permissions']:
if user['accounts'][account_id]['permissions'][action]:
return True, 'User has explicit permission for account {}.'.format(account_id)
return False, 'User does not have rights for account {}.'.format(account_id) | bigcode/self-oss-instruct-sc2-concepts |
def run_single_identify(run_identify): # pylint: disable=redefined-outer-name
"""
Fixture to run the identification step for a given sample file which should
contain only one cluster, and return the result for that cluster.
"""
def inner(sample_name):
res = run_identify(sample_name)
assert len(res) == 1
return res[0]
return inner | bigcode/self-oss-instruct-sc2-concepts |
import re
def parseNeighbors(urls):
"""Parses a urls pair string into urls pair."""
parts = re.split(r'\s+', urls)
return parts[0], parts[1] | bigcode/self-oss-instruct-sc2-concepts |
def join_lines(strings):
"""
Stack strings horizontally.
This doesn't keep lines aligned unless the preceding lines have the same length.
:param strings: Strings to stack
:return: String consisting of the horizontally stacked input
"""
liness = [string.splitlines() for string in strings]
return '\n'.join(''.join(lines) for lines in zip(*liness)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def wrap_line(line, breakable_regex, line_cont,
base_indent=0, max_width=80, rewrap=False):
"""Wrap the given line within the given width.
This function is going to be exported to be used by template writers in
Jinja as a filter.
Parameters
----------
line
The line to be wrapped.
breakable_regex
The regular expression giving the places where the line can be broke.
The parts in the regular expression that needs to be kept can be put in
a capturing parentheses.
line_cont
The string to be put by the end of line to indicate line continuation.
base_indent
The base indentation for the lines.
max_width
The maximum width of the lines to wrap the given line within.
rewrap
if the line is going to be rewrapped.
Return
------
A list of lines for the breaking of the given line.
"""
# First compute the width that is available for actual content.
avail_width = max_width - base_indent - len(line_cont)
# Remove all the new lines and old line-continuation and indentation for
# rewrapping.
if rewrap:
line = re.sub(
line_cont + '\\s*\n\\s*', '', line
)
# Break the given line according to the given regular expression.
trunks = re.split(breakable_regex, line)
# Have a shallow check and issue warning.
for i in trunks:
if len(i) > avail_width:
print('WARNING')
print(
'Trunk {} is longer than the given width of {}'.format(
i, max_width
)
)
print('Longer width or finer partition can be given.')
continue
# Actually break the list of trunks into lines.
lines = []
curr_line = ''
for trunk in trunks:
if len(curr_line) == 0 or len(curr_line) + len(trunk) <= avail_width:
# When we are able to add the trunk to the current line. Note that
# when the current line is empty, the next trunk will be forced to
# be added.
curr_line += trunk
else:
# When the current line is already filled up.
#
# First dump the current line.
lines.append(curr_line)
# Then add the current trunk at the beginning of the next line. The
# left spaces could be striped.
curr_line = trunk.lstrip()
# Go on to the next trunk.
continue
else:
# We need to add the trailing current line after all the loop.
lines.append(curr_line)
# Before returning, we need to decorate the lines with indentation and
# continuation suffix.
decorated = [
''.join([
' ' * base_indent, v, line_cont if i != len(lines) - 1 else ''
])
for i, v in enumerate(lines)
]
return '\n'.join(decorated) | bigcode/self-oss-instruct-sc2-concepts |
def makehist(vals, incr=1, normalize=0):
"""Makes a histogram for the given vals and returns a dict.
Incr is how much each item counts for
If normalize is true, then the sum of return values is normalize.
"""
ret = {}
sum = 0
for v in vals:
if v not in ret:
ret[v] = 0
ret[v] += incr
sum += incr
if normalize:
for k in ret:
ret[k] *= (normalize/sum)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def gravity(z, g0, r0):
"""Relates Earth gravity field magnitude with the geometric height.
Parameters
----------
z: ~astropy.units.Quantity
Geometric height.
g0: ~astropy.units.Quantity
Gravity value at sea level.
r0: ~astropy.units.Quantity
Planet/Natural satellite radius.
Returns
-------
g: ~astropy.units.Quantity
Gravity value at given geometric altitude.
"""
g = g0 * (r0 / (r0 + z)) ** 2
return g | bigcode/self-oss-instruct-sc2-concepts |
def first(lst):
"""Return the first element of the given list - otherwise return None"""
return lst[0] if lst else None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import requests
def validate_request_success(resp: Union[requests.Response, str]):
"""
Validate the response from the webhook request
"""
return not isinstance(resp, str) and resp.status_code in [200, 201] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Optional
import re
def filter_list(arr: List[str], pattern: Optional[str] = None) -> List[str]:
"""Filter a list of strings with given pattern
```python
>> arr = ['crossentropy', 'binarycrossentropy', 'softmax', 'mae',]
>> filter_list(arr, ".*entropy*")
>> # ["crossentropy", "binarycrossentropy"]
```
"""
if pattern is None:
return arr
p = re.compile(pattern)
return [s for s in arr if p.match(s)] | bigcode/self-oss-instruct-sc2-concepts |
def prepend_zeros(length, string):
"""
Prepend zeros to the string until the desired length is reached
:param length: the length that the string should have
:param string: the string that we should appends 0's to
:return: A string with zeros appended
"""
return "{}{}".format("0" * (length - len(string)), string) | bigcode/self-oss-instruct-sc2-concepts |
def plus_haut(points):
""" Trouve le point (xb, yb) le plus en haut à droite, en temps linéaire."""
n = len(points)
xb, yb = points[0]
for j in range(1, n):
xj, yj = points[j]
if (yb < yj) or (yb == yj and xb < xj):
xb, yb = xj, yj
return xb, yb | bigcode/self-oss-instruct-sc2-concepts |
import string
def build_link_exp_decay(adj, weight, words_map, words, from_index, to_index, max_dist, stopwords, links_to_stopwords=True, self_links=False):
"""
Builds a link from a given word in the graph to another word at a defined index.
The farther the other word, the smaller the edge between them.
In this variant, the weight of the edges decays exponentially with the distance
"""
words_len = len(words)
links_made = 0
while to_index < words_len and (words[to_index] in string.punctuation or (not links_to_stopwords and words[to_index] in stopwords) or (not self_links and words[to_index] == words[from_index])):
to_index += 1
weight /= 2
if (to_index - from_index) <= max_dist and to_index < len(words):
links_made = 1
adj[words_map[words[from_index]], words_map[words[to_index]]] = adj[words_map[words[from_index]], words_map[words[to_index]]] + weight
weight /= 2
return weight, to_index + 1, links_made | bigcode/self-oss-instruct-sc2-concepts |
def try_decode(obj: bytes, encoding="utf-8"):
"""
Try decode given bytes with encoding (default utf-8)
:return: Decoded bytes to string if succeeded, else object itself
"""
try:
rc = obj.decode(encoding=encoding)
except AttributeError:
rc = obj
return rc.strip() | bigcode/self-oss-instruct-sc2-concepts |
def apply_parent_validation(clazz, error_prefix=None):
"""
Decorator to automatically invoke parent class validation before applying
custom validation rules. Usage::
class Child(Parent):
@apply_parent_validation(Child, error_prefix="From Child: ")
def validate(data):
# I can assume now that the parent validation method succeeded.
# ...
"""
def decorator(func):
def inner(self, data):
base_validation = clazz.validate(self, data)
if base_validation != True:
if error_prefix is not None:
return error_prefix + base_validation
return base_validation
return func(self, data)
return inner
return decorator | bigcode/self-oss-instruct-sc2-concepts |
def mean(mylist):
"""
function to take the mean of a list
Parameters
----------
mylist : list
list of numbers to take a mean
Returns
-------
mean_list : float
The mean of the list.
Examples
--------
>>> mean([1,2,3,4,5,6,7])
4.0
"""
if not isinstance(mylist, list):
raise TypeError("Mean: %s is not a list!" % mylist)
return (sum(mylist) / len(mylist)) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def reduce_get(cfg: dict, key: str):
"""
gets value from dictionary based on flat 'key' provided
e.g. instead of dict1["alpha"]["beta"]["gamma"], we do: key = "alpha.beta.gamma"
:param cfg: config dictionary
:param key: flat key e.g. "alpha.beta.gamma"
:return: value from dictionary
"""
return reduce(lambda c, k: c[k], key.split('.'), cfg) | bigcode/self-oss-instruct-sc2-concepts |
def traverse(node, order="pre-order", include_terminal=True, acc=None):
"""
Parameters
----------
node: NonTerminal or Terminal
order: str, default "pre-order"
include_terminal: bool, default True
acc: list[T] or None, default None
T -> NonTerminal or Terminal
Returns
-------
list[T]
T -> NonTerminal or Terminal
"""
if acc is None:
acc = []
if node.is_terminal():
if include_terminal:
acc.append(node)
return acc
if order == "pre-order":
# Process the current node
acc.append(node)
# Process the child nodes
for c in node.children:
acc = traverse(c, order=order, include_terminal=include_terminal, acc=acc)
elif order == "post-order":
# Process the child nodes
for c in node.children:
acc = traverse(c, order=order, include_terminal=include_terminal, acc=acc)
# Process the current node
acc.append(node)
else:
raise ValueError("Invalid order=%s" % order)
return acc | bigcode/self-oss-instruct-sc2-concepts |
def safe_open(path):
""" If the file can be opened, returns a file handle; otherwise None."""
try:
return open(path, 'rb')
except (IOError, PermissionError, FileNotFoundError):
return None | bigcode/self-oss-instruct-sc2-concepts |
def getAllReachable1Step(original_nodes):
"""
return all node, value pairs reachable from any of the pairs in the original nodes in a single step
:param original_nodes: a set of node, value, complete_path pairs from which we check what they can reach in 1 step
:return: a set of node, value pairs that can be reached from any of original_nodes in a single step
"""
reachable = set()
for node in original_nodes: # for each node in our set, we gather it's reachable states and add them to our result
lis = node[0].get_edges()
for new_node in lis: # a newly reachable node is only reachable by another node, each node can only have V-1 O(V) outgoing edges
if node[1] + new_node[1] >= 0 and node[1] + new_node[1] not in new_node[0].get_disequalities():
# check if this node does not infringe upon any disequalities or other rules
tup = (new_node[0], node[1] + new_node[1])
reachable.add(tup)
return reachable | bigcode/self-oss-instruct-sc2-concepts |
def select_zmws(zmws, min_requested_bases):
"""
>>> select_zmws([], 0)
([], 0)
>>> select_zmws([], 10)
([], 0)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 10)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4'], 15)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 20)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4', 'zmw/5'], 25)
>>> select_zmws([('zmw/1', 1), ('zmw/1', 2), ('zmw/1', 5), ('zmw/1', 7), ('zmw/1', 10), ('zmw/1', 15)], 20)
(['zmw/1', 'zmw/1', 'zmw/1', 'zmw/1', 'zmw/1'], 25)
"""
# Select the first N ZMWs which sum up to the desired coverage.
num_bases = 0
subsampled_zmws = []
for zmw_name, seq_len in zmws:
num_bases += seq_len
subsampled_zmws.append(zmw_name)
if num_bases >= min_requested_bases:
break
return subsampled_zmws, num_bases | bigcode/self-oss-instruct-sc2-concepts |
def preprocess(sample):
"""Preprocess a single sample."""
return sample | bigcode/self-oss-instruct-sc2-concepts |
def point_on_rectangle(rect, point, border=False):
"""
Return the point on which ``point`` can be projecten on the
rectangle. ``border = True`` will make sure the point is bound to
the border of the reactangle. Otherwise, if the point is in the
rectangle, it's okay.
>>> point_on_rectangle(Rectangle(0, 0, 10, 10), (11, -1))
(10, 0)
>>> point_on_rectangle((0, 0, 10, 10), (5, 12))
(5, 10)
>>> point_on_rectangle(Rectangle(0, 0, 10, 10), (12, 5))
(10, 5)
>>> point_on_rectangle(Rectangle(1, 1, 10, 10), (3, 4))
(3, 4)
>>> point_on_rectangle(Rectangle(1, 1, 10, 10), (0, 3))
(1, 3)
>>> point_on_rectangle(Rectangle(1, 1, 10, 10), (4, 3))
(4, 3)
>>> point_on_rectangle(Rectangle(1, 1, 10, 10), (4, 9), border=True)
(4, 11)
>>> point_on_rectangle((1, 1, 10, 10), (4, 6), border=True)
(1, 6)
>>> point_on_rectangle(Rectangle(1, 1, 10, 10), (5, 3), border=True)
(5, 1)
>>> point_on_rectangle(Rectangle(1, 1, 10, 10), (8, 4), border=True)
(11, 4)
>>> point_on_rectangle((1, 1, 10, 100), (5, 8), border=True)
(1, 8)
>>> point_on_rectangle((1, 1, 10, 100), (5, 98), border=True)
(5, 101)
"""
px, py = point
rx, ry, rw, rh = tuple(rect)
x_inside = y_inside = False
if px < rx:
px = rx
elif px > rx + rw:
px = rx + rw
elif border:
x_inside = True
if py < ry:
py = ry
elif py > ry + rh:
py = ry + rh
elif border:
y_inside = True
if x_inside and y_inside:
# Find point on side closest to the point
if min(abs(rx - px), abs(rx + rw - px)) > min(abs(ry - py), abs(ry + rh - py)):
if py < ry + rh / 2.0:
py = ry
else:
py = ry + rh
else:
if px < rx + rw / 2.0:
px = rx
else:
px = rx + rw
return px, py | bigcode/self-oss-instruct-sc2-concepts |
def for_teuthology(f):
"""
Decorator that adds an "is_for_teuthology" attribute to the wrapped function
"""
f.is_for_teuthology = True
return f | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def loadpfile(path: str) -> list:
"""
Loads whatever object is contained in the pickle file.
Args:
path: file path
Returns:
some object
"""
return pickle.load(open(path, 'rb')) | bigcode/self-oss-instruct-sc2-concepts |
def single_number(nums):
"""
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Args:
nums: list[int]
Returns:
int
"""
# Method 1
nums = sorted(nums)
for i in range(0, len(nums) - 2, 2):
if nums[i] != nums[i + 1]:
return nums[i]
return nums[-1]
# Method 2
# 1) N XOR N = 0
# 2) XOR is associative & commutative
res = 0
for num in nums:
res ^= num
return res | bigcode/self-oss-instruct-sc2-concepts |
def bin_search(query, data):
""" Query is a coordinate interval. Binary search for the query in sorted data,
which is a list of coordinates. Finishes when an overlapping value of query and
data exists and returns the index in data. """
i = int(round(len(data)/2)) # binary search prep
lower, upper = 0, len(data)
while True:
if upper - lower < 2: # stop condition but not necessarily found
break
if data[i][1] < query[0]:
lower = i
i = int(round((i + upper)/2))
elif data[i][0] > query[1]:
upper = i
i = int(round((lower + i)/2))
else: # found
break
return i | bigcode/self-oss-instruct-sc2-concepts |
def _nsec_to_usec_round(nsec: int) -> int:
"""Round nanoseconds to microseconds"""
return (nsec + 500) // 10 ** 3 | bigcode/self-oss-instruct-sc2-concepts |
def _ord(i):
"""Converts a 1-char byte string to int.
This function is used for python2 and python3 compatibility
that can also handle an integer input.
Args:
i: The 1-char byte string to convert to an int.
Returns:
The byte string value as int or i if the input was already an
integer.
"""
if isinstance(i, int):
return i
else:
return ord(i) | bigcode/self-oss-instruct-sc2-concepts |
def _compute_temp_terminus(temp, temp_grad, ref_hgt,
terminus_hgt, temp_anomaly=0):
"""Computes the (monthly) mean temperature at the glacier terminus,
following section 2.1.2 of Marzeion et. al., 2012. The input temperature
is scaled by the given temperature gradient and the elevation difference
between reference altitude and the glacier terminus elevation.
Parameters
----------
temp : netCDF4 variable
monthly mean climatological temperature (degC)
temp_grad : netCDF4 variable or float
temperature lapse rate [degC per m of elevation change]
ref_hgt : float
reference elevation for climatological temperature [m asl.]
terminus_hgt : float
elevation of the glacier terminus (m asl.)
temp_anomaly : netCDF4 variable or float, optional
monthly mean temperature anomaly, default 0
Returns
-------
netCDF4 variable
monthly mean temperature at the glacier terminus [degC]
"""
temp_terminus = temp + temp_grad * (terminus_hgt - ref_hgt) + temp_anomaly
return temp_terminus | bigcode/self-oss-instruct-sc2-concepts |
def featuretype_filter(feature, featuretype):
"""
Only passes features with the specified *featuretype*
"""
if feature[2] == featuretype:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def as_latex(ordinal):
"""
Convert the Ordinal object to a LaTeX string.
"""
if isinstance(ordinal, int):
return str(ordinal)
term = r"\omega"
if ordinal.exponent != 1:
term += f"^{{{as_latex(ordinal.exponent)}}}"
if ordinal.copies != 1:
term += rf"\cdot{as_latex(ordinal.copies)}"
if ordinal.addend != 0:
term += f"+{as_latex(ordinal.addend)}"
return term | bigcode/self-oss-instruct-sc2-concepts |
import re
def filter_comments(string):
"""Remove from `string` any Python-style comments ('#' to end of line)."""
comment = re.compile(r'(^|[^\\])#.*')
string = re.sub(comment, '', string)
return string | bigcode/self-oss-instruct-sc2-concepts |
def apply_ants_transform_to_point(transform, point):
"""
Apply transform to a point
ANTsR function: `applyAntsrTransformToPoint`
Arguments
---------
point : list/tuple
point to which the transform will be applied
Returns
-------
tuple : transformed point
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
>>> params = tx.parameters
>>> tx.set_parameters(params*2)
>>> pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6)
"""
return transform.apply_to_point(point) | bigcode/self-oss-instruct-sc2-concepts |
import string
def remove_punctuation(input_string):
"""Remove the punctuations in input string.
Parameters
----------
input_string : string
String to remove punctuations.
Returns
-------
output_string : string
String without punctuations.
"""
out_string =''
for char in input_string:
if not char in string.punctuation:
out_string = out_string + char
return out_string | bigcode/self-oss-instruct-sc2-concepts |
def MigrateUSBPDSpec(spec):
"""Migrate spec from old schema to newest schema.
Args:
spec: An object satisfies USB_PD_SPEC_SCHEMA.
Returns:
An object satisfies USB_PD_SPEC_SCHEMA_V3.
"""
if isinstance(spec, int):
return {
'port': spec
}
if isinstance(spec, (list, tuple)):
return {
'port': spec[0],
'polarity': spec[1]
}
return spec | bigcode/self-oss-instruct-sc2-concepts |
def series_circuit_UA(*args):
"""
Calculates the total U*A-value for a series circuit of two or more U*A
values.
Parameters:
-----------
UA : float, int, np.ndarray
U*A value (heat conductivity) in [W/K] for each part of the series
circuit. If given as np.ndarray, all arrays have to be of the same
shape.
Returns:
--------
UA_series : float, np.ndarray
Total U*A value (heat conductivity) in [W/K] of the series.
"""
UA_series = 1 / args[0] # get inverse of first value
arg_iter = iter(args) # make iterator out of args
next(arg_iter) # skip first entry since it is already taken
for arg in arg_iter: # iterate over the rest of args
UA_series += 1 / arg # sum up inverse values
return 1 / UA_series | bigcode/self-oss-instruct-sc2-concepts |
def mesh_dual(mesh, cls=None):
"""Construct the dual of a mesh.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
A mesh object.
cls : Type[:class:`compas.datastructures.Mesh`], optional
The type of the dual mesh.
Defaults to the type of the provided mesh object.
Returns
-------
:class:`compas.datastructures.Mesh`
The dual mesh object.
"""
if not cls:
cls = type(mesh)
dual = cls()
face_centroid = {face: mesh.face_centroid(face) for face in mesh.faces()}
inner = list(set(mesh.vertices()) - set(mesh.vertices_on_boundary()))
vertex_xyz = {}
face_vertices = {}
for vertex in inner:
faces = mesh.vertex_faces(vertex, ordered=True)
for face in faces:
if face not in vertex_xyz:
vertex_xyz[face] = face_centroid[face]
face_vertices[vertex] = faces
for vertex in vertex_xyz:
x, y, z = vertex_xyz[vertex]
dual.add_vertex(vertex, x=x, y=y, z=z)
for face in face_vertices:
dual.add_face(face_vertices[face], fkey=face)
return dual | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def site_catalog(site):
"""
Returns a dictionary of CWMS data paths for a particular site
Arguments:
site -- cwms site name, example TDDO
Returns:
json.loads(r.text) -- dictionary of available site data
"""
url = r'http://www.nwd-wc.usace.army.mil/dd/common/web_service/webexec/getjson?tscatalog=%5B%22SITE%22%5D'
url = url.replace('SITE', site.upper())
r = requests.get(url)
return json.loads(r.text) | bigcode/self-oss-instruct-sc2-concepts |
def split_node_lists(num_jobs, total_node_list=None, ppn=24):
"""
Parse node list and processor list from nodefile contents
Args:
num_jobs (int): number of sub jobs
total_node_list (list of str): the node list of the whole large job
ppn (int): number of procesors per node
Returns:
(([int],[int])) the node list and processor list for each job
"""
if total_node_list:
orig_node_list = sorted(list(set(total_node_list)))
nnodes = len(orig_node_list)
if nnodes % num_jobs != 0:
raise ValueError("can't allocate nodes, {} can't be divided by {}".format(
nnodes, num_jobs))
sub_nnodes = nnodes // num_jobs
sub_nproc_list = [sub_nnodes * ppn] * num_jobs
node_lists = [orig_node_list[i:i + sub_nnodes] for i in range(0, nnodes, sub_nnodes)]
else:
sub_nproc_list = [ppn] * num_jobs
node_lists = [None] * num_jobs
return node_lists, sub_nproc_list | bigcode/self-oss-instruct-sc2-concepts |
def undo_keypoint_normalisation(normalised_keypoints, img_wh):
"""
Converts normalised keypoints from [-1, 1] space to pixel space i.e. [0, img_wh]
"""
keypoints = (normalised_keypoints + 1) * (img_wh/2.0)
return keypoints | bigcode/self-oss-instruct-sc2-concepts |
def output_aws_credentials(awscreds, awsaccount):
"""
Format the credentials as a string containing the commands to define the ENV variables
"""
aws_access_key_id = awscreds["data"]["access_key"]
aws_secret_access_key = awscreds["data"]["secret_key"]
shellenv_access = "export AWS_ACCESS_KEY_ID=%s" % aws_access_key_id
shellenv_secret = "export AWS_SECRET_ACCESS_KEY=%s" % aws_secret_access_key
results = "%s && %s" % (shellenv_access, shellenv_secret)
return results | bigcode/self-oss-instruct-sc2-concepts |
def get_phase_refr_index(wlen):
"""Get the phase refractive index for ice as a function of wavelength.
See: https://wiki.icecube.wisc.edu/index.php/Refractive_index_of_ice#Numerical_values_for_ice
or eqn 3 in https://arxiv.org/abs/hep-ex/0008001v1
Parameters
----------
wlen
Wavelength in units of nm
Returns
-------
n
Phase refractive index.
"""
# Convert wavelength to micrometers
wl_um = wlen/1000
return 1.55749 - 1.57988*wl_um + 3.99993*wl_um**2 - 4.68271*wl_um**3 + 2.09354*wl_um**4 | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_github_api_token(tok):
"""
Fetch github personal access token (PAT) for gist api request using POST
Parameters
----------
tok : str
PAT if passed as string, else None and will be fetched
"""
if not tok:
tok_path = Path.home() / ".jupyter_to_medium" / "github_token"
tok = open(tok_path).read().splitlines()[0]
return tok | bigcode/self-oss-instruct-sc2-concepts |
def squeeze_axes(shape, axes, skip='XY'):
"""Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
"""
if len(shape) != len(axes):
raise ValueError("dimensions of axes and shape do not match")
shape, axes = zip(*(i for i in zip(shape, axes)
if i[0] > 1 or i[1] in skip))
return tuple(shape), ''.join(axes) | bigcode/self-oss-instruct-sc2-concepts |
def read_padding(fp, size, divisor=2):
"""
Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size
"""
remainder = size % divisor
if remainder:
return fp.read(divisor - remainder)
return b'' | bigcode/self-oss-instruct-sc2-concepts |
def extractDetails(remoteException):
"""Extract the details of an xml-rpc exception error message"""
try:
details = remoteException.faultString or remoteException.message
details = details.split(":", 2)[-1].replace("'>", "").lstrip()
except AttributeError:
details = str(remoteException)
return details.replace('\n', '; ') | bigcode/self-oss-instruct-sc2-concepts |
def fileopen(fun):
""" Open read-only filehandle if first argument is string
This function can be used to decorate functions that expect a filehandle as
the first argument. If the first argument is a string, it is assumed to be
the path to the input file, and the file is opened in read mode.
Args:
fun: A function that expects a read-only filehandle as the first arg.
Returns:
function: A function that expects a path (str) OR filehandle as the
first argument.
"""
def wrapper(*args, **kwargs):
if isinstance(args[0], str):
try:
fh = open(args[0], 'rU')
return fun(fh, *args[1:], **kwargs)
except IOError as e:
raise e
elif hasattr(args[0], 'read'):
return fun(*args, **kwargs)
else:
raise IOError("Unknown argument for fileopen '%s'" % str(args[0]))
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_baseline2(segment_df, rush_hour):
"""
Preprocess the segment data considering the weather and the rush hour
Algorithm:
Preprocess segment_df to add a new column of rush hour
split the dataframe with groupby(segment_start, segment_end, weather, rush_hour)
Define the new dataframe
For name, item in grouped:
calcualte the average travel duration
save the record into the new dataframe
:param segment_df: dataframe after adding the rush hour from final_segment.csv file
:param rush_hour: tuple to express which is the rush hour, example: ('17:00:00', '20:00:00')
:return: dataframe for the baseline2
"""
# Preprocess segment_df to add a new column of rush hour
rush_hour_column = segment_df['timestamp'].apply(lambda x: x[11:19] < rush_hour[1] and x[11:19] > rush_hour[0])
new_segment_df = segment_df
new_segment_df['rush_hour'] = rush_hour_column
grouped = new_segment_df.groupby(['segment_start', 'segment_end', 'weather', 'rush_hour'])
result = grouped['travel_duration'].mean()
result = result.reset_index()
return result | bigcode/self-oss-instruct-sc2-concepts |
def str_remove(string, index, end_index=None):
"""Remove a substring from an existing string at a certain from-to index range."""
end_index = end_index or (index + 1)
return "%s%s" % (string[:index], string[end_index:]) | bigcode/self-oss-instruct-sc2-concepts |
def m_coef(h_septum):
"""
Calculates the specific coefficient for calculation the heigth ligth layer of liquid equation.
Parameters
----------
h_septum : float
The heigth of drain septum, [m]
Returns
-------
m_coef : float
The specific coefficient for this equation [dimensionless]
References
----------
Дытнерский, страница 239, формула 6.39
"""
return 0.05 - h_septum*4.6 | bigcode/self-oss-instruct-sc2-concepts |
def get(conn, uri, access_token=None):
"""
HTTP GET request with an optional authorization header with the access_token
"""
if access_token:
headers = {'authorization': '%s %s' % (access_token['token_type'], access_token['access_token'])}
else:
headers = {}
conn.request('GET', uri, headers=headers)
response = conn.getresponse()
return response.read() | bigcode/self-oss-instruct-sc2-concepts |
def all_true(iterable):
""" Helper that returns true if the iterable is not empty and all its elements evaluate to true. """
items = list(iterable)
return all(items) if items else False | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
import string
import re
def preprocess_names(name, output_sep=' ', firstname_output_letters=1):
"""
Function that outputs a person's name in the format
<last_name><separator><firstname letter(s)> (all lowercase)
>>> preprocess_names("Samuel Eto'o")
'etoo s'
>>> preprocess_names("Eto'o, Samuel")
'etoo s'
>>> preprocess_names("Eto'o,Samuel")
'etoo s'
>>> preprocess_names('Xavi')
'xavi'
>>> preprocess_names('Yaya Touré')
'toure y'
>>> preprocess_names('José Ángel Pozo')
'pozo j'
>>> preprocess_names('Pozo, José Ángel')
'pozo j'
>>> preprocess_names('Pozo, José Ángel', firstname_output_letters=2)
'pozo jo'
>>> preprocess_names("Eto'o, Samuel", firstname_output_letters=2)
'etoo sa'
>>> preprocess_names("Eto'o, Samuel", firstname_output_letters=0)
'etoo'
>>> preprocess_names("Eto'o, Samuel", output_sep=', ')
'etoo, s'
"""
# set first and last name positions
last, first = 'last', 'first'
last_pos = -1
if ',' in name:
last, first = first, last
name = name.replace(',', ' ')
last_pos = 1
spl = name.split()
if len(spl) > 2:
name = '%s %s' % (spl[0], spl[last_pos])
# remove accents
name = ''.join(x for x in unicodedata.normalize('NFKD', name) if x in string.ascii_letters+' ')
# get first and last name if applicable
m = re.match('(?P<first>\w+)\W+(?P<last>\w+)', name)
if m:
output = '%s%s%s' % (m.group(last), output_sep, m.group(first)[:firstname_output_letters])
else:
output = name
return output.lower().strip() | bigcode/self-oss-instruct-sc2-concepts |
def get_domain_from_fqdn(fqdn):
""" Returns domain name from a fully-qualified domain name
(removes left-most period-delimited value)
"""
if "." in fqdn:
split = fqdn.split(".")
del split[0]
return ".".join(split)
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def GetPartitionsByType(partitions, typename):
"""Given a partition table and type returns the partitions of the type.
Partitions are sorted in num order.
Args:
partitions: List of partitions to search in
typename: The type of partitions to select
Returns:
A list of partitions of the type
"""
out = []
for partition in partitions:
if partition.get('type') == typename:
out.append(partition)
return sorted(out, key=lambda partition: partition.get('num')) | bigcode/self-oss-instruct-sc2-concepts |
def is_admin(user):
"""
:param user:
:return True, (str): if user is admin
:return False, (str): is user is not admin
"""
if 'isAdmin' in user and user['isAdmin'] is True:
return True, None
return False, 'user is not authorized' | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
import collections
def _create_ngrams(tokens: List[Any], n: int) -> collections.Counter:
"""Creates ngrams from the given list of tokens.
Args:
tokens: A list of tokens from which ngrams are created.
n: Number of tokens to use, e.g. 2 for bigrams.
Returns:
A dictionary mapping each ngram to the number of occurrences.
"""
ngrams = collections.Counter()
for i in range(len(tokens) - n + 1):
ngrams[tuple(tokens[i:i + n])] += 1
return ngrams | bigcode/self-oss-instruct-sc2-concepts |
def split_group(name):
"""Split item name containing ``'/'`` into tuple of group/subname.
Examples:
- an input of ``'foo/bar'`` results in ``('foo', 'bar')``
- an input of ``'foo/bar/baz'`` results in ``('foo/bar', 'baz')``
"""
return tuple(reversed([x[::-1] for x in name[::-1].split("/", 1)])) | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
async def preprocessor(input_data: str):
"""Simple feature processing that converts str to int"""
await asyncio.sleep(0.1) # Manual delay for blocking computation
return int(input_data) | bigcode/self-oss-instruct-sc2-concepts |
def _power_of_two(value):
"""Returns whether the given value is a power of two."""
return (value & (value - 1)) == 0 | bigcode/self-oss-instruct-sc2-concepts |
def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def _get_norm_procedure(norm, parameter):
"""
Returns methods description of the provided `norm`
Parameters
----------
norm : str
Normalization procedure
Returns
-------
procedure : str
Reporting procedures
"""
if parameter not in ('sample_norm', 'gene_norm'):
raise ValueError(f'Invalid norm parameter {parameter}')
if parameter == 'sample_norm':
mod = ('tissue sample expression values across genes')
suff = ('tissue sample across genes')
else:
mod = ('gene expression values across tissue samples')
suff = ('gene across tissue samples')
sigmoid = r"""
independently for each donor using a sigmoid function [F2016P]:<br>
$$ x_{{norm}} = \frac{{1}}{{1 + \exp(-\frac{{(x - \overline{{x}})}}
{{\sigma_{{x}}}})}} $$<br>
where $\bar{{x}}$ is the arithmetic mean and $\sigma_{{x}}$ is the
sample standard deviation of the expression of a single
"""
robust_sigmoid = r"""
using a robust sigmoid function [F2013J]:<br>
$$ x_{{norm}} = \frac{{1}}{{1 + \exp(-\frac{{(x-\langle x \rangle)}}
{{\text{{IQR}}_{{x}}}})}} $$<br>
where $\langle x \rangle$ is the median and $\text{{IQR}}_{{x}}$
is the normalized interquartile range of the expression of a single
"""
rescale = r"""
Normalized expression values were then rescaled to the unit interval: <br>
$$ x_{{scaled}} = \frac{{x_{{norm}} - \min(x_{{norm}})}}
{{\max(x_{{norm}}) - \min(x_{{norm}})}} $$<br>
"""
procedure = ''
if norm in ['center', 'demean']:
procedure += """
by demeaning {mod} independently for each donor.
""".format(mod=mod)
elif norm == 'zscore':
procedure += """
by mean- and variance-normalizing (i.e., z-scoring) {mod} independently
for each donor.
""".format(mod=mod)
elif norm == 'minmax':
procedure += r"""
by rescaling {mod} to the unit interval independently for each donor:
<br>
$$ x_{{{{scaled}}}} = \frac{{{{x - \min(x)}}}}{{{{\max(x) - \min(x)}}}}
$$<br>
""".format(mod=mod)
elif norm in ['sigmoid', 'sig']:
procedure += r"""
by normalizing {mod} {sigmoid} {suff}.
""".format(mod=mod, sigmoid=sigmoid, suff=suff)
elif norm in ['scaled_sigmoid', 'scaled_sig']:
procedure += r"""
by normalizing {mod} {sigmoid} {suff}. {rescale}
""".format(mod=mod, sigmoid=sigmoid, suff=suff, rescale=rescale)
elif norm in ['scaled_sigmoid_quantiles', 'scaled_sig_qnt']:
procedure += r"""
by normalizing {mod} {sigmoid} {suff}, calculated using only data in
the 5–95th percentile range to downweight the impact of outliers.
{rescale}
""".format(mod=mod, sigmoid=sigmoid, suff=suff, rescale=rescale)
elif norm in ['robust_sigmoid', 'rsig', 'rs']:
procedure += r"""
by normalizing {mod} {robust_sigmoid} {suff}.
""".format(mod=mod, robust_sigmoid=robust_sigmoid, suff=suff)
elif norm in ['scaled_robust_sigmoid', 'scaled_rsig', 'srs']:
procedure += r"""
by normalizing {mod} {robust_sigmoid} {suff}. {rescale}
""".format(mod=mod, robust_sigmoid=robust_sigmoid, suff=suff,
rescale=rescale)
elif norm in ['mixed_sigmoid', 'mixed_sig']:
procedure += r"""
by normalizing {mod} using a mixed sigmoid function [F2013J]:<br>
$$ x_{{{{norm}}}} = \left\{{{{\begin{{{{array}}}}{{{{r r}}}}
\frac{{{{1}}}}{{{{1 + \exp(-\frac{{{{(x-\overline{{{{x}}}})}}}}
{{{{\sigma_{{{{x}}}}}}}})}}}} ,& \text{{{{IQR}}}}_{{{{x}}}} = 0
\frac{{{{1}}}}{{{{1 + \exp(-\frac{{{{(x-\langle x \rangle)}}}}
{{{{\text{{{{IQR}}}}_{{{{x}}}}}}}})}}}} ,& \text{{{{IQR}}}}_{{{{x}}}}
\neq 0 \end{{{{array}}}}\right. $$<br>
where $\bar{{{{x}}}}$ is the arithmetic mean, $\sigma_{{{{x}}}}$ is the
sample standard deviation, $\langle x \rangle$ is the median, and
$\text{{{{IQR}}}}_{{{{x}}}}$ is the normalized interquartile range of
the expression value of a single {suff}. {rescale}
""".format(mod=mod, suff=suff, rescale=rescale)
return procedure | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Union
from typing import List
import json
import base64
def extract_syft_metadata(data: str) -> Dict[str, Union[str, List[str], bytes]]:
"""
Parse metadata from the syft output string
:param data: syft SBOM json string
:type data: str
:return: dict with metadata
:rtype: Dict[str, Union[str, List[str], bytes]]
"""
parsed = json.loads(data)
digest = parsed["source"]["target"]["manifestDigest"]
local_image_id = parsed["source"]["target"]["imageID"]
tags = parsed["source"]["target"]["tags"]
manifest = base64.standard_b64decode(parsed["source"]["target"]["manifest"])
image_config = base64.standard_b64decode(parsed["source"]["target"]["config"])
return {
"digest": digest,
"local_image_id": local_image_id,
"tags": tags,
"manifest": manifest,
"image_config": image_config,
} | bigcode/self-oss-instruct-sc2-concepts |
def getMObjectByMDagPath(dagPath):
"""
Retrieves an MObject from the given MDagPath.
:type dagPath: om.MDagPath
:rtype: om.MObject
"""
return dagPath.node() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def split_series(
series: List,
*,
reserved_ratio: float = 0.2,
test_ratio: float = 0.5,
) -> Tuple[List, List, List]:
"""
Split a series into 3 parts - training, validation and test.
Parameters
----------
series
a time series to be splitted
reserved_ratio
the ratio of data retained for validation and test
test_ratio
the ratio of reserved data to be set for test
Returns
-------
a tuple of training, validation, and test set
"""
training_boundary = int(len(series) * (1 - reserved_ratio))
reserved = series[training_boundary:]
validation_boundary = int(len(reserved) * (1 - test_ratio))
return (
series[:training_boundary],
reserved[:validation_boundary],
reserved[validation_boundary:],
) | bigcode/self-oss-instruct-sc2-concepts |
import datetime
def group_datetime(d, interval):
"""Group datetime in bins."""
seconds = d.second + d.hour * 3600 + d.minute * 60 + d.microsecond / 1000
k = d - datetime.timedelta(seconds=seconds % interval)
return datetime.datetime(k.year, k.month, k.day, k.hour, k.minute, k.second) | bigcode/self-oss-instruct-sc2-concepts |
import re
def regex_match(pattern):
"""A curried regex match. Gets a pattern and returns a function that expects a text to match the pattern with.
>>> regex_match(r"phone:(\d*)")("phone:1234567").group(1) # noqa: W605
'1234567'
"""
def regex_match_inner(text):
return re.match(pattern, text)
return regex_match_inner | bigcode/self-oss-instruct-sc2-concepts |
def public(fun, scope=None, cookie=False):
"""
Functions that allow any client access, including those that haven't logged
in should be wrapped in this decorator.
:param fun: A REST endpoint.
:type fun: callable
:param scope: The scope or list of scopes required for this token.
:type scope: str or list of str or None
:param cookie: if True, this rest endpoint allows the use of a cookie for
authentication. If this is specified on routes that can alter the
system (those other than HEAD and GET), it can expose an application to
Cross-Site Request Forgery (CSRF) attacks.
:type cookie: bool
"""
fun.accessLevel = 'public'
fun.requiredScopes = scope
if cookie:
fun.cookieAuth = True
return fun | bigcode/self-oss-instruct-sc2-concepts |
def flip_second_half_direction(team):
"""
Flip coordinates in second half so that each team always shoots in the same direction through the match.
"""
second_half_idx = team.Period.idxmax(2)
columns = [c for c in team.columns if c[-1].lower() in ["x", "y"]]
team.loc[second_half_idx:, columns] *= -1
return team | bigcode/self-oss-instruct-sc2-concepts |
import math
def fuel_counter(masses):
"""Function that computes the fuel needed for the input masses.
Expected input is required to either be a list/tuple or scalar"""
if isinstance(masses, (tuple, list)):
return sum(fuel_counter(mass) for mass in masses)
return max(int(math.floor(masses / 3) - 2), 0) | bigcode/self-oss-instruct-sc2-concepts |
def shutdown_cost_rule(mod, prj, tmp):
"""
If no shutdown_cost_rule is specified in an operational type module, the
default shutdown fuel cost is 0.
"""
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def list_medias(api, lang, **params):
# type (ApiClient, str, dict) -> (Iterable[dict])
"""List all the medias.
Args:
api (object): The ApiClient instance used for request.
lang (str): the lang. Defaults to english (en).
``**params``: optional dictionary of search parameters as defined in https://api.lumapps.com/docs/media/list.
Yields:
a Lumapps Media resource
"""
params["lang"] = lang if lang else "en"
return api.iter_call("media", "list", **params) | bigcode/self-oss-instruct-sc2-concepts |
def pseudo_residual_regression(target, output):
"""Compute the pseudo residual for regression with least square error."""
if target.size() != output.size():
msg = "The shape of target {} should be the same as output {}."
raise ValueError(msg.format(target.size(), output.size()))
return target - output | bigcode/self-oss-instruct-sc2-concepts |
def plural(text, num):
"""Pluralizer: adds "s" at the end of a string if a given number is > 1
"""
return "%s%s" % (text, "s"[num == 1:]) | bigcode/self-oss-instruct-sc2-concepts |
def get_time_signature(h5,songidx=0):
"""
Get signature from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.time_signature[songidx] | bigcode/self-oss-instruct-sc2-concepts |
def hamming_distance(a, b):
"""
Counts number of nonequal matched elements in two iterables
"""
return sum([int(i != j) for i, j in zip(a, b)]) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def EER(positive_scores, negative_scores):
"""Computes the EER (and its threshold).
Arguments
---------
positive_scores : torch.tensor
The scores from entries of the same class.
negative_scores : torch.tensor
The scores from entries of different classes.
Example
-------
>>> positive_scores = torch.tensor([0.6, 0.7, 0.8, 0.5])
>>> negative_scores = torch.tensor([0.4, 0.3, 0.2, 0.1])
>>> val_eer, threshold = EER(positive_scores, negative_scores)
>>> val_eer
0.0
"""
# Computing candidate thresholds
thresholds, _ = torch.sort(torch.cat([positive_scores, negative_scores]))
thresholds = torch.unique(thresholds)
# Adding intermediate thresholds
interm_thresholds = (thresholds[0:-1] + thresholds[1:]) / 2
thresholds, _ = torch.sort(torch.cat([thresholds, interm_thresholds]))
# Computing False Rejection Rate (miss detection)
positive_scores = torch.cat(
len(thresholds) * [positive_scores.unsqueeze(0)]
)
pos_scores_threshold = positive_scores.transpose(0, 1) <= thresholds
FRR = (pos_scores_threshold.sum(0)).float() / positive_scores.shape[1]
del positive_scores
del pos_scores_threshold
# Computing False Acceptance Rate (false alarm)
negative_scores = torch.cat(
len(thresholds) * [negative_scores.unsqueeze(0)]
)
neg_scores_threshold = negative_scores.transpose(0, 1) > thresholds
FAR = (neg_scores_threshold.sum(0)).float() / negative_scores.shape[1]
del negative_scores
del neg_scores_threshold
# Finding the threshold for EER
min_index = (FAR - FRR).abs().argmin()
# It is possible that eer != fpr != fnr. We return (FAR + FRR) / 2 as EER.
EER = (FAR[min_index] + FRR[min_index]) / 2
return float(EER), float(thresholds[min_index]) | bigcode/self-oss-instruct-sc2-concepts |
def get_tensor_shape(x):
"""
Get the shape of tensor
Parameters
----------
x : tensor
type float16, float32, float64, int32, complex64, complex128.
Returns
-------
list.
Examples
---------
>>> import tensorlayerx as tlx
>>> x_in = tlx.layers.Input((32, 3, 3, 32))
>>> x_shape = tlx.ops.get_tensor_shape(x_in)
"""
return x.get_shape().as_list() | bigcode/self-oss-instruct-sc2-concepts |
import typing
def validate_list(expected, lst: list) -> typing.Union[str, bool]:
"""
Validate a list against our expected schema.
Returns False if the list is valid.
Returns error in string format if invalid.
"""
if not isinstance(lst, list):
return "Expected argument of type `%s`, got `%s`" % (
str(expected).replace("typing.", ""),
type(lst).__name__,
)
each_arg_type = typing.get_args(expected)[0]
for item in lst:
if not isinstance(item, each_arg_type):
return "Not all list items are of expected value, `%s`, found `%s`" % (
each_arg_type.__name__,
type(item).__name__,
)
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def get_nested(the_dict: dict, nested_key: str, default: Any = None) -> Any:
"""
Returns the value of a nested key in an dictorinary
Args:
the_dict (dict): The dictionary to get the nested value from
nested_key (str): The nested key
default: The value to be returned if the key is not found
Returns:
Examples:
>>> t = {'a': {'b': {'c':'value_of_c'}}}
>>> get_nested(t, 'b:c')
'value_of_c'
>>> get_nested(t, 'b:c:d', 'not found')
'not found'
"""
keys = nested_key.split(':')
if not hasattr(the_dict, '__iter__'):
return default
if len(keys) == 1:
if keys[0] in the_dict:
return the_dict[keys[0]]
else:
return default
else:
if keys[0] in the_dict:
return get_nested(the_dict[keys[0]], ':'.join(keys[1:]), default)
else:
return default | bigcode/self-oss-instruct-sc2-concepts |
import re
def percent_decode(data):
""" Percent decode a string of data.
"""
if data is None:
return None
percent_code = re.compile("(%[0-9A-Fa-f]{2})")
try:
bits = percent_code.split(data)
except TypeError:
bits = percent_code.split(str(data))
out = bytearray()
for bit in bits:
if bit.startswith("%"):
out.extend(bytearray([int(bit[1:], 16)]))
else:
out.extend(bytearray(bit, "utf-8"))
return out.decode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
def always_do(action):
"""Returns a policy that always takes the given action."""
def policy(state, rng):
return action
return policy | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def read_containers(text: str) -> Sequence[int]:
"""
Read the puzzle input into a list of integers representing the container sizes.
"""
return [int(line) for line in text.split("\n")] | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def get_job_id(length=8):
"""Create random job id."""
return "".join(random.choice(string.hexdigits) for x in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
import math
def circle_area(diameter):
"""Returns the area of a circle with a diameter of diameter."""
return 1/4*math.pi*(diameter**2) | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def create_gobnilp_settings(score_type, palim=None, alpha=None):
"""
Creates a string of Gobnilp settings given the allowed arities and parent size.
Parameters
----------
score_type : int
The scoring function used to learn the network
0 for BDeu or 2 for BIC
palim: int
The maximum number of parents a node can have.
alpha : float
The Equivalent Sample Size of the BDeu Score.
Returns
-------
gobnilp_settings : str
A string describing the provided constraints.
"""
if palim is None:
palim = 3
warnings.warn('Maximum number of parents (palim) not defined. Defaulting to palim=3.')
if score_type=='BDeu' and alpha is None:
alpha = 1.0
warnings.warn('ESS (alpha) not defined. Defaulting to alpha=1.0.')
output_dot_location = 'sol.mat'
gobnilp_settings = ''
gobnilp_settings += 'gobnilp/scoring/palim = {}\n'.format(palim)
gobnilp_settings += 'gobnilp/scoring/initpalim = {}\n'.format(palim)
gobnilp_settings += 'gobnilp/delimiter = " "\n'
gobnilp_settings += 'gobnilp/mergedelimiters = TRUE\n'
gobnilp_settings += 'gobnilp/outputfile/solution = "golb.bn"\n'
gobnilp_settings += 'gobnilp/outputfile/adjacencymatrix = "sol.mat"\n'
gobnilp_settings += 'gobnilp/scoring/alpha = {}\n'.format(format(alpha,'f'))
gobnilp_settings += 'limits/time = 3600\n'
if score_type in ["BIC", "BDeu"]:
gobnilp_settings += 'gobnilp/scoring/score_type = "{}"\n'.format(score_type)
return gobnilp_settings | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(array, item):
"""function to search for the value in a list
Args:
array(list): a sorted list of values
item: the value to be searched for in the array
Returns:
the position of the item from the list or a not found
"""
low = 0
high = len(array) - 1
"""whenever a search is to be made the high and low are added and
divided by 2 to get the mid-point and look for the value at that
result in the array. If it is the value, return the position, if
what is found is less than the item found, make the highest point
high to be the result - 1 and if it's higher, make the low point the
result + 1
"""
while low <= high:
mid_point = (low + high) // 2
guess = array[mid_point] # make the guess
if guess == item:
return mid_point
if guess > item:
high = mid_point - 1
else:
low = mid_point + 1
"""at this point, the loop could get any match"""
return 'item not found in the array' | bigcode/self-oss-instruct-sc2-concepts |
def _axes_to_sum(child, parent):
"""Find the indexes of axes that should be summed in `child` to get `parent`"""
return tuple(child.index(i) for i in child if i not in parent) | bigcode/self-oss-instruct-sc2-concepts |
def minimax(val, low, high):
""" Return value forced within range """
try:
val = int(val)
except:
val = 0
if val < low:
return low
if val > high:
return high
return val | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import configparser
def read_login() -> Tuple[str, str]:
"""
read login from file
:return: mail & password
"""
config = configparser.ConfigParser()
config.read("login.ini")
mail = config.get("LOGIN", "email")
password = config.get("LOGIN", "password")
return mail, password | bigcode/self-oss-instruct-sc2-concepts |
def rom_to_hex(rom):
"""Convert rom bytearray to hex string."""
return ''.join('{:02x}'.format(x) for x in rom) | bigcode/self-oss-instruct-sc2-concepts |
def remove_nipsa_action(index, annotation):
"""Return an Elasticsearch action to remove NIPSA from the annotation."""
source = annotation["_source"].copy()
source.pop("nipsa", None)
return {
"_op_type": "index",
"_index": index,
"_type": "annotation",
"_id": annotation["_id"],
"_source": source,
} | bigcode/self-oss-instruct-sc2-concepts |
def read_queries(file, interactive=False):
""" Return list of reference and generated queries """
query_list = []
with open(file, 'r') as src:
for line in src.readlines():
if interactive is True:
reference, gen = line.strip('\n').split(",")
else:
# output files by fairseq-generate contain an ID code as
# first element, which can be omitted
_, reference, gen = line.strip('\n').split(",")
query_list.append([reference, gen])
src.close()
return query_list | bigcode/self-oss-instruct-sc2-concepts |
def _insert_char_at_pos(text, pos, ch):
"""
Inserts a character at the given position in string.
"""
return text[:pos] + ch + text[pos:] | bigcode/self-oss-instruct-sc2-concepts |
def mk_lst(values, unlst=False):
"""
while iterating through several type of lists and items it is convenient to
assume that we recieve a list, use this function to accomplish this. It
also convenient to be able to return the original type after were done
with it.
"""
# Not a list, were not looking to unlist it. make it a list
if not isinstance(values, list) and not unlst:
values = [values]
# We want to unlist a list we get
if unlst:
# single item provided so we don't want it a list
if isinstance(values, list):
if len(values) == 1:
values = values[0]
return values | bigcode/self-oss-instruct-sc2-concepts |
def image_shape(images):
"""Check if all image in `images` have same shape and return that shape."""
shape = None
for image in images:
if not shape:
shape = image.shape
else:
if shape != image.shape:
raise ValueError
return shape | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.