seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def sql_from_dtype(dtype):
"""Returns a sql datatype given a pandas datatype
Args:
dtype (str): The pandas datatype to convert
Returns:
str: the equivalent SQL datatype
Examples:
>>> sql_from_dtype('bool')
'boolean'
>>> sql_from_dtype('float64')
'numeri... | bigcode/self-oss-instruct-sc2-concepts |
def escape_ass_tag(text: str) -> str:
"""Escape text so that it doesn't get treated as ASS tags.
:param text: text to escape
:return: escaped text
"""
return text.replace("\\", r"\\").replace("{", r"\[").replace("}", r"\]") | bigcode/self-oss-instruct-sc2-concepts |
import base64
def encode_base64(input_bytes: bytes, urlsafe: bool = False) -> str:
"""Encode bytes as an unpadded base64 string."""
if urlsafe:
encode = base64.urlsafe_b64encode
else:
encode = base64.b64encode
output_bytes = encode(input_bytes)
output_string = output_bytes.decode... | bigcode/self-oss-instruct-sc2-concepts |
def quicksort(lst):
"""quicksort with filter and lambda"""
if not lst:
return lst
else:
pivot, *rest = lst
return (
quicksort(list(filter(lambda x: x < pivot, rest)))
+ [pivot] +
quicksort(list(filter(lambda x: x >= pivot, rest)))
) | bigcode/self-oss-instruct-sc2-concepts |
def _CheckEnum(value, name, values=None):
"""Checks whether value is a member of the set of values given.
Args:
value: The value to check.
name: The name of the value, to use in error messages.
values: The iterable of possible values.
Returns:
The checked value.
Raises:
ValueError: If the... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility... | bigcode/self-oss-instruct-sc2-concepts |
def get_background_genes_file(filepath):
"""
Get background genes from local file for null-hypothesis formulation.
"""
gene_list = []
with open(filepath) as file_gene:
for line in file_gene:
gene_list.append(line.strip())
return gene_list | bigcode/self-oss-instruct-sc2-concepts |
def uch_leung(us, ut):
"""
Choking velocity based on Equation 6 from Leung [2]_. All parameters must
be in units of ft/s or in units of m/s.
Parameters
----------
us : float
Solids velocity [ft/s or m/s]
ut : float
Terminal velocity of a single particle [ft/s or m/s]
Re... | bigcode/self-oss-instruct-sc2-concepts |
def is_windows_path(path):
"""Checks if the path argument is a Windows platform path."""
return '\\' in path or ':' in path or '|' in path | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def count_even(obj: Union[list, int]) -> int:
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
>>> count_even(3)
0
>>> count_even(16)
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def local_to_utc(dtime, zoneinfo=None):
"""Convert local time to UTC time"""
if dtime.tzinfo is not None:
return dtime - dtime.utcoffset()
year, month, day = dtime.year, dtime.month, dtime.day
hour, minute = dtime.hour, dtime.minute
return datetime(year, mont... | bigcode/self-oss-instruct-sc2-concepts |
def choices_help_text(choices):
"""Return a clear text for choices.
Args:
choices: list of tuples (value, label)
Returns:
a text in the form:
enum1: label1
enum2: label2
"""
choises_str = ('{enum}: {label}'.format(enum=choice[0], label=choice[1]) for choice... | bigcode/self-oss-instruct-sc2-concepts |
def _shape(tensor):
"""Get the shape of a tensor as an int list."""
return tensor.get_shape().as_list() | bigcode/self-oss-instruct-sc2-concepts |
def tipo(inpt, keep_module: bool = True) -> str:
"""
Return the name of an object's type
params:
keep_module
If set to False, the name of the class will be returned without any explicit reference to package nesting
"""
if isinstance(inpt, type):
inpt = str(inpt)
if ke... | bigcode/self-oss-instruct-sc2-concepts |
def replace_corrupted_instruction(script, instruction_index):
"""
Return the copy of a script with the command (JMP or NOP) of a given instruction replaced.
"jmp" -> "nop"
"nop" -> "jmp"
"""
# Copy the script and get the instruction by index.
new_script = script.copy()
instruction = s... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def commit_datetime_string(dt: datetime):
"""
Return a string representation for a commit's timestamp.
Args:
dt: datetime object with tzinfo
Returns:
string representation (should be localized)
"""
return dt.strftime("%c %z") | bigcode/self-oss-instruct-sc2-concepts |
import copy
def get_settings(settings_module):
"""
Get a copy of the settings (upper-cased variables) declared in the given settings module.
:param settings_module: A settings module
:type settings_module: module
:return: Dict of settings
:rtype: dict[str, object]
"""
return copy.deep... | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate(number_of_seeds, seed=None):
"""Uses pythons random integer generator to create a set of unique random
seeds.
Parameters
----------
number_of_seeds : int
number of seeds to generate.
seed : int, optional
The random seed to intialize the generator wit... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_images(images):
"""Normalize image values."""
return images.float().div_(255.0).mul_(2.0).add_(-1) | bigcode/self-oss-instruct-sc2-concepts |
import time
def wait_for_task(task, timeout=300):
"""
Wait for a task to complete
"""
timeout_time = time.time() + timeout
timedout = True
while time.time() < timeout_time:
if task.info.state == 'success':
return (True, task.info.result)
if task.info.state == 'error... | bigcode/self-oss-instruct-sc2-concepts |
from importlib import import_module
def get_code(path):
"""
Given "core.utils:get_code", imports the module "core.utils" and returns
"get_code" from it.
"""
module_name, member_name = path.split(':')
module = import_module(module_name)
return getattr(module, member_name) | bigcode/self-oss-instruct-sc2-concepts |
import math
def ceiling(x, y):
"""
Returns number rounded up, away from zero, to the nearest multiple
of significance. For example, if you want to avoid using pennies in
your prices and your product is priced at $4.42, use the formula
ceiling(4.42,0.05) to round prices up to the nearest nickel.
... | bigcode/self-oss-instruct-sc2-concepts |
def map_dtype_name_to_pixel_type(dtype_name):
"""
Performs mapping of ndarray underlying data type to
proper pixel data type
:param: dtype_name: name of data type representation
of underlying np.ndarray
:return: String representing the correct pixel data type
"""
if dtype_name == 'float1... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_valid_file_category_id(category_id):
"""
Validates a file lifecycle category ID, also known as the categories "category-ext-name".
A valid category ID should look like: category-00000001 - It should
always start with "category-" and end with 8 hexadecimal characters in lower
case.... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_severity_at_baseline(mean_pre_test_treatment, maximum_on_clinical_scale):
"""Normalizes the pre-test scores in order to include them in the SAOB analysis.
Parameters
----------
mean_post_test_treatment: float
Mean score after the treatment.
maximum_on_clinical_sca... | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def _calculate_address_pool(addrmask, ipv6=False):
"""
Return a pool of addresses contained in the network.
@param addrmask: Network in IP/mask format.
@return: A list of ip addresses
"""
if ipv6:
netobj = ipaddress.IPv6Network(addrmask, strict=False)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def _must_be_updated(today_date, last_modification, allowed_age):
"""
:param today_date: Today's date.
:type today_date: datetime.date
:param last_modification: Date of file's last modification.
:type last_modification: datetime.date
:param allowed_age: Maximum age allowed between today and last... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def extract_module_name(obj, full=False):
"""
Get the name of a module for an object.
"""
properties = inspect.getmembers(obj)
for name, value in properties:
if name == '__module__':
if full:
return value.split('.')[-1]
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def product_first_image_alt(product):
"""
Returns main product image alt for seo
"""
all_images = product.images.all()
alt_text =all_images[0].alt if all_images else ''
return alt_text | bigcode/self-oss-instruct-sc2-concepts |
def stripFilename(fname):
""" Strip the path and extension from the filename. """
return str(fname).split("\\")[-1].split(".")[0] | bigcode/self-oss-instruct-sc2-concepts |
import math
def decantor(z):
"""Inverse Cantor"""
w = math.floor(math.sqrt(8 * z + 1) / 2 - 0.5)
t = ((w + 1) * w) / 2
y = z - t
x = w - y
return int(x), int(y) | bigcode/self-oss-instruct-sc2-concepts |
def clean_headers(hdr_tuples, invalid_hdrs=None):
"""
Given a list of header tuples, filters out tuples with empty header names
or in the specified invalid header names list.
"""
if hdr_tuples is None:
return list()
clean_tuples = list()
for entry in hdr_tuples:
if not entry[... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_batch(x):
"""
Flattens a batch of arrays to one dimension.
Args:
x (numpy.ndarray): A batch of arrays to be flattened.
Returns:
numpy.ndarray, a flattened one dimension array.
"""
return x.reshape(x.shape[0], -1) | bigcode/self-oss-instruct-sc2-concepts |
def generate_lhs_tokens(distribution, rng):
"""Generate a set of tokens to build production rules for."""
# Iteration order over a set is apparently non-deterministic, so use a list instead...
tokens = []
token_pool = list(distribution.keys())
token_probabilities = list(distribution.values())
wh... | bigcode/self-oss-instruct-sc2-concepts |
def Likelihood(evidence, hypo):
"""Computes the likelihood of the evidence assuming the hypothesis is true.
Args:
evidence: a tuple of (number of heads, number of tails)
hypo: float probability of heads
Returns:
probability of tossing the given number of heads and tails with a
... | bigcode/self-oss-instruct-sc2-concepts |
def check_permissions(required_permission, payload):
""" Check if required permission exists in the verified token's payload.
Parameters:
required_permission (string|list):
A string describing the type of permission.
e.g: get:drinks, post:drinks, ['get:drinks', '... | bigcode/self-oss-instruct-sc2-concepts |
def detect_publisher(fstring):
""" Detect the publisher of a html file by searching for unique strings
:param fstring: document HTML or XML text
:type: byte string
:returns: publisher name as a unique string
"""
if b'<meta name="dc.Identifier" scheme="doi" content="10.1021/' in fstring:
... | bigcode/self-oss-instruct-sc2-concepts |
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code bloc... | bigcode/self-oss-instruct-sc2-concepts |
def _make_dictnames(tmp_arr, offset=0):
"""
Helper function to create a dictionary mapping a column number
to the name in tmp_arr.
"""
col_map = {}
for i,col_name in enumerate(tmp_arr):
col_map.update({i+offset : col_name})
return col_map | bigcode/self-oss-instruct-sc2-concepts |
def get_ids(df_cat, prd_col, cli_col):
"""
Obtain Client and Produtct IDs positions
Parameters
----------
df_cat: pandas Data Frames
Representation of df_long, with prd_col and cli_col as categories.
prd_col: str
Name of the column containing the ProductIDs.
cli_col: str
... | bigcode/self-oss-instruct-sc2-concepts |
def sphinx_role(record, lang):
"""
Return the Sphinx role used for a record.
This is used for the description directive like ".. c:function::", and
links like ":c:func:`foo`.
"""
kind = record["kind"]
if kind in ["class", "function", "namespace", "struct", "union"]:
return lang + ... | bigcode/self-oss-instruct-sc2-concepts |
def card_name(value, suit):
"""
Constructs a name for the card, using the given value,
and suit.
:arg str value:
The value to use.
:arg str suit:
The suit to use.
:returns:
A newly constructed name, using the given value & suit.
"""
if value == "Joker":
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_string(str, start, end):
""" Returns the string between start and end. """
s = str.find(start)
if s < 0:
return None
slen = len(start)
e = str.find(end, s + slen)
if e < 0:
return None
return str[s + slen:e] | bigcode/self-oss-instruct-sc2-concepts |
def gf_lshift(f, n, K):
"""
Efficiently multiply ``f`` by ``x**n``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_lshift
>>> gf_lshift([3, 2, 4], 4, ZZ)
[3, 2, 4, 0, 0, 0, 0]
"""
if not f:
return f
else:
return ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _signed_area(path: torch.Tensor) -> torch.Tensor:
"""
Calculates the signed area / Lévy area of a 2D path. If the path is closed,
i.e. ends where it starts, this is the integral of the winding number over
the whole plane. If not, consider a closed path made by adding a straight
li... | bigcode/self-oss-instruct-sc2-concepts |
def readKeyValueCSV(filename):
"""
Reads a key-value csv file and returns the contents as a python dictionary. @filename is the path to the file.
returns: file contents as <dictionary>
"""
# Resultant dictionary.
result = {}
# Read file and collect key-value pairs into result.
with open(filename, "r") as... | bigcode/self-oss-instruct-sc2-concepts |
def total_rain(rain_hours: list) -> int:
"""
Sum up the rain mm from list of rain hours
"""
if len(rain_hours) > 0:
return round(sum([list(x.values())[0]['1h'] for x in rain_hours]), 2)
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def match(p1, p2, common):
"""Return whether clauses in common match.
Arguments:
p1 {np.array} -- first possibility
p2 {np.array} -- second possibility
common {(str,int,int)} -- common clauses
Returns:
True/False -- Do clauses in common match?
"""
for c in common:
... | bigcode/self-oss-instruct-sc2-concepts |
def write_int_ranges(int_values, in_hex=True, sep=" "):
"""From a set or list of ints, generate a string representation that can be
parsed by parse_int_ranges to return the original values (not
order_preserving)."""
if not int_values:
return ""
num_list = []
int_values = iter(sorted(i... | bigcode/self-oss-instruct-sc2-concepts |
def build_flow(steps):
"""Builds a flow from a list of steps, by chaining the steps according to their order in the list.
Nested lists are used to represent branches in the flow.
Examples:
build_flow([step1, step2, step3])
is equivalent to
step1.to(step2).to(step3)
build_fl... | bigcode/self-oss-instruct-sc2-concepts |
import time
def toc(tic):
"""Returns the time since 'tic' was called."""
return time.perf_counter() - tic | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _schema_get_docstring(starting_class):
""" Given a class, return its docstring.
If no docstring is present for the class, search base classes in MRO for a
docstring.
"""
for cls in inspect.getmro(starting_class):
if inspect.getdoc(cls):
return inspect.getdoc... | bigcode/self-oss-instruct-sc2-concepts |
def values_to_dict(values):
""" Each row from the spreadsheet is converted to a dict using the first row as the keys.
:param values: a list of lists containing the values of a spreadsheet loaded with the sheets api.
The first row is considered to contain the header information.
:returns: a list of d... | bigcode/self-oss-instruct-sc2-concepts |
def human_time(s):
"""Convert floating-point seconds into human-readable time"""
if s < 60.0: return "%.3f" % s
m = int(s) / 60
if m < 60: return "%d:%06.3f" % (m, s % 60)
return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60) | bigcode/self-oss-instruct-sc2-concepts |
def composition(f, g):
"""Return a composition of two functions
"""
def fg(arg):
return g(f(arg))
return fg | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_fuel_requirement(mass):
"""Calculates the fuel requirement
based on the given mass. (Part 1)
Parameters:
mass (int): mass of the module
Returns:
int:Fuel required
"""
return math.floor(mass / 3) - 2 | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import struct
def unpack_uint64s(data: bytes) -> List[int]:
""" Unpack a series of integers that were packed with pack_uint64."""
if len(data) == 0:
return []
return list(x[0] for x in struct.iter_unpack(">Q", data)) | bigcode/self-oss-instruct-sc2-concepts |
def unique_responses(group_responses: list) -> list:
"""
From the list of group responses, pick out the unique responses.
Args:
group_responses [list] : A list of of lists. Each sub-list contains each
groups' person's responses.
Returns:
list [str] : A list of lists, with d... | bigcode/self-oss-instruct-sc2-concepts |
def calc_tot_orbits(n_orbit_dict):
"""Calculate the total number of direct and indirect orbits in
n_orbit_dict.
Parameters
----------
n_orbit_dict : dictionary
A dictionary where each key is an object in the system and each value
is a tuple of 2 values. The first represents the numb... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def getyrdoy(date):
"""Return a tuple of year, day of year for a supplied datetime object.
Parameters
----------
date : datetime.datetime
Datetime object
Returns
-------
year : int
Integer year
doy : int
Integer day of year
"... | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_df(df):
"""
Select the english captions and extract only the desired columns from the dataframe like 'Name' and 'Description'
df: dataframe which contains the captions
"""
df = df[df['Language'] == 'English'].copy()
df['Name'] = df[['VideoID', 'Start', 'End']].apply(lambda x: x['... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import re
def update_weight_name(repl_patterns: Dict[str, str], weight_name: str) -> str:
"""Updates weight names according a dictionary of replacement patterns."""
# Create a regular expression from all of the dictionary keys
regex = re.compile('|'.join(map(re.escape, repl_patterns.keys... | bigcode/self-oss-instruct-sc2-concepts |
def _RemoveRedundantHandlers(handler_list):
"""Removes duplicated or unnecessary handlers from the list.
If a handler's pattern and functionality are fully matched by another handler
with a more general pattern, we do not need the first handler. At the same
time, we remove duplicates.
Args:
handler_lis... | bigcode/self-oss-instruct-sc2-concepts |
import aiohttp
async def request(url, *, headers=None, **kwargs):
"""Base GET request in case you need more control over GET requests.
Params
=======
headers: dict (Optional)
kwarg: kwargs (Optional)
Returns
=======
Response: aiohttp Response object
"""
async with aiohttp.Cli... | bigcode/self-oss-instruct-sc2-concepts |
def _date_within( some_date, start_date, end_date ):
"""
check if start_date <= some_date <= end_date ,
considering inequality to be true if either
start_date or end_date is None
"""
result = True # start with a truth assumption
if start_date is not None:
result = resu... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def aud_to_usd(aud_amount, date):
"""Convert the AUD amount to USD."""
r = requests.get("https://api.fixer.io/{}?base=USD".format(date))
j = r.json()
rate = j["rates"]["AUD"]
return aud_amount / rate | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Any
from typing import List
def unpack_response(response: dict) -> Tuple[Any, List[str]]:
"""Unpack response from dictionary and fetch ranking and keywords."""
assert isinstance(response, dict), "Empty response. Try again."
rankings = [*response[[*response][0]]... | bigcode/self-oss-instruct-sc2-concepts |
def _preprocess(sentences, preprocess_pipeline, word_tokenize=None):
"""
Helper function to preprocess a list of paragraphs.
Args:
param (Tuple): params are tuple of (a list of strings,
a list of preprocessing functions, and function to tokenize
setences into words). A parag... | bigcode/self-oss-instruct-sc2-concepts |
def extract_task_ids(project_data):
"""
Extract from project data the list of task id
:param project_data: Dictionary of project data of a HOT tasking manager project
:return:
"""
tasks_ids = list()
for feature in project_data['tasks']['features']:
tasks_ids.append(feature['propertie... | bigcode/self-oss-instruct-sc2-concepts |
def _FirewallTargetTagsToCell(firewall):
"""Comma-joins the target tags of the given firewall rule."""
return ','.join(firewall.get('targetTags', [])) | bigcode/self-oss-instruct-sc2-concepts |
def WMSBBOX(region):
""" Return the WMS BBOX query string for this region
Returns:
string: BBOX=w,s,e,n
"""
(n,s,e,w) = region.NSEW()
return 'BBOX=%f,%f,%f,%f' % (w,s,e,n) | bigcode/self-oss-instruct-sc2-concepts |
def GateBranches(x, **unused_kwargs):
"""Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memor... | bigcode/self-oss-instruct-sc2-concepts |
def text(meta):
"""
Returns the meta message's text as a string.
"""
return meta[3].decode('ascii') | bigcode/self-oss-instruct-sc2-concepts |
def get_r12_squared(r1, r2):
"""Get the distance between two centers in Cartesian space."""
return (r1[0] - r2[0])**2.0 + (r1[1] - r2[1])**2.0 + (r1[2] - r2[2])**2.0 | bigcode/self-oss-instruct-sc2-concepts |
def hierarchical_label(*names):
"""
Returns the XNAT label for the given hierarchical name, qualified
by a prefix if necessary.
Example:
>>> from qixnat.helpers import hierarchical_label
>>> hierarchical_label('Breast003', 'Session01')
'Breast003_Session01'
>>> hierarchical_lab... | bigcode/self-oss-instruct-sc2-concepts |
def train_test(df):
"""
split into train and test set
train contains Jan 1, 2018 through July 31, 2018
test contains August 1, 2018 through September 28, 2018
:param df:
:return:
"""
df = df[df['Date'] >= '2018-01-01']
train = df[df['Date'] < '2018-08-01']
test = df[df[... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_regex(tentative_regex: str):
""" Returns true if the argument is a valid python regex, and false otherwise. """
if len(tentative_regex) == 0:
return False
try:
re.compile(tentative_regex)
return True
except re.error:
return False | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def load_vocab(vocab_path):
""" Loading a vocabulary file
:param vocab_path: Path to vocabulary file
:return: Array contains words
"""
with codecs.open(vocab_path, encoding="utf-8") as fobj:
vocab = fobj.readlines()
return vocab | bigcode/self-oss-instruct-sc2-concepts |
import math
def ceil(number):
"""
Return the ceiling of a number as an int.
This is the smallest integral value >= number.
Example:
>>> ceil(1.5)
2
Arguments:
number (float): A numeric value.
Returns:
int: Smallest integer >= number.
Raises:
TypeError: If argument ... | bigcode/self-oss-instruct-sc2-concepts |
def _combine_field_specs(field_specs, exclude_fields):
"""
take a list of FieldSpec objects and return a sorted list where field is unique
and fields in exclude_fields are removed, and where the first mention of a
field in field_specs will win out over any repeats.
"""
combined_field_specs = {... | bigcode/self-oss-instruct-sc2-concepts |
def halflife_to_phi(rho, dt=1):
"""Convert half-life to the AR(1) propagation parameter phi"""
phi = 0.5 ** (dt / rho)
# st_dev = st_dev * np.sqrt(1 - phi**2)
return phi | bigcode/self-oss-instruct-sc2-concepts |
def remove_unreadable_characters_at_start(string):
"""
Removes non ASCII characters from the string start as eggPlant files often begin with some strange symbols.
The string gets also stripped (blank characters at start and end will be removed)
:param string:
:return: the processed string
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def coin_total_usd(coin: str, amount: float, tickers: dict) -> float:
"""
Get value of coin in USD
:param coin: coin symbol from balance
:param amount: total amount of coin from balance
:param tickers: raw tickers fetched from binance
:return: value of coin in USD as float
"""
price_in_b... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cross_entropy(pred, target):
"""
"Proper" cross entropy between distributions.
:param pred: predicted logits
:type pred: torch.autograd.Variable
:param target: target distributions
:type target: torch.autograd.Variable
:return: loss
:rtype: torch.autograd.Variable
... | bigcode/self-oss-instruct-sc2-concepts |
def find_default_vpc(session, region_name):
"""
Looks for every default VPC in a region
:param session: Boto3 Session
:param region_name: The region name to look in
:return: list of vpc id's
"""
result = []
client = session.client("ec2", region_name)
response = client.describe_vpcs(
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def to_polar_coordinates(x, y):
"""Convert the 2D pixel coordinates to polar coordinates
:param x: x coordinate of the point
:param y: y coordinate of the point
:returns: tuple -- (r,phi) of the point as polar coordinates
"""
theta = math.atan2(y, x)
if theta < 0:
thet... | bigcode/self-oss-instruct-sc2-concepts |
def run_replace(block: str, replace_dict: dict) -> str:
"""Replace routine for dealing with n-grams.
:param block: Contains the text block replacement is done on
:param replace_dict: {token: replacement_token}
:return: Occurrences of token replaced with replacement_token
"""
for k in replace_d... | bigcode/self-oss-instruct-sc2-concepts |
def get_class_by_name(classes_dict, class_name, default):
""" Get a class given its name.
Parameters
----------
classes_dict : dict
Dict with the form {class_name: class}
class_name : str
Class name.
default: class
Class to be used if class_name is not in classes_dict.
... | bigcode/self-oss-instruct-sc2-concepts |
def mse(df, y:str, yhats:list):
"""
Calculates Mean Squared Error.
Args:
df: pandas dataframe
y: name of column with actual data
yhats: list of column names with estimated data
Returns:
df: containing the MPE for each column
"""
columns_to_keep = yhats + [y]
... | bigcode/self-oss-instruct-sc2-concepts |
def degree_to_order(degree):
"""Compute the order given the degree of a B-spline."""
return int(degree) + 1 | bigcode/self-oss-instruct-sc2-concepts |
import types
def copy_function(function, module=None, name=None):
"""
Copy a function and optionally change its name and module definition
"""
name = name if name else function.__name__
module = module if module else function.__module__
new_function = types.FunctionType(
function.__co... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import imghdr
def is_image(url) -> bool:
"""
Determine if it is an image of png or jpeg.
Parameters
----------
url : str
Target url.
Returns
-------
True or False: Return True if this url content is an image of png or jpeg else returns False.
"""
img = r... | bigcode/self-oss-instruct-sc2-concepts |
def slope_intercept_form(m, x, b):
"""
Handles the formula used for y=mx+b format to find slope
"""
m = float(m)
x = float(x)
b = float(b)
return m * x + b | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Union
def to_number(s: Any) -> Union[int, float]:
"""Cast the string representation of the given object to a number (int or float), or raise ValueError."""
try:
return int(str(s))
except ValueError:
return float(str(s)) | bigcode/self-oss-instruct-sc2-concepts |
def longest_range(index_list):
"""
select longest index range
eg. [1, 0, 1, 1, 1] ==> (2, 5)
@param index_list: list, element is 0 or 1
@return: a tuple (a, b). a is the range begin, and b is the range off end.
"""
range_list = []
begin = 0
for i in range(len(index_list) - 1):
... | bigcode/self-oss-instruct-sc2-concepts |
def openreadlines(filename, xform=None):
"""Open a file and return a list of all its lines.
xform -- a function to run on all lines"""
with open(filename, "r", encoding="utf-8") as infp:
return [xform(x) if xform else x for x in infp] | bigcode/self-oss-instruct-sc2-concepts |
def set_dict_values(d, value):
"""
Return dict with same keys as `d` and all values equal to `value'.
"""
return dict.fromkeys(d, value) | bigcode/self-oss-instruct-sc2-concepts |
def check_http_code_in_output(http_code, error_message=None):
"""Create a callable to ensure that the given HTTP error code is present in the
output of the response.
Args:
http_code (int): the HTTP error code to check.
error_message (str, optional): the message that will be displayed if the... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def apply_tform(tform, verts):
"""
Applies a 4x4 rigid transform to a list of points
:param tform: tensor (batch, 4, 4)
:param verts: tensor (batch, N, 3)
:return:
"""
verts_homo = torch.cat((verts, torch.ones(verts.shape[0], verts.shape[1], 1, device=verts.device)), 2)
ne... | bigcode/self-oss-instruct-sc2-concepts |
def _should_ignore(class_reference, property_name):
"""Check if a property should be ignored."""
if not hasattr(class_reference, "__deserialize_ignore_map__"):
return False
return class_reference.__deserialize_ignore_map__.get(property_name, False) | 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.