seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from typing import Iterable
from typing import Tuple
from typing import Optional
def fromCode(
desc: str, code_list: Iterable[Tuple[str, str]]
) -> Optional[Tuple[str, str]]:
"""
Returns the matched element by code in the give code list. None otherwise.
"""
res = [item for item in code_list if ite... | bigcode/self-oss-instruct-sc2-concepts |
def srm_to_lovibond(srm: float) -> float:
"""
Convert from Degrees Lovibond color system to
Standard Reference Method (SRM) color system.
"""
return (srm + 0.76) / 1.3546 | bigcode/self-oss-instruct-sc2-concepts |
def add_to_fw_spec(original_wf, metadata):
"""
Add metadata to fireworks to make them easy for querying.
Arags:
original_wf (Workflow)
metadata (dict): metadata to be added to "spec"
Returns:
modified workflows
"""
for fwork in original_wf.fws:
for key, value in... | bigcode/self-oss-instruct-sc2-concepts |
def construct_authorperm(*args):
""" Create a post identifier from comment/post object or arguments.
Examples:
.. code-block:: python
>>> from beem.utils import construct_authorperm
>>> print(construct_authorperm('username', 'permlink'))
@username/permlink
... | bigcode/self-oss-instruct-sc2-concepts |
def friendly_boolean(boolean):
"""
Returns 'Yes' if a boolean is equal to True, else 'No'
"""
if boolean is True or str(boolean).lower() == "true":
return "Yes"
else:
return "No" | bigcode/self-oss-instruct-sc2-concepts |
def visiblename(name):
"""
Checks whether a given name should be documented/displayed by
ignoring builtin ones.
"""
return not (name.startswith('__') and name.endswith('__')) | bigcode/self-oss-instruct-sc2-concepts |
def is_redirect(endpoint):
"""
Endpoint is a redirect if it is a redirect to an external site
"""
return endpoint.redirect_eventually_to_external | bigcode/self-oss-instruct-sc2-concepts |
def msg_err_missing_children(tag, *children):
"""Format message for missing children.
:param tag: tag name
:param children: list of children
:return: message
:rtype: str
"""
return "Missing one or more required children (%s) in xml tag %s" % ('|'.join(children), tag) | bigcode/self-oss-instruct-sc2-concepts |
def adjust_var_name(var_to_check, var_names):
"""
Check if upper or lower case version of name is in namelist and adjust.
Parameters
----------
var_to_check : Str.
var_names : List of Str.
Returns
-------
var_to_check : Str.
"""
if var_to_check not in var_names:
fo... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_text(text):
"""Clean our tweets using regex. Remove weird characters and links."""
cleanedup = text.lower()
return re.sub("(@[A-Za-z0-9]+)|(#[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", "", cleanedup) | bigcode/self-oss-instruct-sc2-concepts |
import six
def FormatTagSpecifications(resource_type, tags_dict):
"""Format a dict of tags into arguments for 'tag-specifications' parameter.
Args:
resource_type: resource type to be tagged.
tags_dict: Tags to be formatted.
Returns:
A list of tags formatted as arguments for 'tag-specifications' pa... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import hashlib
def files_identical(path1: Path, path2: Path) -> bool:
"""Compares content of file using md5 checksum"""
with open(path1, 'rb') as f1, open(path2, 'rb') as f2:
f1 = f1.read()
f2 = f2.read()
if hashlib.md5(f1).hexdigest() == hashlib.md5(f2).hexdigest(... | bigcode/self-oss-instruct-sc2-concepts |
def extract_year(paper_id: str) -> int:
""" Tries to extract the publication year from the ArXiv paper id
:param paper_id: original paper id
:type paper_id: str
:return: year, 0 if no year was found.
:rtype: int
"""
try:
year = 2000 + int(paper_id[:2])
except BaseException:
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def jsonToText(jsonObject, indent='\t'):
"""
Return a JSON object as text
indent: The indent argument to json.dumps. Defaults to '\t' for readability.
Set to None for default json.dumps behavior.
"""
return json.dumps(jsonObject, indent=indent) | bigcode/self-oss-instruct-sc2-concepts |
import math
def prime_check(number: int) -> bool:
"""Checks to see if a number is a prime in O(sqrt(n)).
A number is prime if it has exactly two factors: 1 and itself.
>>> prime_check(0)
False
>>> prime_check(1)
False
>>> prime_check(2)
True
>>> prime_check(3)
True
>>> pr... | bigcode/self-oss-instruct-sc2-concepts |
def _stft_frames_to_samples(frames, size, shift):
"""
Calculates samples in time domain from STFT frames
:param frames: Number of STFT frames.
:param size: FFT size.
:param shift: Hop in samples.
:return: Number of samples in time domain.
"""
return frames * shift + size - shift | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_document_uid(title, body):
"""Generates a nearly unique ID for a document.
Uses the SHA1 hash. Deterministically produces the same result for a given
input, and almost never collides.
Args:
title (bytes): document title
body (bytes): document body text
Returns:
uid (int... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def macro_f1(logits, targets, th=0.5):
"""
pytorch implementation
:param logits: Tensor of shape (B, num_class)
:param targets: Tensor of shape (B, num_class)
:param th: Float threshold
:return: Float
"""
preds = (logits.sigmoid() > th).float()
targets = targets.float(... | bigcode/self-oss-instruct-sc2-concepts |
def get_history_slice(
frame_index: int, history_num_states: int, history_step_size: int, include_current_state: bool = False
) -> slice:
"""Given a frame index and history settings returns a slice that returns the given data in the right order.
Note that this history returned starts with the most "rece... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def sub_clyde(username: Optional[str]) -> Optional[str]:
"""
Replace "e"/"E" in any "clyde" in `username` with a Cyrillic "е"/"E" and return the new string.
Discord disallows "clyde" anywhere in the username for webhooks. It will return a 400.
Return None only if... | bigcode/self-oss-instruct-sc2-concepts |
def subst_plural(wikitext):
"""
Substitutes {{PLURAL}} in wikitext
@param wikitext: Wikitext to process
@type wikitext: str
@rtype: str
"""
return wikitext.replace('{{PLURAL:', '{{subst:PLURAL:') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_string(obj: Any) -> bool:
"""Check whether an object is a string."""
return isinstance(obj, str) | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_list(obj):
""" receives an object and if type tuple or list, return list. Else
return a list containing the one object
"""
if type(obj) is None: return [] # None implies empty list...
if type(obj) is list: return obj
if type(obj) is tuple:
return [x for x in obj]
... | bigcode/self-oss-instruct-sc2-concepts |
def b_if_a_is_none(a, b):
""" Returns 'b' if 'a' is None, otherwise returns 'a' """
if a is None:
return b
else:
return a | bigcode/self-oss-instruct-sc2-concepts |
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1 * U + 10 * O + 100 * Y)'
Non-uppercase words unchanged; compile_word('+') => '+'"""
if word.isupper():
terms = [('%s*%s' % (10 ** i, d))
for (i, d) in enumerate(word[::-1])]
return '(' + '+'.jo... | bigcode/self-oss-instruct-sc2-concepts |
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a
# single token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a ga... | bigcode/self-oss-instruct-sc2-concepts |
def partition(arr: list, low: int, high: int) -> int:
"""Partition the array
Args:
arr (list): the array to partition
low (int): the left-most index
high (int): the right-most index
Returns:
int: the new pivot location
"""
i = low - 1
pivot = arr[high]
# Sw... | bigcode/self-oss-instruct-sc2-concepts |
import re
def __replace_all(repls: dict, input: str) -> str:
""" Replaces from the string **input** all the occurrence of the
keys element of the dictionary **repls** with their relative
value.
:param dict repls: dictionary containing the mapping
between the values to be changed and... | bigcode/self-oss-instruct-sc2-concepts |
def subtract(a,b):
"""Subtract a from b and return value"""
return b - a | bigcode/self-oss-instruct-sc2-concepts |
def _splitList(data, n):
"""Split data list to n sized sub lists."""
return [data[i : i + n] for i in range(0, len(data), n)] | bigcode/self-oss-instruct-sc2-concepts |
def str_to_int(value):
"""Converts an input string
into int value, or returns input
if input is already int
Method curated by Anuj Som
Args:
value (int, str): Accepts an int or string to convert to int
Returns:
tuple (int, bool): returns (integer value, True) if conversion suc... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def uniform_property(section_list, attribute_path):
"""
Define a property that will have a uniform value across a list of sections.
For example, suppose we define a neuron model as a class A, which contains
three compartments: soma, dendrite and axon. Then placing
... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def get_prof(prof_identifier):
"""
Returns all professors that match the identifier entered in the query
"""
#Fetching professor from DB acc to query
conn = sqlite3.connect('./db.sqlite3')
cursor = conn.cursor()
cursor.execute("SELECT * FROM professor WHERE name LIKE ?;", (f... | bigcode/self-oss-instruct-sc2-concepts |
import random
def _shuffle_list(a, b, c, d):
"""
shuffle a, b, c, d simultaneously
"""
x = list(zip(a, b, c, d))
random.shuffle(x)
a, b, c, d = zip(*x)
return a, b, c, d | bigcode/self-oss-instruct-sc2-concepts |
import math
def dist(pos1, pos2):
"""Returns the distance between pos1 and pos2"""
x1, y1 = pos1
x2, y2 = pos2
return math.sqrt(math.pow(x1-x2, 2) + math.pow(y1-y2, 2)) | bigcode/self-oss-instruct-sc2-concepts |
def center_axes(ax):
"""
Makes a plot's axes meet at the
center instead of at the bottom left corner
"""
ax.spines["bottom"].set_position("zero")
ax.spines["left"].set_position("zero")
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
return ax | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
def sanitize_pet_field(pets: List[Dict[str, Any]], field: str = "id") -> str:
"""Concatenate pet fields and return them as a string."""
if len(pets) > 1:
return ", ".join(str(pet[field]) for pet in pets)
if len(pets) == 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_name(manifest):
"""Returns the name from the manifest metadata
Args:
manifest (dict): K8s manifests
Returns:
string: Name of the Kubernetes object, or None
"""
try:
name = manifest["metadata"]["name"].lower()
kind = manifest["kind"].lower()
return f... | bigcode/self-oss-instruct-sc2-concepts |
import re
def insensitize(string):
"""Change upper and lowercase letters to be case insensitive in
the provided string. e.g., 'a' becomes '[Aa]', 'B' becomes
'[bB]', etc. Use for building regexes."""
def to_ins(match):
char = match.group(1)
return '[%s%s]' % (char.lower(), char... | bigcode/self-oss-instruct-sc2-concepts |
def create_response(body, headers):
"""Create a simple HTTP response
:type body: str
:type headers: dict[str, str]
:rtype: bytes
"""
final_headers = {
'Connection': 'keep-alive',
'Content-Type': 'text/plain; charset=utf-8',
'Content-Encoding': 'UTF-8'
}
final_he... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def make_hash_bytes(data, length=20):
"""
Creates a hash of length *length*.
"""
m = hashlib.sha256()
m.update(data)
res = m.hexdigest()[:length]
return res | bigcode/self-oss-instruct-sc2-concepts |
def fifo_pre_sequencing(dataset, *args, **kwargs):
"""
Generates an initial job sequence based on the first-in-first-out
dispatching strategy. The job sequence will be feed to the model.
"""
sequence = [job for job in dataset.values()]
return sequence | bigcode/self-oss-instruct-sc2-concepts |
def lammps_copy_files(job):
"""Check if the submission scripts have been copied over for the job."""
return (
job.isfile("submit.pbs")
and job.isfile("in.minimize")
and job.isfile("in.equilibration")
and job.isfile("in.production-npt")
) | bigcode/self-oss-instruct-sc2-concepts |
def get_maze_centers(maze_path, maze_verts):
"""find the centre of each edge in maze_path and the co-ordinates of the
maze verts - these will be matched to face after the selection is bevelled
input:
maze_path: list of BMEDges that form the links in the maze
output:
link_centers: list of... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def make_target(label, label_to_ix):
"""Turn target labels into a numeric vector where each label has a
unique index"""
return torch.LongTensor([label_to_ix[label]]) | bigcode/self-oss-instruct-sc2-concepts |
def view_kwargs(check_url):
"""Return a dict of valid kwargs to pass to SecurityView(**view_kwargs)."""
return {
"allow_all": False,
"allowed_referrers": ["lms.hypothes.is"],
"authentication_required": True,
"check_url": check_url,
} | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json(path):
"""
Load json file
Args:
path (str): Path to JSON file
Returns:
data (dict): Dictionary form of JSON file
"""
with open(path, "r") as fp:
data = json.load(fp)
return data | bigcode/self-oss-instruct-sc2-concepts |
import random
def introduce_errors(s,
corruption_rate=3e-3,
infill_marker="|?|",
max_infill_len=8):
"""Artificially add spelling errors and infill markers.
This function should be applied to the inputs of a correction model.
The artificial errors ... | bigcode/self-oss-instruct-sc2-concepts |
import sympy
def make_commutative(expr, *symbols):
"""Make sure that specified symbols are defined as commutative.
Parameters
----------
expr: sympy.Expr or sympy.Matrix
symbols: sequace of symbols
Set of symbols that are requiered to be commutative. It doesn't matter
of symbol is... | bigcode/self-oss-instruct-sc2-concepts |
def remove_space(a_string, replace_character):
""" Remove all spaces from a string and return a 'spaceless' version of
the original string.
"""
modified_string = a_string.replace(' ', '')
return modified_string | bigcode/self-oss-instruct-sc2-concepts |
def decode_variable_value(coded, limits):
"""Transform coded values between -1 and +1 into real scale values.
Parameters
----------
coded : float
Coded variable value.
limits : Tuple of 2 floats.
Minimum and maximum real variable values.
Returns
-------
float
Va... | bigcode/self-oss-instruct-sc2-concepts |
def get_session_summary(sessions):
"""
Takes a list of sessions and extract a summary-dictonary.
"""
summary = dict()
summary['all'] = len(sessions)
summary['waiting'] = len([s for s in sessions if s.proc_status == 'initialized'])
summary['running'] = len([s for s in sessions if s.proc_statu... | bigcode/self-oss-instruct-sc2-concepts |
import math
def round_32(x, base=32):
"""Round x to base. Default 32."""
if x == 0:
return 0
else:
return int(math.ceil(float(x) / base)) - 1 | bigcode/self-oss-instruct-sc2-concepts |
def isolate_opening(df, sweepnum, window):
"""
This function will isolate a window in a time series.
Arguments
-------------------
df: dataframe
A pandas dataframe with columns p, ti, tp, and i.
sweepnum: int
The
window: iterable
an iterable with the start and end c... | bigcode/self-oss-instruct-sc2-concepts |
import math
def lr_func_cosine(base_lr, cur_epoch, num_optimizer_epochs):
"""
Retrieve the learning rate of the current step using the cosine learning
rate schedule.
"""
return (
base_lr
* (math.cos(math.pi * cur_epoch / num_optimizer_epochs) + 1.0)
* 0.5
) | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse(data: list) -> list:
# Python Notation: https://www.python.org/dev/peps/pep-3107/
"""
Prase each line of the data
Return a nested list, such as [[id1, id2, id2,...],...]
"""
parsed_data = []
for line in data:
# remove \n at the end of each line
line = re... | bigcode/self-oss-instruct-sc2-concepts |
def setVariable(var, lenght):
"""
Creates set of values defined in 'var' of lenght 'lenght' by doing cylcing (modulo operation)
Example
var = [1, 2, 3], lenght=5, return [1, 2, 3, 1, 2]
"""
nvar = []
l = len(var)
for i in range(lenght):
nvar.append(var[i % l])
return nva... | bigcode/self-oss-instruct-sc2-concepts |
def in_group(user, group_name):
""" Return if a user is in a group called group_name """
try:
return user.groups.filter(name=group_name).exists()
except:
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def expand_ios_ifname(ifname: str) -> str:
"""Get expanded interface name for IOSXR/XE given its short form
:param ifname: str, short form of IOSXR interface name
:returns: Expanded version of short form interface name
:rtype: str
"""
ifmap = {'BE': 'Bundle-Ether',
'BV... | bigcode/self-oss-instruct-sc2-concepts |
def iterable(x):
""" Is x iterable?
>>> iterable([1, 2, 3])
True
>>> iterable('abc')
True
>>> iterable(5)
False
"""
try:
iter(x)
return True
except TypeError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def convertLUtoUN(s):
"""Capitalize a string and remove any underscores.
If 'hello_world' is given, it will return 'HelloWorld'.
"""
return ''.join([word.capitalize() for word in s.split('_')]) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_ece(predictions, labels, num_bins=None):
""" Compute the expected calibration error with binning
Args:
predictions (tensor): a batch of categorical predictions with shape [batch_size, num_classes]
labels (tensor): a batch of labels with shape [batch_size]
num... | bigcode/self-oss-instruct-sc2-concepts |
def genRef(ref):
"""Returns input as function"""
def r():
return ref
return r | bigcode/self-oss-instruct-sc2-concepts |
def kcorrect_calc(
d: float, oldflux: float, z1: float, z2: float, a: float
) -> float:
"""Performs the k-correction calculation given the required arguments.
Args:
d: The distance modulation, in terms of a factor. E.g. a value of 10
would indicate a distance change of 10x.
oldf... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _read_line() -> List[int]:
"""Read an input line, split it and convert to ints."""
return list(map(int, input().split())) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _deduce_images_and_annos_paths(root_path, subset):
"""Deduces paths for images and annotations. It returns the root path
that contains all the sequences belonging to the specific subset.
Args:
root_path (str): Root directory path to the UA-DETRAC dataset.
subs... | bigcode/self-oss-instruct-sc2-concepts |
def linscale(seq, minval=0.0, maxval=1.0):
"""Linearly scales all the values in the sequence to lie between the given values.
Shifts up to minval and scales by the difference ``maxval-minval``
If all values are identical, then sets them to `minval`."""
m, M = min(seq), max(seq)
def sc(s, m=m, M=M):
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def add2dict(key: str, val, dict: dict):
"""Add key/value pair to dict"""
new_dict = copy.deepcopy(dict)
new_dict[key] = val
return new_dict | bigcode/self-oss-instruct-sc2-concepts |
def rotate_counter_clockwise(shape):
"""Given a shape, rotates it counter clockwise"""
return [
[shape[y][x] for y in range(len(shape))]
for x in range(len(shape[0]) - 1, -1, -1)
] | bigcode/self-oss-instruct-sc2-concepts |
def event_counter(object_type: str) -> str:
"""Return db key for the event counter for the object type.
The value stored at this key is used to generate a unique event id.
Args:
object_type (str): Type of object.
Returns:
str, database key for the event counter
"""
return 'ev... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_tags(text: str) -> str:
"""
Removes tags and extracts text inside square brackets [] and angle brackets <>.
Also removes 'cleartext' 'CLEARTEXT' or 'Cleartext' as well as language attributes
(2 letter uppercase sequences following 'cleartext' and space(s) or dash(es)).
:param... | bigcode/self-oss-instruct-sc2-concepts |
def is_every_letter_guessed(word, guesses):
"""Returns if every letter in the target word is accounted for in
the user's guesses.
"""
# It's easier to check the converse; are we missing anything? Check
# if any one of the letters in the target word *isn't* guessed.
for letter in word:
i... | bigcode/self-oss-instruct-sc2-concepts |
def parse_timedelta_from_api(data_dict, key_root):
"""Returns a dict with the appropriate key for filling a two-part timedelta
field where the fields are named <key_root>_number and <key_root>_units.
Parameters
----------
data_dict: dict
API json response containing a key matching the key_r... | bigcode/self-oss-instruct-sc2-concepts |
def construct_api_params(
business_unit=None,
event_type=None,
limit=None,
page_token=None
):
"""
Constructs the parameters object for the API call. Note that startDateUtc and
endDateUtc are not listed here (although they are parameters); this is because
they are included... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_json(name, *args, **kwargs):
"""Retrieve JSON from a (REST) API server after checking correct response."""
r = requests.get(*args, **kwargs)
assert r.ok, "%s access failed: %s" % (name, r.reason)
return r.json() | bigcode/self-oss-instruct-sc2-concepts |
def parse_geometry(geometry):
"""Parse a geometry string and returns a (width, height) tuple
Eg:
'100x200' ==> (100, 200)
'50' ==> (50, None)
'50x' ==> (50, None)
'x100' ==> (None, 100)
None ==> None
A callable `geometry` parameter is also supported.
"""
if n... | bigcode/self-oss-instruct-sc2-concepts |
def signed_shift(val, shift):
"""Bit shifts the value val. +ve values shift left and -ve shift right.
Args:
val (int): Value to be shifted
shift (int): Number of bits to shift by
Returns:
int: Shifted result
"""
return val << shift if shift >= 0 else val >> -shift | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(sub_module, log_name):
"""
Get logger by name and sub module.
Args:
sub_module (str): Sub module name, type is string.
log_name (str): Log file name, type is string.
Returns:
Logger, logger instance named by sub_module and log_name.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def module_exists(module_name):
""" Check if a module can be imported. """
try:
__import__(module_name)
except ImportError:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def match_ans(input_guess, current_guess, ans):
"""
Matching new guess alphabet to each answer char if equals, and return the replaced hint of latest guess.
:param input_guess: str, the new guess alphabet.
:param current_guess: str, the hint of current guess.
:param ans: str, the hidden random word.... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def octet(value):
"""Encode an octet value.
:param value: Value to encode
:rtype: bytes
:raises: TypeError
"""
if not isinstance(value, int):
raise TypeError('int type required')
return struct.pack('B', value) | bigcode/self-oss-instruct-sc2-concepts |
def processFile(fileName: str):
"""
Processes the file and returns the amount of vertices in the graph, as well
as the adjency matrix representation of the graph.
"""
file = open(fileName, "r+")
lines = file.readlines()
if(len(lines) < 2):
raise Exception("File must have atleast two... | bigcode/self-oss-instruct-sc2-concepts |
def cart2wind(cart_angle):
""" 0deg is North, rotate clockwise"""
cart_angle = 90. - cart_angle #rotate so N is 0deg
cart_angle =cart_angle % 360.
return cart_angle | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def to_abs_coord(v, mat):
"""
Change the local vertices coordinate to absolute coordinate
:param v: vector or a list of vertices
:param mat: matrix_world
:return: the Absolute vertices
"""
if isinstance(v, Iterable):
list_verts = []
for i in v:
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_weight_param_summary(wp):
"""Get a summary of _NeuralNetwork_pb2.WeightParams
Args:
wp : _NeuralNetwork_pb2.WeightParams - the _NeuralNetwork_pb2.WeightParams message to display
Returns:
a str summary for wp
"""
summary_str = ''
if wp.HasField('quantization'):
nbits = wp... | bigcode/self-oss-instruct-sc2-concepts |
def ringIsClockwise(ringToTest):
"""
determine if polygon ring coordinates are clockwise. clockwise signifies
outer ring, counter-clockwise an inner ring or hole.
"""
total = 0
i = 0
rLength = len(ringToTest)
pt1 = ringToTest[i]
pt2 = None
for i in range(0, rLength - 1):
... | bigcode/self-oss-instruct-sc2-concepts |
def all_attrs_missing(record):
"""Checks if all attributes have missing values, excluding ID and Class"""
return all(value == '?' for value in record[1:-1]) | bigcode/self-oss-instruct-sc2-concepts |
def is_expression(expression: list) -> bool:
"""Return True if the string is an expression, False otherwise.
A string is an expression if it starts with the "=" symbol.
Raises:
ValueError: Empty expression raises when the string is empty.
"""
if len(expression) == 0:
raise ValueErr... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def convert_date(raw_date: str):
"""
Convert raw date field into a value interpretable by the dataserver.
The date filtering API expects mm/dd/YYYYZ format.
"""
if raw_date.startswith("None"):
return None
try:
date = datetime.strptime(raw_date, "%... | bigcode/self-oss-instruct-sc2-concepts |
def normalise(x):
"""Normalise set of vectors by elementwise mean and standard deviation."""
x_mean = x.mean(0)
x_std = x.std(0)
return (x - x_mean) / x_std, x_mean, x_std | bigcode/self-oss-instruct-sc2-concepts |
def any_in_any(a, b):
"""return true if any item of 'a' is found
inside 'b'
else return false
"""
if len([x for x in a if x in b]) > 0:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def table_name_suffix(load_table_s3_prefix: str) -> str:
"""
Table name suffix should be '__ct' if the S3 prefix is from change tracking.
Parameters
----------
load_table_s3_prefix : str
The load's prefix as determined by its S3 key.
Returns
-------
str
"__ct" or "" dep... | bigcode/self-oss-instruct-sc2-concepts |
def get_portal_registration_status(self) -> dict:
"""Get current Orchestrator Cloud Portal registration status
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- GET
- /spPortal/registration
:return: Retur... | bigcode/self-oss-instruct-sc2-concepts |
def reduce(combiner, seq):
"""Combines elements in seq using combiner.
>>> reduce(lambda x, y: x + y, [1, 2, 3, 4])
10
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
24
>>> reduce(lambda x, y: x * y, [4])
4
"""
reduced = seq[0]
for x in seq[1:]:
reduced = combiner(reduced,... | bigcode/self-oss-instruct-sc2-concepts |
def anglicize1to19(n):
"""
Returns the English equiv of n.
Parameter: the integer to anglicize
Precondition: n in 1..19
"""
if n == 1:
return 'one'
elif n == 2:
return 'two'
elif n == 3:
return 'three'
elif n == 4:
return 'four'
elif n == 5:
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def dejmps_gates_and_measurement_alice(q1, q2):
"""
Performs the gates and measurements for Alice's side of the DEJMPS protocol
:param q1: Alice's qubit from the first entangled pair
:param q2: Alice's qubit from the second entangled pair
:return: Integer 0/1 indicating Alice's measure... | bigcode/self-oss-instruct-sc2-concepts |
def min_max_norm(x):
""" Performs min-max normalization --> scales values in range between 1 and 0
:param x (1-D array like)
:return: (1-D np.array) min-max normalized input
"""
mini = min(x)
maxi = max(x)
return (x - mini) / (maxi - mini) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import torch
def pad_sequences_from_list(array: List[List[int]]) -> torch.Tensor:
"""Performs post padding on sequences to make sequences same length.
Adds padding with id 0
Args:
array (List[List[int]]): List of list of token_ids
Returns:
torch.Tensor: Padded... | bigcode/self-oss-instruct-sc2-concepts |
def clean_country_names(df):
"""
Given a dataframe with only 1 column 'country/region'
cleans country names
"""
cleaned_df = df.replace({'country/region':
{'US': 'United States',
'Taiwan*': 'Taiwan',
'Kor... | bigcode/self-oss-instruct-sc2-concepts |
def get_cik_path(cik):
"""
Get path on EDGAR or S3 for a given CIK.
:param cik: company CIK
:return:
"""
return "edgar/data/{0}/".format(cik) | 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.