seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def segment_length(curve, start, end, start_point, end_point, error, min_depth, depth):
"""Recursively approximates the length by straight lines"""
mid = (start + end) / 2
mid_point = curve.point(mid)
length = abs(end_point - start_point)
first_half = abs(mid_point - start_point)
second_half = a... | bigcode/self-oss-instruct-sc2-concepts |
def get_highest_priority_reachable(Sr):
"""
Sr: The remaining unconsidered part of the original solution
Return: the highest priority rule which is also reachable,
i.e. that is to say it is in table 1. Or None if no
rules are reachable.
"""
reachable = [r for r in Sr if r.tab... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_line(line):
"""
This function is needed to parse one-liner from the controller and extract the information we need
:param line: a one line of output from "show ap database long" command
:return: object, representing AP and it's key values, like MAC-address or given name
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def emc(values: list) -> float:
"""
Fraction of empty cells
"""
if len(values) == 0:
return 0.0
empty_cells_count = sum([
1
for v in values
if len(v.strip()) == 0
])
return empty_cells_count / len(values) | bigcode/self-oss-instruct-sc2-concepts |
def create_search_group(recordset = None, field = None, values = None,
criteria_operator = "EqualTo"):
"""
Create a Coalesce search group/filter object (the value of "group" in a
`Coalesce search request object
<https://github.com/InCadence/coalesce/wiki/REST-API#search-query-dat... | bigcode/self-oss-instruct-sc2-concepts |
def __is_org(string: str) -> bool:
"""
Return if a given string is an org directive
:param string: String to check for org.
:return: True if org.
"""
return string.startswith("org ") | bigcode/self-oss-instruct-sc2-concepts |
def empty_fld_dict(names):
"""creates a dictionary with expected field names initialized to
none
"""
return {_f:None for _f in names} | bigcode/self-oss-instruct-sc2-concepts |
def optlist_to_dict(optlist, opt_sep=',', kv_sep='=', strip_quotes=False):
"""Parse an option list into a dictionary.
Takes a list of options separated by ``opt_sep`` and places them into
a dictionary with the default value of ``True``. If ``kv_sep`` option
is specified then key/value options ``key=va... | bigcode/self-oss-instruct-sc2-concepts |
def unwrap_string(s):
"""A utility function that converts a "'string'" to a "string" """
s = s.replace("'", "")
return s | bigcode/self-oss-instruct-sc2-concepts |
def is_even(n: int) -> bool:
# suggested solution
""" Check if a given number is even
Using modulo 2, and checking if the remainder is zero
"""
return n % 2 == 0 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def calc_total_loss(flow, data):
"""
Compute total loss of model on data.
Parameters
----------
flow : nflows.flows.Flow
Normalising flow, instance of Flow object from nflows.flows, generated
from e.g. load_flow() or setup_MAF().
data : torch.Tensor, shape (N, n_d... | bigcode/self-oss-instruct-sc2-concepts |
def titlecase(string: str):
"""Safely recast a string to title case"""
try:
return string.title()
except AttributeError:
return string | bigcode/self-oss-instruct-sc2-concepts |
import json
def dumps_tree(tree, duplicate_action = 'list', **kwargs):
"""
Dumps a Tree as json.dumps.
First converts to_python using duplicate_action.
Additional kwargs are sent to json.dumps.
"""
obj = tree.to_python(duplicate_action = duplicate_action)
return json.dumps(obj, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def _get_indices(topology, residue_name):
"""
Get the indices of a unique residue in an OpenMM Topology
Parameters
----------
topology : openmm.app.Topology
Topology to search from.
residue_name : str
Name of the residue to get the indices for.
"""
residues = []
for ... | bigcode/self-oss-instruct-sc2-concepts |
def construct_select_original_bericht_query(bericht_uri):
"""
Construct a SPARQL query for selecting the first message in a conversation
:param bericht_uri: URI of a bericht in a conversation
:returns: string containing SPARQL query
"""
q = """
PREFIX schema: <http://schema.org/>
... | bigcode/self-oss-instruct-sc2-concepts |
def is_fq_local_branch(ref):
"""Return True if a Git reference is a fully qualified local branch.
Return False otherwise.
Usage example:
>>> is_fq_local_branch("refs/heads/master")
True
>>> is_fq_local_branch("refs/remotes/origin/master")
False
>>> is_fq_local_bra... | bigcode/self-oss-instruct-sc2-concepts |
import csv
from typing import OrderedDict
def load_tab_delimited_csv(filepath):
"""
loads a tab delimted csv as a list of ordered dictionaries
"""
data = []
with open(filepath) as file:
reader = csv.reader(file, delimiter="\t")
header = []
for csv_row in reader:
... | bigcode/self-oss-instruct-sc2-concepts |
def move_consonant_left(letters: list, positions: list) -> list:
"""Given a list of letters, and a list of consonant positions, move the consonant positions to
the left, merging strings as necessary.
>>> move_consonant_left(['a', 'b', '', '', 'bra'], [1])
['ab', '', '', '', 'bra']"""
for pos in p... | bigcode/self-oss-instruct-sc2-concepts |
import glob
from pathlib import Path
def get_mas_variables(path):
"""
Return a list of variables present in a given directory.
Parameters
----------
path :
Path to the folder containing the MAS data files.
Returns
-------
var_names : list
List of variable names presen... | bigcode/self-oss-instruct-sc2-concepts |
def bundle(*addable):
""" Getting addable objects (such as Matching) and composing them to one.
When nothing is provided, this will raise a ValueError
"""
if len(addable) <= 0:
raise ValueError('Provide at least one Matching object')
return sum(addable[1:], addable[0]) | bigcode/self-oss-instruct-sc2-concepts |
def find_fomoists(events_attendees, rsvp_statuses=['attending']):
"""
"events" is a list of lists of attendees:
[
[
{
"name": "Brittany Miller",
"rsvp_status": "attending",
"id": "1442173849420454"
},
...
]
...
]
... | bigcode/self-oss-instruct-sc2-concepts |
def get_id(record):
"""
Returns the Amazon DynamoDB key.
"""
return record['dynamodb']['Keys']['id']['S'] | bigcode/self-oss-instruct-sc2-concepts |
def join_string(phrase: str, join_s: str):
"""
Take the 'phrase' and intersperse it whit 'join_s' string
:param phrase: string to be interspersed
:param join_s: string
:return: interspersed string
"""
return join_s.join(phrase) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def list_duplicates(iterable):
"""Return a set of duplicates in given iterator."""
return {key for key, count in Counter(iterable).items() if count > 1} | bigcode/self-oss-instruct-sc2-concepts |
def makeFullName(parScope, parName):
""" Create the fully-qualified name (inclues scope if used) """
# Skip scope (and leading dot) if no scope, even in cases where scope
# IS used for other pars in the same task.
if parScope:
return parScope+'.'+parName
else:
return parName | bigcode/self-oss-instruct-sc2-concepts |
def selectPivotIndex (ar, left, right, comparator):
"""Select pivot index for ar[left,right] inclusive using comparator."""
midIndex = (left + right)//2
lowIndex = left
if comparator(ar[lowIndex], ar[midIndex]) >= 0:
lowIndex = midIndex
midIndex = left
# when we get here, ar[lowInd... | bigcode/self-oss-instruct-sc2-concepts |
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""
Calculate the maximum metric value when we have multiple ground truths.
i.e., for each question, we have multiple answers.
:param metric_fn: the function to calculate metric
:param prediction: our model predicted answer str... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_forward(x_input):
"""Perform the reshaping of the tensor of size `(K, L, M, N)`
to the tensor of size `(K, L*M*N)`
# Arguments
x_input: np.array of size `(K, L, M, N)`
# Output
output: np.array of size `(K, L*M*N)`
"""
K, L, M, N = x_input.shape
output = x_in... | bigcode/self-oss-instruct-sc2-concepts |
def is_inside(center_point, corner_point):
"""
Find if center_point inside the bbox(corner_point) or not.
:param center_point: center point (x, y)
:param corner_point: corner point ((x1,y1),(x2,y2))
:return:
"""
x_flag = False
y_flag = False
if (center_point[0] >= corner_point[0][0])... | bigcode/self-oss-instruct-sc2-concepts |
def contains_embedded_molfile(field_value):
"""Returns True if the RD file $DATUM field value contains an embedded
molfile, otherwise returns False."""
return field_value == '$MFMT' | bigcode/self-oss-instruct-sc2-concepts |
def flatten(d, sep='.', flat_type=dict):
"""Flatten a nested dict using a specific separator.
:param sep: When None, return dict with tuple keys (guaranties inversion of
flatten) else join the keys with sep
:param flat_type: Allow other mappings instead of flat_type to be
fl... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def reverse_letter_box(h, w, input_size, boxes, xywh=True):
"""
:param h: 输入网络的图片的原始高度
:param w: 输入网络的图片的原始宽度
:param input_size: 网络的固定输入图片大小
:param boxes: Tensor, shape: (..., 4(cx, cy, w, h))
:param xywh: Bool, True:boxes是(cx, cy, w, h)格式, False: boxes是(xmin, ymin, xmax, ymax)格式... | bigcode/self-oss-instruct-sc2-concepts |
import json
def save_json(data, path_target: str):
"""
Saves json data to file at given path.
:param data: Json to save.
:param path_target: Path where to store the json data. String.
"""
with open(path_target, 'w') as outfile:
json.dump(data, outfile)
print('Json saved to:', path_... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import string
def alphabet_file(tmpdir):
"""Fill a temporary file with the alphabet, one letter per line."""
filename = Path(tmpdir) / "data"
open(filename, "w").write("\n".join(string.ascii_lowercase))
return filename | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_json_string(json_string):
"""Parse json string to object, if it fails then return none
:param json_string: json in string format
:type json_string: str
:return: object or none
:rtype: dict/None
"""
json_object = None
if not isinstance(json_string, str):
... | bigcode/self-oss-instruct-sc2-concepts |
def chunk_into_passages(doc_offsets,
doc_stride,
passage_len_t,
doc_text):
""" Returns a list of dictionaries which each describe the start, end and id of a passage
that is formed when chunking a document using a sliding window approach. ""... | bigcode/self-oss-instruct-sc2-concepts |
def GetNewIssueStarrers(cnxn, services, issue_id, merge_into_iid):
"""Get starrers of current issue who have not starred the target issue."""
source_starrers = services.issue_star.LookupItemStarrers(cnxn, issue_id)
target_starrers = services.issue_star.LookupItemStarrers(
cnxn, merge_into_iid)
return set(... | bigcode/self-oss-instruct-sc2-concepts |
def computeF(V_max, rho_max, rho):
"""Computes flux F=V*rho
Parameters
----------
V_max : float
Maximum allowed velocity
rho : array of floats
Array with density of cars at every point x
rho_max: float
Maximum allowed car density
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def get_atomic_number(molecule, atom_index):
"""Get the atomic number of an atom for a specified index.
Returns the atomic number of the atom present at index atom_index.
Parameters
----------
molecule : Molecule
The molecule to which the atom belongs.
atom_index : int
Index of... | bigcode/self-oss-instruct-sc2-concepts |
def uri_sort_key(uri):
"""return a sort key for the given URI, based on whether it represents the primary work in the record"""
if uri.startswith('http://urn.fi/URN:NBN:fi:bib:me:'):
priority = int(uri[-2:]) # last two digits are 00 for the primary work, 01+ for other works mentioned
else:
p... | bigcode/self-oss-instruct-sc2-concepts |
def _from_stdin(prompt, default=None):
"""
Read from stdin, if default is not set to None, some input is expected.
Parameters
----------
prompt: str
The stdin prompt.
default:
Default value.
Returns
-------
value read
"""
while True:
return_val =... | bigcode/self-oss-instruct-sc2-concepts |
def get_ticket_detail(tickets):
"""
Iterate over ticket details from response.
:param tickets: ticket details from the response.
:return: List of ticket details which include required fields from resp.
"""
return [{
'TicketNumber': ticket.get('ticketNumber', ''),
'TicketStatus':... | bigcode/self-oss-instruct-sc2-concepts |
def _get_local_cache_repo_path(repo_ctx):
""" Return a default local path to clone the repository into else return the cache_directory attribute if supplied
(default location: $HOME/.git-cache/<repo-name>)
Args:
repo_ctx: Repository context of the calling rule
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_col_that_is_primary(common_cols, featuregroups):
"""
Helper method that returns the column among a shared column between featuregroups that is most often marked as
'primary' in the hive schema.
Args:
:common_cols: the list of columns shared between all featuregroups
:featuregro... | bigcode/self-oss-instruct-sc2-concepts |
def ordinal_suffix(n):
"""The ordinal suffix of integer *n* as a string."""
if n % 100 in [11, 12, 13]:
return 'th'
else:
return {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th') | bigcode/self-oss-instruct-sc2-concepts |
def get_dims(slices):
"""Given a set of slices, gets number of pixels along x,y,z of reconstructed
volumetric image."""
ds = next(iter(slices)) #Takes an arbitrary element of slices
x_count = ds.Rows
y_count = ds.Columns
z_count = len(slices)
return (x_count,y_count,z_count) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def pessimistic_aggregation(alternative_assessment: List[int]) -> int:
"""
Aggregates the assessments of an alternative, using the minimum as aggregation function.
Args:
alternative_assessment: A list of integers, representing the assessments made of an alternative by a gr... | bigcode/self-oss-instruct-sc2-concepts |
import math
def complexLog(value, base = math.e):
"""Computes the log of a complex number."""
mag = (value*value.conjugate()).real**.5
tan_theta = value.imag/value.real
theta = math.atan(tan_theta)/math.log(base, math.e)
return complex(math.log(mag, base), theta) | bigcode/self-oss-instruct-sc2-concepts |
def team_sign(team: int) -> int:
"""Gives the sign for a calculation based on team.
Arguments:
team {int} -- 0 if Blue, 1 if Orange.
Returns:
int -- 1 if Blue, -1 if Orange
"""
return 1 if team == 0 else -1 | bigcode/self-oss-instruct-sc2-concepts |
def _get_pt_to_obj(cvt_archive):
"""Creates a dict from centroid index to objective value in a CVTArchive."""
data = cvt_archive.as_pandas(include_solutions=False)
pt_to_obj = {}
for row in data.itertuples():
# row.index is the centroid index. The dataframe index is row.Index.
pt_to_obj[... | bigcode/self-oss-instruct-sc2-concepts |
def apply(func, args, kwargs):
"""
a helper method that applies args and kwargs to given function and gets the result.
:param function func: function to be used.
:param tuple args: function positional arguments.
:param dict kwargs: function keyword arguments.
:returns: function result
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_translated_node(target_node, target_dom_to_doc_dom):
"""Convenience function to get node corresponding to 'target_node'
and to assign the tail text of 'target_node' to this node."""
dom_node = target_dom_to_doc_dom[target_node]
dom_node.tail = target_node.tail
return dom_node | bigcode/self-oss-instruct-sc2-concepts |
def tree_child(tree, cname):
"""Locate a descendant subtree named cname using breadth-first search and
return it. If no such subtree exists, return None."""
for st in tree.iter_subtrees_topdown():
if (st.data == cname):
return st
return None | bigcode/self-oss-instruct-sc2-concepts |
def explicit_transform(tarinfo):
""" Reject files with 'bar' anywhere in their path """
if 'bar' in tarinfo.name:
return False
else:
return tarinfo | bigcode/self-oss-instruct-sc2-concepts |
def _Append(text):
"""Inserts a space to text if it is not empty and returns it."""
if not text:
return ''
if text[-1].isspace():
return text
return ' ' + text | bigcode/self-oss-instruct-sc2-concepts |
def dict_recursive_update(existing_dict: dict, new_dict: dict):
"""
Recursively add values from new_dict to existing_dict.
:param existing_dict: existing dict to be updated
:param new_dict: new values to enter if an existing value does not already exist.
:return: udpated dict
"""
for key, va... | bigcode/self-oss-instruct-sc2-concepts |
def sort_list_by_keys(values, sort_keys):
""" Sorts list values by a second list sort_keys
e.g. given ["a","c","b"], [1, 3, 2], returns ["a", "b", "c"]
Args:
values: a list of values to be sorted
sort_keys: a list of keys to sort values by
Returns:
list of values, sorte... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_traversals(
vec: torch.Tensor,
dim_i: int,
min_value: float,
max_value: float,
n_samples: int
) -> torch.Tensor:
"""Given a single 1dim vector, get a batch of 1dim vectors by traversing
`dim_i`th dimension of `vec` linearly, from `min_value` to `max... | bigcode/self-oss-instruct-sc2-concepts |
def leftshift(x, c):
""" Left shift the number x by c bytes."""
return x << c | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import binascii
def crc32(path) -> Optional[int]:
"""
Compute the CRC-32 checksum of the given *path*, consistent with
checksums stored in a ZIP file.
Returns None if *path* does not exist.
"""
if path.exists():
crc = 0
# Directories always return ... | bigcode/self-oss-instruct-sc2-concepts |
def ar_to_vaf(ar):
"""
Convert AR to VAF.
VAF (variant allele frequency) = V-AF
AR (allele ratio) = V-AF / WT-AF
V-AF + WT-AF = 100 (%)
Args:
ar (float): AR to convert.
Returns:
VAF (float)
"""
return ar/(ar + 1) * 100 | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Tuple
def pack_right_padded_seq(seqs: torch.Tensor, lengths: torch.Tensor, device: str) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Function for packing a right-padded sequence, inspired by the functionality of
torch.nn.utils.rnn.pack_padded_sequence.
Instead of relying o... | bigcode/self-oss-instruct-sc2-concepts |
def reward_lives_left(lives_left):
"""Returns rewards for number of lives left after beating the game."""
return lives_left + 1 | bigcode/self-oss-instruct-sc2-concepts |
def clean_attrib(value):
"""Cleans up value string.
Removes any trailing '_0' that randomly show up
Args:
value (str): attrib value to clean
Returns:
str: cleaned attribute value
"""
clean_value = value
if value.endswith("_0"):
clean_value = clean_value.strip('_0')... | bigcode/self-oss-instruct-sc2-concepts |
def _remove_nones(**kwargs):
"""
Removes any kwargs whose values are `None`.
"""
final = kwargs.copy()
for k in kwargs:
if kwargs[k] is None:
final.pop(k)
return final | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_xml_attrib(el, key):
"""Gets an Element attribute value without regard to namespace.
Returns:
Value of given key or None.
"""
for k in el.attrib.keys():
if key == re.sub("^{.*}", "", k):
return el.attrib[k] | bigcode/self-oss-instruct-sc2-concepts |
def _merge_dicts(*dicts):
"""Merge any number of dictionaries, some of which may be None."""
final = {}
for dict in dicts:
if dict is not None:
final.update(dict)
return final | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
import click
def validate_version_string(ctx, param, value: Optional[str]) -> Optional[str]:
"""
Callback for click commands that checks that version string is valid
"""
if value is None:
return None
version_pattern = re.compile(r"\d+(?:\.\d+)+")
... | bigcode/self-oss-instruct-sc2-concepts |
def list_policies(iot_client, old_certificate_arn):
"""
Creates a list of all the policies attached to the old certificate
:param iot_client: the boto client to connect and execute
IoT APIs
:param old_certificate_arn: the old certificate arn
:return: list of policies
"""
policy_list = []... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def execution_time(func):
"""Decorator to print in console the execution time of the 'func' function passed."""
def wrapper(*args, **kwargs):
t0 = datetime.now()
res = func(*args, **kwargs)
t1 = datetime.now()
print(f"\nExecution time of '{func.__n... | bigcode/self-oss-instruct-sc2-concepts |
def args_from_constants(constants):
"""
>>> c = {
... "proof_of_work_nonce_size": 8,
... "nonce_length": 32,
... "max_anon_ops_per_block": 132,
... "max_operation_data_length": 32768,
... "max_proposals_per_delegate": 20,
... "max_micheline_node_count": 50000,
... | bigcode/self-oss-instruct-sc2-concepts |
def get_description_value(obj):
"""
Returns object description from LLDB value.
:param lldb.SBValue obj: LLDB value object.
:return: Object description from LLDB value.
:rtype: str | None
"""
desc = None if obj is None else obj.GetObjectDescription()
if desc == "<nil>":
desc = N... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
import json
def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
... | bigcode/self-oss-instruct-sc2-concepts |
def clean_get_table(df):
"""Default table cleaner for get_table()"""
return df | bigcode/self-oss-instruct-sc2-concepts |
def is_natural_number(number, include_zero: bool = False) -> bool:
"""
Returns True if `number` is the natural number.
Args:
number : an integer number to be checked.
include_zero (bool, optional): A flag to swith to include 0
in the natural numbers.
Defaults to Fals... | bigcode/self-oss-instruct-sc2-concepts |
def exclude_keys(d, keys):
"""Return a new dictionary excluding all `keys`."""
return {k: v for k, v in d.items() if k not in keys} | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Tuple
def global_average_precision_score(
y_true: Dict[Any, Any], y_pred: Dict[Any, Tuple[Any, float]]
) -> float:
"""
Compute Global Average Precision score (GAP)
Parameters
----------
y_true : Dict[Any, Any]
Dictionary... | bigcode/self-oss-instruct-sc2-concepts |
def get_tag(commands):
"""Generates a preprocessor tag from a set of grid commands."""
# Extra line break prevents unclosed paragraphs in markdown HTML output
return "\n<!--grid:%s-->" % ';'.join([str(cmd) for cmd in commands]) | bigcode/self-oss-instruct-sc2-concepts |
def flatten_dictionary(nested_dict, separator):
"""Flattens a nested dictionary.
New keys are concatenations of nested keys with the `separator` in between.
"""
flat_dict = {}
for key, val in nested_dict.items():
if isinstance(val, dict):
new_flat_dict = flatten_dictionary(val,... | bigcode/self-oss-instruct-sc2-concepts |
def _gnurl(clientID):
"""
Helper function to form URL to Gracenote service
"""
clientIDprefix = clientID.split('-')[0]
return 'https://c' + clientIDprefix + '.web.cddbp.net/webapi/xml/1.0/' | bigcode/self-oss-instruct-sc2-concepts |
def hasManyOccurencies(elt, listx):
"""Find if a point has many similar occurences in a list.
This function is based on a threshold by default it is 80%.
Args:
elt: One element of the list.
listx: The list of elements
Returns:
True if it is a very frequent element, False other... | bigcode/self-oss-instruct-sc2-concepts |
def run_test(cfg, init_state):
"""
Run an execution given initial values for variables.
Arguments:
cfg -- control flow graph of the input program
init_state -- a test
Returns:
path -- path of the execution
state -- state after execution
"""
state = init... | bigcode/self-oss-instruct-sc2-concepts |
def get_platform_folder_to_keyword_map(ctx):
"""
Get the cached map of platforms to their PAL platform folder and keyword, so we can
attempt to search for platform-specific 3rd party fragments to combine with the input config file
:param ctx: Context
:return: Map of platform names to their keyword
... | bigcode/self-oss-instruct-sc2-concepts |
def tree_search(states, goal_reached, get_successors, combine_states):
"""
Given some initial states, explore a state space until reaching the goal.
`states` should be a list of initial states (which can be anything).
`goal_reached` should be a predicate, where `goal_reached(state)` returns
`True` ... | bigcode/self-oss-instruct-sc2-concepts |
def add_args_to_parser(arg_list, parser):
"""
Adds arguments from one of the argument lists above to a passed-in
arparse.ArgumentParser object. Formats helpstrings according to the
defaults, but does NOT set the actual argparse defaults (*important*).
Args:
arg_list (list) : A list of the s... | bigcode/self-oss-instruct-sc2-concepts |
def updateTracker(idx,newChar,tracker,force=False):
"""Set final sequence value by column index if 'None'.
Optionally force overwrite of previously updated base."""
if tracker[idx].base and force:
# Note: Add alert when overwriting a previously set base
tracker[idx] = tracker[idx]._replace(base=newChar)
elif n... | bigcode/self-oss-instruct-sc2-concepts |
def strSQLite(string):
"""
Sanitizes input for SQLite TEXT fields by converting to string and replacing
each single quote (') with two single quotes ('')
"""
return str(string).replace(r"'", "''") | bigcode/self-oss-instruct-sc2-concepts |
def inherit_docs(original):
"""A decorator that copies the docstring from a function to the decorated one"""
def wrapper(target):
target.__doc__ = original.__doc__
return target
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
def forecast_error(y, y_predicted):
"""Calculate the forecast error in a regression model.
Parameters
----------
y : array-like of shape = number_of_outputs
Represent the target values.
y_predicted : array-like of shape = number_of_outputs
Target values predicted by the model.
... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_yaml(fname):
"""Read a YAML file and return a list of Python dictionaries, one for each
document in the YAML file."""
stream = open(fname, 'r')
docs = [doc for doc in yaml.safe_load_all(stream)]
return docs | bigcode/self-oss-instruct-sc2-concepts |
def win_check(hidden_word, guessed_letters):
"""
hidden_word: string, the hidden word to guess
guessed_letters: list, with all letters user have used
return: boolean, True if all letters of hidden_word exist in guessed_letters otherwise False
"""
for letter in hidden_word:
if letter not ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def macro_double_soft_f1(y, y_hat):
"""Compute the macro soft F1-score as a cost (average 1 - soft-F1 across all labels).
Use probability values instead of binary predictions.
This version uses the computation of soft-F1 for both positive and negative class for each label.
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def sumAvailable(value):
"""Sum available_in_bytes over all partitions."""
result = [x['available_in_bytes'] for x in value]
return sum(result) | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(n, base=10):
"""
Is the given number n a palindrome in the given base?
"""
if base == 10:
n_str = str(n)
elif base == 2:
n_str = "{0:b}".format(n)
else:
raise RuntimeError("Only 2 and 10 bases supported")
for i in range(len(n_str) // 2):
... | bigcode/self-oss-instruct-sc2-concepts |
def find_place(lines, size_x):
"""
Finds the highest place at the left for a panel with size_x
:param lines:
:param size_x:
:return: line with row, col, len
"""
for line in lines:
if line['len'] >= size_x:
return line | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize(s):
""" Normalize a string """
return re.sub('[^a-z0-9_]', '_', re.sub('[()]', '', s.lower())) | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def _log_warnings_postprocess(response):
"""Logs warnings contained within the x-wf-warnings response header."""
# NOTE: .initial_metadata() will block.
for key, value in response.initial_metadata():
if key == "x-wf-warnings":
warnings.warn(value)
return response | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_token(token: str):
"""Makes sure a given token is valid for usage within the Discord API.
Args:
token (:class:`str`): The token to be processed.
Returns:
:class:`str`: The modified, adapted token.
Examples:
.. testsetup::
from serpcord.util... | bigcode/self-oss-instruct-sc2-concepts |
def if_exception_type(*exception_types):
"""Creates a predicate to check if the exception is of a given type.
Args:
exception_types (Sequence[:func:`type`]): The exception types to check
for.
Returns:
Callable[Exception]: A predicate that returns True if the provided
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_extra_space(
text: str,
) -> str:
"""To remove extra space in a given text.
Parameters
----------
text : str
The text to clean.
Returns
-------
str
returns text after removing all redundant spaces.
Examples
--------
>>> from SkillNer.cleaner impo... | 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.