seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def serialize_drive(drive) -> str:
"""
Serialize the drive residues and calibration state to xml.
"""
drivexml = drive.state_to_xml()
return drivexml | bigcode/self-oss-instruct-sc2-concepts |
def return_list_smart(func):
"""
Decorator. If a function is trying to return a list
of length 1 it returns the list element instead
"""
def inner(*args, **kwargs):
out = func(*args, **kwargs)
if not out:
return None
if len(out) == 1:
return out[0]
else:
return out
return inner | bigcode/self-oss-instruct-sc2-concepts |
def vec_bin(v, nbins, f, init=0):
"""
Accumulate elements of a vector into bins
Parameters
----------
v: list[]
A vector of scalar values
nbins: int
The number of bins (accumulators) that will be returned as a list.
f: callable
A function f(v)->[bo,...,bn] that maps the vector into the "bin space".
Accepts one argument (a vector element) and returns a 2-tuple
(i, val), where 'i' is the bin index to be incremented and 'val'
the increment value. If no bin shall be incremented, set i to None.
init: scalar, optional
A scalar value used to initialize the bins. Defaults to 0.
Returns
-------
list
A list of bins with the accumulated values.
"""
acc = [init] * nbins
for e in v:
i, val = f(e)
if i is not None:
acc[i] += val
return acc | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""
input url, output a soup object of that url
"""
page=requests.get(url)
soup = BeautifulSoup(page.text.encode("utf-8"), 'html.parser')
return soup | bigcode/self-oss-instruct-sc2-concepts |
import functools
def if_inactive(f):
"""decorator for callback methods so that they are only called when inactive"""
@functools.wraps(f)
def inner(self, loop, *args, **kwargs):
if not self.active:
return f(self, loop, *args, **kwargs)
return inner | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
import functools
def async_test(loop=None):
"""Wrap an async test in a run_until_complete for the event loop."""
loop = loop or asyncio.get_event_loop()
def _outer_async_wrapper(func):
"""Closure for capturing the configurable loop."""
@functools.wraps(func)
def _inner_async_wrapper(*args, **kwargs):
return loop.run_until_complete(func(*args, **kwargs))
return _inner_async_wrapper
return _outer_async_wrapper | bigcode/self-oss-instruct-sc2-concepts |
def get_strains(output_file):
"""
Returns a dictionary that maps cell id to strain.
Takes Biocellion output as the input file.
"""
strain_map = {}
with open(output_file, 'r') as f:
for line in f:
if line.startswith("Cell:"):
tokens = line.split(',')
cell = int(tokens[0].split(':')[1])
strain = int(tokens[1].split(':')[1])
strain_map[cell] = strain
return strain_map | bigcode/self-oss-instruct-sc2-concepts |
def is_iterable(x):
"""Returns True for all iterables except str, bytes, bytearray,
else False."""
return hasattr(x, "__iter__") and not isinstance(x, (str, bytes, bytearray)) | bigcode/self-oss-instruct-sc2-concepts |
def bprop_scalar_log(x, out, dout):
"""Backpropagator for primitive `scalar_log`."""
return (dout / x,) | bigcode/self-oss-instruct-sc2-concepts |
def _get_drive_distance(maps_response):
"""
from the gmaps response object, extract the driving distance
"""
try:
return maps_response[0].get('legs')[0].get('distance').get('text')
except Exception as e:
print(e)
return 'unknown distance' | bigcode/self-oss-instruct-sc2-concepts |
def calc_tcp(gamma, td_tcd, eud):
"""Tumor Control Probability / Normal Tissue Complication Probability
1.0 / (1.0 + (``td_tcd`` / ``eud``) ^ (4.0 * ``gamma``))
Parameters
----------
gamma : float
Gamma_50
td_tcd : float
Either TD_50 or TCD_50
eud : float
equivalent uniform dose
Returns
-------
float
TCP or NTCP
"""
return 1.0 / (1.0 + (td_tcd / eud) ** (4.0 * gamma)) | bigcode/self-oss-instruct-sc2-concepts |
def get_enrollment(classroom, enrolled_only=False):
"""Gets the list of students that have enrolled.
Args:
classroom: The classroom whose enrollment to get.
enrolled_only: If True, only return the set that are enrolled. Default is
False.
Returns:
Set of Enrollment entries for the classroom.
"""
if enrolled_only:
query = classroom.enrollment_set.filter('is_enrolled =', True)
else:
query = classroom.enrollment_set
return query.fetch(classroom.max_enrollment) | bigcode/self-oss-instruct-sc2-concepts |
def get_price_for_market_state_crypto(result):
"""Returns the price for the current state of the market for Cryptocurrency symbols"""
## Crypto always on REGULAR market state, as it never sleeps ZZzzZZzzz...
return {
"current": result['regularMarketPrice']['fmt'],
"previous": result['regularMarketPreviousClose']['fmt'],
"change": result['regularMarketChange']['fmt'],
"percent": result['regularMarketChangePercent']['fmt']
} | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_latest_archive_url(data: dict) -> str:
"""
Use the given metadata to find the archive URL of the latest image.
"""
metadata = data[-1]
img = metadata["image"]
date = datetime.strptime(metadata["date"], "%Y-%m-%d %H:%M:%S")
archive_path = f"{date.year:04}/{date.month:02}/{date.day:02}/png/{img}.png"
archive_url = f"https://epic.gsfc.nasa.gov/archive/natural/{archive_path}"
return archive_url | bigcode/self-oss-instruct-sc2-concepts |
import shlex
def generate_input_download_command(url, path):
"""Outputs command to download 'url' to 'path'"""
return f"python /home/ft/cloud-transfer.py -v -d {shlex.quote(url)} {shlex.quote(path)}" | bigcode/self-oss-instruct-sc2-concepts |
def _calculate_shrinking_factor(initial_shrinking_factor: float, step_number: int, n_dim: int) -> float:
"""The length of each in interval bounding the parameter space needs to be multiplied by this number.
Args:
initial_shrinking_factor: in each step the total volume is shrunk by this amount
step_number: optimization step -- if we collected only an initial batch, this step is 1
n_dim: number of dimensions
Example:
Assume that ``initial_shrinking_factor=0.5`` and ``step_number=1``. This means that the total volume should
be multiplied by :math:`1/2`. Hence, if there are :math:`N` dimensions (``n_dim``), the length of each
bounding interval should be multiplied by :math:`1/2^{1/N}`.
However, if ``step_number=3``, each dimension should be shrunk three times, i.e. we need to multiply it by
:math:`1/2^{3/N}`.
Returns:
the shrinking factor for each dimension
"""
assert 0 < initial_shrinking_factor < 1, (
f"Shrinking factor must be between 0 and 1. " f"(Was {initial_shrinking_factor})."
)
assert step_number >= 1 and n_dim >= 1, (
f"Step number and number of dimensions must be greater than 0. "
f"(Where step_number={step_number}, n_dim={n_dim})."
)
return initial_shrinking_factor ** (step_number / n_dim) | bigcode/self-oss-instruct-sc2-concepts |
def calc_grv(thickness, height, area, top='slab', g=False):
"""Calculate GRV for given prospect
Args:
thickness [float]: average thickness of reservoir
height [float]: height of hydrocarbon column
area [float]: area of hydrocarbon prospect
top: structure shape, one of `{'slab', 'round', 'flat'}`
g [float]: geometric correction factor
Returns:
grv following `thickness * area * geometric_correction_factor`
"""
if g:
g = g
else:
ratio = thickness / height
if top == 'round':
g = -0.6 * ratio + 1
elif top == 'flat':
g = -0.3 * ratio + 1
else:
g = 1
return thickness * area * g, g | bigcode/self-oss-instruct-sc2-concepts |
import struct
def decode_override_information(data_set):
"""decode result from override info
:param tuple result_set: bytes returned by the system parameter query command R_RI for
override info
:returns: dictionary with override info values
:rtype: dict
"""
override_info = dict()
override_info['Feed_override'] = struct.unpack('!L', data_set[0:4])[0]/100
override_info['Speed_override'] = struct.unpack('!L', data_set[4:8])[0]/100
override_info['Rapid_override'] = struct.unpack('!L', data_set[8:12])[0]/100
return override_info | bigcode/self-oss-instruct-sc2-concepts |
def is_link_displayed(link: str, source: str):
"""Check if the link is explicitly displayed in the source.
Args:
link: a string containing the link to find in the webpage source code.
source: the source code of the webpage.
Returns:
True is the link is visible in the webpage, False otherwise.
"""
return ('>' + link + '</a>') in source or (
'>' + link[:link.find('.')]) in source | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text | bigcode/self-oss-instruct-sc2-concepts |
def create_user2(django_user_model):
"""
create another user
"""
user = django_user_model.objects.create_user(
username='user_2', email='another@gmail.com', password='pass123'
)
return user | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _time_stamp_filename(fname, fmt='%Y-%m-%d_{fname}'):
"""
Utility function to add a timestamp to names of uploaded files.
Arguments:
fname (str)
fmt (str)
Returns: str
"""
return datetime.now().strftime(fmt).format(fname=fname) | bigcode/self-oss-instruct-sc2-concepts |
def _format_size(x: int, sig_figs: int = 3, hide_zero: bool = False) -> str:
"""
Formats an integer for printing in a table or model representation.
Expresses the number in terms of 'kilo', 'mega', etc., using
'K', 'M', etc. as a suffix.
Args:
x (int) : The integer to format.
sig_figs (int) : The number of significant figures to keep
hide_zero (bool) : If True, x=0 is replaced with an empty string
instead of '0'.
Returns:
str : The formatted string.
"""
if hide_zero and x == 0:
return str("")
def fmt(x: float) -> str:
# use fixed point to avoid scientific notation
return "{{:.{}f}}".format(sig_figs).format(x).rstrip("0").rstrip(".")
if abs(x) > 1e14:
return fmt(x / 1e15) + "P"
if abs(x) > 1e11:
return fmt(x / 1e12) + "T"
if abs(x) > 1e8:
return fmt(x / 1e9) + "G"
if abs(x) > 1e5:
return fmt(x / 1e6) + "M"
if abs(x) > 1e2:
return fmt(x / 1e3) + "K"
return str(x) | bigcode/self-oss-instruct-sc2-concepts |
def normalize(df, col_name, replace=True):
"""Normalize number column in DataFrame
The normalization is done with max-min equation:
z = (x - min(x)) / (max(x) - min(x))
replace -- set to False if it's desired to return new DataFrame
instead of editing it.
"""
col = df[col_name]
norm_col = (col - col.min()) / (col.max() - col.min())
if replace:
df[col_name] = norm_col
return df
else:
norm_df = df.copy()
norm_df[col_name] = norm_col
return norm_df | bigcode/self-oss-instruct-sc2-concepts |
import torch
def csv_collator(samples):
"""Merge a list of samples to form a batch.
The batch is a 2-element tuple, being the first element
the BxHxW tensor and the second element a list of dictionaries.
:param samples: List of samples returned by CSVDataset as (img, dict) tuples.
"""
imgs = []
dicts = []
for sample in samples:
img = sample[0]
dictt = sample[1]
# # We cannot deal with images with 0 objects (WHD is not defined)
# if dictt['count'][0] == 0:
# continue
imgs.append(img)
dicts.append(dictt)
data = torch.stack(imgs)
return data, dicts | bigcode/self-oss-instruct-sc2-concepts |
def in_box(coords, box):
"""
Find if a coordinate tuple is inside a bounding box.
:param coords: Tuple containing latitude and longitude.
:param box: Two tuples, where first is the bottom left, and the second is the top right of the box.
:return: Boolean indicating if the coordinates are in the box.
"""
if box[0][0] < coords[0] < box[1][0] and box[0][1] < coords[1] < box[1][1]:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def batch_delete(query, session):
"""
Delete the result rows from the given query in batches.
This minimizes the amount of time that the table(s) that the query selects
from will be locked for at once.
"""
n = 0
query = query.limit(25)
while True:
if query.count() == 0:
break
for row in query:
n += 1
session.delete(row)
session.commit()
return n | bigcode/self-oss-instruct-sc2-concepts |
def to_triplets(colors):
"""
Coerce a list into a list of triplets.
If `colors` is a list of lists or strings, return it as is. Otherwise,
divide it into tuplets of length three, silently discarding any extra
elements beyond a multiple of three.
"""
try:
colors[0][0]
return colors
except:
pass
# It's a 1-dimensional list
extra = len(colors) % 3
if extra:
colors = colors[:-extra]
return list(zip(*[iter(colors)] * 3)) | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_text(n) :
"""Generate random text 'n' characters"""
return ''.join([random.choice(string.digits + string.ascii_letters) for x in range(n)]) | bigcode/self-oss-instruct-sc2-concepts |
import six
import re
def to_bytes(value):
"""Convert numbers with a byte suffix to bytes.
"""
if isinstance(value, six.string_types):
pattern = re.compile('^(\d+)([K,M,G]{1})$')
match = pattern.match(value)
if match:
value = match.group(1)
suffix = match.group(2)
factor = {
'K': 1024,
'M': 1024 ** 2,
'G': 1024 ** 3,
}[suffix]
return int(round(factor * float(value)))
return value | bigcode/self-oss-instruct-sc2-concepts |
def is_perfect_slow(n):
""" decides if a given integer n is a perfect number or not
this is the straightforward implementation
"""
if n <= 0:
return(False)
sum = 0
for i in range(1,n):
if n % i == 0:
sum += i
return(sum == n) | bigcode/self-oss-instruct-sc2-concepts |
def licence_name_to_file_name(licence_name: str) -> str:
"""
Converts a licence name to the name of the file
containing its definition.
:param licence_name: The licence name.
:return: The file name.
"""
return licence_name.lower().replace(" ", "-") + ".txt" | bigcode/self-oss-instruct-sc2-concepts |
def format_position(variant):
"""Gets a string representation of the variants position.
Args:
variant: third_party.nucleus.protos.Variant.
Returns:
A string chr:start + 1 (as start is zero-based).
"""
return '{}:{}'.format(variant.reference_name, variant.start + 1) | bigcode/self-oss-instruct-sc2-concepts |
def score(goal, test_string):
"""compare two input strings and return decimal value of quotient likeness"""
#goal = 'methinks it is like a weasel'
num_equal = 0
for i in range(len(goal)):
if goal[i] == test_string[i]:
num_equal += 1
return num_equal / len(goal) | bigcode/self-oss-instruct-sc2-concepts |
import copy
def pad_1d_list(data, element, thickness=1):
""" Adds padding at the start and end of a list
This will make a shallow copy of the original
eg: pad_1d_list([1,2], 0) -> returns [0,1,2,0]
Args:
data: the list to pad
element: gets added as padding (if its an object, it won't be instanced, just referenced in the lists)
thickness: how many layers of padding
Returns:
the padded list
"""
# shallow copy
data = copy.copy(data)
for i in range(thickness):
data.insert(0, element)
data.append(element)
return data | bigcode/self-oss-instruct-sc2-concepts |
def process_single(word):
"""
Process a single word, whether it's identifier, number or symbols.
:param word: str, the word to process
:return: str, the input
"""
if word[0].isnumeric():
try:
int(word)
except ValueError:
raise ValueError("Expression {} not valid".format(word))
return word | bigcode/self-oss-instruct-sc2-concepts |
def remove_non_seriasable(d):
""" Converts AnnotationType and EntityType classes to strings. This is
needed when saving to a file.
"""
return {
k: str(val.name).lower() if k in ('annotation_type',
'entity_type') else val
for k, val in d.items()
} | bigcode/self-oss-instruct-sc2-concepts |
def merge_dictionaries(dict1, dict2):
"""Merge dictionaries together, for the case of aggregating bindings."""
new_dict = dict1.copy()
new_dict.update(dict2)
return new_dict | bigcode/self-oss-instruct-sc2-concepts |
def transpose(matrix):
"""
Compute the matrix transpose
:param matrix: the matrix to be transposed,
the transposing will not modify the input matrix
:return: the transposed of matrix
"""
_transposed = []
for row in range(len(matrix)):
_transposed.append(
[matrix[i][row] for i in range(len(matrix))]
)
return _transposed | bigcode/self-oss-instruct-sc2-concepts |
def rivers_with_station(stations):
"""Given a list of stations, return a alphabetically sorted set of rivers with at least one monitoring station"""
river_set = set()
for station in stations:
river_set.add(station.river)
river_set = sorted(river_set)
return river_set | bigcode/self-oss-instruct-sc2-concepts |
def permute(lst, perm):
"""Permute the given list by the permutation.
Args:
lst: The given list.
perm: The permutation. The integer values are the source indices, and the
index of the integer is the destination index.
Returns:
A permutation copy of lst.
"""
return tuple([lst[i] for i in perm]) | bigcode/self-oss-instruct-sc2-concepts |
import socket
def gethostbyaddr(ip):
"""
Resolve a single host name with gethostbyaddr. Returns a string on success.
If resolution fails, returns None.
"""
host = None
try:
host = socket.gethostbyaddr(ip)[0]
except OSError:
pass
return host | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def gain_change(dstrfs, batch_size=8):
"""
Measure standard deviation of dSTRF gains.
Arguments:
dstrfs: tensor of dSTRFs with shape [time * channel * lag * frequency]
Returns:
gain_change: shape change parameter, tensor of shape [channel]
"""
tdim, cdim, ldim, fdim = dstrfs.shape
if cdim > batch_size:
return torch.cat([
gain_change(
dstrfs[:, k*batch_size:(k+1)*batch_size],
batch_size=batch_size
) for k in range(math.ceil(cdim / batch_size))
])
return dstrfs.norm(dim=[-2, -1]).std(dim=0).cpu() | bigcode/self-oss-instruct-sc2-concepts |
def multiply(*fields, n):
"""
Multiply ``n`` to the given fields in the document.
"""
def transform(doc):
for field in fields:
doc = doc[field]
doc *= n
return transform | bigcode/self-oss-instruct-sc2-concepts |
def to_matrix_vector(transform):
"""Split an homogeneous transform into its matrix and vector components.
The transformation must be represented in homogeneous coordinates.
It is split into its linear transformation matrix and translation vector
components.
This function does not normalize the matrix. This means that for it to be
the inverse of from_matrix_vector, transform[-1, -1] must equal 1, and
transform[-1, :-1] must equal 0.
Parameters
----------
transform : numpy.ndarray
Homogeneous transform matrix. Example: a (4, 4) transform representing
linear transformation and translation in 3 dimensions.
Returns
-------
matrix, vector : numpy.ndarray
The matrix and vector components of the transform matrix. For
an (N, N) transform, matrix will be (N-1, N-1) and vector will be
a 1D array of shape (N-1,).
See Also
--------
from_matrix_vector
"""
ndimin = transform.shape[0] - 1
ndimout = transform.shape[1] - 1
matrix = transform[0:ndimin, 0:ndimout]
vector = transform[0:ndimin, ndimout]
return matrix, vector | bigcode/self-oss-instruct-sc2-concepts |
def prompt_int(prompt):
""" Prompt until the user provides an integer. """
while True:
try:
return int(input(prompt))
except ValueError as e:
print('Provide an integer') | bigcode/self-oss-instruct-sc2-concepts |
def check_overlap(stem1, stem2):
""" Checks if 2 stems use any of the same nucleotides.
Args:
stem1 (tuple):
4-tuple containing stem information.
stem2 (tuple):
4-tuple containing stem information.
Returns:
bool: Boolean indicating if the two stems overlap.
"""
# Check for string dummy variable used when implementing a discrete variable.
if type(stem1) == str or type(stem2) == str:
return False
# Check if any endpoints of stem2 overlap with stem1.
for val in stem2:
if stem1[0] <= val <= stem1[1] or stem1[2] <= val <= stem1[3]:
return True
# Check if endpoints of stem1 overlap with stem2.
# Do not need to check all stem1 endpoints.
for val in stem1[1:3]:
if stem2[0] <= val <= stem2[1] or stem2[2] <= val <= stem2[3]:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import ast
def str_to_list(string: str) -> list:
"""
convert list-like str to list
:param string: "[(0, 100), (105, 10) ...]"
:return: list of tuples
"""
return ast.literal_eval(string) | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_load(path, verbose=False):
"""Load python dictionary stored in JSON file at ``path``.
Args:
path (str): Path to the file
verbose (bool): Verbosity flag
Returns:
(dict): Loaded JSON contents
"""
with open(path, 'r') as f:
if verbose:
print('Loading data from {0}'.format(path))
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def center_crop(img_mat, size = (224, 224)):
"""
Center Crops an image with certain size, image must be bigger than crop size (add check for that)
params:
img_mat: (3D-matrix) image matrix of shape (width, height, channels)
size: (tuple) the size of crops (width, height)
returns:
img_mat: that has been center cropped to size of center crop
"""
w,h,c = img_mat.shape
start_h = h//2-(size[1]//2) # Size[1] - h of cropped image
start_w = w//2-(size[0]//2) # Size[0] - w of cropepd image
return img_mat[start_w:start_w+size[0],start_h:start_h+size[1], :] | bigcode/self-oss-instruct-sc2-concepts |
def plot_line(m, line, colour='b', lw=1, alpha=1):
"""
Plots a line given a line with lon,lat coordinates.
Note:
This means you probably have to call shapely `transform` on your
line before passing it to this function.
There is a helper partial function in utils called `utm2lola` which
makes this easy.
Args:
m (Basemap): A matplotlib Basemap.
line (shape): A shapely geometry.
colour (str): A colour from the matplotlib dictionary.
Returns:
list: A list of matplotlib lines.
"""
lo, la = line.xy
x, y = m(lo, la)
return m.plot(x, y,
color=colour,
linewidth=lw,
alpha=alpha,
solid_capstyle='round') | bigcode/self-oss-instruct-sc2-concepts |
def _get_orientation(exif):
"""Get Orientation from EXIF.
Args:
exif (dict):
Returns:
int or None: Orientation
"""
if not exif:
return None
orientation = exif.get(0x0112) # EXIF: Orientation
return orientation | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_layers(layer_limit: int, size_limit: int, matching: bool):
"""
Helper function for generating a random layer set
NOTE: Randomized!
:param layer_limit: The maximum amount of layers to generate
:param size_limit: The maximum size of each layer
:param matching: Specifies whether the amount of layers, and activation functions is equal
:return: Two lists, the first containing the sizes of each layer, the second one the activation functions
"""
layer_amount = random.randint(1, layer_limit)
activation_amount = random.randint(1, layer_limit)
while (
(activation_amount != layer_amount)
if matching
else (activation_amount >= layer_amount)
):
activation_amount = random.randint(1, layer_limit)
layer_amount = random.randint(1, layer_limit)
rnd_hidden = [random.randint(1, size_limit) for _ in range(layer_amount)]
rnd_activation = ["ReLU"] * activation_amount
return rnd_hidden, rnd_activation | bigcode/self-oss-instruct-sc2-concepts |
def expand_resources(resources):
"""
Construct the submit_job arguments from the resource dict.
In general, a k,v from the dict turns into an argument '--k v'.
If the value is a boolean, then the argument turns into a flag.
If the value is a list/tuple, then multiple '--k v' are presented,
one for each list item.
:resources: a dict of arguments for the farm submission command.
"""
cmd = ''
for field, val in resources.items():
if type(val) is bool:
if val is True:
cmd += '--{} '.format(field)
elif type(val) is list or type(val) is tuple:
for mp in val:
cmd += '--{} {} '.format(field, mp)
else:
cmd += '--{} {} '.format(field, val)
return cmd | bigcode/self-oss-instruct-sc2-concepts |
def gen_workspace_tfvars_files(environment, region):
"""Generate possible Terraform workspace tfvars filenames."""
return [
# Give preference to explicit environment-region files
"%s-%s.tfvars" % (environment, region),
# Fallback to environment name only
"%s.tfvars" % environment,
] | bigcode/self-oss-instruct-sc2-concepts |
def comma_sep(values, limit=20, stringify=repr):
"""
Print up to ``limit`` values, comma separated.
Args:
values (list): the values to print
limit (optional, int): the maximum number of values to print (None for no limit)
stringify (callable): a function to use to convert values to strings
"""
count = len(values)
if limit is not None and count > limit:
values = values[:limit]
continuation = f", ... ({count - limit} more)" if count > limit else ""
else:
continuation = ""
rendered = ", ".join(stringify(x) for x in values)
return rendered + continuation | bigcode/self-oss-instruct-sc2-concepts |
def myround (val, r=2):
"""
Converts a string of float to rounded string
@param {String} val, "42.551"
@param {int} r, the decimal to round
@return {string} "42.55" if r is 2
"""
return "{:.{}f}".format(float(val), r) | bigcode/self-oss-instruct-sc2-concepts |
def normaliseports(ports):
"""Normalise port list
Parameters
----------
ports : str
Comma separated list of ports
Returns
-------
str | List
If None - set to all
Otherwise make sorted list
"""
if ports is None:
return 'all'
if ports in ('all', 'update', 'test'):
return ports
# use a set to remove possible duplicate values
return sorted(list(set(map(int, ports.split(','))))) | bigcode/self-oss-instruct-sc2-concepts |
def review_pks(database):
"""
Check that all tables have a PK. It's not necessarily wrong, but gives a warning that they don't exist.
:param database: The database to review. Only the name is needed.
:type database: Database
:return: A list of recommendations.
:rtype: list of str
"""
print(f"reviewing primary keys for {database.database_name} database")
issues = []
for table in database:
if not table.primary_key:
issues.append(f"No primary key on table {database.database_name}.{table.schema_name}.{table.table_name}")
return issues | bigcode/self-oss-instruct-sc2-concepts |
import re
def read_sta_file(sta_file):
"""
Read information from the station file with free format: net,sta,lon,lat,ele,label.
The label is designed with the purpose to distinguish stations into types.
"""
cont = []
with open(sta_file,'r') as f:
for line in f:
line = line.rstrip()
net,sta,_lon,_lat,_ele,label = re.split(" +",line)
cont.append([net,sta,float(_lon),float(_lat),int(_ele),label])
f.close()
if len(cont)==0:
raise Exception(f"No content in the station file {sta_file}")
return cont | bigcode/self-oss-instruct-sc2-concepts |
def read_file(file_name):
"""Returns the content of file file_name."""
with open(file_name) as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
def t_add(t, v):
"""
Add value v to each element of the tuple t.
"""
return tuple(i + v for i in t) | bigcode/self-oss-instruct-sc2-concepts |
def fix_nonload_cmds(nl_cmds):
"""
Convert non-load commands commands dict format from Chandra.cmd_states
to the values/structure needed here. A typical value is shown below:
{'cmd': u'SIMTRANS', # Needs to be 'type'
'date': u'2017:066:00:24:22.025',
'id': 371228, # Store as params['nonload_id'] for provenence
'msid': None, # Goes into params
'params': {u'POS': -99616},
'scs': None, # Set to 0
'step': None, # Set to 0
'time': 605233531.20899999, # Ignored
'timeline_id': None, # Set to 0
'tlmsid': None, # 'None' if None
'vcdu': None}, # Set to -1
"""
new_cmds = []
for cmd in nl_cmds:
new_cmd = {}
new_cmd['date'] = str(cmd['date'])
new_cmd['type'] = str(cmd['cmd'])
new_cmd['tlmsid'] = str(cmd['tlmsid'])
for key in ('scs', 'step', 'timeline_id'):
new_cmd[key] = 0
new_cmd['vcdu'] = -1
new_cmd['params'] = {}
new_cmd['params']['nonload_id'] = int(cmd['id'])
if cmd['msid'] is not None:
new_cmd['params']['msid'] = str(cmd['msid'])
# De-numpy (otherwise unpickling on PY3 has problems).
if 'params' in cmd:
params = new_cmd['params']
for key, val in cmd['params'].items():
key = str(key)
try:
val = val.item()
except AttributeError:
pass
params[key] = val
new_cmds.append(new_cmd)
return new_cmds | bigcode/self-oss-instruct-sc2-concepts |
import copy
def _update_inner_xml_ele(ele, list_):
"""Copies an XML element, populates sub-elements from `list_`
Returns a copy of the element with the subelements given via list_
:param ele: XML element to be copied, modified
:type ele: :class:`xml.ElementTree.Element`
:param list list_: List of subelements to append to `ele`
:returns: XML element with new subelements from `list_`
:rtype: :class:`xml.ElementTree.Element`
"""
ret = copy.copy(ele)
for i, v in enumerate(list_):
ret[i] = v
return ret | bigcode/self-oss-instruct-sc2-concepts |
def construct_fixture_middleware(fixtures):
"""
Constructs a middleware which returns a static response for any method
which is found in the provided fixtures.
"""
def fixture_middleware(make_request, web3):
def middleware(method, params):
if method in fixtures:
return {
'result': fixtures[method],
}
else:
return make_request(method, params)
return middleware
return fixture_middleware | bigcode/self-oss-instruct-sc2-concepts |
def can_leftarc(stack, graph):
"""
Checks that the top of the has no head
:param stack:
:param graph:
:return:
"""
if not stack:
return False
if stack[0]['id'] in graph['heads']:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def concatenate_dictionaries(d1: dict, d2: dict, *d):
"""
Concatenate two or multiple dictionaries. Can be used with multiple `find_package_data` return values.
"""
base = d1
base.update(d2)
for x in d:
base.update(x)
return base | bigcode/self-oss-instruct-sc2-concepts |
def nulls(x):
"""
Convert values of -1 into None.
Parameters
----------
x : float or int
Value to convert
Returns
-------
val : [x, None]
"""
if x == -1:
return None
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def compute_skew(sequence: str) -> List[float]:
"""Find the skew of the given sequence
Arguments:
sequence {str} -- DNA string
Returns:
List[float] -- skew list
"""
running_skew = []
skew = 0
for base in sequence.upper():
if base == "G":
skew += 1
elif base == "C":
skew -= 1
else:
skew += 0
running_skew.append(skew)
return running_skew | bigcode/self-oss-instruct-sc2-concepts |
import base64
import hashlib
def generate_hash(url):
"""
Generates the hash value to be stored as key in the redis database
"""
hashval = base64.urlsafe_b64encode(hashlib.md5(url).digest())
hashval=hashval[0:6]
return hashval | bigcode/self-oss-instruct-sc2-concepts |
def Fplan(A, Phi, Fstar, Rp, d, AU=False):
"""
Planetary flux function
Parameters
----------
A : float or array-like
Planetary geometric albedo
Phi : float
Planetary phase function
Fstar : float or array-like
Stellar flux [W/m**2/um]
Rp : float
Planetary radius [Earth radii]
d : float
Distance to star [pc]
AU : bool, optional
Flag that indicates d is in AU
Returns
-------
Fplan : float or array-like
Planetary flux [W/m**2/um]
"""
Re = 6.371e6 # radius of Earth (m)
ds = 3.08567e16 # parsec (m)
if AU:
ds = 1.495979e11 # AU (m)
return A*Phi*Fstar*(Rp*Re/d/ds)**2. | bigcode/self-oss-instruct-sc2-concepts |
def create_inventory(items):
"""
Create an inventory dictionary from a list of items.
The string value of the item becomes the dictionary key.
The number of times the string appears in items becomes
the value, an integer representation of how many times.
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
items_dict = {}
for item in items:
if item in items_dict:
items_dict[item] += 1
else:
items_dict[item] = 1
return items_dict | bigcode/self-oss-instruct-sc2-concepts |
import six
def get_paramfile(path, cases):
"""Load parameter based on a resource URI.
It is possible to pass parameters to operations by referring
to files or URI's. If such a reference is detected, this
function attempts to retrieve the data from the file or URI
and returns it. If there are any errors or if the ``path``
does not appear to refer to a file or URI, a ``None`` is
returned.
:type path: str
:param path: The resource URI, e.g. file://foo.txt. This value
may also be a non resource URI, in which case ``None`` is returned.
:type cases: dict
:param cases: A dictionary of URI prefixes to function mappings
that a parameter is checked against.
:return: The loaded value associated with the resource URI.
If the provided ``path`` is not a resource URI, then a
value of ``None`` is returned.
"""
data = None
if isinstance(path, six.string_types):
for prefix, function_spec in cases.items():
if path.startswith(prefix):
function, kwargs = function_spec
data = function(prefix, path, **kwargs)
return data | bigcode/self-oss-instruct-sc2-concepts |
def adds_comment_sign(data: str, comment_sign: str) -> str:
"""Adds comment signs to the string."""
return "\n".join(list(f"{comment_sign} {line}".strip() for line in data.split("\n")[:-1])) | bigcode/self-oss-instruct-sc2-concepts |
def positive_coin_types_to_string(coin_dict):
"""
Converts only the coin elements that are greater than 0 into a string.
Arguments:
coin_dict (dict): A dictionary consisting of all 4 coin types.
Returns:
(string): The resulting string.
"""
plat = ""
gold = ""
silver = ""
copper = ""
if coin_dict['plat'] > 0:
plat = f"{coin_dict['plat']}p "
if coin_dict['gold'] > 0:
gold = f"{coin_dict['gold']}g "
if coin_dict['silver'] > 0:
silver = f"{coin_dict['silver']}s "
if coin_dict['copper'] > 0:
copper = f"{coin_dict['copper']}c"
return f"{plat}{gold}{silver}{copper}".strip() | bigcode/self-oss-instruct-sc2-concepts |
def finalize_model(input_model):
"""
Extracts string from the model data. This function is always the last
stage in the model post-processing pipeline.
:param input_model: Model to be processed
:return: list of strings, ready to be written to a module file
"""
finalized_output = []
for mline in input_model:
finalized_output.append(mline[0])
return finalized_output | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def load_object(worksheet):
"""
Converts worksheet to dictionary
Args:
object: worksheet
Returns:
object: dictionary
"""
#d = {}
#d = OrderedDict()
d = OrderedDict()
for curr_col in range(0, worksheet.ncols):
liste_elts = worksheet.col_values(curr_col)
d[worksheet.cell_value(0, curr_col)] = liste_elts[1:len(liste_elts)]
return d | bigcode/self-oss-instruct-sc2-concepts |
def getConstructors(jclass):
"""Returns an array containing Constructor objects reflecting all the public
constructors of the class represented by this Class object."""
return jclass.class_.getConstructors()[:] | bigcode/self-oss-instruct-sc2-concepts |
def ask_move(player: int) -> int:
"""Ask the player which pawn to move. Returns an integer between 0 and 3."""
while True:
try:
pawn_number = int(input(f"Player {player}: Choose a piece to move (0-3): "))
except ValueError:
continue
else:
if 0 <= pawn_number <= 3:
break
return pawn_number | bigcode/self-oss-instruct-sc2-concepts |
def find(arr, icd_code=False):
"""Search in the first column of `arr` for a 'Yes' and return the respective
entry in the second column."""
search = [str(item) for item in arr[:,0]]
find = [str(item) for item in arr[:,1]]
try:
idx = [i for i,item in enumerate(search) if "Yes" in item]
found = find[idx[0]]
except:
found = "unknown"
if icd_code:
found = found.replace("\xa0", "")
found = found.replace(" ", "")
else:
found = found.lower()
return found | bigcode/self-oss-instruct-sc2-concepts |
from typing import IO
def open_file_or_stream(fos, attr, **kwargs) -> IO:
"""Open a file or use the existing stream. Avoids adding this logic to every function that wants to provide
multiple ways of specifying a file.
Args:
fos: File or stream
attr: Attribute to check on the ``fos`` object to see if it is a stream, e.g. "write" or "read"
kwargs: Additional keywords passed to the ``open`` call. Ignored if the input is a stream.
Returns:
Opened stream object
"""
if hasattr(fos, attr):
output = fos
else:
output = open(fos, **kwargs)
return output | bigcode/self-oss-instruct-sc2-concepts |
def find_max_sub(l):
"""
Find subset with higest sum
Example: [-2, 3, -4, 5, 1, -5] -> (3,4), 6
@param l list
@returns subset bounds and highest sum
"""
# max sum
max = l[0]
# current sum
m = 0
# max sum subset bounds
bounds = (0, 0)
# current subset start
s = 0
for i in range(len(l)):
m += l[i]
if m > max:
max = m
bounds = (s, i)
elif m < 0:
m = 0
s = i+1
return bounds, max | bigcode/self-oss-instruct-sc2-concepts |
def f_W(m_act, n, Wint):
"""
Calculate shaft power
"""
return m_act * n - Wint | bigcode/self-oss-instruct-sc2-concepts |
def _formatDict(d):
""" Returns dict as string with HTML new-line tags <br> between key-value pairs. """
s = ''
for key in d:
new_s = str(key) + ": " + str(d[key]) + "<br>"
s += new_s
return s[:-4] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def clusters_list(num_clusters: int) -> List[list]:
"""Create a list of empty lists for number of desired clusters.
Args:
num_clusters: number of clusters to find, we will be storing points in these empty indexed lists.
Returns:
clusters: empty list of lists.
"""
clusters = []
for _ in range(num_clusters):
clusters.append([])
return clusters | bigcode/self-oss-instruct-sc2-concepts |
def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal places"""
places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""
count = 0
formatted = []
for i in range(len(integer), 0, -1):
count += 1
formatted.append(integer[i - 1])
if count % 3 == 0 and i - 1:
formatted.append(",")
integer = "".join(formatted[::-1])
return integer+decimal | bigcode/self-oss-instruct-sc2-concepts |
def get_cdm_cluster_location(self, cluster_id):
"""Retrieves the location address for a CDM Cluster
Args:
cluster_id (str): The ID of a CDM cluster
Returns:
str: The Cluster location address
str: Cluster location has not be configured.
str: A cluster with an ID of {cluster_id} was not found.
Raises:
RequestException: If the query to Polaris returned an error
"""
try:
query_name = "cdm_cluster_location"
variables = {
"filter": {
"id": [cluster_id]
}
}
query = self._query(query_name, variables)
if query['nodes']:
if query['nodes'][0]['geoLocation'] != None:
return query['nodes'][0]['geoLocation']['address']
else:
return "No Location Configured"
else:
raise Exception("A CDM Cluster with an ID of {} was not found.".format(cluster_id))
except Exception:
raise | bigcode/self-oss-instruct-sc2-concepts |
def is_session_dir(path):
"""Return whether a path is a session directory.
Example of a session dir: `/path/to/root/mainenlab/Subjects/ZM_1150/2019-05-07/001/`
"""
return path.is_dir() and path.parent.parent.parent.name == 'Subjects' | bigcode/self-oss-instruct-sc2-concepts |
def coalesce(*xs):
"""
Coalescing monoid operation: return the first non-null argument or None.
Examples:
>>> coalesce(None, None, "not null")
'not null'
"""
if len(xs) == 1:
xs = xs[0]
for x in xs:
if x is not None:
return x
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def __is_rut_perfectly_formatted(rut: str) -> bool:
"""
Validates if Chilean RUT Number is perfectly formatted
Args:
rut (str): A Chilean RUT Number. For example 5.126.663-3
Returns:
bool: True when Chilean RUT number (rut:str) is perfectly formatted
** Only validates the format not if the RUT is valid or not
"""
perfect_rut_regex = r"^(\d{1,3}(?:\.\d{1,3}){2}-[\dkK])$"
return re.match(perfect_rut_regex, rut) is not None | bigcode/self-oss-instruct-sc2-concepts |
def create_single_object_response(status, object, object_naming_singular):
"""
Create a response for one returned object
@param status: success, error or fail
@param object: dictionary object
@param object_naming_singular: name of the object, f.ex. book
@return: dictionary.
"""
return {"status": status,
"data": {
object_naming_singular: object
}} | bigcode/self-oss-instruct-sc2-concepts |
def _query_item(item, query_id, query_namespace):
"""
Check if the given cobra collection item matches the query arguments.
Parameters
----------
item: cobra.Reaction or cobra.Metabolite
query_id: str
The identifier to compare. The comparison is made case insensitively.
query_namespace: str
The miriam namespace identifier in which the given metabolite is
registered. See https://www.ebi.ac.uk/miriam/main/collections
The comparison is made case insensitively.
Returns
-------
bool
True if the given id exists in the default namespace, or in the model
annotations by the queried namespace, otherwise False.
"""
# Try the default identifiers (without confirming the namespace)
if query_id.lower() == item.id.lower():
return True
# Otherwise, try to find a case insensitive match for the namespace key
for namespace in item.annotation:
if query_namespace.lower() == namespace.lower():
annotation = item.annotation[namespace]
# Compare the identifier case insensitively as well
# Annotations may contain a single id or a list of ids
if isinstance(annotation, list):
if query_id.lower() in [i.lower() for i in annotation]:
return True
else:
if query_id.lower() == annotation.lower():
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_html_tags(text):
"""Strip HTML tags in a string.
:param text: String containing HTML code
:type text: str
:return: String without HTML tags
:rtype: str
:Example:
>>> strip_html_tags('<div><p>This is a paragraph</div>')
'This is a paragraph'
>>> strip_html_tags('<em class="highlight">Highlighted</em> text')
'Highlighted text'
"""
return re.sub('<[^<]+?>', '', text) | bigcode/self-oss-instruct-sc2-concepts |
def get_next_open_row(board, col):
"""
Finds the topmost vacant cell in column `col`, in `board`'s grid.
Returns that cell's corresponding row index.
"""
n_rows = board.n_rows
# check row by row, from bottom row to top row ([0][0] is topleft of grid)
for row in range(n_rows - 1, -1, -1):
if board.grid[row][col] == 0:
return row
# so pylint doesn't complain
return None | bigcode/self-oss-instruct-sc2-concepts |
import csv
def proc_attendees(att_file, config):
"""Opens the attendee list file, reads the contents and collects the
desired information (currently first name, last name and email addresses)
of the actual attendees into a dictionary keyed by the lowercase email
address. This collection is returned.
This collection allows for quick look-up (for checking attendance)
and eliminates duplicate email addresses.
Args:
att_file - file object for the file containing the list of attendees
We assume that this file object is valid, so no checking
config - ConfigParser object containing the configuration data
Returns:
dictionary containing the de-duplicated collection of all attendees.
Keys are the email attendee email addresses forced to lower case.
"""
attendees = {}
email_field = config['ATTENDEES']['EMAIL_FIELD']
with att_file:
reader = csv.DictReader(att_file)
# use splitlines() to remove the line end characters
#attendees = att.read().lower().splitlines()
for row in reader:
attendees[row[email_field].lower()] = row
return attendees | bigcode/self-oss-instruct-sc2-concepts |
import re
def _parse_arn(arn):
"""
ec2) arn:aws:ec2:<REGION>:<ACCOUNT_ID>:instance/<instance-id>
arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id
Returns: resource_list, [regions]
"""
p = (r"(?P<arn>arn):"
r"(?P<partition>aws|aws-cn|aws-us-gov):"
r"(?P<service>[A-Za-z0-9_\-]*):"
r"(?P<region>[A-Za-z0-9_\-]*):"
r"(?P<account>[A-Za-z0-9_\-]*):"
r"(?P<resources>[A-Za-z0-9_\-:/]*)")
r = re.compile(p)
match = r.match(arn)
if match:
d = match.groupdict()
else:
return (None, None)
region = d.get('region', None)
resource_id = None
resources = d.get('resources', None)
if resources:
items = re.split('/|:', resources)
if len(items) == 1:
resource_id = items[0]
elif len(items) == 2:
resource_type = items[0]
resource_id = items[1]
else:
print(f'ERROR parsing: {resources}')
return [resource_id], [region] | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def is_subpath(parent_path: str, child_path: str):
"""Return True if `child_path is a sub-path of `parent_path`
:param parent_path:
:param child_path:
:return:
"""
return Path(parent_path) in Path(child_path).parents | bigcode/self-oss-instruct-sc2-concepts |
def getIPaddr(prefix):
"""
Get the IP address of the client, by grocking the .html report.
"""
addr="Unknown"
f=open(prefix+".html", "r")
for l in f:
w=l.split(" ")
if w[0] == "Target:":
addr=w[2].lstrip("(").rstrip(")")
break
f.close()
return(addr)
"""
Busted (but otherwise more correct) web100 method
Open a web100 logfile to extract the "RemoteAddr"
print "Opening", log
vlog = libweb100.web100_log_open_read(log)
agent = libweb100.web100_get_log_agent(vlog)
group = libweb100.web100_get_log_group(vlog)
conn = libweb100.web100_get_log_connection(vlog)
var = libweb100.web100_var_find(group, "RemoteAddr")
snap = libweb100.web100_snapshot_alloc(group, conn)
libweb100.web100_snap_from_log(snap, vlog)
buf=cast(create_string_buffer(20), cvar.anything) # XXX
libweb100.web100_snap_read(var, snap, buf)
val=libweb100.web100_value_to_text(WEB100_TYPE_IP_ADDRESS, buf)
libweb100.web100_log_close_read(vlog)
print val
""" | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_text(text, max_words=None, stopwords=None):
"""
Remove stopwords, punctuation, and numbers from text.
Args:
text: article text
max_words: number of words to keep after processing
if None, include all words
stopwords: a list of words to skip during processing
if None, ignored
Returns:
Space-delimited and cleaned string
"""
text = re.sub(r"[^a-zA-Z0-9\s]", "", text)
tokens = re.split(r"\s+", text)
good_tokens = []
for token in tokens:
token = token.lower().strip()
# remove stopwords
if stopwords is not None and token in stopwords:
continue
# remove tokens without alphabetic characters (i.e. punctuation, numbers)
if any(char.isalpha() for char in token):
good_tokens.append(token)
# skipping first ~20 words, which are often introductory
if max_words is None:
return good_tokens[20:]
else:
return good_tokens[20:20+max_words] | bigcode/self-oss-instruct-sc2-concepts |
def array_value(postiion, arr):
"""Returns the value at an array from the tuple"""
row, col = postiion[0], postiion[1]
value = arr[row, col]
return value | 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.