seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import math
def length (v):
""" Length of a vector in 2-space.
Params: v (2-tuple) vector in 2-space
Returns: (float) length
"""
# INSERT CODE HERE, replacing 'pass'
x,y = v[0],v[1]
return math.sqrt ((x**2) + (y**2)) | bigcode/self-oss-instruct-sc2-concepts |
def descending_coin(coin):
"""Returns the next descending coin in order.
>>> descending_coin(25)
10
>>> descending_coin(10)
5
>>> descending_coin(5)
1
>>> descending_coin(2) # Other values return None
"""
if coin == 25:
return 10
elif coin == 10:
return 5
elif coin == 5:
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def _ds_or_none(ds):
"""return none if ds is empty"""
if any(ds.coords) or any(ds.variables) or any(ds.attrs):
return ds
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Any
def assert_and_pass(func: Callable, arg: Any):
"""Call ``func``` with ``arg`` and return ``arg``. Additionally allow arg
to be ``None``.
Args:
func: Test function.
arg: Function argument.
Returns:
Result of ``func(arg)``.
"""
if arg is not None:
func(arg)
return arg | bigcode/self-oss-instruct-sc2-concepts |
def type_name(obj):
"""Fetch the type name of an object.
This is a cosmetic shortcut. I find the normal method very ugly.
:param any obj: The object you want the type name of
:returns str: The type name
"""
return type(obj).__name__ | bigcode/self-oss-instruct-sc2-concepts |
from typing import Generic
from re import T
def filter_by_organization(model: Generic[T], organization_id: str) -> QuerySet: # type: ignore
"""
Filters active resources that belong to an organization.
Args:
model (Generic[T]): Model that is going to be queried.
organization_id (str): ID of the organization whose clients are to filtered.
Returns:
QuerySet of the active resources of an organization whose ID has been supplied.
"""
queryset = model.objects.filter(organization_id=organization_id, is_deleted=False, deleted_at__isnull=True) # type: ignore
return queryset | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pad_feature_map(feature_map: torch.Tensor, padding_size: int):
"""Zero-pad feature map by a constant padding margin.
Args:
feature_map: The map to extract features from.
padding_size: The padding size.
"""
return torch.nn.ConstantPad2d(padding_size, 0.0)(feature_map) | bigcode/self-oss-instruct-sc2-concepts |
def is_identity_matrix(L):
"""
Returns True if the input matrix is an identity matrix, False otherwise.
"""
result = len(L) == len(L[0])
for i in range(len(L)):
for j in range(len(L)):
if i == j:
result *= (L[i][j] == 1)
else:
result *= (L[i][j] == 0)
return result | bigcode/self-oss-instruct-sc2-concepts |
def has_value(value):
"""
We want values like 0 and False to be considered values, but values like
None or blank strings to not be considered values
"""
return value or value == 0 or value is False | bigcode/self-oss-instruct-sc2-concepts |
def create_container(swift_connection, name, storage_policy=None):
"""
Create a container with an optional storage policy.
:param swift_connection: connection to Swift
:type swift_connection: :py:class:`swiftclient.client.Connection`
:param name: container name
:type name: string
:param storage_policy: container storage policy (optional)
:type storage_policy: string
:return: policy of the craeted container
"""
headers = {'X-Storage-Policy': storage_policy} if storage_policy else {}
swift_connection.put_container(name, headers)
return swift_connection.head_container(name).get('x-storage-policy') | bigcode/self-oss-instruct-sc2-concepts |
import pprint
def block_indent(text, spaces=4):
"""
Given a multi-line string, indent every line of it by the given number of spaces.
If `text` is not a string it is formatted using pprint.pformat.
"""
return '\n'.join([(' ' * spaces) + l for l in pprint.pformat(text).splitlines()]) | bigcode/self-oss-instruct-sc2-concepts |
def get_single_company_identifiers(data: dict, identifier: str) -> dict:
"""Retrieves the three identifiers (CIK, ticker, title) of a single company.
:param data: The dictionary mapping CIKs with tickers and title from the SEC.
:type data: dict.
:param identifier: The identifier passed by the user when constructing the object.
:type identifier: str.
:return: A dictionary with the identifiers.
:rtype: dict.
"""
data = {identifier: {
'cik': str(data[c].get('cik_str')),
'ticker': data[c].get('ticker'),
'title': data[c].get('title')
} for c in data if str(data[c].get('cik_str')) == identifier or data[c].get('ticker') == identifier}
return data | bigcode/self-oss-instruct-sc2-concepts |
def remove_overlap(ranges):
""" Simplify a list of ranges; I got it from https://codereview.stackexchange.com/questions/21307/consolidate-list-of-ranges-that-overlap """
result = []
current_start = -1
current_stop = -1
for start, stop in sorted(ranges):
if start > current_stop:
# this segment starts after the last segment stops
# just add a new segment
result.append( (start, stop) )
current_start, current_stop = start, stop
else:
# current_start already guaranteed to be lower
current_stop = max(current_stop, stop)
# segments overlap, replace
result[-1] = (current_start, current_stop) # SLAV: I modified this to update the stop too.
return(result) | bigcode/self-oss-instruct-sc2-concepts |
def get_supported_os(scheduler):
"""
Return a tuple of the os supported by parallelcluster for the specific scheduler.
:param scheduler: the scheduler for which we want to know the supported os
:return: a tuple of strings of the supported os
"""
return "alinux" if scheduler == "awsbatch" else "alinux", "centos6", "centos7", "ubuntu1604", "ubuntu1804" | bigcode/self-oss-instruct-sc2-concepts |
def get_strand(read):
"""Get the strand of the mapped read"""
if read.is_reverse:
return '-'
return '+' | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import List
def get_home_and_node_id_from_device_id(device_id: Tuple[str, str]) -> List[str]:
"""
Get home ID and node ID for Z-Wave device registry entry.
Returns [home_id, node_id]
"""
return device_id[1].split("-") | bigcode/self-oss-instruct-sc2-concepts |
def get_tag(td, tag, o1, o2):
"""Return the tag between offsets o1 and o2 if there is one, return None if
there is no such tag."""
tags = td.tags.find_tags(tag)
for t in tags:
if t.begin == o1 and t.end == o2:
return t
return None | bigcode/self-oss-instruct-sc2-concepts |
def enum(*values, **kwargs):
"""Generates an enum function that only accepts particular values. Other
values will raise a ValueError.
Parameters
----------
values : list
These are the acceptable values.
type : type
The acceptable types of values. Values will be converted before being
checked against the allowed values. If not specified, no conversion
will be performed.
Example
-------
>>> my_enum = enum(1, 2, 3, 4, 5, type=int)
>>> a = my_enum(1)
>>> b = my_enum(2)
>>> c = mu_enum(6) # Raises ValueError
"""
if len(values) < 1:
raise ValueError("At least one value is required.")
enum_type = kwargs.pop('type', str)
if kwargs:
raise TypeError(
f'Unexpected parameters: {", ".join(kwargs.keys())}')
def __new__(cls, value):
if value not in cls.values:
raise ValueError(
f'{value} is an unexpected value. '
f'Expected one of {cls.values}')
return super(enum, cls).__new__(cls, value)
enum = type(
'Enum',
(enum_type,),
{
'values': values,
'__new__': __new__,
})
return enum | bigcode/self-oss-instruct-sc2-concepts |
import codecs
import yaml
def load_yaml_file(file_path: str):
"""Load a YAML file from path"""
with codecs.open(file_path, 'r') as f:
return yaml.safe_load(f) | bigcode/self-oss-instruct-sc2-concepts |
def remove_underscores(value):
"""
Removes the underscores from a given string
"""
return value.replace("_", " ").title() | bigcode/self-oss-instruct-sc2-concepts |
def _getView(syn, view_id, clause=None):
"""
Based on a user-defined query calls to synapse's tableQuery function and returns the entity-view generator object.
:param syn: A Synapse object: syn = synapseclient.login(username, password) - Must be logged into synapse
:param view_id: A Synapse ID of an entity-view (Note: Edit permission on its' files is required)
:param clause: A SQL clause to allow for sub-setting & row filtering in order to reduce the data-size
:return: An object of type synapse entity-view
"""
if clause is None:
query = "".join(['select * from ', view_id])
view = syn.tableQuery(query)
else:
query = "".join(['select * from ', view_id, ' ', clause])
view = syn.tableQuery(query)
return view | bigcode/self-oss-instruct-sc2-concepts |
def _dms2dd(d: float, m: float, s: float) -> float:
"""
Converts a DMS coordinate to DD
:param d: degrees
:param m: minutes
:param s: seconds
:return: equivalent in decimal degrees
"""
return d + m / 60 + s / 3600 | bigcode/self-oss-instruct-sc2-concepts |
import struct
import socket
def _ConvertMaskToCIDR(mask):
"""Convert a netmask like 255.255.255.0 to a CIDR length like /24."""
bits = int(struct.unpack('!I', socket.inet_pton(socket.AF_INET, mask))[0])
found_one_bit = False
maskbits = 0
for i in range(32):
if (bits >> i) & 1 == 1:
found_one_bit = True
elif found_one_bit:
return -1
else:
maskbits += 1
return 32 - maskbits | bigcode/self-oss-instruct-sc2-concepts |
import jinja2
def invite_form(event, context):
"""Get response for invite code page. Invoked by AWS Lambda."""
template = jinja2.Environment(
loader=jinja2.FileSystemLoader('./')
).get_template('public/tmpl/enter_invite.html')
return {
"statusCode": 200,
"headers": {"Content-Type": "text/html"},
"body": template.render()
} | bigcode/self-oss-instruct-sc2-concepts |
def mean(iterable):
"""Returns the average of the list of items."""
return sum(iterable) / len(iterable) | bigcode/self-oss-instruct-sc2-concepts |
def strip_prefix(prefix, string):
"""Strip prefix from a string if it exists.
:param prefix: The prefix to strip.
:param string: The string to process.
"""
if string.startswith(prefix):
return string[len(prefix):]
return string | bigcode/self-oss-instruct-sc2-concepts |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = [list(map(int, ln.split(" "))) for ln in lines]
return res | bigcode/self-oss-instruct-sc2-concepts |
def skip_names(mol_list):
"""
Check if a list of molecules contains nomenclature that suggests
it can be skipped.
i.e. lignin implies polymeric species.
"""
# lignin - a polymeric species that can form under oxidative
# polymerisation
# many forms exist. HRP produces some.
# add white space to avoid getting the word in the middle of other
# terms
skippable_strings = [' lignin']
for name in mol_list:
for i in skippable_strings:
if i in name:
print('skipping this molecule because it contains:', i)
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_morsel_cookie(info, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if info.cookies is not None and name in info.cookies:
return info.cookies[name].value
return default | bigcode/self-oss-instruct-sc2-concepts |
def readId2Name(fin):
"""
Reconstruct a global id=>username dictionary from an open csv file
Reads the globalId2Name file (or equivalent) and constructs an id=>username
dictionary. Input is an open csv.reader file such as the one constructed
by the main method of this module. Returns a dictionary of id=>username
"""
retDict = {}
fin.readrow()
for iden, name in fin:
retDict[iden] = name
return retDict | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_filetypes(format: str = 'json') -> List[str]:
"""Get filetypes based on specified format."""
return ['yml', 'yaml'] if format == 'yaml' else [format] | bigcode/self-oss-instruct-sc2-concepts |
def min_x_pt(pt_dict):
"""Returns the key of the point at minimum x
(with minimum y) in the XY plane (Z is ignored)
pt_dict is a collection of 'pt_ID: (x, y, z)'
key-value pairs"""
nmin = (9.9E12, 9.9E12)
the_node = None
for k,v in pt_dict.items():
if v[0] == nmin[0]:
if v[1] < nmin[1]:
the_node = k
nmin = (v[0], v[1])
elif v[0] < nmin[0]:
the_node = k
nmin = (v[0], v[1])
return the_node | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import random
def get_wav_files(data_dir: Path):
"""
Get all *.wav files in the data directory.
"""
files = sorted(data_dir.glob("*.wav"))
random.Random(42).shuffle(files)
return files | bigcode/self-oss-instruct-sc2-concepts |
def get_z_prop(p, pi, n):
"""
Function to get the Z value (standard deviations number under or over the average)
correspondent of the x value (parameter) in the standard normal distribution.
Applied in proportions.
Parameters:
--------------------------
p : double, float
"Succeses" observations sample proportion.
Each value should be in the range [0, 1].
pi : double, float
Population proportion given.
Each value should be in the range [0, 1].
n : int
Sample size.
Returns:
--------------------------
z : float, double
The Z value (standard deviations number under or over the average)
correspondent of the x value (parameter) in the standard normal distribution.
"""
error = ((pi * (1 - pi)) / n)**0.5
z = (p - pi) / error
return z | bigcode/self-oss-instruct-sc2-concepts |
def compress_indexes(indexes):
"""Compress a list of indexes. The list is assumed to be sorted in ascending
order, and this function will remove the all the consecutives numbers and
only keep the first and the number of the consecutives in a dict.
eg : [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 18, 19, 20, 21, 22]
become : {0: 5, 18: 5, 7: 7}
:param indexes: the list of indexes asc sorted to compress
:type indexes: list of int
:return: a dict containing the indexes as keys and # of consecutives
numbers as value.
:rtype: dict
"""
d = {}
c = indexes[0]
j = 0
for i in range(1, len(indexes)):
j += 1
if c + j != indexes[i]:
d[c] = j
c = indexes[i]
j = 0
d[c] = j + 1
return d | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_wbgene_string(string):
"""
Receives a string that contains WBGene indices. Parses the string into a set of WBGene indices. \
The format of a WBGene index is 'WBGene' and exactly 8 digits.
:type string: str
:param string: The string to be parsed. Can be any format of string.
:return:
a set of the WBGene indices that appear in the given string.
:Examples:
>>> from rnalysis import general
>>> string = '''WBGene WBGenes WBGene12345678, WBGene98765432WBGene00000000& the geneWBGene44444444daf-16A5gHB.5
... WBGene55555555'''
>>> parsed = general.parse_wbgene_string(string)
>>> print(parsed)
{'WBGene12345678', 'WBGene44444444', 'WBGene98765432', 'WBGene55555555', 'WBGene00000000'}
"""
return set(re.findall(r'WBGene[0-9]{8}', string)) | bigcode/self-oss-instruct-sc2-concepts |
import math
def rotate(vec, degrees):
"""
Rotates a 2D vector x, y counter-clockwise by degrees degrees
"""
x, y = vec
sin = math.sin(math.radians(degrees))
cos = math.cos(math.radians(degrees))
rot_x = cos * x + -sin * y
rot_y = sin * x + cos * y
return rot_x, rot_y | bigcode/self-oss-instruct-sc2-concepts |
import torch
def topk_accuracy(k, logits: torch.Tensor, labels: torch.Tensor, unk_id=None, pad_id=None):
"""
Averaged per sample:
1, if one of the k predictions with highest confidence was the correct one for all sub tokens
0, else
if `unk_id` is given, the best non <unk> prediction will be used and <unk> tokens in the labels will be
completely ignored, i.e., it does not matter what the 5 predictions with highest score at this position were.
:param logits: batch_size x num_predict x num_sub_tokens x vocab_size
:param labels: batch_size x num_predict x num_sub_tokens
:param k: The k highest logits will be considered as predictions and for every sub token when any of the k
highest valued predictions was the correct one, it will count as an accurate prediction
:param unk_id: ID of the <unk> token
"""
assert unk_id is None or pad_id is not None, "When unk_id is given, pad_id must be given as well"
topk_pred = logits.topk(k, -1)
# Accept if any of the top k predictions is the label
topk_correct = (topk_pred.indices == labels.unsqueeze(-1).expand((-1, -1, -1, k)))
topk_correct = topk_correct.any(-1)
if unk_id is None:
topk_correct = topk_correct.all(-1) # Only accept if for all sub tokens a top k prediction was correct
if unk_id is not None:
idx_unk_labels = (labels == unk_id)
topk_correct[idx_unk_labels] = True
topk_correct = topk_correct.all(-1) # Only accept if for all sub tokens a top k prediction was correct
idx_label_all_unk = ((labels == unk_id) | (labels == pad_id)).all(-1) & ~(labels == pad_id).all(-1)
topk_correct = topk_correct[~idx_label_all_unk] # Completely ignore if labels only
# consists of <unk>
return topk_correct.float().mean().item() | bigcode/self-oss-instruct-sc2-concepts |
import re
def _parse_host(id):
"""
This helper function parses the host from `id` in scope nodes.
Returns the host name if it is a host, else return None.
"""
host_name = None
r = re.match(r"^(.*);<host>$", id)
if r:
host_name = r.group(1)
return host_name | bigcode/self-oss-instruct-sc2-concepts |
def retrieve_row_values(row, field_names, index_dict):
"""This function will take a given list of field names, cursor row, and an index dictionary provide
a tuple of passed row values.
:param - row - cursor row
:param - field_names -list of fields and their order to retrieve
:param - index_dict - cursors dictionary in the form of {field_name : row_index}
:return - list of values from cursor"""
row_values = []
for field in field_names:
index = index_dict.get(field, None)
if index is None:
print("Field could not be retrieved. Passing None.")
value = None
else:
value = row[index]
row_values.append(value)
return row_values | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Union
from typing import Any
from typing import List
def hash_dict(
item_dict: Dict[str, Union[Dict[str, Any], List[Any], str]]
) -> Dict[str, Any]:
"""
Hash dictionary values.
Parameters
----------
item_dict : Dict[str, Union[Dict[str, Any], List[Any], str]]
Input item can be a Dict of strings, lists or other
dictionaries.
Returns
-------
Dict[str, Any]
Dictionary with hashed values.
"""
out_dict = {}
for key, val in item_dict.items():
if isinstance(val, dict):
hash_val = hash_dict(val)
elif isinstance(val, list):
hash_val = hash_list(val) # type: ignore
else:
hash_val = hash_string(val) # type: ignore
out_dict[key] = hash_val
return out_dict | bigcode/self-oss-instruct-sc2-concepts |
def ant_2_containing_baslines(ant, antennas):
"""
Given antenna returns list of all baselines among given list with that
antenna.
"""
baselines = list()
for antenna in antennas:
if antenna < ant:
baselines.append(256 * antenna + ant)
elif antenna > ant:
baselines.append(256 * ant + antenna)
else:
pass
return baselines | bigcode/self-oss-instruct-sc2-concepts |
def count_commas(s: str) -> int:
"""
count commas:
- english comma [,](\u002c)
- Chinese full-width comma [,](\uff0c)
- Chinese seperator / Japanese comma [、](\u3001)
"""
count = 0
for c in s:
if c in "\u002c\uff0c\u3001":
count += 1
return count | bigcode/self-oss-instruct-sc2-concepts |
def list_to_dict(node_list: list):
"""
Convert the list to a dictionary,
Create a dictionary, key is a element in the list,
value is a element which next the key, if no exists, the value is None.
Args:
node_list (list): normal, list of node
Returns:
schema (dict): a dictionary
"""
length = len(node_list)
if length == 0:
schema = {}
elif length == 1:
schema = {node_list[0]: None}
else:
new_node_list = node_list[1:]
new_node_list.append(None)
schema = {k: v for k, v in zip(node_list, new_node_list)}
return schema | bigcode/self-oss-instruct-sc2-concepts |
def clipAlpha(aj, H, L):
"""
调整aj的值,使L<=aj<=H
Args:
aj 目标值
H 最大值
L 最小值
Returns:
aj 目标值
"""
aj = min(aj, H)
aj = max(L, aj)
return aj | bigcode/self-oss-instruct-sc2-concepts |
def safe_cast(val, to_type, default=None):
"""A helper for safe casts between types"""
try:
return to_type(val)
except (ValueError, TypeError):
return default | bigcode/self-oss-instruct-sc2-concepts |
import re
def _replace_labels(html: str) -> str:
"""
Replace Django's question-level labels with legend elements
"""
return re.sub(
"<fieldset><label [^>]+>(.*?)</label>",
lambda m: f'<fieldset><legend class="tdp-question-legend">{m[1]}</legend>', # noqa: B950
html,
) | bigcode/self-oss-instruct-sc2-concepts |
import math
def tanh(value):
"""
This function calculates the hyperbolic tangent function.
"""
return math.tanh(value) | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def center_roi_around(center_rc, size_hw):
"""
Return a rectangular region of interest (ROI) of size `size_hw` around the
given center coordinates. The returned ROI is defined as
(start_row, start_column, end_row, end_column)
where the start_row/column are ment to be *included* and the
end_row/column are excluded.
- `center_rc`: Tuple of `(row, column)`. The numbers will be rounded to
the closest integer. The `row` corresponds to the height and the
`column` to the width. In mathematical notation you could think of the
center to be given as the tuple `(y, x)`. Be aware of this; It does
fit well to numpy's `shape` method.
- `size_hw`: A tuple of `(height, width)` of the resulting ROI. If this
numbers are even, a UserWarning is issued.
"""
height, width = size_hw
if height % 2 == 0 or width % 2 == 0:
warnings.warn(f"ROI with even height and width cannot be exactly "
f"centered. (height, width)=({height}, {width})")
row, col = int(round(center_rc[0])), int(round(center_rc[1]))
return (row - height//2,
col - width//2,
row + height//2 + 1,
col + width//2 + 1) | bigcode/self-oss-instruct-sc2-concepts |
def conv_lin(a, b=1.0, c=0.0, inverse=False):
"""Simple linear transform
will I think store parameters against each sensor then they are handy
>>> conv_lin(4,2,3)
11
>>> conv_lin(11,2,3.0,True)
4.0
>>>"""
if inverse is False:
return a * b + c
else:
return (a - c) / b | bigcode/self-oss-instruct-sc2-concepts |
def get_param_dict(self):
"""Get the parameters dict for the ELUT of PMSM at the operationnal temperature and frequency
Parameters
----------
self : ELUT
an ELUT_PMSM object
Returns
----------
param_dict : dict
a Dict object
"""
# getting parameters of the abstract class ELUT (stator parameters)
param_dict = super(type(self), self).get_param_dict()
param_dict["R2"] = self.R2
param_dict["L2"] = self.L2
param_dict["T2_ref"] = self.T2_ref
param_dict["Phi_m"] = self.Phi_m
param_dict["I_m"] = self.I_m
return param_dict | bigcode/self-oss-instruct-sc2-concepts |
def train_batch(model, x, target, optimizer, criterion):
"""Train a model for one iteration
Args:
model (torch.nn.Module): model to train
x (torch.Tensor): input sample
target (torch.Tensor): output target
optimizer (torch.optim.Optimizer): parameter optimizer
criterion (torch.nn.Module): loss used for backpropagation
Returns:
batch_loss (float): training loss
"""
# Forward
outputs = model(x)
# Loss computation
batch_loss = criterion(outputs, target)
# Backprop
optimizer.zero_grad()
batch_loss.backward()
optimizer.step()
return batch_loss.item() | bigcode/self-oss-instruct-sc2-concepts |
def patch_init(mocker):
"""
Makes patching a class' constructor slightly easier
"""
def patch_init(*args, **kwargs):
for item in args:
mocker.patch.object(item, '__init__', return_value=None, **kwargs)
return patch_init | bigcode/self-oss-instruct-sc2-concepts |
import json
def getCommandsFromLog(inFile,filterList,coverage):
"""
Get commands from a log
Parameters
----------
inFile : str
path to pyrpipe log file.
filterList : str
list of commands to ignore.
coverage : char
type of commands to report all, passed or failed: a,p, i.
Returns
-------
commands : TYPE
DESCRIPTION.
"""
with open(inFile) as f:
data=f.read().splitlines()
commands=[]
for l in data:
if not l.startswith("#"):
thisLog=json.loads(l)
thisName=thisLog["cmd"].split(' ')[0]
if filterList and thisName in filterList:
continue
status=int(thisLog['exitcode'])
#skip passed
if coverage=='i' and status==0:
continue
#skip failed
if coverage=='p' and status!=0:
continue
commands.append(thisLog["cmd"])
return commands | bigcode/self-oss-instruct-sc2-concepts |
def get_panel_groups_at_depth(group, depth=0):
"""Return a list of the panel groups at a certain depth below the node group"""
assert depth >= 0
if depth == 0:
return [group]
else:
assert group.is_group()
return [
p
for gp in group.children()
for p in get_panel_groups_at_depth(gp, depth - 1)
] | bigcode/self-oss-instruct-sc2-concepts |
def get_class(name, defmod=None):
"""Finds a class.
Search a class from its fully qualified name, e.g.
'pyconstruct.domains.predefined.Class'. If the class name is not fully
qualified, e.g. 'Class', it is searched inside the default module.
Parameters
----------
name : str
The fully qualified name of the class or the name of the class or the
class name in the default module.
defmod : str
The default module where to search the class if not fully qualified.
"""
ns = name.split('.')
if len(ns) == 1:
if not defmod:
raise ValueError(
'Provide either the fully qualified name of the class or the '
'default module where to look for it'
)
mod = defmod
else:
mod = '.'.join(ns[:-1])
module = __import__(mod, fromlist=[ns[-1]])
return getattr(module, ns[-1]) | bigcode/self-oss-instruct-sc2-concepts |
def max_endtime(graph):
"""
A method to calculate the maximum endtime of a network.
Parameter(s):
-------------
graph : TemporalDiGraph
A directed, temporal graph.
Returns:
--------
maxEndtime : int
the maximum endtime of a network.
"""
timespan = graph.edges.timespan()
maxEndtime = timespan[-1]
return maxEndtime | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_jobdesc_config(job):
"""Function for extracting job description config file."""
job_desc_url = '%s/job_description.json' % job['job_url']
r = requests.get(job_desc_url, verify=False)
r.raise_for_status()
return job_desc_url | bigcode/self-oss-instruct-sc2-concepts |
def ReadableSize(num):
"""Get a human-readable size."""
for unit in ['B', 'KB', 'MB', 'GB']:
if abs(num) <= 1024.0:
return '%3.2f%s' % (num, unit)
num /= 1024.0
return '%.1f TB' % (num,) | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_tuples(examples):
"""
Convert a list of Example objects to tuples of the form:
(source, translation, language, author, reference).
"""
convert1 = lambda e: e.to_simple_tuple()
return list(filter(bool, map(convert1, examples))) | bigcode/self-oss-instruct-sc2-concepts |
def prop_get_nyquistsampling(wf, lamx = 0.0):
"""Funtion determines the Nyquist sampling interval for the current beam,
which is focal_ratio * wavelength / 2.
Parameters
----------
wf : obj
Wavefront class object
lamx : float
Wavelength to use for computing sampling. By default, the current
wavefront's wavelength is used. This parameter can be used when you
want to know the Nyquist sampling for a wavelength other than for the
current wavefront.
Returns
-------
float
Nyquist sampling interval corresponding to the current wavefront
"""
if lamx != 0.:
return wf.current_fratio * lamx / 2.
else:
return wf.current_fratio * wf.lamda / 2. | bigcode/self-oss-instruct-sc2-concepts |
def _len_arg(typ):
"""Returns the length of the arguments to the given type."""
try:
return len(typ.__args__)
except AttributeError:
# For Any type, which takes no arguments.
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def gen_cppcheck_enables(enables):
"""生成cppcheck的enable参数
格式:enable1, enable2, ...
"""
# 每个enable参数用逗号隔开
return '--enable={}'.format(','.join(enables)) | bigcode/self-oss-instruct-sc2-concepts |
def get_file_text(path, encoding):
"""Returns all text contents of a file at the given path in the form of a string."""
with open(path, mode='r', encoding=encoding) as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def call_module_function(*arguments):
""" Dynamically calls specified function from specified package and module, on the given image. The three arguments
of the function represent, in order: the input image, any extra input images (necessary in the case of many-to-
operations, empty otherwise) and the parameters dictionary to be given to the call
"""
# Unwind parameters and gather the operation details
image, extra_inputs_dict, parameters_dict = arguments[0], arguments[1], arguments[2]
package, module, function = parameters_dict['function'].split('.')
parameters = parameters_dict['params']
# Call the requested function on the image
imported_module = importlib.import_module('backend.' + package + '.' + module)
results = getattr(imported_module, function)(image, extra_inputs_dict, parameters)
return results | bigcode/self-oss-instruct-sc2-concepts |
def get_dict_from_list(smu_info_list):
"""
Given a SMUInfo array, returns a dictionary keyed by the SMU name with SMUInfo as the value.
"""
smu_info_dict = {}
for smu_info in smu_info_list:
smu_info_dict[smu_info.name] = smu_info
return smu_info_dict | bigcode/self-oss-instruct-sc2-concepts |
def _c_null_pointer(p):
"""Returns true if ctypes pointer is null."""
return (not bool(p)) | bigcode/self-oss-instruct-sc2-concepts |
def get_rev_recon(tree, recon, stree):
"""
Returns a reverse reconciliation
A reverse reconciliation is a mapping from nodes in the species tree to
lists of nodes in the gene tree.
"""
rev_recon = {}
nodes = set(tree.postorder())
for node, snode in recon.iteritems():
if node not in nodes:
raise Exception("node '%s' not in tree" % node.name)
rev_recon.setdefault(snode, []).append(node)
return rev_recon | bigcode/self-oss-instruct-sc2-concepts |
def _unshaped_initializer(fn,
**kwargs):
"""Build a flax-style initializer that ignores shapes.
Args:
fn: Callable that takes a random number generator and some keyword
arguments, and returns an initial parameter value.
**kwargs: Arguments to pass to fn.
Returns:
Callable that takes a PRNGKey and an (unused) shape, and returns the value
returned by fn.
"""
def _initialize(rng_key, unused_shape):
return fn(rng_key, **kwargs)
return _initialize | bigcode/self-oss-instruct-sc2-concepts |
def get_consecutive_num(arr):
"""
Method to get indices of second number in a pair of consecutive numbers
Note: solve_90f3ed37 uses this function
"""
rows = []
for i in range(len(arr) - 1):
if (arr[i] + 1) == arr[i + 1]:
rows.append(arr[i + 1])
return rows | bigcode/self-oss-instruct-sc2-concepts |
def getFileId(fname):
"""
Extract the id from a filename
"""
return '_'.join(fname.split('_')[:4]) | bigcode/self-oss-instruct-sc2-concepts |
def station_name(f):
"""
From the file name (f), extract the station name. Gets the data
from the file name directly and assumes the file
name is formatted as Data/Station_info.csv.
"""
return f.split('/')[1].split('_')[0] | bigcode/self-oss-instruct-sc2-concepts |
def string_to_values(input_string):
"""Method that takes a string of '|'-delimited values and converts them to a list of values."""
value_list = []
for token in input_string.split('|'):
value_list.append(float(token))
return value_list | bigcode/self-oss-instruct-sc2-concepts |
def generate_reference(model, gen, field='reference', prefix='', max_retries=10):
"""
Generate a unique reference given:
:param model: the class of the django model
:param gen: a function without arguments that returns part or all the reference
:param field: reference field of the model that needs to be unique
:param prefix: optional prefix
:param max_retries: max number of retries before failing
:raises RuntimeError: after trying max_retries times without being able to generate a
valid value
"""
manager = model.objects
for _ in range(max_retries):
reference = f'{prefix}{gen()}'
if not manager.filter(**{field: reference}).exists():
return reference
raise RuntimeError('Cannot generate random reference') | bigcode/self-oss-instruct-sc2-concepts |
def _has_eval_results_call(cls):
"""Return True if cls has a __call__ decorated with @eval_results
"""
return getattr(getattr(cls, '__call__', None), '_eval_results', False) | bigcode/self-oss-instruct-sc2-concepts |
def CommonSymbolsToOrder(symbols, common_symbols):
"""Returns s -> index for all s in common_symbols."""
result = {}
index = 0
for s in symbols:
if s not in common_symbols:
continue
result[s] = index
index += 1
return result | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sdd_bmm_diag_torch(t1, t2):
"""
Perform bmm and diagonal for sparse x dense -> dense. The diagonalized result is returned in vector tensor.
With s_t1.shape = (b, x, s), d_t2.shape = (b, s, x), the output shape is (b, x).
This method avoids a temporal (b, x, x) for memory efficiency.
:param t1: tensor 1
:param t2: tensor 2
:return: bmm_diag result in dense
"""
assert t1.shape[0] == t2.shape[0], 'Batch size mismatch.'
assert t1.shape[2] == t2.shape[1] and t1.shape[1] == t2.shape[2], 'Matrix shape mismatch.'
if t1.is_sparse:
d_t1 = t1.transpose(1, 2).to_dense()
outp = torch.sum(d_t1.mul_(t2), dim=1)
else:
d_t2 = t2.transpose(1, 2).to_dense()
outp = torch.sum(d_t2.mul_(t1), dim=2)
return outp | bigcode/self-oss-instruct-sc2-concepts |
def ip_pool_to_dict(ipp):
"""Convert an IPPool object to a dict"""
return {
'input': ipp.input[0],
'unused': [str(x) for x in ipp.pool.iter_cidrs()],
} | bigcode/self-oss-instruct-sc2-concepts |
def flat_list(l):
""" Convert a nested list to a flat list """
try:
return [item for sublist in l for item in sublist]
except:
return l | bigcode/self-oss-instruct-sc2-concepts |
import re
import itertools
def _java_hex(uuid):
"""Java Mongo Driver transfers byte representation of UUIDs in little endian format.
See also https://jira.mongodb.org/browse/JAVA-403
:param uuid:
:return: reordered hex sequence
"""
_hex = re.sub(r'[{}-]', '', uuid)
bytes = list(zip(_hex[0::2], _hex[1::2]))
msb = "".join(itertools.chain(*bytes[0:8][::-1]))
lsb = "".join(itertools.chain(*bytes[8:16][::-1]))
_hex = msb + lsb
return _hex | bigcode/self-oss-instruct-sc2-concepts |
def fibonacci(n):
"""フィボナッチ数を求める関数
:param n: ``n`` 番目のフィボナッチ数を求める
:returns: n番目のフィボナッチ数
:raises: ``ValueError`` when ``n`` is less than 0
"""
if n < 0:
raise ValueError('nは0以上を指定してください')
if n in (0, 1):
return n
return fibonacci(n - 1) + fibonacci(n - 2) | bigcode/self-oss-instruct-sc2-concepts |
def clean_github_repository(repo):
"""
get the username/repository from a Github url
:param repo:str the Github url of the repository
:return: username/repository
"""
if repo is None:
return None
repo = repo.replace("http://github.com/", "") \
.replace("https://github.com/", "")
if repo[-1] == '/':
repo = repo[:-1]
split_repo = repo.split("/")
(username, repository) = split_repo[0:2]
branch = "master"
if len(split_repo) > 2:
if split_repo[2] == "tree":
branch = split_repo[3]
return username, repository, branch | bigcode/self-oss-instruct-sc2-concepts |
def str2bool(value):
"""Returns a boolean reflecting a human-entered string."""
return value.lower() in (u'yes', u'1', u'true', u't', u'y') | bigcode/self-oss-instruct-sc2-concepts |
def filter_low_swh(ds):
"""Remove all records with low significant wave heights."""
return ds['sea_state_30m_significant_wave_height_spectral'] > 1.0 | bigcode/self-oss-instruct-sc2-concepts |
def _unique_retrieval(element_list, elem_identifier, search_identifier):
"""
Get the text from a ResultSet that is expected to have a length of 1.
Parameters
----------
element_list : bs4.element.ResultSet
Result of a `findAll`
elem_identifier : str
An identifier for the element being searched, used in error messages.
search_identifier : str
An identifier for the thing being searched for, used in error messages.
Returns
-------
str
Text for the single matching element if one was found.
"""
if len(element_list) > 1:
raise ValueError(f"{elem_identifier} has more than one {search_identifier}.")
elif len(element_list) == 0:
raise ValueError(f"{elem_identifier} has no {search_identifier}.")
else:
return element_list[0].text | bigcode/self-oss-instruct-sc2-concepts |
def time_to_knx(timeval, dow=0):
"""Converts a time and day-of-week to a KNX time object"""
knxdata = [0, 0, 0]
knxdata[0] = ((dow & 0x07) << 5) + timeval.hour
knxdata[1] = timeval.minute
knxdata[2] = timeval.second
return knxdata | bigcode/self-oss-instruct-sc2-concepts |
def prepare_cell_align_type(in_cell_align):
"""
Basic function that renames the cell alignment
string from the ArcGIS Pro UI and makes it dea
aws stac query compatible.
Parameters
-------------
in_cell_align : str
The ArcGIS Pro UI string for stac cell alignment.
Example: Top-left, Center.
Returns
----------
Processed cell alignment string name for use in dea
aws compatible stac query. Example: topleft, center.
"""
# checks
if not isinstance(in_cell_align, str):
raise TypeError('Cell alignment must be a string.')
elif in_cell_align not in ['Top-left', 'Center']:
raise ValueError('Cell alignment must be either Top-left or Center.')
# prepare and return
return in_cell_align.lower().replace('-', '') | bigcode/self-oss-instruct-sc2-concepts |
def get_pretrain_stop_metric(early_stopping_method, pretrain_tasks):
"""
Get stop_metric, which is used for early stopping.
Parameters
-------------------
early_stopping_method: str,
pretrain_tasks: List[Task]
Returns
-------------------
stop_metric: str
"""
if early_stopping_method != "auto":
pretrain_names = [task.name for task in pretrain_tasks]
if early_stopping_method in pretrain_names:
index = pretrain_names.index(early_stopping_method)
stop_metric = pretrain_tasks[index].val_metric
else:
raise ValueError("args.early_stopping_method must be either 'auto' or a task name")
else:
stop_metric = pretrain_tasks[0].val_metric if len(pretrain_tasks) == 1 else "macro_avg"
return stop_metric | bigcode/self-oss-instruct-sc2-concepts |
def read_D(filename):
"""reads an upper triangular matrix with phylogentic distances
between species.
Returns a dictionary with distances for species names."""
D = {}
f = open(filename)
cols = f.readline().rstrip().split('\t')
for line in f:
elems = line.strip().split('\t')
for i,e in enumerate(elems):
if e!='' and i>0:
D[(cols[i],elems[0])] = float(e)
D[(elems[0],cols[i])] = float(e)
f.close()
return D | bigcode/self-oss-instruct-sc2-concepts |
import torch
def corn_labels_from_logits(logits):
"""
Returns the predicted rank label from logits for a
network trained via the CORN loss.
Parameters
----------
logits : torch.tensor, shape=(n_examples, n_classes)
Torch tensor consisting of logits returned by the
neural net.
Returns
----------
labels : torch.tensor, shape=(n_examples)
Integer tensor containing the predicted rank (class) labels
Examples
----------
>>> # 2 training examples, 5 classes
>>> logits = torch.tensor([[14.152, -6.1942, 0.47710, 0.96850],
... [65.667, 0.303, 11.500, -4.524]])
>>> corn_label_from_logits(logits)
>>> tensor([1, 3])
"""
probas = torch.sigmoid(logits)
probas = torch.cumprod(probas, dim=1)
predict = probas > 0.5
preds = torch.sum(predict, dim=1)
return preds | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_yml(filepath: str) -> dict:
"""Load a yml file to memory as dict."""
with open(filepath, 'r') as ymlfile:
return dict(yaml.load(ymlfile, Loader=yaml.FullLoader)) | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json_file(filename):
"""Load data from a json file."""
data = {}
print('Loading file "{}"'.format(filename))
with open(filename, 'r') as infile:
data = json.load(infile)
return data | bigcode/self-oss-instruct-sc2-concepts |
def num_nodes_with_name (root,name,recurse=True):
###############################################################################
"""
Count nodes with certain name in an XML tree
>>> xml = '''
... <root>
... <a/>
... <sub>
... <a/>
... </sub>
... </root>
... '''
>>> import xml.etree.ElementTree as ET
>>> tree = ET.fromstring(xml)
>>> num_nodes_with_name(tree,'a',recurse=False)
1
>>> num_nodes_with_name(tree,'a',recurse=True)
2
"""
count = 0
for elem in root:
if elem.tag==name:
count += 1
if recurse:
count += num_nodes_with_name(elem,name)
return count | bigcode/self-oss-instruct-sc2-concepts |
def binary_freq(data, expression, feature_name=str, analyze=True):
"""Search data for occurrences of a binary feature as a regex.
Args:
data (pd.Series): a series with text instances.
expression (re.compile): a regex or string to search for.
feature_name (str, optional): a name for the feature to extract. Defaults to str.
Returns:
list: a list with a dict mapping feature name to 1 or 0 (true/false) based on occurrence in texts.
"""
b = data.str.contains(expression).astype(int) # cast bools to 0/1
if analyze == True:
bList = [{feature_name: x[1]} for x in b.items()]
return bList
else:
return b | bigcode/self-oss-instruct-sc2-concepts |
def confirm_mirror(uri):
"""Check if line follows correct sources.list URI"""
deb = ('deb', 'deb-src')
proto = ('http://', 'ftp://')
if (uri and (uri[0] in deb) and
(proto[0] in uri[1] or
proto[1] in uri[1])):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def sum_of_integers_in_string(s: str) -> int:
""" This function calculates the sum of the integers inside a string """
return sum([int(i) for i in re.findall(r'\d+', s)]) | bigcode/self-oss-instruct-sc2-concepts |
def add_nonN_count(df, nonN_count_file):
"""Count number of nonambiguous nucleotides per sequence and
add counts to dataframe"""
count_dict = {}
with open(nonN_count_file, 'r') as f:
for line in f:
id, count = line.rstrip('\n').split('\t')
count_dict[id] = int(count)
assert len(df.index) == len(count_dict)
count_list = [count_dict[id] for id in df["strain"]]
df["nonN_count"] = count_list
return df | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
import re
def list_to_patt(lst: Sequence[str], name: str) -> str:
"""
Create a regex pattern in string form capable of matching each element
in a list.
Beware of having empty string in lst!
Arguments:
lst: list of strings for which a regex pattern is to be determined.
name: name to be given to the output group pattern.
Returns:
regex pattern in string form that can match each element in lst.
"""
# longer strings need to be matched first
lst = sorted(lst, key=len, reverse=True)
patt = "|".join(re.escape(elem) for elem in lst)
patt = f"(?P<{name}>{patt})"
return patt | bigcode/self-oss-instruct-sc2-concepts |
import struct
def parse_linkidandlinkedbehavior(number):
"""
Returns a link ID index and behavior tuple for the given number.
"""
number = int(number)
byteval = struct.pack('>i', number)
(linkid, junk, behavior) = struct.unpack('>bbH', byteval)
return (linkid, behavior) | bigcode/self-oss-instruct-sc2-concepts |
def echo(text):
"""create job that just prints text"""
return ['echo', text] | 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.