seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def fix_tuple_length(t, n):
"""Extend tuple t to length n by adding None items at the end of the tuple. Return the new tuple."""
return t + ((None,) * (n - len(t))) if len(t) < n else t | bigcode/self-oss-instruct-sc2-concepts |
def url(context, link_url):
"""
Get the path for a page in the Cactus build.
We'll need this because paths can be rewritten with prettifying.
"""
site = context['__CACTUS_SITE__']
url = site.get_url_for_page(link_url)
if site.prettify_urls:
return url.rsplit('index.html', 1)[0]
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_coords(coord_str):
"""Parse a line like <x=1, y=2, z=-3> into [1, 2, -3]"""
coords = coord_str.strip('<>\n').split(',')
return [int(coords[x].split('=')[1]) for x in range(0, 3)] | bigcode/self-oss-instruct-sc2-concepts |
def wrap_check_stop(l, stop):
"""Check that stop index falls in (-l, l] and wrap negative values to l + stop.
For convenience, stop == 0 is assumed to be shorthand for stop == l.
"""
if (stop <= -l) or (stop > l):
raise IndexError('stop index out of range')
elif stop <= 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def snake_to_camel_case(s):
"""
Converts strings from 'snake_case' (Python code convention)
to CamelCase
"""
new_string = s
leading_count = 0
while new_string.find('_') == 0:
new_string = new_string[1:]
leading_count += 1
trailing_count = 0
while new_string.rfind('_... | bigcode/self-oss-instruct-sc2-concepts |
def eulers_richardson_method(f, dx, y, yp, range, return_yp = False):
""" The Eulers Richardson method for solving a differential equation of second
order. Works by taking the Euler method, but uses the average values instead.
This produces a better approximation to the solution faster (in theory) than
... | bigcode/self-oss-instruct-sc2-concepts |
def url_is_secure(data):
"""
=> Check if the passed in url is a secure
url
=> based on whether the url starts with https or https://
"""
return data.startswith("https://") | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_key(path=".keys/AES.key"):
"""
Load key from .keys/AES.key file
:param path: file path
:type path: String
:return: key
:rtype: bytearray
"""
with open(path, 'r') as f:
k = json.load(f)
return bytearray.fromhex(k["key"]) | bigcode/self-oss-instruct-sc2-concepts |
def validateDir(value):
"""
Validate direction.
"""
msg = "Direction must be a 3 component vector (list)."
if not isinstance(value, list):
raise ValueError(msg)
if 3 != len(value):
raise ValueError(msg)
try:
nums = map(float, value)
except:
raise ValueError(msg)
return value | bigcode/self-oss-instruct-sc2-concepts |
def _get_pgsql_command(name, host="localhost", password=None, port=5432, user="postgres"):
"""Get a postgres-related command using commonly required parameters.
:param name: The name of the command.
:type name: str
:param host: The host name.
:type host: str
:param password: The password to u... | bigcode/self-oss-instruct-sc2-concepts |
def snap_to_cube(q_start, q_stop, chunk_depth=16, q_index=1):
"""
For any q in {x, y, z, t}
Takes in a q-range and returns a 1D bound that starts at a cube
boundary and ends at another cube boundary and includes the volume
inside the bounds. For instance, snap_to_cube(2, 3) = (1, 17)
Arguments:... | bigcode/self-oss-instruct-sc2-concepts |
def main(*, a, b):
"""entrypoint function for this component
Usage example:
>>> main(
... a = pd.Series(
... {
... "2019-08-01T15:20:12": 1.2,
... "2019-08-01T15:44:12": None,
... "2019-08-03T16:20:15": 0.3,
... "2019-08-05T12:0... | bigcode/self-oss-instruct-sc2-concepts |
def nrz_decision(x,t):
"""produces nrz symbol from analog voltage
Parameters
----------
x : float
the analog voltage
t: float
voltage threshold between 0 and 1 symbol
Returns
-------
int
the nrz symbol that represents x
"""
if x<t:
r... | bigcode/self-oss-instruct-sc2-concepts |
def serialize_quantity(quantity):
"""Serializes a propertyestimator.unit.Quantity into a dictionary of the form
`{'value': quantity.value_in_unit(quantity.unit), 'unit': quantity.unit}`
Parameters
----------
quantity : unit.Quantity
The quantity to serialize
Returns
-------
dic... | bigcode/self-oss-instruct-sc2-concepts |
def migrate(engine):
"""Replace 'backend' with 'store' in meta_data column of image_locations"""
sql_query = ("UPDATE image_locations SET meta_data = REPLACE(meta_data, "
"'\"backend\":', '\"store\":') where INSTR(meta_data, "
" '\"backend\":') > 0")
# NOTE(abhishekk): INS... | bigcode/self-oss-instruct-sc2-concepts |
def get_all_collections(self):
"""Return all collections in the database"""
return self.app.db.table('collections').all() | bigcode/self-oss-instruct-sc2-concepts |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
file = open(path, 'r')
return [line.strip() for line in file.readlines()] | bigcode/self-oss-instruct-sc2-concepts |
def make_ops_ast(expr, nfops, is_write=False):
"""
Transform a devito expression into an OPS expression.
Only the interested nodes are rebuilt.
Parameters
----------
expr : Node
Initial tree node.
nfops : OPSNodeFactory
Generate OPS specific nodes.
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def resort_points(points, idx):
"""
Resort Set of points along G dim
:param points: [N, G, 3]
:param idx: [N, G]
:return: [N, G, 3]
"""
device = points.device
N, G, _ = points.shape
n_indices = torch.arange(N, dtype=torch.long).to(device).view([N, 1]).repeat([1, G])
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _include_local_or_system(x):
"""Wrap **x** in quotes if it is not wrapped in angle brackets."""
if re.fullmatch("<.*>", x):
return x
return '"' + x.strip('"') + '"' | bigcode/self-oss-instruct-sc2-concepts |
def is_ambiguous(num_sensed_blocked: int, num_confirmed_blocked: int, num_sensed_unblocked: int,
num_confirmed_unblocked: int):
"""
Check whether the conditions are ambiguous or not
:param num_sensed_blocked: number of sensed blocks
:param num_confirmed_blocked: number of confirmed bloc... | bigcode/self-oss-instruct-sc2-concepts |
import json
def enjson(obj, indent=4, encoding='UTF-8'):
"""
Dumps unicode json allowing non-ascii characters encoded as needed.
"""
return json.dumps(obj, indent=indent, ensure_ascii=False).encode(encoding) | bigcode/self-oss-instruct-sc2-concepts |
def nombre_sommets(G):
"""Renvoie le nombre de sommets d'un graphe"""
return len(G.keys()) | bigcode/self-oss-instruct-sc2-concepts |
def headingToYaw(heading):
""" Convert heading (degrees, NED) to yaw (degrees, ENU).
Args:
heading: float heading: degrees, NED
Returns:
Float, yaw: degrees, ENU
"""
return 90.0-heading | bigcode/self-oss-instruct-sc2-concepts |
def opts_dd(lbl, value):
"""Format an individual item in a Dash dcc dropdown list.
Args:
lbl: Dropdown label
value: Dropdown value
Returns:
dict: keys `label` and `value` for dcc.dropdown()
"""
return {'label': str(lbl), 'value': value} | bigcode/self-oss-instruct-sc2-concepts |
def rc_to_xy(row, col, rows):
"""
Convert from (row, col) coordinates (eg: numpy array) to (x, y) coordinates (bottom left = 0,0)
(x, y) convention
* (0,0) in bottom left
* x +ve to the right
* y +ve up
(row,col) convention:
* (0,0) in top left
* row +ve down
* col +ve to the... | bigcode/self-oss-instruct-sc2-concepts |
def has_relative_protocol(uri):
"""Return True if URI has relative protocol '//' """
start = uri[:2]
if start == '//':
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def wrap(value):
"""Return *value* as a list.
Reader._parse(elem, unwrap=True) returns single children of *elem* as bare
objects. wrap() ensures they are a list.
"""
return value if isinstance(value, list) else [value] | bigcode/self-oss-instruct-sc2-concepts |
def get_labelled_idxs(dataset):
"""
Get all indices with labels
"""
split_dict = dataset.get_idx_split()
train_idx = split_dict['train']
valid_idx = split_dict['valid']
test_idx = split_dict['test']
idxs_labelled = set(train_idx)
idxs_labelled = idxs_labelled.union(set(valid_idx))
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Tuple
from typing import Optional
def utm_region_code(
epsg: Union[int, Tuple[int, int, int]], tidx: Optional[Tuple[int, int]] = None
) -> str:
"""
Construct UTM gridspec identifier.
Examples:
- 32751 -> "51S"
- 32633, 10, 2 -> "33N_10_02... | bigcode/self-oss-instruct-sc2-concepts |
def unique(a):
"""Find unique elements, retaining order."""
b = []
for x in a:
if x not in b:
b.append(x)
return b | bigcode/self-oss-instruct-sc2-concepts |
def upload_tenx_library_path(instance, filename):
"""Make a proper file path for uploading 10x library files."""
return "{0}/{1}/{2}".format(
'tenxlibrary',
instance.library.id,
filename
) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
import base64
def get_file_hash(filename, algorithm='md5'):
"""Linux equivalent: openssl <algorithm> -binary <filename> | base64"""
hash_obj = getattr(hashlib, algorithm)()
with open(filename, 'rb') as file_:
for chunk in iter(lambda: file_.read(1024), b""):
hash_obj.upd... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def kl_divergence(d1, d2, K=100):
"""Computes closed-form KL if available, else computes a MC estimate."""
if (type(d1), type(d2)) in torch.distributions.kl._KL_REGISTRY:
return torch.distributions.kl_divergence(d1, d2)
else:
samples = d1.rsample(torch.Size([K]))
retur... | bigcode/self-oss-instruct-sc2-concepts |
def forcerange(colval):
"""Caps a value at 0 and 255"""
if colval > 255:
return 255
elif colval < 0:
return 0
else:
return colval | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def weekday_of_birth_date(date):
"""Takes a date object and returns the corresponding weekday string"""
get_weekday = date.weekday()
weekday = calendar.day_name[get_weekday]
return weekday | bigcode/self-oss-instruct-sc2-concepts |
def r_to_q_Ri(params, substep, state_history, prev_state, policy_input):
"""
For a 'r to q' trade this function returns the amount of token UNI_R for the respective asset depending on the policy_input
"""
asset_id = policy_input['asset_id'] # defines asset subscript
r = (policy_input['ri_sold']) #am... | bigcode/self-oss-instruct-sc2-concepts |
import six
def _hex2rgb(h):
"""Transform rgb hex representation into rgb tuple of ints representation"""
assert isinstance(h, six.string_types)
if h.lower().startswith('0x'):
h = h[2:]
if len(h) == 3:
return (int(h[0] * 2, base=16), int(h[1] * 2, base=16), int(h[2] * 2, base=16))
i... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
from typing import Set
def select_functions(vw, asked_functions: Optional[List[int]]) -> Set[int]:
"""
Given a workspace and an optional list of function addresses,
collect the set of valid functions,
or all valid function addresses.
arguments:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def load_model(model, load_path, device):
"""Load torch model."""
model.load_state_dict(torch.load(load_path, map_location = device))
return model | bigcode/self-oss-instruct-sc2-concepts |
def is_encrypted_value(value):
"""
Checks value on surrounding braces.
:param value: Value to check
:return: Returns true when value is encrypted, tagged by surrounding braces "{" and "}".
"""
return value is not None and value.startswith("{") and value.endswith("}") | bigcode/self-oss-instruct-sc2-concepts |
def duplicates(L):
"""
Return a list of the duplicates occurring in a given list L.
If there are no duplicates, return empty list.
"""
dupes = list()
seen = set()
for x in L:
if x in seen:
dupes.append(x)
seen.add(x)
return dupes | bigcode/self-oss-instruct-sc2-concepts |
def make_regexps_for_path(path):
"""
given a path like a/b/c/d/e.ipynb, return
many regexps mathing this path. specifically,
[^/]+/b/c/d/e.ipy
a/[^/]+/c/d/e.ipy
a/b/[^/]+/d/e.ipy
a/b/c/[^/]+/e.ipy
a/b/c/d/[^/]+
"""
components = path.split("/")
patterns = []
for i in range... | bigcode/self-oss-instruct-sc2-concepts |
def format_math(expr):
"""Replace math symbols with HTML conterparts
:param expr: expression to format
:type expr: str
:returns: replaced string
"""
expr2 = expr.replace(".gt.", ">")
expr2 = expr2.replace(".geq.", ">=")
expr2 = expr2.replace(".lt.", "<")
expr2 = expr2.repl... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_github_list(base_url):
"""
Helper to traverse paginated results from the GitHub API.
Used to retrieve lists of tags and releases.
"""
results = []
per_page = 100
page_number = 1
while True:
response = requests.get("%s?per_page=%s&page=%s" %
(... | bigcode/self-oss-instruct-sc2-concepts |
def add_labels_to_predictions_strict(preds, golds, strict=True):
"""
Returns predictions and missed gold annotations with
a "label" key, which can take one of "TP", "FP", or "FN".
"""
pred_spans = {(s["start"], s["end"]) for s in preds}
gold_spans = {(s["start"], s["end"]) for s in golds}
ou... | bigcode/self-oss-instruct-sc2-concepts |
def connection_mock_factory(mocker):
"""Factory of DB connection mocks."""
def factory(vendor, fetch_one_result=None):
connection_mock = mocker.MagicMock(vendor=vendor)
cursor_mock = connection_mock.cursor.return_value
cursor_mock = cursor_mock.__enter__.return_value # noqa: WPS609
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_longest_match(digraph, html_files):
"""Find the longest match between ``digraph`` and the contents of ``html_files``.
Parameters
----------
digraph : str
The ``digraph`` attribute of a :py:class:`Dotfile` object
html_files : list
A list of the Sphinx html files
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def get_attributes(parent, selector, attribute):
"""Get a list of attribute values for child elements of parent matching the given CSS selector"""
return [child.get(attribute) for child in parent.cssselect(selector)] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def mock_random_choice(candidates: List, weights: List[float], *, k: int) -> List:
"""
This is a mock function for random.choice(). It generates a deterministic sequence of the
candidates, each one with frequency weights[i] (count: int(len(candidates) * k). If the
sum of total ... | bigcode/self-oss-instruct-sc2-concepts |
def reformat_icd_code(icd_code: str, is_diag: bool = True) -> str:
"""Put a period in the right place because the MIMIC-3 data files exclude them.
Generally, procedure ICD codes have dots after the first two digits, while diagnosis
ICD codes have dots after the first three digits.
Adopted from: https://... | bigcode/self-oss-instruct-sc2-concepts |
def milky_way_extinction_correction(lamdas, data):
"""
Corrects for the extinction caused by light travelling through the dust and
gas of the Milky Way, as described in Cardelli et al. 1989.
Parameters
----------
lamdas : :obj:'~numpy.ndarray'
wavelength vector
data : :obj:'~numpy.... | bigcode/self-oss-instruct-sc2-concepts |
def build_anytext(name, value):
"""
deconstructs free-text search into CQL predicate(s)
:param name: property name
:param name: property value
:returns: string of CQL predicate(s)
"""
predicates = []
tokens = value.split()
if len(tokens) == 1: # single term
return f"{nam... | bigcode/self-oss-instruct-sc2-concepts |
import math
def compensatoryAnd(m, g=0.5):
"""
anding function
m = list of membership values for x derived from n membership functions
g = gamma value 0=product 1=algebraic sum
returns compensatory AND value of x
"""
g = float(g)
product1 = 1
product2 = 1
for mem ... | bigcode/self-oss-instruct-sc2-concepts |
import random
def _get_a_word(words, length=None, bound='exact', seed=None):
"""Return a random word.
:param list words: A list of words
:param int length: Maximal length of requested word
:param bound: Whether to interpret length as upper or exact bound
:type bound: A string 'exact' or 'atmost'
... | bigcode/self-oss-instruct-sc2-concepts |
def dict2str(opt, indent_level=1):
"""dict to string for printing options.
Args:
opt (dict): Option dict.
indent_level (int): Indent level. Default: 1.
Return:
(str): Option string for printing.
"""
msg = ''
for k, v in opt.items():
if isinstance(v, dict):
... | bigcode/self-oss-instruct-sc2-concepts |
def is_pos_tag(token):
"""Check if token is a part-of-speech tag."""
return(token in ["CC", "CD", "DT", "EX", "FW", "IN", "JJ", "JJR",
"JJS", "LS", "MD", "NN", "NNS", "NNP", "NNPS", "PDT",
"POS", "PRP", "PRP$", "RB", "RBR", "RBS", "RP", "SYM", "TO",
"UH", "VB... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import List
def set_user_defined_functions(
fha: Dict[str, Any], functions: List[str]
) -> Dict[str, Any]:
"""Set the user-defined functions for the user-defined calculations.
.. note:: by default we set the function equal to 0.0. This prevents ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def bbox_to_zoom_level(bbox):
"""Computes the zoom level of a lat/lng bounding box
Parameters
----------
bbox : list of list of float
Northwest and southeast corners of a bounding box, given as two points in a list
Returns
-------
int
Zoom level of map in a WG... | bigcode/self-oss-instruct-sc2-concepts |
def scale_size(widget, size):
"""Scale the size based on the scaling factor of tkinter.
This is used most frequently to adjust the assets for
image-based widget layouts and font sizes.
Parameters:
widget (Widget):
The widget object.
size (Union[int, List, Tuple]):
... | bigcode/self-oss-instruct-sc2-concepts |
def pdf_field_type_str(field):
"""Gets a human readable string from a PDF field code, like '/Btn'"""
if not isinstance(field, tuple) or len(field) < 4 or not isinstance(field[4], str):
return ''
else:
if field[4] == '/Sig':
return 'Signature'
elif field[4] == '/Btn':
return 'Checkbox'
... | bigcode/self-oss-instruct-sc2-concepts |
def get_task_prerun_attachment(task_id, task, args, kwargs, **cbkwargs):
"""Create the slack message attachment for a task prerun."""
message = "Executing -- " + task.name.rsplit(".", 1)[-1]
lines = ["Name: *" + task.name + "*"]
if cbkwargs["show_task_id"]:
lines.append("Task ID: " + task_id)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Tuple
def make_response(status: int, data: Optional[str] = None) -> Tuple[str, int]:
"""Construct a non-error endpoint response."""
if data is None:
data = ""
return (data, status) | bigcode/self-oss-instruct-sc2-concepts |
def mse_grad(y, tx, w):
"""Compute gradient for MSE loss."""
e = y - tx @ w
return (-1/tx.shape[0]) * tx.T @ e | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _get_func_expr(s: str) -> Tuple[str, str]:
"""
Get the function name and then the expression inside
"""
start = s.index("(")
end = s.rindex(")")
return s[0:start], s[start + 1:end] | bigcode/self-oss-instruct-sc2-concepts |
def get_df_rng(ws, df, start_row=1, start_col=1, include_headers=True):
"""Gets a range that matches size of dataframe"""
nrow = len(df) + 1 if include_headers else len(df)
ncol = len(df.columns)
return ws.get_range(row=start_row,
column=start_col,
numb... | bigcode/self-oss-instruct-sc2-concepts |
def get_numeric_columns(df):
"""
# Returns a list of numeric columns of the dataframe df
# Parameters:
# df (Pandas dataframe): The dataframe from which extract the columns
# Returns:
# A list of columns names (strings) corresponding to numeric columns
"""
numeric_columns = lis... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Optional
def get_file_by_type(folder: Path, suffix: str) -> Optional[Path]:
""" Extracts a file by the suffix. If no files with the suffix are found or more than one file is found returns `None`"""
if not suffix.startswith('.'):
suffix = '.' + suffix
candidates = [i fo... | bigcode/self-oss-instruct-sc2-concepts |
def get_text_list(list_, last_word='or'):
"""
>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>> get_text_list(['a', 'b'], 'and')
'a and b'
>> get_text_list(['a'])
'a'
>> get_text_list([])
''
"""
if len(list_... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_robust(feature, feature_scale=(None, 0.5)):
"""normalize feature with robust method.
Args:
feature: pd.Series, sample feature value.
feature_scale: list or tuple, [feature.median(), feature.quantile(0.75)-feature.quantile(0.25)];
if feature_scale[0] is n... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
from typing import Set
def get_parents_of(image_and_parents: Dict[str, List[str]], commit_id: str) -> Set[str]:
"""Returns a set of all parents of a given commit id."""
parents = None
parents_list = [commit_id]
i = 0
while i < len(parents_list):
... | bigcode/self-oss-instruct-sc2-concepts |
import six
def partition(list_, columns=2):
"""
Break a list into ``columns`` number of columns.
"""
iter_ = iter(list_)
columns = int(columns)
rows = []
while True:
row = []
for column_number in range(1, columns + 1):
try:
value = six.next(ite... | bigcode/self-oss-instruct-sc2-concepts |
def filt(items, keymap, sep='.'):
"""
Filters a list of dicts by given keymap.
By default, periods represent nesting (configurable by passing `sep`).
For example:
items = [
{'name': 'foo', 'server': {'id': 1234, 'hostname': 'host1'}, 'loc': 4},
{'name': 'bar', 'server': ... | bigcode/self-oss-instruct-sc2-concepts |
def count_lines(in_path):
"""Counts the number of lines of a file"""
with open(in_path, 'r', encoding='utf-8') as in_file:
i = 0
for line in in_file:
i += 1
return i | bigcode/self-oss-instruct-sc2-concepts |
def partition(l, condition):
"""Returns a pair of lists, the left one containing all elements of `l` for
which `condition` is ``True`` and the right one containing all elements of
`l` for which `condition` is ``False``.
`condition` is a function that takes a single argument (each individual
element... | bigcode/self-oss-instruct-sc2-concepts |
def GetKeywordArgs(prop, include_default=True):
"""Captures attributes from an NDB property to be passed to a ProtoRPC field.
Args:
prop: The NDB property which will have its attributes captured.
include_default: An optional boolean indicating whether or not the default
value of the property should... | bigcode/self-oss-instruct-sc2-concepts |
def space_check(board, position):
"""
Returns a boolean indicating whether a space on the board is freely available.
:param board:
:param position:
:return:
"""
return board[position] == ' ' | bigcode/self-oss-instruct-sc2-concepts |
def _flatten_vectors(vectors):
"""Returns the flattened array of the vectors."""
return sum(map(lambda v: [v.x, v.y, v.z], vectors), []) | bigcode/self-oss-instruct-sc2-concepts |
def co(self) -> tuple:
"""
Solve last layer face.
Returns
-------
tuple of (list of str, dict of {'LAST LAYER FACE': int})
Moves to solve last layer face, statistics (move count in ETM).
Notes
-----
If the last layer face is not solved, rotate the cube so that the
yellow si... | bigcode/self-oss-instruct-sc2-concepts |
def list2str(args):
"""
Convert list[str] into string. For example: [x, y] -> "['x', 'y']"
"""
if args is None: return '[]'
assert isinstance(args, (list, tuple))
args = ["'{}'".format(arg) for arg in args]
return '[' + ','.join(args) + ']' | bigcode/self-oss-instruct-sc2-concepts |
def lower_bits(sequence,n):
"""Return only the n lowest bits of each term in the sequence"""
return map(lambda x: x%(2**n), sequence) | bigcode/self-oss-instruct-sc2-concepts |
def make_callback_dictionary(param_dict, status_flag, status_msg):
"""Utility function that adds extra return values to parameter dictionary."""
callback_dict = param_dict.copy()
callback_dict['status_flag'] = status_flag
callback_dict['status_msg'] = status_msg
return callback_dict | bigcode/self-oss-instruct-sc2-concepts |
import re
def filter_lines(output, filter_string):
"""Output filter from build_utils.check_output.
Args:
output: Executable output as from build_utils.check_output.
filter_string: An RE string that will filter (remove) matching
lines from |output|.
Returns:
The filtered outpu... | bigcode/self-oss-instruct-sc2-concepts |
def get_savwriter_integer_format(series):
"""
Derive the required SAV format value for the given integer series.
savReaderWriter requires specific instructions for each variable
in order to correctly create target variables. This function
determines the width of the maximum integer in the given ser... | bigcode/self-oss-instruct-sc2-concepts |
def get_monitor_name(domain_name: str) -> str:
"""
Encapsulate the RUM monitors naming convention.
:param domain_name: the domain name for which a RUM
monitor is to be created.
:return: a Rams' compliant RUM monitor name
"""
return domain_name + "_RUM" | bigcode/self-oss-instruct-sc2-concepts |
def get_release_version(version):
"""
If version ends with "-SNAPSHOT", removes that, otherwise returns the
version without modifications.
"""
if version is None:
return None
if version.endswith("-SNAPSHOT"):
return version[0:-len("-SNAPSHOT")]
return version | bigcode/self-oss-instruct-sc2-concepts |
def typeOut(typename, out):
"""
Return type with const-ref if out is set
"""
return typename if out else "const " + typename + " &" | bigcode/self-oss-instruct-sc2-concepts |
def Double_list (list_genomes):
"""
Create the new headers of the contig/s of the individual genomes and save the
headers and sequences in different lists. In the same position in a list
it will be the header and in the other its respective nucleotide sequence.
"""
# Create the lists:
heade... | bigcode/self-oss-instruct-sc2-concepts |
def WrapFunction(lib, funcname, restype, argtypes):
"""
Simplify wrapping ctypes functions
:param lib: library (object returned from ctypes.CDLL()
:param funcname: string of function name
:param restype: type of return value
:param argtypes: a list of types of the function arguments
:return:... | bigcode/self-oss-instruct-sc2-concepts |
def teleport_counts(shots, hex_counts=True):
"""Reference counts for teleport circuits"""
targets = []
if hex_counts:
# Classical 3-qubit teleport
targets.append({'0x0': shots / 4, '0x1': shots / 4,
'0x2': shots / 4, '0x3': shots / 4})
else:
# Classical 3-... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_generator(func):
"""Check whether object is generator."""
return inspect.isgeneratorfunction(func) | bigcode/self-oss-instruct-sc2-concepts |
def org(mocker):
"""Fake Organisation instance."""
org = mocker.Mock()
org.id = "003"
org.name = "org-003"
return org | bigcode/self-oss-instruct-sc2-concepts |
def normalize_space(data):
"""Implements attribute value normalization
Returns data normalized according to the further processing rules
for attribute-value normalization:
"...by discarding any leading and trailing space (#x20)
characters, and by replacing sequences of space (#x20)
... | bigcode/self-oss-instruct-sc2-concepts |
def lstrip_docstring(docstring: str) -> str:
"""
Strips leading whitespace from a docstring.
"""
lines = docstring.replace('\t', ' ').split('\n')
indent = 255 # highest integer value
for line in lines[1:]:
stripped = line.lstrip()
if stripped: # ignore empty lines
... | bigcode/self-oss-instruct-sc2-concepts |
def PROPER(text):
"""
Capitalizes each word in a specified string. It converts the first letter of each word to
uppercase, and all other letters to lowercase. Same as `text.title()`.
>>> PROPER('this is a TITLE')
'This Is A Title'
>>> PROPER('2-way street')
'2-Way Street'
>>> PROPER('76BudGet')
'76Bu... | bigcode/self-oss-instruct-sc2-concepts |
def split(l: list, n_of_partitions: int) -> list:
"""
Splits the given list l into n_of_paritions partitions of approximately equal size.
:param l: The list to be split.
:param n_of_partitions: Number of partitions.
:return: A list of the partitions, where each partition is a list itself.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def new_value_part_2(seat: str, visible_count: int) -> str:
"""
Returns the next state for one seat.
"""
if seat == "L" and visible_count == 0:
return "#"
elif seat == "#" and 5 <= visible_count:
return "L"
else:
return seat | bigcode/self-oss-instruct-sc2-concepts |
import torch
def euler_to_q(euler):
"""Converts an Euler angle vector to Quaternion.
The Euler angle vector is expected to be (X, Y, Z).
Arguments:
euler (B,3) - Euler angle vectors.
Returns:
q (B,4) - Quaternions.
"""
euler *= 0.5
cx = euler[:, 0].cos()
sx = euler[:,... | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def mean_logits(logits, dim=0):
"""Return the mean logit, where the average is taken over across `dim` in probability space."""
# p = e^logit / (sum e^logit) <=> log(p) = logit - log_sum_exp(logit)
log_prob = logits - torch.logsumexp(logits, -1, keepdim=True)
# mean(p) = 1/Z s... | bigcode/self-oss-instruct-sc2-concepts |
def rotate(string, n):
"""Rotate characters in a string. Expects string and n (int) for
number of characters to move.
"""
if type(n) != int:
return "Not an integer"
if n == 0:
return string
if n > 0:
s_new = string[0:n]
l = list(string)
l[0:n] = ""
... | 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.