seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def first_alpha(s):
"""
Returns the length of the shortest substring of the input that
contains an alpha character.
"""
for i, c in enumerate(s):
if c.isalpha():
return i + 1
raise Exception("No alpha characters in string: {}".format(s)) | bigcode/self-oss-instruct-sc2-concepts |
def vswr_to_gama(vswr):
"""Calculate Gama (Reflection Coefficient) from VSWR"""
gama = (vswr-1)/(vswr+1)
return gama | bigcode/self-oss-instruct-sc2-concepts |
def lerp(a, b, pos) -> float:
"""### Basic linear interpolation.
This method returns a value between the given `a`->`b` values.\n
When `pos=0` the return value will be `a`.\n
When `pos=1` the turn value will be the value of `b`. `pos=0.5` would be\
half-way between `a` and `b`.
"""
lerp... | bigcode/self-oss-instruct-sc2-concepts |
def __get_codeclimate_severity(cpio_severity: str) -> str:
"""Get Code Climate severity, from CppCheck severity string
CodeQuality: info, minor, major, critical, blocker
"""
map_severity_to_severity = {
"high": "critical",
"medium" : "major",
"low" : "minor"
}
return map... | bigcode/self-oss-instruct-sc2-concepts |
def change_parameter_unit(
parameter_dict: dict,
multiplier: float
) -> dict:
"""
Currently only used to adapt the latency parameters from the earlier functions according to whether they are needed as by year rather than by day.
Could be more generally applicable.
Args:
parameter_dict:... | bigcode/self-oss-instruct-sc2-concepts |
def is_in(elements, value):
"""
Determines if a value is in a list. It also handles degenerate cases
when instead of a list, elements is True, False or None
"""
if not elements:
return False
elif elements is True:
return True
else:
return value in elements | bigcode/self-oss-instruct-sc2-concepts |
def parse_endpoint(endpoint):
"""
Parse endpoint into (blueprint, endpoint).
blueprint can be :const:`None`
"""
if '.' in endpoint:
return endpoint.split('.', 1)
return None, endpoint | bigcode/self-oss-instruct-sc2-concepts |
def dict_swap(d):
"""
Swap dictionary keys and values.
:type d: dict
"""
done = {}
for k, v in d.items():
done[v] = k
return done | bigcode/self-oss-instruct-sc2-concepts |
import copy
def merge_dict(bot, top):
"""Helper function for merging dict fields over another dict.
Merge top dict onto bot dict, so that the returned new dict has the updated top vals."""
new = copy.deepcopy(bot)
for k, v in top.items():
new[k] = v
return new | bigcode/self-oss-instruct-sc2-concepts |
def get_gene_capacity(genes_df, database, col='GeneID'):
"""Get gene capcaity from the stored metadata"""
capacity = (database.groupby('geneid').capacity.mean()
.to_frame(name='GeneCapacity'))
genes_df = genes_df.merge(capacity, how='left', left_on='GeneID', right_index=True)
return gene... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_model_id_list(redis):
""" Get the list of model ids """
ids = redis.get("m:ids") or "{}"
return json.loads(ids) | bigcode/self-oss-instruct-sc2-concepts |
def graph_list_to_features(graphs):
"""Get a TFRecord feature dictionary from a list of graphs.
The features from each graph is prepended with a prefix and all
added to the final dictionary at the same level.
Parameters
----------
graphs : [Graph]
Returns
-------
features : dict (... | bigcode/self-oss-instruct-sc2-concepts |
def mkdir_cmd(path):
"""Return mkdir command"""
return " ".join(["/bin/mkdir", "-p", path]) | bigcode/self-oss-instruct-sc2-concepts |
def transform_region_to_coordinates(x_coord,
y_coord,
prefix_len,
image_bit_level=10):
"""Transforms (x,y)-bit region into a square for a final level.
This method converts a leaf on some level `prefix_le... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def join_address_and_port(address: Optional[str], port: int) -> str:
"""
Join address and port using format "{address}:{port}".
:param address: The address. If not given, "localhost" is used.
:param port: The port number.
:return: Joined address and port.
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def merge_st(S1, S2):
"""Merge two sorted Python Lists S1 and S2 into properly sized list S"""
i = j = 0
S = S1+S2
while i+j < len(S):
if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
S[i+j] = S1[i]
i = i+1
else:
S[i+j] = S2[j]
j = j+1
... | bigcode/self-oss-instruct-sc2-concepts |
def deny(blacklist):
"""
Decorates a handler to filter out a blacklist of commands.
The decorated handler will not be called if message.command is in the
blacklist:
@deny(['A', 'B'])
def handle_everything_except_a_and_b(client, message):
pass
Single-item blacklists may... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanatize_text(text):
""" Replace non alphanumeric characters in text with '_'
Parameters
----------
text : str
text to sanatize
Returns
-------
text
the sanatized text
"""
if text is None:
return text
return re.sub('[^a-zA-Z0-9]', '_', text... | bigcode/self-oss-instruct-sc2-concepts |
def first_key(d):
"""get the first key of a dict"""
return list(d.keys())[0] | bigcode/self-oss-instruct-sc2-concepts |
def n_coeffs_from_ell_max(ell_max):
"""Returns the number of coefficients for an SWSFT with max degree ell_max."""
return (ell_max + 1)**2 | bigcode/self-oss-instruct-sc2-concepts |
def declare_temp(var_type, var_name):
"""Create a declaration of the form
(declare (temporary) <var_type> <var_name)
"""
return [['declare', ['temporary'], var_type, var_name]] | bigcode/self-oss-instruct-sc2-concepts |
def _iteritems(d):
"""Like d.iteritems, but accepts any collections.Mapping."""
return d.iteritems() if hasattr(d, "iteritems") else d.items() | bigcode/self-oss-instruct-sc2-concepts |
def file_session_to_import_file(file_session):
"""Get the import file of its session."""
return file_session.file | bigcode/self-oss-instruct-sc2-concepts |
def get_project_id_from_service_account_email(service_account_email: str) -> str:
"""
Get GCP project id from service_account_email
>>> get_project_id_from_service_account_email('cromwell-test@tob-wgs.iam.gserviceaccount.com')
'tob-wgs'
"""
# quick and dirty
return service_account_email.spl... | bigcode/self-oss-instruct-sc2-concepts |
def _filter_slabs(provisional, max_size):
"""
Filters the repeat slabs from the list of all the zero dipole slabs.
Creates lists of large and repeat slabs if any are present for the warnings
Args:
provisional (`list`): All zero dipole slabs generated with SlabGenerator
max_size (`int... | bigcode/self-oss-instruct-sc2-concepts |
import curses
def resolve_capability(term, attr):
"""
Resolve a raw terminal capability using :func:`tigetstr`.
:arg Terminal term: :class:`~.Terminal` instance.
:arg str attr: terminal capability name.
:returns: string of the given terminal capability named by ``attr``,
which may be empty... | bigcode/self-oss-instruct-sc2-concepts |
def prettify_format(format):
"""
Return the date format in a more human readable form.
"""
f = format.replate('%Y', 'yyyy')
f = f.replace('%m', 'mm')
f = f.replace('%d', 'dd')
return f | bigcode/self-oss-instruct-sc2-concepts |
import copy
def merge_left_with_defaults(defaults, loaded_config):
"""
Merge two configurations, with one of them overriding the other.
Args:
defaults (dict): A configuration of defaults
loaded_config (dict): A configuration, as loaded from disk.
Returns (dict):
A merged confi... | bigcode/self-oss-instruct-sc2-concepts |
def get_version_name(lang: str, major: int, minor: int, patch: int):
"""Return the package name associated with the lang ``name`` and version (``major``, ``minor``, ``patch``)"""
return f"{lang}_{major}_{minor}_{patch}" | bigcode/self-oss-instruct-sc2-concepts |
def _environment_intersection(run, caseversion):
"""Intersection of run/caseversion environment IDs."""
run_env_ids = set(
run.environments.values_list("id", flat=True))
case_env_ids = set(
caseversion.environments.values_list("id", flat=True))
return run_env_ids.intersection(case_env_id... | bigcode/self-oss-instruct-sc2-concepts |
import tempfile
def wrap_in_tempfile(data):
"""Return SpooledTemporaryFile with given data as content, ready to read
eg. as a subprocess input.
"""
wrapped = tempfile.SpooledTemporaryFile()
wrapped.write(data)
wrapped.flush()
wrapped.seek(0)
return wrapped | bigcode/self-oss-instruct-sc2-concepts |
def number_of_internal_nodes(tree):
"""Return the number of internal nodes of tree."""
if tree.is_empty():
return 0
elif tree.left_child().is_empty() and tree.right_child().is_empty():
return 0
else:
return 1\
+ number_of_internal_nodes(tree.left_child())\
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_gender() -> bool:
"""Returns a random gender. True is male and False is female.
Returns:
bool: A gender represented by a bool.
"""
return bool(random.getrandbits(1)) | bigcode/self-oss-instruct-sc2-concepts |
def compute_optimum(groups, elements):
"""Compute the number of elements per group and the remainder.
:param elements: total number of elements
:param groups: total number of groups
"""
return elements // groups, elements % groups | bigcode/self-oss-instruct-sc2-concepts |
import math
import random
def create_spiral_galaxy(system_count=100, spirals=2):
"""
Creates a spiral galaxy with given spirals (arms) and system count.
The galaxy is unlinked and just creates the galaxy shape
"""
sep = 2*math.pi/spirals
spiral_list = []
for x in range(spirals):
... | bigcode/self-oss-instruct-sc2-concepts |
def valid_filename_from_query(query):
"""
Generates a filename from a query.
This just gets the descriptor string from the query and replaces any
spaces with hyphens. (At the time of writing, descriptors can't contain
spaces, but in the future they will be able to.)
"""
return query.dnode.t... | bigcode/self-oss-instruct-sc2-concepts |
import re
def trim_offset(name):
"""_trim_offset(name: str) -> str
Remove address offset from name.
Example:
some_function+0x42beef -> some_function
"""
return re.sub(r'\+0x[0-9a-fA-F]+$', '', name) | bigcode/self-oss-instruct-sc2-concepts |
import random
def choose_false_edges(non_edges, K):
"""
Randomly choose a fixed number of non-existing edges
:param non_edges: Edges that are not in the graph
:param K: Fixed number of edges to choose
:return: A list of K false edges
"""
indexes = random.sample(range(1, len(non_edges)), K)... | bigcode/self-oss-instruct-sc2-concepts |
def caption() -> str:
"""Caption to be displayed at the end.
Returns:
str: Message for the users.
"""
return 'Thank you for using crypto-candlesticks\
Consider supporting your developers\
ETH: 0x06Acb31587a96808158BdEd07e53668d8ce94cFE\
' | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_approx_flame_length(head_fire_intensity: float):
""" Returns an approximation of flame length (in meters).
Formula used is a field-use approximation of
L = (I / 300)^(1/2), where L is flame length in m and I is Fire Intensity in kW/m
"""
return math.sqrt(head_fire_intensity / 3... | bigcode/self-oss-instruct-sc2-concepts |
def indicator_function_ei(X_i, M, X_nk_n):
"""Returns 1 if M is smaller or equal than X_nk_n and if X_nk_n is smaller
than X_i, and 0 otherwise."""
return 1*(M <= X_nk_n < X_i) | bigcode/self-oss-instruct-sc2-concepts |
def remove_http_https_prefix(endpoint):
"""remove http:// or https:// prefix if presented in endpoint"""
endpoint = endpoint.replace("https://", "")
endpoint = endpoint.replace("http://", "")
return endpoint | bigcode/self-oss-instruct-sc2-concepts |
def timedelta_as_string(td):
"""Formatted 'HH:MM:SS' representation of a timedelta object"""
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
return "{:02d}:{:02d}:{:02d}".format(*map(int, (hours, minutes, seconds))) | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def remove_name_prefix(path: pathlib.Path, prefix: str) -> pathlib.Path:
"""Remove prefix from path name.
Does nothing if prefix is not part of path name.
Args:
path: File system path to edit.
prefix: String prefix to remove from path name.
Returns:
Path witho... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_multi_agg_with_relabel(**kwargs: Any) -> bool:
"""
Check whether the kwargs pass to .agg look like multi-agg with relabling.
Parameters
----------
**kwargs : dict
Returns
-------
bool
Examples
--------
>>> is_multi_agg_with_relabel(a='max')
... | bigcode/self-oss-instruct-sc2-concepts |
def IsInTargetRange(
target, error_ref, warning_percentage, error_percentage, value):
"""Test if a value falls into warning or error range around a target.
Args:
target: The target value.
error_ref: The error reference as the base for warning/error percentage.
warning_percentage: The percentage of ... | bigcode/self-oss-instruct-sc2-concepts |
def SplitStringAtSeparator(string,sep):
""" split string at commas
:param str string: string
:param str sep: separator character
:return: strlst(lst) - list of splited strings
"""
#return filter(lambda s: len(s) > 0, string.split(sep))
strlst=[]; items=string.split(sep)
for s in... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_color() -> str:
"""Generate a random hex string."""
return "".join("{0:02x}".format(random.randrange(1 << 8)) for _ in range(3)) | bigcode/self-oss-instruct-sc2-concepts |
def get_row_values(model, keys):
"""Get the values needed to fill a row in the table
Parameters
----------
model : `dmsky.Model`
Model that we are getting the data from
keys : list
Names of the properties we are reading
Returns
-------
vals : dict
A dict... | bigcode/self-oss-instruct-sc2-concepts |
def _str_to_list(s):
"""Converts a comma separated string to a list"""
_list = s.split(",")
return list(map(lambda i: i.lstrip(), _list)) | bigcode/self-oss-instruct-sc2-concepts |
def seed_generator(generator, logger, seed=0):
"""Set seed for Dataloader generators. DataLoader will reseed workers the
"Randomness in multi-process data loading" algorithm. Use `generator` to
preserve reproducibility. For more information, see
https://pytorch.org/docs/stable/notes/randomness.html.
... | bigcode/self-oss-instruct-sc2-concepts |
def __check_epsilon_productions(cnf_variables, cnf_productions, cfg_productions):
"""
Check whether all reachable epsilon productions from
Context Free Grammar are present in Chomsky Normal Form productions.
"""
cfg_epsilon_productions = set(
filter(
lambda prod: prod.head in cn... | bigcode/self-oss-instruct-sc2-concepts |
def bytes_to_readable_str(num_bytes, include_b=False):
"""Generate a human-readable string representing number of bytes.
The units B, kB, MB and GB are used.
Args:
num_bytes: (`int` or None) Number of bytes.
include_b: (`bool`) Include the letter B at the end of the unit.
Returns:
(`str`) A strin... | bigcode/self-oss-instruct-sc2-concepts |
def issue_to_dict(issue):
"""
Convert an issue to a dictionary suitable for outputting to csv
"""
issue_data = {}
issue_data['id'] = issue.id
issue_data['title'] = issue.title
issue_data['description'] = issue.description
issue_data['due_date'] = issue.due_date
issue_data['labels'] =... | bigcode/self-oss-instruct-sc2-concepts |
def filterLargeClusters(clusters, input_size, cluster_fraction_thresh):
""" Remove big clusters which have more points than a given fraction of total points in the input data.
Arguments:
clusters: [list] a python list containing found clusters in the reachability diagram plot (optional)
- ... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def search_qms(keyword, limit=10, list_only=True, add_prefix=True):
"""Search for QMS tile providers from Quick Map Services.
Args:
keyword (str): The keyword to search for.
limit (int, optional): The maximum number of results to return. Defaults to 10.
list_only (bool... | bigcode/self-oss-instruct-sc2-concepts |
import re
def validate_language_code(language_code):
"""
Checks whether the language code given follows the ISO format, e.g "en"
:param language_code: the string being checked
:type language_code: str
:returns: whether the code is valid
:rtype: bool
"""
return re.match('[a-z]{2}', la... | bigcode/self-oss-instruct-sc2-concepts |
import math
def to_time(seconds):
"""Convert a number of seconds into human readable compact string."""
prefix = ''
if seconds < 0:
prefix = '-'
seconds *= -1
minutes = math.floor(seconds / 60)
seconds -= minutes * 60
hours = math.floor(minutes / 60)
minutes -= hours * 60
days = math.floor(hou... | bigcode/self-oss-instruct-sc2-concepts |
def task_docs() -> dict:
"""Build sphinx document."""
return {
'actions': ['sphinx-build -q -W -j 4 -b html docs docs/_build/html'],
} | bigcode/self-oss-instruct-sc2-concepts |
def _infection_indicator(
health_states, infected_state_index):
"""Returns a binary vector that indicates whether individuals are infected."""
return [int(state == infected_state_index) for state in health_states] | bigcode/self-oss-instruct-sc2-concepts |
def productOfAdjacents(i, n, number):
"""Returns the product of n adjacent digits starting at i"""
"""Takes in the number as a string"""
product = 1
for i in range (i, i+n):
product *= int(number[i])
return product | bigcode/self-oss-instruct-sc2-concepts |
def filter_stops(stop_info):
""" Filter for only type 0 stops, ie load/unload"""
new_stop_info = {}
for stop in stop_info:
if stop_info[stop]["location_type"] == "0":
new_stop_info[stop] = stop_info[stop]
return new_stop_info | bigcode/self-oss-instruct-sc2-concepts |
def tokens_to_ops(token_dict):
"""returns a list of ops from a {tokenId:token_obj} dict"""
outops = []
for t in token_dict.values():
outops.append(t.as_op())
return outops | bigcode/self-oss-instruct-sc2-concepts |
def table_exists(table_name, connection, schema=None):
"""Returns `True` if a table exists in a database.
Parameters
----------
table_name : str
The name of the table.
connection : .PeeweeDatabaseConnection
The Peewee database connection to use.
schema : str
The schema i... | bigcode/self-oss-instruct-sc2-concepts |
def format_test_id(test_id) -> str:
"""Format numeric to 0-padded string"""
return f"{test_id:0>5}" | bigcode/self-oss-instruct-sc2-concepts |
def _format_column_name(raw_column_name, year=None):
"""Formats a raw column name to remove: spaces, year and character with
accents.
Args:
raw_column_name (str): a column name
year: the year tu remove
Returns:
(str) The formatted column name.
"""
raw_column_name = ('_'... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_interval_in_s(interval: List[str]) -> List[int]:
"""Converts an interval in string form (e.g. [1:10, 2:30] in seconds, e.g. [70, 150] seconds"""
return [int(sec.split(":")[0]) * 60 + int(sec.split(":")[1]) for sec in interval] | bigcode/self-oss-instruct-sc2-concepts |
def qualifier(entry):
"""
Get the qualifer for this entry.
"""
return entry["Qualifier"][0] | bigcode/self-oss-instruct-sc2-concepts |
def get_info_dic(s):
"""
Parse the string from the VCF INFO
column and return it as a dictionary.
"""
info_tuples = [t.split('=') for t in s.split(';')]
info_tuples = [t for t in info_tuples if len(t) == 2]
tags = [t for t in info_tuples if len(t) != 2]
# try:
d = {k: v for (k, v) in ... | bigcode/self-oss-instruct-sc2-concepts |
def get_strings(soup, tag):
"""Get all the string children from an html tag."""
tags = soup.find_all(tag)
strings = [s.string for s in tags if s.string]
return strings | bigcode/self-oss-instruct-sc2-concepts |
def require_methods(*method_args):
"""Class decorator to require methods on a subclass.
Example usage
------------
@require_methods('m1', 'm2')
class C(object):
'This class cannot be instantiated unless the subclass defines m1() and m2().'
def __init__(self):
pass
... | bigcode/self-oss-instruct-sc2-concepts |
def get_val_string(input):
"""
String for a value, formatted for CSycles
"""
val = ""
if input.type == 'VALUE':
val = "{0: .3f}f".format(input.default_value)
elif input.type in ('RGBA', 'VECTOR'):
val = "new float4({0: .3f}f, {1: .3f}f, {2: .3f}f)".format(
input.defau... | bigcode/self-oss-instruct-sc2-concepts |
def fmt_addr(addr):
""" Format a Bluetooth hardware address as a hex string.
Args:
addr (bytes): raw Bluetooth address in dongle format.
Returns:
str. Address in xx:xx:xx:xx:xx:xx format.
"""
return ':'.join(reversed(['{:02x}'.format(v) for v in bytearray(addr)])) | bigcode/self-oss-instruct-sc2-concepts |
def _new_block_definition(block_name):
"""
This will return a new block definition with the given block name
:param block_name: Name of the block to define
:return: str
"""
return """
myData = attributes "%s" version:1
(
-- Define the act... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from pathlib import Path
def install_requires() -> List[str]:
""" Populate install_requires from requirements.txt """
requirements_txt = Path(__file__).parent.joinpath("requirements.txt").read_text()
return [requirement for requirement in requirements_txt.split("\n")] | bigcode/self-oss-instruct-sc2-concepts |
def _parse_control_depends(fields):
"""
Parse the package names of the 'Depends:' directive in a debian control file.
References:
https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-controlsyntax
https://www.debian.org/doc/debian-policy/ch-relationships.html#declaring-relations... | bigcode/self-oss-instruct-sc2-concepts |
def get_ipsec_udp_key_config(
self,
) -> dict:
"""Get IPSEC UDP key material configuration, seed lifetime, max
activation wait time, and whether to persist seed on appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - ikeless
... | bigcode/self-oss-instruct-sc2-concepts |
def decode_pass(boarding_pass : str) -> tuple[int, int, int]:
"""Get the row, column and seat id from a boarding pass"""
row = int(boarding_pass[:7].replace("F", "0").replace("B", "1"), 2)
column = int(boarding_pass[7:].replace("L", "0").replace("R", "1"), 2)
return row, column, row * 8 + column | bigcode/self-oss-instruct-sc2-concepts |
def _has_version(name):
"""Check whether a package identifier has a version component."""
return name.rpartition("-")[2].replace(".", "").isdigit() | bigcode/self-oss-instruct-sc2-concepts |
def is_comment(line):
"""check whether a line is a comment"""
return line.strip().startswith("#") | bigcode/self-oss-instruct-sc2-concepts |
def merge_bindings(program, node, bindings):
"""Create a combined Variable for a list of bindings.
Args:
program: A cfg.Program instance.
node: The current CFG node.
bindings: A list of cfg.Bindings.
Returns:
A cfg.Variable.
"""
v = program.NewVariable()
for b in bindings:
v.PasteBindin... | bigcode/self-oss-instruct-sc2-concepts |
async def heartbeat():
""" Example heartbeat function for proxies and load balancers to check """
return {
'status': 'ok'
} | bigcode/self-oss-instruct-sc2-concepts |
def ct_mimetype(content_type):
"""Return the mimetype part of a content type."""
return (content_type or '').split(';')[0].strip() | bigcode/self-oss-instruct-sc2-concepts |
def correct_description(description):
"""Given an description, return a version with any typos pedantically corrected."""
for old, new in (
('- ', ' - '),
(' -', ' - '),
(' -', ' -'),
('- ', '- '),
):
description = description.replace(old, new)
r... | bigcode/self-oss-instruct-sc2-concepts |
def dunder_partition(key):
"""Splits a dunderkey into 2 parts
The first part is everything before the final double underscore
The second part is after the final double underscore
>>> dunder_partition('a__b__c')
>>> ('a__b', 'c')
"""
parts = key.rsplit('__', 1)
return tuple(parts)... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
import collections
def shortest_path_grid(grid: List[List[int]], start:Tuple[int, int], end:Tuple[int, int]):
"""
Finds shortest path in a grid of mxn using BFS and returns it's path length including start and end.
Uses direction vetors and each cell treats... | bigcode/self-oss-instruct-sc2-concepts |
def intercalate_sigma_into_peak_params(reduced_peak_params, sigmas):
"""
Insert the sigmas back into reduced_peak_params to form peak_params.
To describe N peaks,
Input
-----
reduced_peak_params : A vector of length = 2*N.
Every odd element describe an amplitude,
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def parse_iso_date(txt: str) -> datetime:
"""Parse a datetime in ISO format."""
return datetime.strptime(txt[:19], "%Y-%m-%d %H:%M:%S") | bigcode/self-oss-instruct-sc2-concepts |
def profit_filler(df, max_length):
"""Takes a dataframe and ensures all the profit rows are the same length for
adding together profits over the number of games, shorter rows will be
filled with their final value.
example: row 0 = [1,2,3,4], row 1 = [1,2,3] -> row 0 = [1,2,3,4],
row 1 = [1,2,3,3]
... | bigcode/self-oss-instruct-sc2-concepts |
def progress_bar(val, val_max, val_min=0, prefix="", suffix="", bar_len=20):
"""
Displays a progress bar in the simulation tree.
:param val: current value
:param val_max: maximum value
:param val_min: minimum value
:param prefix: marker for the completed part
:param suffix: marker for the in... | bigcode/self-oss-instruct-sc2-concepts |
def iteratively_query_dict(path: list, d: dict):
"""
Query a multidimensional dict with a list as the key.
:param path:
:param d:
:return:
"""
tmp = d
for key in path:
tmp = tmp[key]
return tmp | bigcode/self-oss-instruct-sc2-concepts |
from textwrap import dedent
def indent(text, spaces=4, strip=False):
"""Return the ``text`` indented by the given number of ``spaces``."""
if not hasattr(text, 'splitlines'):
text = '\n'.join(text)
if strip:
text = dedent(text)
prefix = ' ' * spaces
output = '\n'.join(prefix + lin... | bigcode/self-oss-instruct-sc2-concepts |
def fseq_sign_changes(f, arr, i):
"""
Checks whether a sequence's i'th image through a function f has different
sign from the i+1'th element
"""
return f(arr[i]) * f(arr[i+1]) < 0 | bigcode/self-oss-instruct-sc2-concepts |
import re
def parseTargetUrl(url):
"""
Parse target URL
"""
retVal = url
if not re.search("^http[s]*://", retVal, re.I) and not re.search("^ws[s]*://", retVal, re.I):
if re.search(":443[/]*$", retVal):
retVal = "https://" + retVal
else:
retVal = "http://" +... | bigcode/self-oss-instruct-sc2-concepts |
def _get_word_ids(tokens, model_type="bert"):
"""Given the BPE split results, mark each token with its original word ids.
Args:
tokens: a list of BPE units
For example, if original sentnece is `iran and afghanistan speak the same language .`, then the roberta
tokens will be:
['ir', 'an', '... | bigcode/self-oss-instruct-sc2-concepts |
def _FilterForImageType(artifacts, image_type):
"""Return only images for given |image_type|."""
return [i for i in artifacts if i.image_type == image_type] | bigcode/self-oss-instruct-sc2-concepts |
import json
def createJSONPackage(data):
"""
Returns a JSON package.
Args:
data (dict) : A dictionary consisting of the data to JSONify.
"""
return json.dumps(data) | bigcode/self-oss-instruct-sc2-concepts |
def objective(model):
"""
The objective function of the model.
Parameters
----------
model : pyomo model object
The pyomo model that the optimization shall be run on.
Returns
-------
dev : float
The summed squared deviation between the resulting charging load
(... | bigcode/self-oss-instruct-sc2-concepts |
def get_property_annotations(self, all=False):
"""Returns a dict with non-empty property annotations.
If `all` is true, also annotations with no value are included."""
onto = self.namespace.ontology
d = {a.label.first(): a._get_values_for_class(self)
for a in onto.annotation_properties()}
... | bigcode/self-oss-instruct-sc2-concepts |
def recurse_access_key(current_val, keys):
""" Given a list of keys and a dictionary, recursively access the dicionary
using the keys until we find the key its looking for
If a key is an integer, it will convert it and use it as a list index
Example:
>>> recurse_access_key({'a': 'b'}, ['a'])
... | 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.