seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import torch
def init_control(ctrl_obj, env, live_plot_obj, rec, params_general, random_actions_init,
costs_tests, idx_test, num_repeat_actions=1):
"""
Init the gym env and memory. Define the lists containing the points for visualisations.
Control the env with random actions for a number of steps.
Args:
ctrl_obj (control_objects.gp_mpc_controller.GpMpcController):
Object containing the control functions.
Used here to compute cost and add_memory.
env (gym env): environment used to get the next observation given current observation and action
live_plot_obj (object): object used for visualisation in real time of the control in a 2d graph.
Must contain a function called update, that adds new points on the graph
rec (object): object used to visualise the gym env in real-time.
Must heve a function called capture_frame that updates the visualisation
params_general (dict): see parameters.md for more information
random_actions_init (int): number of random actions to apply for the initialization.
costs_tests (numpy.array): contains the costs of all the tests realized, which is used to compute
the mean cost over a large number of control. Parameter not relevant if num_tests=1.
Dim=(num_runs, num_timesteps)
idx_test (int): index of the test realized
num_repeat_actions (int): number of consecutive actions that are constant.
The GPs only store points at which the control change.
"""
# Lists used for plotting values
obs_lst = []
actions_lst = []
rewards_lst = []
env.reset()
obs, reward, done, info = env.step(env.action_space.sample())
obs_prev_ctrl = None
action = None
cost = None
for idx_action in range(random_actions_init):
if idx_action % num_repeat_actions == 0:
if obs_prev_ctrl is not None and action is not None and cost is not None:
ctrl_obj.add_memory(obs=obs_prev_ctrl, action=action, obs_new=obs,
reward=-cost, check_storage=False)
obs_prev_ctrl = obs
action = env.action_space.sample()
obs_new, reward, done, info = env.step(action)
if params_general['render_env']:
try: env.render()
except: pass
if params_general['save_render_env']:
try: rec.capture_frame()
except: pass
cost, cost_var = ctrl_obj.compute_cost_unnormalized(obs_new, action)
costs_tests[idx_test, idx_action] = cost
obs_lst.append(obs)
actions_lst.append(action)
rewards_lst.append(-cost)
if params_general['render_live_plots_2d']:
live_plot_obj.update(obs=obs, action=action, cost=cost, info_dict=None)
obs = obs_new
# Necessary to store the last action in case that the parameter limit_action_change is set to True
ctrl_obj.action_previous_iter = torch.Tensor(action)
return ctrl_obj, env, live_plot_obj, rec, obs, action, cost, obs_prev_ctrl, \
costs_tests, obs_lst, actions_lst, rewards_lst | bigcode/self-oss-instruct-sc2-concepts |
def create_keyword_string(command_string):
"""Creates the keyword string. The keyword string is everything before
the first space character."""
cmd_str = command_string.split(" ")[0]
return cmd_str | bigcode/self-oss-instruct-sc2-concepts |
def normalize_azimuth(azimuth):
"""Normalize azimuth to (-180, 180]."""
if azimuth <= -180:
return azimuth + 360
elif azimuth > 180:
return azimuth - 360
else:
return azimuth | bigcode/self-oss-instruct-sc2-concepts |
def real_calculate_check_digit(gs1_value):
"""
Calculate the check digit without specifying the identifier key.
:param gs1_value: GS1 identifier.
:return: Check digit.
"""
multipliers = []
counter = 0
total = 0
for i in reversed(range(len(gs1_value))):
d = gs1_value[i]
if counter % 2 == 0:
multiplier = 3
else:
multiplier = 1
multipliers.append(multiplier)
total += int(d) * multiplier
counter += 1
return (10 - total % 10) % 10 | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def make_epoch_seed(epoch_tx_count, ledger_count, sorted_ledger, address_from_ledger):
"""
epoch_tx_count = number of transactions made in a given epoch
ledger_count = the total number of ledger entries in the ledger database.
sorted_ledger = iterable that returns the nth ledger item. Must be sorted by
amount and then address.
address_from_ledger = callable that returns the address from the ledger entry
returned by sorted_ledger
"""
index = epoch_tx_count % ledger_count
return hashlib.sha256(
str(epoch_tx_count) + address_from_ledger(sorted_ledger[index])
).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def change_list_value(array: list, value_old: str, value_new: str) -> list:
""" Returns a given list with a changed value. """
for index, value in enumerate(array):
if value == value_old:
array[index] = value_new
return array | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_clusters(infile):
"""
Loads clusters in a sparse format from a JSON file.
Parameters
----------
infile : str
The JSON file containing sparse cluster information.
Returns
-------
list of set of tuple of int
The sets are clusters, the tuples are the indices of entries in that
cluster.
"""
with open(infile, 'r') as handle:
return [set([tuple(e) for e in cluster])
for cluster in json.load(handle)] | bigcode/self-oss-instruct-sc2-concepts |
def inclusion_one_default_from_template(one, two='hi'):
"""Expected inclusion_one_default_from_template __doc__"""
return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)} | bigcode/self-oss-instruct-sc2-concepts |
def build_metric_link(region, alarm_name):
"""Generate URL link to the metric
Arguments:
region {string} -- aws region name
alarm_name {string} -- name of the alarm in aws
Returns:
[type] -- [description]
"""
url = 'https://{}.console.aws.amazon.com/cloudwatch/home?region={}#alarmsV2:alarm/{}'.format(
region, region, alarm_name
)
return url | bigcode/self-oss-instruct-sc2-concepts |
def vector_multiply(vector_in, scalar):
""" Multiplies the vector with a scalar value.
This operation is also called *vector scaling*.
:param vector_in: vector
:type vector_in: list, tuple
:param scalar: scalar value
:type scalar: int, float
:return: updated vector
:rtype: tuple
"""
scaled_vector = [v * scalar for v in vector_in]
return tuple(scaled_vector) | bigcode/self-oss-instruct-sc2-concepts |
def load_meta(meta_file):
"""Load metadata file with rows like `utt_id|unit_sequence`.
Args:
meta_file: Filepath string for metadata file with utterance IDs and
corresponding quantized unit sequences, separated by pipes. Input
unit sequences should be separated by spaces.
Returns:
A list of (utterance ID, quantized unit sequence) tuples.
"""
quantized_utts = []
with open(meta_file) as f:
for row in f:
utt_id, unit_seq = row.strip().split("|")
unit_seq = [i for i in unit_seq.split()]
quantized_utts.append((utt_id, unit_seq))
return quantized_utts | bigcode/self-oss-instruct-sc2-concepts |
def _module_name(*components):
"""Assemble a fully-qualified module name from its components."""
return '.'.join(components) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def find_prefix(root, prefix: str) -> Tuple[bool, int]:
"""
Check and return
1. If the prefix exsists in any of the words we added so far
2. If yes then how may words actually have the prefix
"""
node = root
# If the root node has no children, then return False.
# Because it means we are trying to search in an empty trie
if not root.children:
return False, 0
for char in prefix:
char_not_found = True
# Search through all the children of the present `node`
for child in node.children:
if child.char == char:
# We found the char existing in the child.
char_not_found = False
# Assign node as the child containing the char and break
node = child
break
# Return False anyway when we did not find a char.
if char_not_found:
return False, 0
# Well, we are here means we have found the prefix. Return true to indicate that
# And also the counter of the last node. This indicates how many words have this
# prefix
return True, node.counter | bigcode/self-oss-instruct-sc2-concepts |
from PIL import ImageFile as PillowImageFile
import zlib
import struct
def get_pillow_attribute(file, pil_attr):
"""
Returns an attribute from a Pillow image of the given file,
file
a file. wrappable by Pillow. Must be open
pil_attr
the attribute to read.
return
the attribut, or None, if unreadaable. the file is not closed.
"""
# This devilish, ticketed code is lifted from
# django.core.files.images, where it seeks image dimensions.
# Unfortunately, that code is not configurable nor overridable.
p = PillowImageFile.Parser()
file_pos = file.tell()
file.seek(0)
try:
# Most of the time Pillow only needs a small chunk to parse the
# image and get data, but with some TIFF files Pillow needs to
# parse the whole file.
chunk_size = 1024
while 1:
data = file.read(chunk_size)
if not data:
break
try:
p.feed(data)
except zlib.error as e:
# ignore zlib complaining on truncated stream, just feed more
# data to parser (ticket #19457).
if e.args[0].startswith("Error -5"):
pass
else:
raise
except struct.error:
# Ignore PIL failing on a too short buffer when reads return
# less bytes than expected. Skip and feed more data to the
# parser (ticket #24544).
pass
except RuntimeError:
# e.g. "RuntimeError: could not create decoder object" for
# WebP files. A different chunk_size may work.
pass
if p.image:
return getattr(p.image, pil_attr)
chunk_size *= 2
return None
finally:
file.seek(file_pos) | bigcode/self-oss-instruct-sc2-concepts |
def find_check_run_by_name(check_runs, name):
""" Search through a list of check runs to see if it contains
a specific check run based on the name.
If the check run is not found this returns 'None'.
Parameters
----------
check_runs : list of dict
An array of check runs. This can be an empty array.
name : str
The name of the check.
Returns
-------
check : dict
The check run that was created for the commit that matches the name
parameter. If no check matches the name, then this is an empty
dict.
"""
for check in check_runs:
if check.get('name') == name:
return check
return None | bigcode/self-oss-instruct-sc2-concepts |
def count_words(item):
"""Convert the partitioned data for a word to a
tuple containing the word and the number of occurances.
"""
word, occurances = item
return word, sum(occurances) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def randomized_argmax(x: torch.Tensor) -> int:
"""
Like argmax, but return a random (uniformly) index of the max element
This function makes sense only if there are ties for the max element
"""
if torch.isinf(x).any():
# if some scores are inf, return the index for one of the infs
best_indices = torch.nonzero(torch.isinf(x)).squeeze()
else:
max_value = torch.max(x)
best_indices = torch.nonzero(x == max_value).squeeze()
if best_indices.ndim == 0:
# if there is a single argmax
chosen_idx = int(best_indices)
else:
chosen_idx = int(
best_indices[
torch.multinomial(
1.0 / len(best_indices) * torch.ones(len(best_indices)), 1
)[0]
]
)
return chosen_idx | bigcode/self-oss-instruct-sc2-concepts |
from typing import Literal
def compatible_operation(*args, language_has_vectors = True):
"""
Indicates whether an operation requires an index to be
correctly understood
Parameters
==========
args : list of PyccelAstNode
The operator arguments
language_has_vectors : bool
Indicates if the language has support for vector
operations of the same shape
Results
=======
compatible : bool
A boolean indicating if the operation is compatible
"""
if language_has_vectors:
# If the shapes don't match then an index must be required
shapes = [a.shape[::-1] if a.order == 'F' else a.shape for a in args if a.shape != ()]
shapes = set(tuple(d if isinstance(d, Literal) else -1 for d in s) for s in shapes)
order = set(a.order for a in args if a.order is not None)
return len(shapes) <= 1 and len(order) <= 1
else:
return all(a.shape==() for a in args) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def _get_player_pts_stat_type(player_pts: Dict[str, Any]) -> str:
"""
Helper function to get the stat type within the pulled player
points. Will be either 'projectedStats' or 'stats'.
"""
unique_type = set([list(v.keys())[0] for v in player_pts.values()])
if len(unique_type) > 1:
raise ValueError(f"More than one unique stats type detected: {unique_type}")
stats_type = list(unique_type)[0]
if stats_type not in ("projectedStats", "stats"):
raise ValueError(
f"Unrecognized stats type: '{stats_type}'. "
+ "Expected either 'projectedStats' or 'stats'."
)
return stats_type | bigcode/self-oss-instruct-sc2-concepts |
def formatEdgeDestination(node1, node2):
"""
Gera uma string que representa um arco node1->node2
Recebe dois inteiros (dois vértices do grafo), e o formata com a notação de
aresta a->b onde a é o vértice de origem, e b o de destino.
Args:
node1 (int): número de um dos vértices ligados à aresta
node2 (int): número de um dos vértices ligados à aresta
Returns:
str: arco no formato "a->b"
Raises:
TypeError: caso os argumentos não sejam do tipo inteiro
"""
if not(isinstance(node1, int)) or not(isinstance(node2, int)):
raise TypeError('arguments node1 and node2 must be integers')
return '{:d}->{:d}'.format(node1, node2) | bigcode/self-oss-instruct-sc2-concepts |
def make_response(response):
"""
Make a byte string of the response dictionary
"""
response_string = response["status"] + "\r\n"
keys = [key for key in response if key not in ["status", "content"]]
for key in keys:
response_string += key + ": " + response[key] + "\r\n"
response_string += "\r\n"
response_string = response_string.encode()
if "content" in response:
content = response["content"]
if isinstance(content, str):
content = content.encode()
new_line = b"\r\n\r\n"
response_string += content + new_line
return response_string | bigcode/self-oss-instruct-sc2-concepts |
def repetition_plane(repetitions, n=8):
"""
:param int repetitions: Number of times a chess position (state) has been reached.
:param int n: Chess game dimension (usually 8).
:return: An n x n list containing the same value for each entry, the repetitions number.
:rtype: list[list[int]]
This function computes the n x n repetitions plane.
"""
return [[repetitions for _ in range(n)] for _ in range(n)] | bigcode/self-oss-instruct-sc2-concepts |
def line_from_text(content='', some_text=[]):
"""
returns the first line containing 'content'
:param content:
:param some_text: list of strings
:return: line containing text
"""
matching_line = ''
for line in some_text:
if line.find(content) >= 0:
matching_line = line
break
return matching_line | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batch_matrix_norm(matrix, norm_order=2):
""" normalization of the matrix
Args:
matrix: torch.Tensor. Expected shape [batch, *]
norm_order: int. Order of normalization.
Returns:
normed matrix: torch.Tensor.
"""
return torch.norm(matrix, p=norm_order, dim=[1,2]) | bigcode/self-oss-instruct-sc2-concepts |
def _jaccard(a, b):
""" Return the Jaccard similarity between two sets a and b. """
return 1. * len(a & b) / len(a | b) | bigcode/self-oss-instruct-sc2-concepts |
def compute_grade(questions_coeff, questions_grade):
"""
Compute a grade from grade for each question (/2) and
associated coefficients
:param questions_coeff: list of coefficients for each question
:param questions_grade: list of grade for each question
"""
assign_grade = 0
sum_coeff = 0
for coeff, grade in zip(questions_coeff, questions_grade):
assign_grade += coeff * grade
sum_coeff += coeff
return int(assign_grade * 10 * 100 / sum_coeff) / 100 | bigcode/self-oss-instruct-sc2-concepts |
def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha):
"""
An implementation of [1] Equation 8.9
References
----------
.. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
optimizer for linear programming: an implementation of the
homogeneous algorithm." High performance optimization. Springer US,
2000. 197-232.
"""
x = x + alpha * d_x
tau = tau + alpha * d_tau
z = z + alpha * d_z
kappa = kappa + alpha * d_kappa
y = y + alpha * d_y
return x, y, z, tau, kappa | bigcode/self-oss-instruct-sc2-concepts |
def bgr_to_rgb(color: tuple) -> tuple:
"""Converts from BGR to RGB
Arguments:
color {tuple} -- Source color
Returns:
tuple -- Converted color
"""
return (color[2], color[1], color[0]) | bigcode/self-oss-instruct-sc2-concepts |
def get_run_data_from_cmd(line):
"""Parser input data from a command line that looks like
`command: python3 batch_runner.py -t benders -k cache -i s6.xml -v y -r 0`
and put it into a dict.
"""
words = line.split(" ")[3:]
word_dict = {}
for (i, word) in enumerate(words):
if word.startswith("-"):
word_dict[word] = words[i+1]
return {
"runName": word_dict["-i"],
"runId": word_dict["-r"],
"runType": word_dict["-k"],
"runValue": word_dict["-v"]
} | bigcode/self-oss-instruct-sc2-concepts |
def slurp(fname: str) -> str:
"""
Reads a file and all its contents, returns a single string
"""
with open(fname, 'r') as f:
data = f.read()
return data | bigcode/self-oss-instruct-sc2-concepts |
def create_img(height, width, color):
"""
Creates an image of the given height/width filled with the given color
PARAMS/RETURN
height: Height of the image to be created, as an integer
width: Width of the image to be created, as an integer
color: RGB pixel as a tuple of 3 integers
returns: An image as a list of lists of pixels
EXAMPLE USES
from CSEPixelArt import *
# Create a 16x16 image filled with white pixels
img = create_img(16, 16, (255, 255, 255))
"""
result = [None] * height
for i in range(len(result)):
result[i] = [color] * width
return result | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
def _NoClassFiles(jar_paths):
"""Returns True if there are no .class files in the given JARs.
Args:
jar_paths: list of strings representing JAR file paths.
Returns:
(bool) True if no .class files are found.
"""
for jar_path in jar_paths:
with zipfile.ZipFile(jar_path) as jar:
if any(name.endswith('.class') for name in jar.namelist()):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
def process_sequence_wise(cell, x, h=None):
"""
Process the entire sequence through an GRUCell.
Args:
cell (DistillerGRUCell): the cell.
x (torch.Tensor): the input
h (tuple of torch.Tensor-s): the hidden states of the GRUCell.
Returns:
y (torch.Tensor): the output
h (tuple of torch.Tensor-s): the new hidden states of the GRUCell.
"""
results = []
for step in x:
y, h = cell(step, h)
results.append(y)
h = (y, h)
return torch.stack(results), h | bigcode/self-oss-instruct-sc2-concepts |
import csv
def file_to_position_depths(file_path):
"""Get the position and depths from one file. Read into memory as a dictionary with (lat, lon) as the key and depth
as the value."""
# create the dictionary
result = {}
# read the position and depth data from the input csv file
with open(file_path) as csvfile:
contents = csv.reader(csvfile)
next(contents)
count = 1
# print progress
for line in contents:
if count % 100_000 == 0:
print(count)
count += 1
# get the latitude, longitude and depth from the row in the file
_, lat, long, depth = line
lat_long = (float(lat), float(long))
# if the depth is empty, then continue
if depth == '':
continue
result[lat_long] = float(depth)
return result | bigcode/self-oss-instruct-sc2-concepts |
def serialize_email_principal(email):
"""Serialize email principal to a simple dict."""
return {
'_type': 'Email',
'email': email.email,
'id': email.name,
'name': email.name,
'identifier': email.identifier
} | bigcode/self-oss-instruct-sc2-concepts |
def dates_to_str(dates):
"""Transforms list of dates into a string representation with the ARRAY keyword heading.
Parameters
----------
dates: list
Returns
-------
dates: str
"""
heading = 'ARRAY DATE'
footing = '/'
res = [heading] + [d.strftime('%d %b %Y').upper() for d in dates] + [footing]
res = '\n'.join(res) + '\n\n'
return res | bigcode/self-oss-instruct-sc2-concepts |
def convert_size_in_points_to_size_in_pixels(size):
"""
6pt = 8px = 0.5em
7pt = 9px = 0.55em
7.5pt = 10px = 0.625em
8pt = 11px = 0.7em
9pt = 12px = 0.75em
10pt = 13px = 0.8em
10.5pt = 14px = 0.875em
11pt = 15px = 0.95em
12pt = 16px = 1em
13pt = 17px = 1.05em
13.5pt = 18px = 1.125em
14pt = 19px = 1.2em
14.5pt = 20px = 1.25em
15pt = 21px = 1.3em
16pt = 22px = 1.4em
17pt = 23px = 1.45em
18pt = 24px = 1.5em
20pt = 26px = 1.6em
22pt = 29px = 1.8em
24pt = 32px = 2em
26pt = 35px = 2.2em
27pt = 36px = 2.25em
28pt = 37px = 2.3em
29pt = 38px = 2.35em
30pt = 40px = 2.45em
32pt = 42px = 2.55em
34pt = 45px = 2.75em
36pt = 48px = 3em
:param int size:
Size in points.
:rtype: int
:return: Size in pixels.
"""
return int(size * 4 / 3) | bigcode/self-oss-instruct-sc2-concepts |
def scaleto255(value):
"""Scale the input value from 0-100 to 0-255."""
return max(0, min(255, ((value * 255.0) / 100.0))) | bigcode/self-oss-instruct-sc2-concepts |
def receivables_turnover(revenue, average_receivables):
"""Computes receivables turnover.
Parameters
----------
revenue : int or float
Revenue
average_receivables : int or float
Average receivables for the period
Returns
-------
out : int or float
Receivables turnover
"""
return revenue / average_receivables | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_files(extensions):
"""List all files with given extensions in subfolders
:param extensions: Array of extensions, e.g. .ttl, .rdf
"""
all_files = []
for ext in extensions:
all_files.extend(pathlib.Path('cloned_repo').rglob(ext))
return all_files | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
from typing import Tuple
def flatten(xs: Union[List, Tuple]) -> List:
""" Flatten a nested list or tuple. """
return (
sum(map(flatten, xs), [])
if (isinstance(xs, list) or isinstance(xs, tuple))
else [xs]
) | bigcode/self-oss-instruct-sc2-concepts |
import csv
def read_csv(filepath, encoding='utf-8'):
"""
This function reads in a csv and returns its contents as a list
Parameters:
filepath (str): A str representing the filepath for the file to be read
encoding (str): A str representing the character encoding of the file
Returns:
(list): A list with the content of the file
"""
with open(filepath, 'r', encoding=encoding) as file:
reader = csv.reader(file)
data = []
for line in reader:
data.append(line)
return data | bigcode/self-oss-instruct-sc2-concepts |
def subtract_year(any_date):
"""Subtracts one year from any date and returns the result"""
date = any_date.split("-")
date = str(int(date[0])-1) + "-" + date[1] + "-" + date[2]
return date | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_whitespace(s, right=False, left=False):
"""
Remove white-space characters from the given string.
If neither right nor left is specified (the default),
then all white-space is removed.
Parameters
----------
s : str
The string to be modified.
right : bool
If True, remove white-space from the end of the string.
left : bool
If True, remove white-space from the beginning of the string.
Returns
-------
str
The string with white-space removed.
"""
if not left and not right:
return re.sub(r"\s+", "", s, flags=re.UNICODE)
elif right and left:
return re.sub(r"^\s+|\s+$", "", s, flags=re.UNICODE)
elif right:
return re.sub(r"\s+$", "", s, flags=re.UNICODE)
else: # left
return re.sub(r"^\s+", "", s, flags=re.UNICODE) | bigcode/self-oss-instruct-sc2-concepts |
def compact(text, **kw):
"""
Compact whitespace in a string and format any keyword arguments into the
resulting string. Preserves paragraphs.
:param text: The text to compact (a string).
:param kw: Any keyword arguments to apply using :py:func:`str.format()`.
:returns: The compacted, formatted string.
"""
return '\n\n'.join(' '.join(p.split()) for p in text.split('\n\n')).format(**kw) | bigcode/self-oss-instruct-sc2-concepts |
def parse_ingredients(raw_ingredients):
"""Parse individual ingredients from ingredients form data."""
ingredients = []
for ingredient in raw_ingredients.split("\r\n"):
if ingredient:
ingredients.append(ingredient)
return ingredients | bigcode/self-oss-instruct-sc2-concepts |
def read(metafile):
"""
Return the contents of the given meta data file assuming UTF-8 encoding.
"""
with open(str(metafile), encoding="utf-8") as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_ftp_md5(ftp, remote_file):
"""Compute checksum on remote ftp file."""
m = hashlib.md5()
ftp.retrbinary(f'RETR {remote_file}', m.update)
return m.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def usd(value):
""" Format value as USD """
return f"${value:,.2f}" | bigcode/self-oss-instruct-sc2-concepts |
def get_batch(file_h5, features, batch_number, batch_size=32):
"""Get a batch of the dataset
Args:
file_h5(str): path of the dataset
features(list(str)): list of names of features present in the dataset
that should be returned.
batch_number(int): the id of the batch to be returned.
batch_size(int): the mini-batch size
Returns:
A list of numpy arrays of the requested features"""
list_of_arrays = []
lb, ub = batch_number * batch_size, (batch_number + 1) * batch_size
for feature in features:
list_of_arrays.append(file_h5[feature][lb: ub])
return list_of_arrays | bigcode/self-oss-instruct-sc2-concepts |
import random
def randhex() -> str:
"""Returns random hex code as string"""
return "#" + "".join(random.choices("ABCDEF123456", k=6)) | bigcode/self-oss-instruct-sc2-concepts |
def split_byte_into_nibbles(value):
"""Split byte int into 2 nibbles (4 bits)."""
first = value >> 4
second = value & 0x0F
return first, second | bigcode/self-oss-instruct-sc2-concepts |
def _count_spaces_startswith(line):
"""
Count the number of spaces before the first character
"""
if line.split("#")[0].strip() == "":
return None
spaces = 0
for i in line:
if i.isspace():
spaces += 1
else:
return spaces | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def get_proc_name(cmd):
"""
Get the representative process name from complex command
:param str | list[str] cmd: a command to be processed
:return str: the basename representative command
"""
if isinstance(cmd, Iterable) and not isinstance(cmd, str):
cmd = " ".join(cmd)
return cmd.split()[0].replace('(', '').replace(')', '') | bigcode/self-oss-instruct-sc2-concepts |
import socket
def is_port_open(port_num):
""" Detect if a port is open on localhost"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return sock.connect_ex(('127.0.0.1', port_num)) == 0 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
from typing import Tuple
def get_paths(base_path: Union[str, Path]) -> Tuple[Path, Path]:
"""
Get fsh input and output paths from base path.
:param base_path: Base path
:return: FSH input path, FSH output path
"""
return (
Path(base_path) / "input" / "fsh",
Path(base_path) / "fsh-generated" / "resources",
) | bigcode/self-oss-instruct-sc2-concepts |
import json
def inline_json(obj):
"""
Format a python object as JSON for inclusion in HTML.
Parameters:
obj: A python object that can be converted to JSON.
Returns:
An escaped :term:`native string` of JSON.
"""
return json.dumps(obj).replace("</script", r"<\/script").replace("<!--", r"<\!--") | bigcode/self-oss-instruct-sc2-concepts |
def readCols(cols_file):
"""
Read a .cols file (normally correspondingly to a .dm file) and return two dictionaries:
word:index and index:word. In the .cols file, the line number is used as index.
:param cols_file: str -- file path to a list of words (words' line numbers are their index)
:return: {int:str} -- 1:1 mapping of indices to words
:return: {str:int} -- 1:1 mapping of words to indices
"""
i_to_cols = {}
cols_to_i = {}
# line count
c = 0
with open(cols_file,'r') as f:
for l in f:
l = l.rstrip('\n')
i_to_cols[c] = l
cols_to_i[l] = c
c+=1
return i_to_cols, cols_to_i | bigcode/self-oss-instruct-sc2-concepts |
def get_invalid_user_credentials(data=None):
"""
Returns error response for invalid user credentials
:param str data: message
:return: response
:rtype: object
"""
response = {"status": 401, "message": "Invalid user credentials.", "data": data}
return response | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
def item_iter(obj):
"""
Return item (key, value) iterator from dict or pair sequence.
Empty seqence for None.
"""
if obj is None:
return ()
if isinstance(obj, Mapping):
return obj.items()
return obj | bigcode/self-oss-instruct-sc2-concepts |
import torch
def mean_std_integrand(fx, px):
"""Compute the expectation value and the standard deviation of a function evaluated
on a sample of points taken from a known distribution.
Parameters
----------
fx: torch.Tensor
batch of function values
px: torch.tensor
batch of PDF values for each of the sampled x
Returns
-------
tuple of float
"""
assert len(px.shape) == 1
assert fx.shape == fx.shape
v, m = torch.var_mean(fx / px)
return m.detach().item(), v.detach().sqrt().item() | bigcode/self-oss-instruct-sc2-concepts |
def start_ind(model, dbg=False):
"""
equation 1 in the paper (called i_0): returns the first index
of the w vector used in the random power law graph model
"""
assert model.gamma > 2 #if gamma=2, this returns 0
num_nodes = model.num_nodes
max_deg = model.max_deg
avg_deg = model.avg_deg
gamma = model.gamma
numerator = avg_deg*(gamma-2)
denominator = max_deg*(gamma-1)
base = numerator/denominator
res = num_nodes * base**(gamma-1)
if dbg:
print(num_nodes, max_deg, avg_deg, gamma, numerator, denominator, base, res)
return res | bigcode/self-oss-instruct-sc2-concepts |
import base64
import six
def serialize(obj):
"""Serialize the given object
:param obj: string representation of the object
:return: encoded object (its type is unicode string)
"""
result = base64.urlsafe_b64encode(obj)
# this workaround is needed because in case of python 3 the
# urlsafe_b64encode method returns string of 'bytes' class.
if six.PY3:
result = result.decode()
return result | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def create_soup(url):
""" This function takes a url and creates a soup for us to work with"""
html = requests.get(url).text
soup = BeautifulSoup(html, "html5lib")
return soup | bigcode/self-oss-instruct-sc2-concepts |
def rad2equiv_evap(energy):
"""
Converts radiation in MJ m-2 day-1 to the equivalent evaporation in
mm day-1 assuming a grass reference crop using FAO equation 20.
Energy is converted to equivalent evaporation using a conversion
factor equal to the inverse of the latent heat of vapourisation
(1 / lambda = 0.408).
Arguments:
energy - energy e.g. radiation, heat flux [MJ m-2 day-1]
"""
# Determine the equivalent evaporation [mm day-1]
equiv_evap = 0.408 * energy
return equiv_evap | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_sentiment_json(doc_id, sent, label):
"""Convert the sentiment info to json.
Args:
doc_id: Document id
sent: Overall Sentiment for the document
label: Actual label +1, 0, -1 for the document
Returns:
String json representation of the input
"""
json_doc = {}
json_doc['doc_id'] = doc_id
json_doc['sentiment'] = float('%.3f' % sent)
json_doc['label'] = label
return json.dumps(json_doc) | bigcode/self-oss-instruct-sc2-concepts |
def get_top_matches(matches, top):
"""Order list of tuples by second value and returns top values.
:param list[tuple[str,float]] matches: list of tuples
:param int top: top values to return
"""
sorted_names = sorted(matches, key=lambda x: x[1], reverse=True)
return sorted_names[0:top] | bigcode/self-oss-instruct-sc2-concepts |
def GetCounterSetting(counter_spec, name):
"""
Retrieve a particular setting from a counter specification; if that setting is not present, return None.
:param counter_spec: A dict of mappings from the name of a setting to its associated value.
:param name: The name of the setting of interest.
:return: Either the value of the setting (if present in counterSpec) or None.
"""
if name in counter_spec:
return counter_spec[name]
return None | bigcode/self-oss-instruct-sc2-concepts |
def jaccard_similariy_index(first, second):
"""
Returns the jaccard similarity between two strings
:param first: first string we are comparing
:param second: second string we are comparing
:return: how similar the two strings are
"""
# First, split the sentences into words
tokenize_first = set(first.lower().split())
tokenize_second = set(second.lower().split())
# Then, find the ratio between their intersection and their total length
intersection = tokenize_first.intersection(tokenize_second)
return float(len(intersection)) / (len(tokenize_first) + len(tokenize_second) - len(intersection)) | bigcode/self-oss-instruct-sc2-concepts |
def scale(score, omax, omin, smax, smin):
"""
>>> scale(2871, 4871, 0, 1000, 0)
589
"""
try:
return ((smax - smin) * (score - omin) / (omax - omin)) + smin
except ZeroDivisionError:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def add_prefix_un(word):
"""
:param word: str of a root word
:return: str of root word with un prefix
This function takes `word` as a parameter and
returns a new word with an 'un' prefix.
"""
prefix = 'un'
return prefix+word | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import re
def parse_dot_argument(dot_argument: str) -> List[str]:
"""
Takes a single argument (Dict key) from dot notation and checks if it also contains list indexes.
:param dot_argument: Dict key from dot notation possibly containing list indexes
:return: Dict key and possible List indexes
"""
list_indexes = re.search(r"((\[[0-9]+])+$)", dot_argument) # Check for List indexes at the argument's end.
if list_indexes is not None: # Get each List index in '[index]' format and get index only.
parsed_list_indexes = re.findall(r"(\[[0-9]+])", list_indexes.group())
parsed_list_indexes = [index for index in parsed_list_indexes]
return [dot_argument[0:list_indexes.start()]] + parsed_list_indexes
return [dot_argument] | bigcode/self-oss-instruct-sc2-concepts |
def apply_building_mapping(mapdict, label):
"""
Applies a building map YAML to a given label, binning it
into the appropriate category.
"""
for category in mapdict:
#print(mapdict, category, label)
if label in mapdict[category]['labels']:
return category
return "house" | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_text(raw_text,nlp):
"""
Preprocesses the raw metaphor by removing sotp words and lemmatizing the words
Args:
raw_text: (string) the original metaphor text to be processed
nlp: (spacy language object)
"""
tokens=[]
for token in nlp(raw_text):
if not token.is_stop:
tokens.append(token.lemma_)
return " ".join(tokens) | bigcode/self-oss-instruct-sc2-concepts |
def get_major_version(version):
"""
:param version: the version of edge
:return: the major version of edge
"""
return version.split('.')[0] | bigcode/self-oss-instruct-sc2-concepts |
def ordinal(number):
"""
Get ordinal string representation for input number(s).
Parameters
----------
number: Integer or 1D integer ndarray
An integer or array of integers.
Returns
-------
ord: String or List of strings
Ordinal representation of input number(s). Return a string if
input is int; else, return a list of strings.
Examples
--------
>>> from bibmanager.utils import ordinal
>>> print(ordinal(1))
1st
>>> print(ordinal(2))
2nd
>>> print(ordinal(11))
11th
>>> print(ordinal(111))
111th
>>> print(ordinal(121))
121st
>>> print(ordinal(np.arange(1,6)))
['1st', '2nd', '3rd', '4th', '5th']
"""
ending = ["th", "st", "nd", "rd"]
unit = number % 10
teen = (number//10) % 10 != 1
idx = unit * (unit<4) * teen
if type(number) is int:
return f"{number}{ending[idx]}"
return [f"{n}{ending[i]}" for n,i in zip(number,idx)] | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_accents(text):
"""Removes common accent characters."""
text = re.sub(u"[àáâãäå]", 'a', text)
text = re.sub(u"[èéêë]", 'e', text)
text = re.sub(u"[ìíîï]", 'i', text)
text = re.sub(u"[òóôõö]", 'o', text)
text = re.sub(u"[ùúûü]", 'u', text)
text = re.sub(u"[ýÿ]", 'y', text)
text = re.sub(u"[ñ]", 'n', text)
return text | bigcode/self-oss-instruct-sc2-concepts |
def cluster_list(list_to_cluster: list, delta: float) -> list:
"""
Clusters a sorted list
:param list_to_cluster: a sorted list
:param delta: the value to compare list items to
:return: a clustered list of values
"""
out_list = [[list_to_cluster[0]]]
previous_value = list_to_cluster[0]
current_index = 0
for item in list_to_cluster[1:]:
if item - previous_value <= delta:
out_list[current_index].append(item)
else:
current_index += 1
out_list.append([])
out_list[current_index].append(item)
previous_value = item
return out_list | bigcode/self-oss-instruct-sc2-concepts |
def external_pressure(rho, g, d):
"""Return the external pressure [Pa] at water depth.
:param float rho: Water density [kg/m^3]
:param float g: Acceleration of gravity [m/s/s]
:param float d: Water depth [m]
"""
return rho * g * d | bigcode/self-oss-instruct-sc2-concepts |
def sort_words(arguments, words):
"""
Takes a dict of command line arguments and a list of words to be sorted.
Returns a sorted list based on `alphabetical`, `length` and `reverse`.
"""
if arguments.get('--alphabetical', False):
words.sort()
elif arguments.get('--length', False):
words.sort(key=len)
if arguments.get('--reverse', False):
words.reverse()
return words | bigcode/self-oss-instruct-sc2-concepts |
def source_from_url(link):
"""
Given a link to a website return the source .
"""
if 'www' in link:
source = link.split('.')[1]
else:
if '.com' in link:
source = link.split('.com')[0]
else:
source = link.split('.')[0]
source = source.replace('https://', '')
source = source.replace('http://', '')
return source | bigcode/self-oss-instruct-sc2-concepts |
def _check_type(type_, value):
"""Return true if *value* is an instance of the specified type
or if *value* is the specified type.
"""
return value is type_ or isinstance(value, type_) | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def get_callback_class(hyperparams):
"""
Get one or more Callback class specified as a hyper-parameter
"callback".
e.g.
callback: stable_baselines3.common.callbacks.CheckpointCallback
for multiple, specify a list:
callback:
- utils.callbacks.PlotActionWrapper
- stable_baselines3.common.callbacks.CheckpointCallback
:param hyperparams: (dict)
:return: (List[BaseCallback])
"""
def get_module_name(callback_name):
return '.'.join(callback_name.split('.')[:-1])
def get_class_name(callback_name):
return callback_name.split('.')[-1]
callbacks = []
if 'callback' in hyperparams.keys():
callback_name = hyperparams.get('callback')
if callback_name is None:
return callbacks
if not isinstance(callback_name, list):
callback_names = [callback_name]
else:
callback_names = callback_name
# Handle multiple wrappers
for callback_name in callback_names:
# Handle keyword arguments
if isinstance(callback_name, dict):
assert len(callback_name) == 1, ("You have an error in the formatting "
f"of your YAML file near {callback_name}. "
"You should check the indentation.")
callback_dict = callback_name
callback_name = list(callback_dict.keys())[0]
kwargs = callback_dict[callback_name]
else:
kwargs = {}
callback_module = importlib.import_module(get_module_name(callback_name))
callback_class = getattr(callback_module, get_class_name(callback_name))
callbacks.append(callback_class(**kwargs))
return callbacks | bigcode/self-oss-instruct-sc2-concepts |
def area_under_curve(x, y):
"""Finds the area under unevenly spaced curve y=f(x)
using the trapezoid rule. x,y should be arrays of reals
with same length.
returns: a - float, area under curve"""
a = 0.0
for i in range(0, len(x) - 1):
# add area of current trapezium to sum
a += (x[i + 1] - x[i]) * (y[i + 1] + y[i])
a = a * 0.5
return a | bigcode/self-oss-instruct-sc2-concepts |
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n) because the number of calculations performed depends on the size of num.
Space Complexity: Space complexity is also O(n) becuase newman_conway_nums array to store sequence values,
nm_sequence_without_leading_zero to store result with leading 0 removed and result a array to which the properly
formatted result is saved are created and the amount of space that they occupy will depend on the size of the given num.
"""
if num == 0:
raise ValueError
if num == 1:
return '1'
if num == 2:
return '1 1'
#array to store sequence values and provide starting values
newman_conway_nums = [0, 1, 1]
for i in range(3, num + 1):
newman_conway_nums.append(newman_conway_nums[newman_conway_nums[i-1]] + newman_conway_nums[i-newman_conway_nums[i-1]])
nm_sequence_without_leading_zero = [str(num) for num in newman_conway_nums if num != 0]
result = " ".join(nm_sequence_without_leading_zero)
return result | bigcode/self-oss-instruct-sc2-concepts |
def _get_position_precedence(position: str) -> int:
"""Get the precedence of a position abbreviation (e.g. 'GK') useful for ordering."""
PLAYER_POSITION_PRECEDENCE = {
"GK": 1,
"LB": 2,
"LCB": 3,
"CB": 4,
"RCB": 5,
"RB": 6,
"LDM": 7,
"CDM": 8,
"RDM": 9,
"LM": 10,
"LCM": 11,
"CM": 12,
"RCM": 13,
"RM": 14,
"LW": 15,
"CAM": 16,
"RW": 17,
"LF": 18,
"LCF": 19,
"CF": 20,
"RCF": 21,
"RF": 22,
"SUB": 99,
}
# unknown positions are inserted between known positions and substitutes
precedence = PLAYER_POSITION_PRECEDENCE.get(position, 23)
return precedence | bigcode/self-oss-instruct-sc2-concepts |
def v1_deep_add(lists):
"""Return sum of values in given list, iterating deeply."""
total = 0
lists = list(lists)
while lists:
item = lists.pop()
if isinstance(item, list):
lists.extend(item)
else:
total += item
return total | bigcode/self-oss-instruct-sc2-concepts |
def ngrams(sequence, N):
"""Return all `N`-grams of the elements in `sequence`"""
assert N >= 1
return list(zip(*[sequence[i:] for i in range(N)])) | bigcode/self-oss-instruct-sc2-concepts |
def pollutants_per_country(summary):
"""
Get the available pollutants per country from the summary.
:param list[dict] summary: The E1a summary.
:return dict[list[dict]]: All available pollutants per country.
"""
output = dict()
for d in summary.copy():
country = d.pop("ct")
if country in output:
output[country].append(d)
else:
output[country] = [d]
return output | bigcode/self-oss-instruct-sc2-concepts |
import string
def read_cstring(view, addr):
"""Read a C string from address."""
s = ""
while True:
c = view.read(addr, 1)
if c not in string.printable:
break
if c == "\n": c = "\\n"
if c == "\t": c = "\\t"
if c == "\v": c = "\\v"
if c == "\f": c = "\\f"
s+= c
addr += 1
return s | bigcode/self-oss-instruct-sc2-concepts |
def _format_time(time_us):
"""Defines how to format time in FunctionEvent"""
US_IN_SECOND = 1000.0 * 1000.0
US_IN_MS = 1000.0
if time_us >= US_IN_SECOND:
return '{:.3f}s'.format(time_us / US_IN_SECOND)
if time_us >= US_IN_MS:
return '{:.3f}ms'.format(time_us / US_IN_MS)
return '{:.3f}us'.format(time_us) | bigcode/self-oss-instruct-sc2-concepts |
def product_turnover(units_sold_in_period, average_items_stocked_in_period):
"""Return the product turnover (or sell through rate) for a product based on units sold versus items stocked.
Args:
units_sold_in_period (int): Number of units of product X sold in the period.
average_items_stocked_in_period (int): Average stock holding for product X in the period.
Returns:
product_turnover (float): Percentage of average stock holding sold during the period.
"""
return (units_sold_in_period / average_items_stocked_in_period) * 100 | bigcode/self-oss-instruct-sc2-concepts |
def fib_n_efficient(n):
"""Efficient way to compute Fibonacci's numbers. Complexity = O(n)"""
a = 0
b = 1
for i in range(n - 1):
c = a + b
a = b
b = c
print(b)
return b | bigcode/self-oss-instruct-sc2-concepts |
def _get_single_reg(asm_str):
"""returns a single register from string and check proper formatting (e.g "r5")"""
if len(asm_str.split()) > 1:
raise SyntaxError('Unexpected separator in reg reference')
if not asm_str.lower().startswith('r'):
raise SyntaxError('Missing \'r\' character at start of reg reference')
if not asm_str[1:].isdigit():
raise SyntaxError('reg reference not a number')
return int(asm_str[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_boolean(val):
""" Checks if given value is boolean """
values = [True, False]
return val in values | bigcode/self-oss-instruct-sc2-concepts |
def massage_data(raw_data):
""" Preprocess the data for predictions
"""
raw_data.rename(index=str, columns={"whether he/she donated blood in March 2007": "label"}, inplace=True)
# generate features for year for time columns
for x, y in zip(['time_years', 'recency_years'], ['Time (months)', 'Recency (months)']):
raw_data[x] = (raw_data[y] / 12).astype('int')
# generate features for quarter for time columns (3 month periods)
for x, y in zip(['time_quarters', 'recency_quarters'], ['Time (months)', 'Recency (months)']):
raw_data[x] = (raw_data[y] / 3).astype('int')
return raw_data | bigcode/self-oss-instruct-sc2-concepts |
def remove_multiedges(E):
"""Returns ``(s, d, w)`` with unique ``(s, d)`` values and `w` minimized.
:param E: a set of edges
:type E: [(int, int, float)]
:return: a subset of edges `E`
:rtype: [(int, int, float), ...]
"""
result = []
exclusion = set()
for i, (si, di, wi) in enumerate(E):
if i in exclusion:
continue
minimum = 0
for j in range(i + 1, len(E)):
if j in exclusion:
continue
sj, dj, wj = E[j]
if si == sj and di == dj:
if wi > wj:
exclusion.add(i)
elif wi < wj:
exclusion.add(j)
if i in exclusion:
continue
result.append(E[i])
return result | bigcode/self-oss-instruct-sc2-concepts |
import six
import importlib
def load_class(requested_class):
"""
Check if requested_class is a string, if so attempt to load
class from module, otherwise return requested_class as is
"""
if isinstance(requested_class, six.string_types):
module_name, class_name = requested_class.rsplit(".", 1)
try:
m = importlib.import_module(module_name)
return getattr(m, class_name)
except:
raise
return requested_class | bigcode/self-oss-instruct-sc2-concepts |
def calc_tristimulus_array_length(data_array):
"""
calcurate the array length of tristimulus ndarray.
Parameters
----------
data_array : ndarray
tristimulus values
Returns
-------
int
length of the tristimulus array.
Examples
--------
>>> data_1 = np.ones((3, 4, 3))
>>> calc_tristimulus_array_length(data_array=data_1)
12
>>> data_2 = np.ones((3))
>>> calc_tristimulus_array_length(data_array=data_2)
1
"""
length = 1
for coef in data_array.shape[:-1]:
length = length * coef
return length | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_user_ips(file):
"""Read in the JSON file of the user-IP address mapping."""
with open(file, 'r') as file:
return json.loads(file.read()) | 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.