seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def has_bad_first_or_last_char(val: str) -> bool:
"""Returns true if a string starts with any of: {," ; or ends with any of: },".
Args:
val: The string to be tested.
Returns:
Whether or not the string starts or ends with bad characters.
"""
return val is not None and (val.startswit... | bigcode/self-oss-instruct-sc2-concepts |
def is_own_piece(v, h, turn, grid):
"""Check if the player is using the correct piece
:param v: Vertical position of man
:param h: Horizontal position of man
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:return: True, if the player is using their own piece, False if otherwise.
... | bigcode/self-oss-instruct-sc2-concepts |
def linear_interpolation(tbounds, fbounds):
"""Linear interpolation between the specified bounds"""
interp = []
for t in range(tbounds[0], tbounds[1]):
interp.append(fbounds[0] + (t - tbounds[0]) * ((fbounds[1] - fbounds[0]) /
(tbounds[1] - tbou... | bigcode/self-oss-instruct-sc2-concepts |
import time
def make_expr_sig(args = None):
"""create experiment signature string from args and timestamp"""
# print ("make_expr_sig", args)
# infile = args.infile.replace("/", "_").replace(".wav", "")
# expr_sig = "MN%s_MS%d_IF%s_IS%d_NE%d_EL%d_TS%s" % (args.mode, args.modelsize, infile, args.sample... | bigcode/self-oss-instruct-sc2-concepts |
def filter_nc_files(path_list):
"""Given a list of paths, return only those that end in '.nc'"""
return [p for p in path_list if p.suffix == '.nc'] | bigcode/self-oss-instruct-sc2-concepts |
def _indent_for_list(text, prefix=' '):
"""Indent some text to make it work as a list entry.
Indent all lines except the first with the prefix.
"""
lines = text.splitlines()
return '\n'.join([lines[0]] + [
prefix + l
for l in lines[1:]
]) + '\n' | bigcode/self-oss-instruct-sc2-concepts |
def transform_results(results, keys_of_interest):
"""
Take a list of results and convert them to a multi valued dictionary. The
real world use case is to take values from a list of collections and pass
them to a granule search.
[{key1:value1},{key1:value2},...] -> {"key1": [value1,value2]} ->
... | bigcode/self-oss-instruct-sc2-concepts |
def calc_iou(bbox_a, bbox_b):
"""
Calculate intersection over union (IoU) between two bounding boxes with a (x, y, w, h) format.
:param bbox_a: Bounding box A. 4-tuple/list.
:param bbox_b: Bounding box B. 4-tuple/list.
:return: Intersection over union (IoU) between bbox_a and bbox_b, between 0 and 1... | bigcode/self-oss-instruct-sc2-concepts |
def make_target(objtype, targetid):
"""Create a target to an object of type objtype and id targetid"""
return "coq:{}.{}".format(objtype, targetid) | bigcode/self-oss-instruct-sc2-concepts |
def get_search_params(url_path):
"""
From the full url path, this prunes it to just the query section,
that starts with 'q=' and ends either at the end of the line of the
next found '&'.
Parameters
----------
url_path : str
The full url of the request to chop up
Returns
-... | bigcode/self-oss-instruct-sc2-concepts |
def _first_multiple_of(num: int, above: int) -> int:
"""
Returns first multiple of num >= above
"""
return above + ((num-(above%num)) % num) | bigcode/self-oss-instruct-sc2-concepts |
def linear_cb(valve):
"""
Linear opening valve function callback.
"""
@valve.Expression(valve.flowsheet().time)
def valve_function(b, t):
return b.valve_opening[t] | bigcode/self-oss-instruct-sc2-concepts |
def _publications_urls(request, analyses):
"""Return set of publication URLS for given analyses.
Parameters
----------
request
HTTPRequest
analyses
seq of Analysis instances
Returns
-------
Set of absolute URLs (strings)
"""
# Collect publication links, if any
... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def preservation_copy(row: typing.Mapping[str, str]) -> typing.Optional[str]:
"""A path to the original digital asset in the 'Masters/' netapp mount.
If the File Name starts with "Masters/", it will be used as is. Otherwise,
it will be prepended with "Masters/dlmasters/", in order to match ... | bigcode/self-oss-instruct-sc2-concepts |
def _test_int_pickling_compare(int_1, int_2):
"""Add the two given ints."""
return int_1 + int_2 | bigcode/self-oss-instruct-sc2-concepts |
from networkx import get_edge_attributes
def uninformative_prediction(G, required_links):
"""
Function to predict links in an uninformative manner, i.e., the majority
parity. So, if there are more positive links that negative links, then a
positive link is predicted and vice-versa
Args:
G... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(lst, out=None):
"""
@return: a flat list containing the leaves of the given nested
list.
@param lst: The nested list that should be flattened.
"""
if out is None: out = []
for elt in lst:
if isinstance(elt, (list, tuple)):
flatten(elt, out)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def int_pair(s, default=(0, None)):
"""Return the digits to either side of a single non-digit character as a 2-tuple of integers
>>> int_pair('90210-007')
(90210, 7)
>>> int_pair('04321.0123')
(4321, 123)
"""
s = re.split(r'[^0-9]+', str(s).strip())
if len(s) and len(s[0]):
... | bigcode/self-oss-instruct-sc2-concepts |
def find_match_brackets(search, opening='<', closing='>'):
"""Returns the index of the closing bracket that matches the first opening bracket.
Returns -1 if no last matching bracket is found, i.e. not a template.
Example:
'Foo<T>::iterator<U>''
returns 5
"""
index = search.f... | bigcode/self-oss-instruct-sc2-concepts |
def get_synapse_from_layer(cur,layer):
"""
Returns synapses in given layer list of tuples:
(mid_object,x-pos,y-pos)
Parameters
----------
cur : MySQLdb cursor
layer : str
Name of layer
"""
sql = ("select synapsecombined.mid,"
"object.OBJ_X,"
"ob... | bigcode/self-oss-instruct-sc2-concepts |
def get_fieldnames(records):
"""
Extract fieldnames for CSV headers from list of results
:param records: list
:return: list
"""
fieldnames = []
ordered_fieldname = (
"time_last",
"time_first",
"source",
"count",
"bailiwick",
"rrname",
... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def get_stage1_command(stage1_file):
"""
The format of a PowerShell encoded command is a base64 encoded UTF-16LE string.
This function reads the stage 1 file (UTF-8) into a string, converts it into UTF-16LE encoding, and then base64 encodes that.
In Python, Base64 conversion requires Bytes objects, ... | bigcode/self-oss-instruct-sc2-concepts |
def is_int(object):
"""Check if the given object is an integer"""
return isinstance(object, int) | bigcode/self-oss-instruct-sc2-concepts |
def isCardinallyEnvyFree(prefProfile, allocation):
"""
INPUT:
prefProfile: a PrefProfile with cardinal utilities.
allocation: a dictionary that maps agents to their bundles.
OUTPUT:
True iff the given allocation is envy-free according to the agents' cardinal value function
>>> prefProfile ... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def tiles_info(panoid, zoom=5):
"""
Generate a list of a panorama's tiles and their position.
The format is (x, y, filename, fileurl)
"""
# image_url = 'http://maps.google.com/cbk?output=tile&panoid={}&zoom={}&x={}&y={}'
image_url = "http://cbk0.google.com/cbk?output=tile&pan... | bigcode/self-oss-instruct-sc2-concepts |
def extend(s, var, val):
"""
Returns a new dict with var:val added.
"""
s2 = {a: s[a] for a in s}
s2[var] = val
return s2 | bigcode/self-oss-instruct-sc2-concepts |
def collect_vowels(s):
""" (str) -> str
Return the vowels (a, e, i, o, and u) from s.
>>> collect_vowels('Happy Anniversary!')
'aAiea'
>>> collect_vowels('xyz')
''
"""
vowels = ''
for char in s:
if char in 'aeiouAEIOU':
vowels = vowels + char
return vowel... | bigcode/self-oss-instruct-sc2-concepts |
def reward_scaling(r, scale=1):
"""
Scale immediate rewards by a factor of ``scale``.
Can be used as a reward shaping function passed to an algorithm
(e.g. ``ActorCriticAlgorithm``).
"""
return r * scale | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
import math
def get_mean(data: Dict[int, List[float]]) -> Dict[int, float]:
"""
Turns a dictionary with float lists into a dict with mean values of all non-NaN list entries.
:param data: Input dictionary with float lists
:return: Output... | bigcode/self-oss-instruct-sc2-concepts |
def clear_bgp_neighbor_soft(device, command='clear bgp neighbor soft all', alternative_command='clear bgp neighbor soft',
fail_regex=None):
""" Clear bgp neighbor soft using one of two commands
Args:
device ('obj'): Device object
command ('str'): Command with a... | bigcode/self-oss-instruct-sc2-concepts |
def is_custom_session(session):
"""Return if a ClientSession was created by pyatv."""
return hasattr(session, '_pyatv') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Callable
from typing import List
def remove(items: Iterable, predicate: Callable) -> List:
"""Return a new list without the items that match the predicate."""
return [x for x in items if not predicate(x)] | bigcode/self-oss-instruct-sc2-concepts |
def cap_length(q, a, r, length):
"""Cap total length of q, a, r to length."""
assert length > 0, "length to cap too short: %d" % length
while len(q) + len(a) + len(r) >= length:
max_len = max(len(q), len(a), len(r))
if len(r) == max_len:
r = r[:-1]
elif len(a) == max_len:
a = a[:-1]
el... | bigcode/self-oss-instruct-sc2-concepts |
def PySequence_Contains(space, w_obj, w_value):
"""Determine if o contains value. If an item in o is equal to value,
return 1, otherwise return 0. On error, return -1. This is
equivalent to the Python expression value in o."""
w_res = space.contains(w_obj, w_value)
return space.int_w(w_res) | bigcode/self-oss-instruct-sc2-concepts |
def argmax(lst):
"""Given a list of numbers, return the index of the biggest one."""
return max(range(len(lst)), key=lst.__getitem__) | bigcode/self-oss-instruct-sc2-concepts |
def parse_response_browse_node(browse_nodes_response_list):
"""
The function parses Browse Nodes Response and creates a dict of BrowseNodeID to AmazonBrowseNode object
params
*browse_nodes_response_list*
List of BrowseNodes in GetBrowseNodes response
return
Dict of BrowseNo... | bigcode/self-oss-instruct-sc2-concepts |
def depth_calculator(obj):
"""Determine how far in the hierarchy the file/folder is in. Works for either File or Folder class"""
depth = 0
dad = obj.parent_folder
next_in = True
while next_in:
if dad.parent_folder:
depth += 1
dad = dad.parent_folder
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def validate_base_sequence(base_sequence, RNAflag=False):
"""Return True if the string base_sequence contains only upper- or lowercase T (or U, if RNAflag), C, A, G characters, otherwise False"""
seq = base_sequence.upper()
return len(seq) == (seq.count('A') + seq.count('U' if RNAflag else 'T') +
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_csrf(REQ_URL):
"""Get a csrf token from the request url to authenticate further requests
Parameters
----------
REQ_URL string
The URL that you want to make a request against after getting the token
Returns
-------
csrftoken
csrf token to use for... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_uint32(value_in):
"""
Convert integer to unsigned 32-bit (little endian)
:param value_in:
:return:
"""
return list(value_in.to_bytes(4, byteorder='little', signed=False)) | bigcode/self-oss-instruct-sc2-concepts |
def merge_overlapping_intervals(intervals):
"""
Given a collection of intervals, merge all overlapping intervals.
Given the list of intervals A.
A = [Interval(1, 3), Interval(2, 6),
Interval(8, 10), Interval(15, 18)]
The function should return the list of merged intervals.
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_bearing(vehicle, aLocation1, aLocation2):
"""
Returns the bearing between the two LocationGlobal objects passed as parameters.
This method is an approximation, and may not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
... | bigcode/self-oss-instruct-sc2-concepts |
def insignificant(path):
"""Return True if path is considered insignificant."""
# This part is simply an implementation detail for the code base that the
# script was developed against. Ideally this would be moved out to a config
# file.
return path.endswith('Dll.H') or path.endswith('Forward.H') or \
pa... | bigcode/self-oss-instruct-sc2-concepts |
def vect3_reverse(v):
"""
Reverses a 3d vector.
v (3-tuple): 3d vector
return (3-tuple): 3d vector
"""
return (v[0]*-1, v[1]*-1, v[2]*-1) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import re
def wikitext_detokenize(example: Dict[str, str]) -> Dict[str, str]:
"""
Wikitext is whitespace tokenized and we remove these whitespaces.
Taken from https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt2/detokenizer.py
"""
# Contractions
text = e... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def generate_bulkiness_section(cat_properties: Dict[str, Any]) -> str:
"""Generate the CAT bulkiness input section."""
def replace_None(x):
return "NULL" if x is None else x
if "bulkiness" not in cat_properties:
return "bulkiness: False"
b... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_string(date_object):
"""
Converts a datetime object to a date string of the format MM/DD/YYYY.
Args:
date_object: datetime object representing datetime
Returns:
String representing datetime object of the format MM/DD/YYYY
"""
return date_object.strftime("%m/%d/%... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_package_name_for_code(package: str) -> str:
"""Normalize given string into a valid python package for code usage.
Parameters
------------------------
package: str,
The name of the package.
Raises
------------------------
ValueError,
When the name of the packag... | bigcode/self-oss-instruct-sc2-concepts |
def is_list(element):
"""
Check if element is a Python list
"""
return isinstance(element, list) | bigcode/self-oss-instruct-sc2-concepts |
def process_info(table):
""" Helper of get_availabilities_by_url
Parser information and
returns the room type, price, and number of rooms left.
"""
rooms = []
for row in table:
if len(row) >= 5:
rooms.append({
'type': row[0].split("\n")[0].replace("\n... | bigcode/self-oss-instruct-sc2-concepts |
def depends_one_or_more(dependencies):
"""Returns true if any of the dependencies exist, else false"""
return any([x.get_exists() for x in dependencies]) | bigcode/self-oss-instruct-sc2-concepts |
def find_value_in_list(l_r, value):
"""
Purpose: To get value in a given list
Parameters: list, value
Returns: True or False
Raises:
"""
result = False
for item in l_r:
if item['id'] == value:
result = True
break
return result | bigcode/self-oss-instruct-sc2-concepts |
def check_duration(sec, larger=True):
"""
Creates a function you can use to check songs
Args:
sec:
duration that we compare to in seconds
larger:
determines if we do a larger than operation
Returns:
Function that can be used to check songs
"""
def... | bigcode/self-oss-instruct-sc2-concepts |
import decimal
def j_round(float_num):
"""java like rounding for complying with the OpenLR java: 2.5 -> 3"""
num = decimal.Decimal(float_num).to_integral_value(rounding=decimal.ROUND_HALF_UP)
return int(num) | bigcode/self-oss-instruct-sc2-concepts |
def filter_dict_nulls(mapping: dict) -> dict:
"""Return a new dict instance whose values are not None."""
return {k: v for k, v in mapping.items() if v is not None} | bigcode/self-oss-instruct-sc2-concepts |
def check_string(string, pos, sep, word):
"""Checks index 'pos' of 'string' seperated by 'sep' for substring 'word'
If present, removes 'word' and returns amended string
"""
if sep in string:
temp_string = string.split(sep)
if temp_string[pos] == word:
temp_string.pop(pos)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import string
def remove_punctuation(input_text: str, punctuations: Optional[str] = None) -> str:
"""
Removes all punctuations from a string, as defined by string.punctuation or a custom list.
For reference, Python's string.punctuation is equivalent to '!"#$%&\'()*+,-./:;<=>?@[... | bigcode/self-oss-instruct-sc2-concepts |
def coordstr(roi):
"""String representation of coordinates. Also for URL arguments."""
return str(roi['xll']) + ',' + str(roi['yll']) + ','\
+ str(roi['xur']) + ',' + str(roi['yur']) | bigcode/self-oss-instruct-sc2-concepts |
def calc_validation_error(di_v, xv, tv, err, val_iter):
"""
Calculate validation error rate
Args:
di_v; validation dataset
xv: variable for input
tv: variable for label
err: variable for error estimation
val_iter: number of iteration
Returns:
error rate
... | bigcode/self-oss-instruct-sc2-concepts |
def dict_get(d, key, default=None):
"""
exactly the same as standard python. this is to remind that get() never raises an exception
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
"""
return d.get(key, default) | bigcode/self-oss-instruct-sc2-concepts |
def list_to_dict(keyslist,valueslist):
"""
convert lists of keys and values to a dict
"""
if len(keyslist) != len(valueslist):
return {}
mydict = {}
for idx in range(0,len(keyslist)):
mydict[keyslist[idx]] = valueslist[idx]
return mydict | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def linkify(url: str, text: Optional[str] = None):
"""Make a link clickable using ANSI escape sequences.
See https://buildkite.com/docs/pipelines/links-and-images-in-log-output
"""
if text is None:
text = url
return f"\033]1339;url={url};content={text}\a" | bigcode/self-oss-instruct-sc2-concepts |
import math
def dist_d3 (p1, p2):
"""Returns the euclidian distance in space between p1 and p2.
"""
return math.sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 + (p2[2] - p1[2])**2) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batched_gather(data, inds, dim=0, no_batch_dims=0):
"""https://github.com/aqlaboratory/openfold/blob/5037b3d029efcc9eeb3f5f33eedd4ecdd27ca962/openfold/utils/tensor_utils.py#L67"""
ranges = []
for i, s in enumerate(data.shape[:no_batch_dims]):
r = torch.arange(s)
r = r.view(*(*((1,) * i), -1, *... | bigcode/self-oss-instruct-sc2-concepts |
def find_between(s, start, end):
"""
Return a string between two other strings
"""
return (s.split(start))[1].split(end)[0] | bigcode/self-oss-instruct-sc2-concepts |
import requests
def currency_data_last_n_days(currency = 'ETH', to = 'EUR', days = 14):
"""Get day by day price of a currency in respect to another one,
using the APIs at "min-api.cryptocompare.com".
Data are from the last "days" days."""
currencies = 'fsym={0}&tsym={1}'.format(currency, to)
days... | bigcode/self-oss-instruct-sc2-concepts |
def row2dict(row):
"""Converts SQLAlchemy row to dict
Args:
row: A SQLAlchemy query result object
Returns
dict: Returns the row as dictionary
"""
d = {}
for column in row.__table__.columns:
d[column.name] = str(getattr(row, column.name))
return d | bigcode/self-oss-instruct-sc2-concepts |
def calc_term_overlap(termsA, termsB):
"""
Calculate the reciprocal overlap between two lists of HPO terms
"""
nA = len(termsA)
nB = len(termsB)
if nA == 0 or nB == 0:
ro = 0
else:
nOvr = len(set(termsA).intersection(set(termsB)))
oA = nOvr / nA
oB = nOvr / ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def is_palindrome(word: str) -> Union[bool, str]:
"""Function to check if word is a palindrome
>>> from snakypy.helpers.checking import is_palindrome
>>> is_palindrome("ana")
True
>>> from snakypy.helpers.checking import is_palindrome
>>> is_palindrome("banana")
Fa... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def day_end(date: datetime) -> datetime:
"""
Calculates end of date
Args:
date (datetime): datetime object, for which to calculate the end of the day
Returns:
date_end (datetime): timestamp for end of the given date
"""
return datetime(date.year,... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def quaternion_into_axis_angle(quaternion):
"""
Takes an quaternion rotation and converts into axis-angle rotation.
https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
:param quaternion: 4-element tensor, containig quaternion (q0,q1,q2,q3).
:return: (Axis of rotatio... | bigcode/self-oss-instruct-sc2-concepts |
def get_offsprings(g, nodes):
"""
Find the offspring nodes in a DAG
:param g: a directed acyclic graph
:param nodes: targeted nodes
:return: a set of offspring nodes
"""
return set.union(*[g.descendants(d) for d in nodes]) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def rotated_range(start, stop, starting_value):
"""Produces a range of integers, then rotates so that the starting value
is starting_value"""
r = list(range(start, stop))
start_idx = r.index(starting_value)
d = collections.deque(r)
d.rotate(-start_idx)
return list(d) | bigcode/self-oss-instruct-sc2-concepts |
def lab2phonemes(labels):
"""Convert labels to phonemes.
Args:
labels (str): path to a label file
Returns:
List[str]: phoneme sequence
"""
phonemes = []
for c in labels.contexts:
if "-" in c:
ph = c.split("-")[1].split("+")[0]
else:
ph = ... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def modify_namespace(namespace, args):
"""Modify the specified arguments in the passed Namespace.
namespace argparse.Namespace object
args dict of argument: value pairs
For most command-line tests, we define a base argparse.Namespace object, then
change a few argumen... | bigcode/self-oss-instruct-sc2-concepts |
def xyY2XYZ(xyY):
"""
convert xyY to XYZ
:param xyY: array-like
:return: array like
"""
X = xyY[0] * xyY[2] / xyY[1]
Y = xyY[2]
Z = ((1 - xyY[0] - xyY[1]) * xyY[2]) / xyY[1]
return [X, Y, Z] | bigcode/self-oss-instruct-sc2-concepts |
def get_leader(units):
"""Return the leader unit for the array of units."""
for unit in units:
out = unit.run('is-leader')
if out[0] == 'True':
return unit | bigcode/self-oss-instruct-sc2-concepts |
def vector_to_tuple(vector):
"""Converts a column vector into a tuple."""
return tuple(row[0] for row in vector) | bigcode/self-oss-instruct-sc2-concepts |
def get_position_by_substring(tofind, list):
"""
Get index where `tofind` is a substring of the entry of `list`
:param tofind: string to find in each element of `list`
:param list: list to search through
:return: index in `list` where `tofind` is found as a substring
"""
for i, e in enumera... | bigcode/self-oss-instruct-sc2-concepts |
def _get_creator(hardict):
"""
Get creator of HAR file.
"""
creator = hardict["log"]["creator"]
return "%s %s%s" % (creator["name"], creator["version"],
" (Comment: %s)" % creator["comment"] if creator.get("comment") else "") | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_iso(time_millis):
"""Converts the given time since epoch in millis to an ISO 8601 string"""
return datetime.utcfromtimestamp(time_millis / 1000).isoformat() | bigcode/self-oss-instruct-sc2-concepts |
def _format_range(start, end):
"""
Build string for format specification.
used by many commands, like delete, load, etc...
:param start:
:param end:
:return: the string to be used for range in the command
"""
if start is None:
return ''
if end is None:
return str(star... | bigcode/self-oss-instruct-sc2-concepts |
def prefix_to_items(items, prefix):
"""Add a prefix to the elements of a listing. For example, add "Base" to
each item in the list.
"""
return ['{}{}'.format(prefix, x) for x in items] | bigcode/self-oss-instruct-sc2-concepts |
def dedupe_in_order(in_list, dont_add=set()):
"""
Deduplicate the in_list, maintaining order
:param dont_add: an additional stoplist
"""
dedupe = set() | dont_add
ordered_deduped = []
for l in in_list:
if l not in dedupe:
ordered_deduped.append(l)
dedupe.add(l)
return ordered_deduped | bigcode/self-oss-instruct-sc2-concepts |
def is_page_editor(user, page):
"""
This predicate checks whether the given user is one of the editors of the given page.
:param user: The user who's permission should be checked
:type user: ~django.contrib.auth.models.User
:param page: The requested page
:type page: ~integreat_cms.cms.models.... | bigcode/self-oss-instruct-sc2-concepts |
def parse_row(row):
"""
Take in a tr tag and get the data out of it in the form of a list of
strings.
"""
return [str(x.string) for x in row.find_all('td')] | bigcode/self-oss-instruct-sc2-concepts |
def eco_fen(board):
"""
Takes a board position and returns a FEN string formatted for matching with
eco.json
"""
board_fen = board.board_fen()
castling_fen = board.castling_xfen()
to_move = 'w' if board.turn else 'b'
return "{} {} {}".format(board_fen, to_move, castling_fen) | bigcode/self-oss-instruct-sc2-concepts |
def minus(a:int,b:int)->int:
"""
minus operation
:param a: first number
:param b: second number
:return: a-b
"""
return a-b | bigcode/self-oss-instruct-sc2-concepts |
def create_wiki_url(page: str) -> str:
"""Creates canonical URL to `page` on wiki
Args:
page (str): subject page
Returns:
str: canonical URL
"""
return f"https://genshin-impact.fandom.com{page}" | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def get_flattened_subclasses(cls):
"""
Returns all the given subclasses and their subclasses recursively for the given class
:param cls: Class to check
:type cls: Type
:return: Flattened list of subclasses and their subclasses
"""
classes = cls.__subclasses__()
return ... | bigcode/self-oss-instruct-sc2-concepts |
def accuracy(labels, scores, threshold=0.5):
"""
Computes accuracy from scores and labels. Assumes binary classification.
"""
return ((scores >= threshold) == labels).mean() | bigcode/self-oss-instruct-sc2-concepts |
def deal_hands(deck, start):
"""
Deal hands from the deck starting at index i
"""
return (
[deck[start], deck[start + 2]],
[deck[start + 1], deck[start + 3]],
) | bigcode/self-oss-instruct-sc2-concepts |
def set_training_mode_for_dropout(net, training=True):
"""Set Dropout mode to train or eval."""
for m in net.modules():
# print(m.__class__.__name__)
if m.__class__.__name__.startswith('Dropout'):
if training==True:
m.train()
else:
m.eval()... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_object(filename):
"""
Load python object
-------------------------------------------
Inputs:
filename: name of pickle file I want to load. Example: 'dump_file.pkl'
-------------------------------------------
Output:
loaded object
"""
with open(filename, "... | bigcode/self-oss-instruct-sc2-concepts |
def mean_dim(tensor, dim=None, keepdims=False):
"""Take the mean along multiple dimensions.
Args:
tensor (torch.Tensor): Tensor of values to average.
dim (list): List of dimensions along which to take the mean.
keepdims (bool): Keep dimensions rather than squeezing.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def humanize_time(secs):
"""
Takes *secs* and returns a nicely formatted string
"""
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return "%02d:%02d:%02d" % (hours, mins, secs) | bigcode/self-oss-instruct-sc2-concepts |
def get_first_and_last_names(user):
"""
Returns a the most reliable values we have for a user's first and last name based on
what they have entered for their legal address and profile.
Args:
user (django.contrib.auth.models.User):
Returns:
(str or None, str or None): A tuple contai... | bigcode/self-oss-instruct-sc2-concepts |
def _reorder(xs, indexes):
"""Reorder list xs by indexes"""
if not len(indexes) == len(xs):
raise ValueError("xs and indexes must be the same size")
ys = [None] * len(xs)
for i, j in enumerate(indexes):
ys[j] = xs[i]
return ys | bigcode/self-oss-instruct-sc2-concepts |
def error_applookuprecord_unknown(value:str) -> str:
"""
Return an error message for a unknown record identifier.
Used when setting the field of an applookup control to a record identifier
that can't be found in the target app.
"""
return f"Record with id {value!r} unknown." | bigcode/self-oss-instruct-sc2-concepts |
def digest_repr(obj):
""" Return a short digest of a possibly deeply nested (JSON) object.
"""
if isinstance(obj, (tuple, list, set, dict)):
def nesting(collection):
"Helper"
if isinstance(collection, dict):
collection = collection.values()
if isin... | 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.