seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def create_files_dict(file_name, metadata_content, bitstream_content):
"""Create dict of files to upload to S3."""
package_files = [
{
"file_name": f"{file_name}.json",
"file_content": metadata_content,
},
{
"file_name": f"{file_name}.pdf",
"file_content": bitstream_content,
},
]
return package_files | bigcode/self-oss-instruct-sc2-concepts |
def supra_adjacency_matrix(net,includeCouplings=True):
"""Returns the supra-adjacency matrix and a list of node-layer pairs.
Parameters
----------
includeCoupings : bool
If True, the inter-layer edges are included, if False, only intra-layer
edges are included.
Returns
-------
matrix, nodes : numpy.matrix, list
The supra-adjacency matrix and the list of node-layer pairs. The order
of the elements in the list and the supra-adjacency matrix are the same.
"""
return net.get_supra_adjacency_matrix(includeCouplings=includeCouplings) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def expand_wildcards(paths: Union[str, Path]) -> list:
"""Expand the wildcards that may be present in Paths."""
path = Path(paths).expanduser()
parts = path.parts[1:] if path.is_absolute() else path.parts
return [f for f in Path(path.root).glob(str(Path("").joinpath(*parts)))] | bigcode/self-oss-instruct-sc2-concepts |
def test_arg_index_attrs() -> None:
"""Accessing argument index and attributes."""
assert "{0.real}, {0.imag}".format(3 - 5j) == "3.0, -5.0"
class Point:
"""Point with x-y coordinates."""
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def __str__(self) -> str:
return "Point({self.x}, {self.y})".format(self=self)
assert str(Point(3, 4)) == "Point(3, 4)"
assert "x: {0[0]}, y: {0[1]}".format((3, 4)) == "x: 3, y: 4" | bigcode/self-oss-instruct-sc2-concepts |
import torch
def validate(model, testloader, criterion):
"""Validate the model
Arguments:
model -- The network to validate
testloader -- Test data
criterion -- Loss function to use
"""
test_loss = 0
accuracy = 0
for images, targets in testloader:
images.resize_(images.size()[0], 784)
output = model.forward(images)
test_loss += criterion(output, targets).item()
class_probabilities = torch.exp(output)
equality = (targets.data == class_probabilities.max(dim=1)[1])
accuracy += equality.type(torch.FloatTensor).mean()
return test_loss, accuracy | bigcode/self-oss-instruct-sc2-concepts |
def add_integers(*args: int) -> int:
"""Sum integers.
Arguments:
*args: One or more integers.
Returns:
Sum of integers.
Raises:
TypeError: No argument was passed or a passed argument is not of type
`int`.
Example:
>>> add_integers(3, 4)
7
"""
if not len(args):
raise TypeError(
f"{add_integers.__name__}() requires at least one argument"
)
for i in args:
if not isinstance(i, int):
raise TypeError(
f"Passed argument of type '{type(i).__name__}', but only "
f"integers allowed: {i}"
)
return sum(args) | bigcode/self-oss-instruct-sc2-concepts |
def select_by_year(year, D):
"""Select year from specification given in dictionary or list of ranges.
Examples:
>>> spec = {(..., 1990): 'foo',
... 1991: 'bar',
... (1992, 2000): 'foobar',
... (2001, ...): 'blah'}
>>> select_by_year(1990, spec)
'foo'
>>> select_by_year(1991, spec)
'bar'
>>> select_by_year(1999, spec)
'foobar'
>>> select_by_year(2010, spec)
'blah'
"""
# Must have a list of specifications
if hasattr(D, 'items'):
D = list(D.items())
# We want a sorted and normalized list
spec = []
for item, value in D:
if isinstance(item, (tuple, list)):
a, b = item
else:
a = b = item
a = -float('inf') if a in [..., None] else a
b = float('inf') if b in [..., None] else b
spec.append((a, b, value))
spec.sort()
# Now let us test each interval
for a, b, value in spec:
if a <= year <= b:
return value
else:
raise ValueError('no valid range for year %s: %s' % (year, spec)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def md(MD_tag):
"""
Given MD tag and a sequence, find the number of matched, deletion, and substitution bps
Return: 1-level dictionary
"""
#matchLens = re.sub("\D"," ",MD_tag).split() #replace non-digit chars by blanks
#matchLens = map(int, matchLens) #length of the matches before a mismatch/deletion
match_len = sum(map(int,re.findall("\d+",MD_tag))) #Get all the numbers in MD tag, these are the number of matches
nonMatches = re.findall("\D+",MD_tag) #mismatch/deletion, replace digits by blanks
del_len = 0
sub_len = 0
for string in nonMatches:
if string.startswith('^'): # deletion
del_len += (len(string) - 1)
else: # substitution
sub_len += len(string)
return {'match_len':match_len, 'del_len':del_len, 'sub_len':sub_len} | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sqlite_md5(text):
"""
md5 - Returns the md5 of the text
"""
if (text!=None):
hash = hashlib.md5()
hash.update(text.encode("utf-8"))
return hash.hexdigest()
return None | bigcode/self-oss-instruct-sc2-concepts |
import random
def MERB_config(BIM):
"""
Rules to identify a HAZUS MERB configuration based on BIM data
Parameters
----------
BIM: dictionary
Information about the building characteristics.
Returns
-------
config: str
A string that identifies a specific configration within this buidling
class.
"""
year = BIM['year_built'] # just for the sake of brevity
# Roof cover
if BIM['roof_shape'] in ['gab', 'hip']:
roof_cover = 'bur'
# no info, using the default supoorted by HAZUS
else:
if year >= 1975:
roof_cover = 'spm'
else:
# year < 1975
roof_cover = 'bur'
# shutters
if year >= 2000:
shutters = BIM['WBD']
else:
if BIM['WBD']:
shutters = random.random() < 0.45
else:
shutters = False
# Wind Debris (widd in HAZSU)
# HAZUS A: Res/Comm, B: Varies by direction, C: Residential, D: None
WIDD = 'C' # residential (default)
if BIM['occupancy_class'] in ['RES1', 'RES2', 'RES3A', 'RES3B', 'RES3C',
'RES3D']:
WIDD = 'C' # residential
elif BIM['occupancy_class'] == 'AGR1':
WIDD = 'D' # None
else:
WIDD = 'A' # Res/Comm
# Metal RDA
# 1507.2.8.1 High Wind Attachment.
# Underlayment applied in areas subject to high winds (Vasd greater
# than 110 mph as determined in accordance with Section 1609.3.1) shall
# be applied with corrosion-resistant fasteners in accordance with
# the manufacturer’s instructions. Fasteners are to be applied along
# the overlap not more than 36 inches on center.
if BIM['V_ult'] > 142:
MRDA = 'std' # standard
else:
MRDA = 'sup' # superior
# Window area ratio
if BIM['window_area'] < 0.33:
WWR = 'low'
elif BIM['window_area'] < 0.5:
WWR = 'med'
else:
WWR = 'hig'
if BIM['stories'] <= 2:
bldg_tag = 'MERBL'
elif BIM['stories'] <= 5:
bldg_tag = 'MERBM'
else:
bldg_tag = 'MERBH'
bldg_config = f"{bldg_tag}_" \
f"{roof_cover}_" \
f"{WWR}_" \
f"{int(shutters)}_" \
f"{WIDD}_" \
f"{MRDA}_" \
f"{int(BIM['terrain'])}"
return bldg_config | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_accuracy(logits, ys_ref, pad):
"""Compute teacher-forcing accuracy.
Args:
logits (FloatTensor): `[B, T, vocab]`
ys_ref (LongTensor): `[B, T]`
pad (int): index for padding
Returns:
acc (float): teacher-forcing accuracy
"""
pad_pred = logits.view(ys_ref.size(0), ys_ref.size(1), logits.size(-1)).argmax(2)
mask = ys_ref != pad
numerator = torch.sum(pad_pred.masked_select(mask) == ys_ref.masked_select(mask))
denominator = torch.sum(mask)
acc = float(numerator) * 100 / float(denominator)
return acc | bigcode/self-oss-instruct-sc2-concepts |
def length(iterable):
"""
Return number of items in the iterable.
Attention: this function consumes the whole iterable and
can never return if iterable has infinite number of items.
:Example:
>>> length(iter([0, 1]))
2
>>> length([0, 1, 2])
3
"""
try:
return len(iterable)
except TypeError:
return sum(1 for item in iterable) | bigcode/self-oss-instruct-sc2-concepts |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the pgdb Connection
constructor.
"""
dsn['password'] = dsn['passwd']
del dsn['passwd']
dsn['database'] = dsn['db']
del dsn['db']
return [], dsn | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_request(url: str, headers: dict, path: str)->dict:
"""
Perform an HTTP GET request
:param url: the url to request
:param headers: a dict containing the ZT Auth header
:param path: the path at the url to request
:return: a dict representing the returned JSON object.
raises a requests.exceptions.HTTPError when th response is not 200
"""
_url = url + path
r = requests.get(_url, headers=headers)
r.raise_for_status()
return r.json() | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_iso_8601(dt):
"""Format a datetime as an iso 8601 string - YYYY-MM-DDTHH:MM:SS with optional timezone +HH:MM."""
if dt:
return dt.replace(microsecond=0).isoformat()
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import List
def get_key_mapping(inverse_mapping: Dict[Any, List[str]]) -> Dict[str, Any]:
"""Returns the key mapping from the inverse mapping.
Args:
inverse_mapping: A mapping from the mapped input to the list of keys.
Returns:
a mapping from the keys to their mapped input.
"""
mapped_keys = {}
for mapped_key, keys in inverse_mapping.items():
for key in keys:
mapped_keys[key] = mapped_key
return mapped_keys | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def combos(indices):
""" Return all combinations of indices in a list of index sublists.
Arguments:
indices: list of int lists
List of index lists.
"""
return list(itertools.product(*indices)) | bigcode/self-oss-instruct-sc2-concepts |
def setDefaults(configObj={}):
""" Return a dictionary of the default parameters
which also been updated with the user overrides.
"""
gain = 7 # Detector gain, e-/ADU
grow = 1 # Radius around CR pixel to mask [default=1 for 3x3 for non-NICMOS]
ctegrow = 0 # Length of CTE correction to be applied
rn = 5 # Read noise in electrons
snr = "4.0 3.0" # Signal-to-noise ratio
scale = "0.5 0.4" # scaling factor applied to the derivative
backg = 0 # Background value
expkey = "exptime" # exposure time keyword
paramDict={"gain":gain,
"grow": grow,
"ctegrow":ctegrow,
"rn":rn,
"snr":snr,
"scale":scale,
"backg":backg,
"expkey":expkey}
if (len(configObj) != 0):
for key in configObj:
paramDict[key]=configObj[key]
return paramDict | bigcode/self-oss-instruct-sc2-concepts |
def init_comm(base_comm, grid_shape):
"""Create an MPI communicator with a cartesian topology."""
return base_comm.Create_cart(grid_shape, len(grid_shape) * (False,),
reorder=False) | bigcode/self-oss-instruct-sc2-concepts |
def is_test(obj) -> bool:
"""Is the object a test, i.e. test_func()?"""
assert hasattr(obj, "__name__")
obj_name = obj.__name__.lower()
patterns = ("test", "_test", "__test")
return any(obj_name.startswith(pattern) for pattern in patterns) | bigcode/self-oss-instruct-sc2-concepts |
def harm(x,y):
"""Harmonic mean of x and y"""
return x*y/(x+y) | bigcode/self-oss-instruct-sc2-concepts |
def remove_dups(lst):
"""
Inputs:
lst - A list object
Outputs:
Returns a new list with the same elements in lst,
in the same order, but without duplicates. Only
the first element of each replicated element will
appear in the output.
"""
result = []
dups = set()
for item in lst:
if item not in dups:
result.append(item)
dups.add(item)
return result | bigcode/self-oss-instruct-sc2-concepts |
def normalize_service_argument(argument):
"""
normalize service name and set type: $object, $variable$
Examples:
>>> normalize_service_argument('$Mongodb')
['Mongodb', 'object']
>>> normalize_service_argument('%batch_size%')
['batch_size', 'variable']
"""
if isinstance(argument, dict):
dict_argument = {}
for key, value in argument.items():
if value.startswith('$'):
dict_argument[key] = [value[1:], 'object']
elif value.startswith('%') and value.endswith('%'):
dict_argument[key] = [value[1:-1], 'variable']
return [dict_argument, 'dict']
elif type(argument) is str:
if argument.startswith('$'):
return [argument[1:], 'object']
elif argument.startswith('%') and argument.endswith('%'):
return [argument[1:-1], 'variable']
return [None] | bigcode/self-oss-instruct-sc2-concepts |
import re
def camel_to_snake(camel):
"""
make a camelcase from a snakecase
with a few things thrown in - we had a case where
we were parsing a spreadsheet and using the headings as keys in an object
one of the headings was "Who Uploads?"
"""
camel = camel.strip()
camel = re.sub(' ', '', camel)
camel = re.sub('?', '', camel)
return re.sub(r'(?<!^)(?=[A-Z])', '_', camel).lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def format_board(board: List[str]) -> str:
"""Return the board formatted for output"""
out_board = ''
for i in range(0, len(board)):
if i == 0 or i % 3 == 0:
out_board += '\n' + '-------------' + '\n|'
tic = board[i] if board[i] in 'XO' else i + 1
out_board += f' {tic} |'
out_board += '\n' + '-' * 13
return out_board.strip() | bigcode/self-oss-instruct-sc2-concepts |
import re
def _include_exclude(
dictionary: dict,
include_pattern: str,
exclude_pattern: str,
) -> bool:
"""
Filters the items of a dictionary based on a include / exclude regexp pair.
Returns `True` if the size of the dictionary changed.
"""
incl, excl = re.compile(include_pattern), re.compile(exclude_pattern)
keys = list(dictionary.keys())
for k in keys:
if excl.match(k) or not incl.match(k):
del dictionary[k]
return len(dictionary) != len(keys) | bigcode/self-oss-instruct-sc2-concepts |
def fruity_file(models_path):
"""Return fruity sample data file as a Path object."""
return models_path.joinpath("fruity.txt") | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _modified_date(f: Path) -> str:
"""Get the modified date of the file"""
return str(f.stat().st_mtime) | bigcode/self-oss-instruct-sc2-concepts |
def separate_gradients(gradients, weight_vars, input_vars):
"""
split the gradient dictionary up into one for input and one for weights.
Parameters
----------
gradients: dict:
dictionary of gradients. Should be str, list[Objective] key/value pairs.
input_vars: list:
the input variables of the Objective
weight_vars: list:
the internal weight variables of the Objective
Returns
-------
tuple(dict):
a pair of dictionaries, respectively the gradients for input and weight variables.
"""
i_grad = {}
w_grad = {}
for var in input_vars:
i_grad[var] = gradients[var]
for var in weight_vars:
w_grad[var] = gradients[var]
return w_grad, i_grad | bigcode/self-oss-instruct-sc2-concepts |
import re
def subject_id_of(path) -> str:
"""
Returns the subject ID closest to the end of the input string or Path.
Inputs
------
path : str or Path
String or Path containing the subject ID.
Returns
-------
str
Subject ID found in the filename
Raises
------
RuntimeError
If no subject ID found in input filename.
"""
try:
subject_ids = re.findall(r"sub-(\d+)", str(path))
return subject_ids[-1]
except IndexError:
raise RuntimeError(f"No subject ID found in {path}") | bigcode/self-oss-instruct-sc2-concepts |
import logging
import inspect
def get_file_logger(
log_file=None,
log_filemode='a',
log_level=logging.INFO,
log_msg_fmt='%(asctime)s %(levelname)s %(message)s',
log_date_fmt='%a, %d %b %Y %H:%M:%S',
log_prefix=None
):
"""
Purpose:
Get Logger to file
Args:
log_level (log level from logging): Minimum level for messages to log
log_msg_fmt (String): Mesage format for all logs with variable
substitution for known logging options
log_date_fmt (Stringg): Dateformat to append to message
log_prefix (String): prefix to append to message
Return:
logging (Python logging object): Configured logging object
Examples:
>>> logging = get_file_logger()
or
>>> logging =\
get_file_logger(
log_level=logging.ERROR,
prefix='[test_script]: '',
log_file='./script_im_writing.log'
)
"""
# If no log_file is specified, find the calling file and use that name
if not log_file:
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
log_file = calframe[1].filename.replace('.py', '.log')
if log_prefix:
log_msg_fmt = f"{log_prefix}{log_msg_fmt}"
logging.basicConfig(
filename=log_file,
filemode=log_filemode,
level=log_level,
format=log_msg_fmt,
datefmt=log_date_fmt,
)
return logging | bigcode/self-oss-instruct-sc2-concepts |
def class_name(obj):
""" Returns the class name of an object"""
return obj.__class__.__name__ | bigcode/self-oss-instruct-sc2-concepts |
def Split(string,n):
"""Split a string into lines of length n with \n in between them"""
N =len(string)//n
return '\n'.join([string[i*n:(i+1)*n] for i in range(N)]+[string[N*n:]]) | bigcode/self-oss-instruct-sc2-concepts |
def molm2_to_molec_cm2(spc_array):
"""
Convert moles/m2 to molec/cm2
"""
avo_num = 6.0221409e23
molec_per_m2 = spc_array * avo_num
molec_per_cm2 = molec_per_m2 * 1e4
return molec_per_cm2 | bigcode/self-oss-instruct-sc2-concepts |
def dms2dd(dms):
"""
DMS to decimal degrees.
Args:
dms (list). d must be negative for S and W.
Return:
float.
"""
d, m, s = dms
return d + m/60. + s/3600. | bigcode/self-oss-instruct-sc2-concepts |
def br(value):
""" Replaces newlines with HTML-style <br>'s """
return value.replace("\n", "<br>") | bigcode/self-oss-instruct-sc2-concepts |
import math
def binary_entropy(p):
"""
Uses the binary entropy function denoted H(p) in information theory/statistics
Computes the entropy of a Bernoulli process with probability of success p
When p = .5, entropy is at its max value (unbiased bit, most common unit of information entropy)
@param {float} p = probability of success p
@return {float}
"""
return -p * math.log(p,2) - (1 - p) * math.log(1-p, 2) | bigcode/self-oss-instruct-sc2-concepts |
def quantify(iterable, pred=bool):
"""Count how many times the predicate is true.
:param iterable: source of values
:param pred: the predicate whose result is to be quantified when applied to
all values in iterable. Defaults to bool()
"""
# quantify([2, 56, 3, 10, 85], lambda x: x >= 10) -> 3
return sum(map(pred, iterable)) | bigcode/self-oss-instruct-sc2-concepts |
def ensure_all_tokens_exist(input_tokens, output_tokens, include_joiner_token,
joiner):
"""Adds all tokens in input_tokens to output_tokens if not already present.
Args:
input_tokens: set of strings (tokens) we want to include
output_tokens: string to int dictionary mapping token to count
include_joiner_token: bool whether to include joiner token
joiner: string used to indicate suffixes
Returns:
string to int dictionary with all tokens in input_tokens included
"""
for token in input_tokens:
if token not in output_tokens:
output_tokens[token] = 1
if include_joiner_token:
joined_token = joiner + token
if joined_token not in output_tokens:
output_tokens[joined_token] = 1
return output_tokens | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
def async_return(result):
"""Mock a return from an async function."""
future = asyncio.Future()
future.set_result(result)
return future | bigcode/self-oss-instruct-sc2-concepts |
def get_ttylog_lines_from_file(ttylog):
"""Read from ttylog. If lines have '\r' at end, remove that '\r'. Return the read lines"""
ttylog_file = open(ttylog,'r',errors='ignore', newline='\n',encoding='utf-8')
ttylog_read_data = ttylog_file.read()
#Replace escaped double qoutes with qoutes
ttylog_read_data = ttylog_read_data.replace(r'\"','"')
ttylog_file.close()
ttylog_lines = ttylog_read_data.split('\n')
ttylog_lines_file = []
for line in ttylog_lines:
if len(line) > 0:
if line[-1] == '\r':
ttylog_lines_file.append(line[:-1])
else:
ttylog_lines_file.append(line)
return ttylog_lines_file | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def read_input_file(input_file_path):
""" read the input file and convert the contents
to a list of ints """
p = Path(input_file_path)
with p.open() as f:
data = list(map(int, f.readlines()))
return data | bigcode/self-oss-instruct-sc2-concepts |
def variable_to_jsonpath(p):
"""Converts a expression variable into a valid JSON path starting with $."""
# replace JSON_ with $ and _ with .
return p.var.replace('JSON_', '$').replace('_', '.') | bigcode/self-oss-instruct-sc2-concepts |
def remove_bottom(pnts, gt_box, bottom):
"""
Args:
* `pnts`: Lidar Points
* `gt_box`: The 3D bounding box of the object
* `bottom`: A height threshold, deciding which points to keep\n
Return:
`pnts` whose heights are larger than -dz/2 + bottom, where dz is from the `gt_box`.
"""
if bottom == 0.0:
return pnts
zthresh = -gt_box[5] / 2 + bottom
keep_bool = pnts[:, 2] > zthresh
return pnts[keep_bool] | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _convert_to_datetime(unix_timestamp):
"""
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
"""
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, TypeError):
return "Invalid Timestamp" | bigcode/self-oss-instruct-sc2-concepts |
def _extract_username(request):
"""
Look for the "username" in a request. If there is no valid username we
will simply be throttling on IP alone.
"""
return request.POST.get("username", "notfound").lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import time
def tmp_path(base: str, _time_stamp: List[int] = []) -> str:
"""Get a temporary path containing a time stamp."""
if not _time_stamp:
_time_stamp.append(int(time.time()))
return f"{base}{_time_stamp[0]}" | bigcode/self-oss-instruct-sc2-concepts |
def is_error_response(res):
"""
check the status code of http response
:param res: http response
:return: True if the status code less than 200 or larger than 299;
False if the status code is between 200 and 299
"""
if res is None:
return True
if res.status_code < 200 or res.status_code > 299:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_content(*filename:str) -> str:
""" Gets the content of a file or files and returns
it/them as a string
Parameters
----------
filename : (str)
Name of file or set of files to pull content from
(comma delimited)
Returns
-------
str:
Content from the file or files
"""
content = ""
for file in filename:
with open(file, "r") as full_description:
content += full_description.read()
return content | bigcode/self-oss-instruct-sc2-concepts |
def get_index(fields, keys):
""" Get indices of *keys*, each of which is in list *fields* """
assert isinstance(keys, list)
assert isinstance(fields, list)
return [fields.index(k) for k in keys] | bigcode/self-oss-instruct-sc2-concepts |
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
num1:
The first number to find the lcm for
num2:
The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bigger % num2 == 0:
return bigger
bigger += 1 | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def find_type_object(type_name):
"""Try to find the type object given the name of the type.
Deals with cases such as `argparse.ArgumentParser` where a module needs to
be imported before we can find the correct type object. If the type object
cannot be found, a `NameError` is raised.
Parameters
----------
type_name : str
The name of the type to search for.
Returns
-------
type_object : type
The type object corresponding to the given type name.
"""
if '.' in type_name:
# Full module name specified. Try to import it.
module_name, object_name = type_name.rsplit('.', maxsplit=1)
try:
module = importlib.import_module(module_name)
except ModuleNotFoundError:
raise NameError(f'Type checker could not import `{module_name}`.')
if object_name not in module.__dict__:
raise NameError(f'Type checker could not find `{type_name}`.')
return module.__dict__[object_name]
else:
# No module name specified. Assume it's a python buildin type.
return eval(type_name) | bigcode/self-oss-instruct-sc2-concepts |
def add(x, y):
"""Add two coordinate pairs."""
return (x[0] + y[0], x[1] + y[1]) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def get_permutations(a):
"""
get all permutations of list a
"""
p = []
for r in range(len(a)+1):
c = list(itertools.combinations(a,r))
for cc in c:
p += list(itertools.permutations(cc))
return p | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def fm_string(dt_string, millisecond=False):
"""
Input a date string and returns a datetime object.
"""
if millisecond:
return datetime.strptime(
dt_string, '%Y/%m/%d %H:%M:%S.%f')
else:
return datetime.strptime(
dt_string, '%Y/%m/%d %H:%M:%S') | bigcode/self-oss-instruct-sc2-concepts |
def _is_weekend(date):
"""Returns whether the date is a weekend."""
return date.isoweekday() in (6, 7) # Saturday, Sunday | bigcode/self-oss-instruct-sc2-concepts |
import math
def _selection_size_heuristic(num_samples):
"""Return size of mini-batch, given size of dataset."""
# Incrase size of mini-batch gradually as number of samples increases,
# with a soft cap (using log).
# But do not return size larger than number of samples
return min(num_samples,
int(20.0 *
(math.log(num_samples + 10, 2) - math.log(10.0) + 1.0))) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_md5(unicode):
"""
Generate an MD5 hash
Args:
unicode (bytes): Unicode bytes representing the string you want to be hashed
Returns:
str: An MD5 hash (hex characters)
"""
hasher = hashlib.md5()
hasher.update(unicode)
return hasher.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import math
def factors_of(x):
"""Returns a set of tuples of factors of x.
Examples
--------
>>> factors_of(12)
{(1, 12), (2, 6), (3, 4)}
>>> factors_of(20)
{(1, 20), (2, 10), (4,5)}
"""
factors = set()
sqrt_x = math.sqrt(x)
if sqrt_x == int(sqrt_x):
factors.add((sqrt_x, sqrt_x))
for d in range(math.floor(sqrt_x)): # d for divisor
if x % d == 0:
factors.add((d,int(x/d)))
return factors | bigcode/self-oss-instruct-sc2-concepts |
import math
def uv(sped, drct2):
"""Convert to u,v components."""
dirr = drct2 * math.pi / 180.00
s = math.sin(dirr)
c = math.cos(dirr)
u = round(-sped * s, 2)
v = round(-sped * c, 2)
return u, v | bigcode/self-oss-instruct-sc2-concepts |
def getfmt(n,dtype ="d"):
"""
Generates the binary format n dtype
defualts to double
@param n: number of particles
@param dtype: data type
returns the format string used to decode the binary data
"""
fmt = ""
fmt += dtype
for i in range(n):
fmt += dtype
return fmt | bigcode/self-oss-instruct-sc2-concepts |
def clean_timestamp(timestamp, format=False):
"""
used to remove unwanted characters from the overly long timestamp in the json data of a tweet
eg: timestamp comes in as 'Thu Dec 17 13:44:24 +0000 2020' and for now we only want 'Thu Dec 17 13:44'
"""
cleaned_timestamp_list = str(timestamp).split(' ')[0:4]
# remove the seconds from the actual time part of the string
cleaned_timestamp_list[3] = cleaned_timestamp_list[3][0:5]
# join them back into a string
cleaned_timestamp = ' '.join(cleaned_timestamp_list)
return cleaned_timestamp | bigcode/self-oss-instruct-sc2-concepts |
import torch
def transform_tensor_by_dict(tensor, map_dict, device="cpu"):
"""
Given a tensor of any shape, map each of its value
to map_dict[value].
:param tensor: input tensor
:param map_dict: value mapping dict. Both key and value are numbers
:return: mapped tensor, type is FloatTensor
"""
mapped_tensor = torch.FloatTensor(
[map_dict[k] for k in tensor.reshape(-1).cpu().tolist()]
).reshape(tensor.shape).to(device)
return mapped_tensor | bigcode/self-oss-instruct-sc2-concepts |
def connection_callback(isolation_level=None,
read_only=None,
deferrable=None,
application_name=None,
inherit=None):
"""
Decorator for functions used in :meth:`IConnectionManager.open_and_call`.
When the function is called, it will be given a connection that has
the given traits.
Use ``inherit=BaseClass.func`` when you're overriding a callback
function ``func``.
"""
if inherit is not None:
isolation_level = isolation_level or inherit.transaction_isolation_level
application_name = application_name or inherit.transaction_application_name
read_only = read_only or inherit.transaction_read_only
deferrable = deferrable or inherit.transaction_deferrable
def f(func):
func.transaction_isolation_level = isolation_level
func.transaction_read_only = read_only
func.transaction_deferrable = deferrable
func.transaction_application_name = application_name
return func
return f | bigcode/self-oss-instruct-sc2-concepts |
def _generate_variable_name(variable_counter):
"""
Generates a unique variable name.
"""
return "v{}".format(variable_counter.next()) | bigcode/self-oss-instruct-sc2-concepts |
def null_padded(string, length):
"""
Force a string to a given length by right-padding it with zero-bytes,
clipping the initial string if neccessary.
"""
return bytes(string[:length] + ('\0' * (length - len(string))), 'latin1') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def get_border_width(width: int) -> Dict[str, int]:
"""Replicates border_width parameter from Gtk3, by producing a dict equivalent margin parameters
Args:
width (int): the border width
Returns:
Dict[str, int]: the dict with margin parameters
"""
return dict(
margin_start=width,
margin_end=width,
margin_top=width,
margin_bottom=width,
) | bigcode/self-oss-instruct-sc2-concepts |
def filter_dataframe(df, column, value):
"""Filter DataFrame for a column and a value or a list of value
Parameters
----------
df: DataFrame
DataFrame to filter
column: str
column name
value: list or 1dim value
values
Returns
-------
DataFrame: filtered DataFrame
"""
if type(value) == list:
if len(value) > 1:
df_filtered = df.loc[df[column].isin(value)].copy()
else:
df_filtered = df.loc[df[column] == value[0]].copy()
else:
df_filtered = df.loc[df[column] == value].copy()
return df_filtered | bigcode/self-oss-instruct-sc2-concepts |
def phi(T):
"""
:param T: [°C] Temperatura
:return: Factor que cuantifica la rapidez de cambios en los canales iónicos debido a la temperatura (T).
"""
Q_10 = 3 # Radio de las tasas por un incremento de temperatura de 10 °C
T_base = 6.3 # Temperatura base [°C]
return Q_10 ** ((T - T_base) / 10.0) | bigcode/self-oss-instruct-sc2-concepts |
def int_to_rgb(int_):
"""Integer to RGB conversion"""
red = (int_ >> 24) & 255
green = (int_ >> 16) & 255
blue = (int_ >> 8) & 255
return red, green, blue | bigcode/self-oss-instruct-sc2-concepts |
def model_uname(value):
"""Returns a model name such as 'baking_oils'"""
words = value._meta.verbose_name.lower().replace("&", "").split()
return "_".join(words) | bigcode/self-oss-instruct-sc2-concepts |
import re
def chunk_paf(paf_record):
""" Takes a PafRecord object or a full cs string and returns a list of fields from its cs string """
if type(paf_record) == str:
cs = paf_record
else:
cs = paf_record.tags["cs"]
separable_cs = re.sub(r'(?<!\A)([-:*+])', r',\1', cs)
return separable_cs.split(",") | bigcode/self-oss-instruct-sc2-concepts |
def heatmap_figsize(nrow, ncol=None):
"""Generate size tuple for heatmap based on number of rows and columns"""
if ncol is None:
ncol = nrow
return ncol * 0.3 + 3, nrow * 0.3 | bigcode/self-oss-instruct-sc2-concepts |
def getBit(val, idx: int) -> int:
"""Gets a bit."""
return 1&(val>>idx) | bigcode/self-oss-instruct-sc2-concepts |
def flatten_list(nested_list):
"""
Given a list of lists, it flattens it to a single list.
:param nested_list: list of lists
:return: Single list containing flattened list.
"""
return [item for sub_list in nested_list for item in sub_list] | bigcode/self-oss-instruct-sc2-concepts |
def rn_sub(a, b):
"""
a - b
uses rn_sum and rn_neg to get the difference like a + (-b)
:param a: RN object
:param b: RN object
:return: difference array
"""
return a + (-b) | bigcode/self-oss-instruct-sc2-concepts |
def split_sig(params):
"""
Split a list of parameters/types by commas,
whilst respecting brackets.
For example:
String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3]
=> ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]']
"""
result = []
current = ''
level = 0
for char in params:
if char in ('<', '{', '['):
level += 1
elif char in ('>', '}', ']'):
level -= 1
if char != ',' or level > 0:
current += char
elif char == ',' and level == 0:
result.append(current)
current = ''
if current.strip() != '':
result.append(current)
return result | bigcode/self-oss-instruct-sc2-concepts |
def sum_factorial_digits(x):
"""
Returns the sum of the factorials of the digits of x
"""
factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
sum_factorial_digits_ = 0
for i in str(x):
sum_factorial_digits_ += factorials[int(i)]
return(sum_factorial_digits_) | bigcode/self-oss-instruct-sc2-concepts |
import random
import time
def retry(initial_delay,
max_delay,
factor=2.0,
jitter=0.25,
is_retriable=None):
"""Simple decorator for wrapping retriable functions.
Args:
initial_delay: the initial delay.
factor: each subsequent retry, the delay is multiplied by this value.
(must be >= 1).
jitter: to avoid lockstep, the returned delay is multiplied by a random
number between (1-jitter) and (1+jitter). To add a 20% jitter, set
jitter = 0.2. Must be < 1.
max_delay: the maximum delay allowed (actual max is
max_delay * (1 + jitter).
is_retriable: (optional) a function that takes an Exception as an argument
and returns true if retry should be applied.
"""
if factor < 1:
raise ValueError('factor must be >= 1; was %f' % (factor,))
if jitter >= 1:
raise ValueError('jitter must be < 1; was %f' % (jitter,))
# Generator to compute the individual delays
def delays():
delay = initial_delay
while delay <= max_delay:
yield delay * random.uniform(1 - jitter, 1 + jitter)
delay *= factor
def wrap(fn):
"""Wrapper function factory invoked by decorator magic."""
def wrapped_fn(*args, **kwargs):
"""The actual wrapper function that applies the retry logic."""
for delay in delays():
try:
return fn(*args, **kwargs)
except Exception as e: # pylint: disable=broad-except)
if is_retriable is None:
continue
if is_retriable(e):
time.sleep(delay)
else:
raise
return fn(*args, **kwargs)
return wrapped_fn
return wrap | bigcode/self-oss-instruct-sc2-concepts |
def fixup_acl(acl: str) -> str:
"""
Replace standard ip/mask entries with "none" and "any" if present
"""
if acl is None:
acl = "none"
if acl == '':
acl = "none"
if acl == "255.255.255.255/32":
acl = "none"
if acl == "0.0.0.0/0":
acl = "any"
return acl | bigcode/self-oss-instruct-sc2-concepts |
import aiohttp
import base64
async def render(eqn: str, **kwargs) -> bytes:
"""
Render LaTeX using Matthew Mirvish's "TeX renderer slave microservice thing".
Returns raw image data or raises ValueError if an error occurred.
"""
kwargs["source"] = eqn
async with aiohttp.request("POST", "http://tex-slave/render", json=kwargs) as resp:
result = await resp.json()
if result["status"] != "ok":
if "internal_error" in result:
raise ValueError(f"Internal error: `{result['internal_error']}`")
raise ValueError(result["reason"])
data = result["result"]
return base64.b64decode(data) | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize(s):
""" Remove escape codes and non ASCII characters from output
"""
ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
s = ansi_escape.sub('', s)
mpa = dict.fromkeys(range(32))
return s.translate(mpa).strip().replace(' ', '') | bigcode/self-oss-instruct-sc2-concepts |
def get_max_region(regions, field='area'):
"""Return the region from the list that maximizes the field."""
max_region = regions[0]
for i in range(1, len(regions)):
if regions[i][field] > max_region[field]:
max_region = regions[i]
return max_region | bigcode/self-oss-instruct-sc2-concepts |
def get_bucket_config(config, bucket_name):
"""
Pulls correct bucket config from application config based on name/alias.
Args:
config(dict)
bucket_name(string): bucket name or bucket reference name
Returns:
dict | None: config for bucket or None if not found
"""
bucket_config = None
for bucket in config["buckets"]:
if bucket_name == bucket["referenceName"]:
bucket_config = bucket
return bucket_config | bigcode/self-oss-instruct-sc2-concepts |
def _has_dns_message_content_type(flow):
"""
Check if HTTP request has a DNS-looking 'Content-Type' header
:param flow: mitmproxy flow
:return: True if 'Content-Type' header is DNS-looking, False otherwise
"""
doh_content_types = ['application/dns-message']
if 'Content-Type' in flow.request.headers:
if flow.request.headers['Content-Type'] in doh_content_types:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def cast_to_str(labels, nested=False):
""" Convert every label to str format.
If nested is set to True, a flattened version of the input
list is also returned.
Args:
labels: list
Input labels
nested: bool
Indicate if the input list contains (or may contain) sublists.
False by default. If True, a flattened version of the
list is also returned.
Results:
labels_str: list
Labels converted to str format
labels_str_flat: list
Flattened list of labels. Only returned if nested is set to True.
"""
if not nested:
labels_str = [str(x) for x in labels]
return labels_str
else:
labels_str = []
labels_str_flat = []
for x in labels:
if isinstance(x, list):
sublist = []
for xx in x:
labels_str_flat.append(str(xx))
sublist.append(str(xx))
labels_str.append(sublist)
else:
labels_str_flat.append(str(x))
labels_str.append(str(x))
return labels_str, labels_str_flat | bigcode/self-oss-instruct-sc2-concepts |
def binary_string_to_int(s):
"""
Convert a string of a binary representation to a number
:param s: a binary representation as a string
:return: an integer
"""
return int(s,2) | bigcode/self-oss-instruct-sc2-concepts |
def optimal_merge_pattern(files: list) -> float:
"""Function to merge all the files with optimum cost
Args:
files [list]: A list of sizes of different files to be merged
Returns:
optimal_merge_cost [int]: Optimal cost to merge all those files
Examples:
>>> optimal_merge_pattern([2, 3, 4])
14
>>> optimal_merge_pattern([5, 10, 20, 30, 30])
205
>>> optimal_merge_pattern([8, 8, 8, 8, 8])
96
"""
optimal_merge_cost = 0
while len(files) > 1:
temp = 0
# Consider two files with minimum cost to be merged
for i in range(2):
min_index = files.index(min(files))
temp += files[min_index]
files.pop(min_index)
files.append(temp)
optimal_merge_cost += temp
return optimal_merge_cost | bigcode/self-oss-instruct-sc2-concepts |
def total_mass(particles):
"""
Returns the total mass of the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(3)
>>> particles.mass = [1.0, 2.0, 3.0] | units.kg
>>> particles.total_mass()
quantity<6.0 kg>
"""
return particles.mass.sum() | bigcode/self-oss-instruct-sc2-concepts |
def _str_to_int(_str):
"""Convert the input str to an int if possible
:param _str: input string
:return: integer if text is a digit, else string
"""
return int(_str) if _str.isdigit() else _str | bigcode/self-oss-instruct-sc2-concepts |
def proto_to_bytes(proto):
""" Converts a proto object to a bytes array """
return proto.SerializeToString() | bigcode/self-oss-instruct-sc2-concepts |
def gen_key_i(i, kappa, K):
"""
Create key value where key equals kappa, except:
key_(i mod n) = kappa_(i mod n) XOR K_(i mod n)
Parameters:
i -- integer in [0,n-1]
kappa -- string
K -- string
Return:
key -- list of bool
"""
# Transform string into list of booleans
kappa = list(kappa)
kappa = [bool(int(j)) for j in kappa]
K = list(K)
K = [bool(int(j)) for j in K]
# Initialize new key value
key_i = kappa.copy()
# XOR at indice i
key_i[i] = K[i] ^ kappa[i]
return key_i | bigcode/self-oss-instruct-sc2-concepts |
def get_intent_queries(infold, intent_names, mode):
""" Get list of queries with their corresponding intent number. """
intent_queries = ['sentence\tlabel\n']
for index, intent in enumerate(intent_names):
queries = open(f'{infold}/{mode}set/{intent}.csv', 'r').readlines()
for query in queries[1:]:
phrases = query.split(";")
intent_query = phrases[4][1:-1] + "\t" + str(index)
intent_queries.append(intent_query)
return intent_queries | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def irot(x: int, y: int, deg: int, origin: Tuple[int, int] = (0, 0)) -> Tuple[int, int]:
"""
Rotate an integer point by `deg` around the `origin`. Only works when deg % 90 == 0.
"""
transformed_x = x - origin[0]
transformed_y = y - origin[1]
assert deg % 90 == 0
for _ in range((deg // 90) % 4):
transformed_x, transformed_y = -transformed_y, transformed_x
return (transformed_x + origin[0], transformed_y + origin[1]) | bigcode/self-oss-instruct-sc2-concepts |
def lsearch(l,pattern):
""" Search for items in list l that have substring match to pattern. """
rvals = []
for v in l:
if not v.find(pattern) == -1:
rvals.append(v)
return rvals | bigcode/self-oss-instruct-sc2-concepts |
def parse_to_short_cmd(command):
"""Takes any MAPDL command and returns the first 4 characters of
the command
Examples
--------
>>> parse_to_short_cmd('K,,1,0,0,')
'K'
>>> parse_to_short_cmd('VPLOT, ALL')
'VPLO'
"""
try:
short_cmd = command.split(',')[0]
return short_cmd[:4].upper()
except: # pragma: no cover
return | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def md5sum(path):
"""Return the MD5 hash of the file contents.
"""
BUF_SIZE = 1024 * 64
buf = bytearray(BUF_SIZE)
mv = memoryview(buf)
md5 = hashlib.md5()
with open(path, 'rb') as fh:
while True:
num_bytes = fh.readinto(buf)
md5.update(mv[:num_bytes])
if num_bytes < BUF_SIZE:
break
return md5.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def allowed_file(filename, extensions):
"""
chceck if file extension is in allowed extensions
:param filename: name of file
:param extensions: allowed files extensions
:return: True if extension is correct else False
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions | bigcode/self-oss-instruct-sc2-concepts |
def parse_bool(val):
"""
Parse bool value from cli.
Must be represented by integer number 0 or 1.
Return: (bool) True/False
"""
try:
val = int(val)
assert val == 0 or val == 1, 'Wrong value: {}'.format(val)
except:
raise ValueError('Cannot parse flag {}. It must an integer 0 or 1'.format(val))
return bool(val) | bigcode/self-oss-instruct-sc2-concepts |
def is_list_or_tuple(x):
"""Return True if list or tuple."""
return isinstance(x, tuple) or isinstance(x, list) | 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.