seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def cleaned_code(arg):
"""
Strip discord code blocks
"""
arg = arg.strip('`')
if arg.startswith('py'):
arg = arg[2:]
return arg.strip() | bigcode/self-oss-instruct-sc2-concepts |
def edge_index_set_equiv(a, b):
"""Compare edge_index arrays in an unordered way."""
# [[0, 1], [1, 0]] -> {(0, 1), (1, 0)}
a = a.numpy() # numpy gives ints when iterated, tensor gives non-identical scalar tensors.
b = b.numpy()
return set(zip(a[0], a[1])) == set(zip(b[0], b[1])) | bigcode/self-oss-instruct-sc2-concepts |
def reverse_geometric_key(string):
"""Reverse a geometric key string into xyz coordinates."""
xyz = string.split(',')
return [float(i) for i in xyz] | bigcode/self-oss-instruct-sc2-concepts |
def chooseSize(string):
"""
Determines appropriate latex size to use so that the string fits in RAVEN-standard lstlisting examples
without flowing over to newline. Could be improved to consider the overall number of lines in the
string as well, so that we don't have multi-page examples very often.
... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def shinglify(clean_text):
"""
Generates list of 'shingles': crc sums of word subsequences of default length
:param clean_text: cleaned text to calculate shingles sequence.
:return: shingles sequence
"""
shingle_length = 3
result = []
for idx in range(len(clean_text) - ... | bigcode/self-oss-instruct-sc2-concepts |
def plot_arrow(ax, x1, y1, x2, y2, shrink_a=1, shrink_b=1, connectionstyle="arc3,rad=0", arrow_style="<-"):
""" This function plots arrows of the task schematic
:param ax: Axis object
:param x1: x-position of starting point
:param y1: y-position of starting point
:param x2: x-position of end point
... | bigcode/self-oss-instruct-sc2-concepts |
def writeResults(Patterns, df):
"""
utility function to write patterns in a pandas dataframe
Parameters
----------
Patterns : list
list of patterns
df : pandas dadaframe
input dataframe
Returns
-------
pandas dadaframe
updated dataframe
"""
for pat i... | bigcode/self-oss-instruct-sc2-concepts |
def is_ip_per_task(app):
"""
Return whether the application is using IP-per-task.
:param app: The application to check.
:return: True if using IP per task, False otherwise.
"""
return app.get('ipAddress') is not None | bigcode/self-oss-instruct-sc2-concepts |
def map_atoms(indices, nres_atoms=1):
""" Map the indices of a sub-system to indices of the full system
:param indices: indices of atoms to map with respect to full system
:param nres_atoms: number of atoms per residue
:type indices: list
:type nres_atoms: int
:return: dictionary of mapped in... | bigcode/self-oss-instruct-sc2-concepts |
def match_token(token, tok_type, tok_str=None):
"""Returns true if token is of the given type and, if a string is given, has that string."""
return token.type == tok_type and (tok_str is None or token.string == tok_str) | bigcode/self-oss-instruct-sc2-concepts |
import time
def wait_until(somepredicate, timeout, period=0.1, *args, **kwargs):
"""Waits until some predicate is true or timeout is over."""
must_end = time.time() + timeout
while time.time() < must_end:
if somepredicate(*args, **kwargs):
return True
time.sleep(period)
ret... | bigcode/self-oss-instruct-sc2-concepts |
def crop_to_subarray(data, bounds):
"""
Crop the given full frame array down to the appropriate
subarray size and location based on the requested subarray
name.
Parameters
----------
data : numpy.ndarray
Full frame image or ramp. (x,y) = (2048, 2048)
May be 2D, 3D, or 4D
... | bigcode/self-oss-instruct-sc2-concepts |
def get_rpath_deps(pkg):
"""Return immediate or transitive RPATHs depending on the package."""
if pkg.transitive_rpaths:
return [d for d in pkg.spec.traverse(root=False, deptype=('link'))]
else:
return pkg.spec.dependencies(deptype='link') | bigcode/self-oss-instruct-sc2-concepts |
def double_factorial(n: int) -> int:
"""
Compute double factorial using recursive method.
Recursion can be costly for large numbers.
To learn about the theory behind this algorithm:
https://en.wikipedia.org/wiki/Double_factorial
>>> import math
>>> all(double_factorial(i) == math.prod(rang... | bigcode/self-oss-instruct-sc2-concepts |
def is_even(value: int) -> str:
"""Return 'even' or 'odd' depending on if the value is divisible by 2."""
if value % 2 == 0 or value == 0:
return 'even'
else:
return 'odd' | bigcode/self-oss-instruct-sc2-concepts |
def dtool_lookup_config(dtool_config):
"""Provide default dtool lookup config."""
dtool_config.update({
"DTOOL_LOOKUP_SERVER_URL": "https://localhost:5000",
"DTOOL_LOOKUP_SERVER_TOKEN_GENERATOR_URL": "http://localhost:5001/token",
"DTOOL_LOOKUP_SERVER_USERNAME": "testuser",
"DTOO... | bigcode/self-oss-instruct-sc2-concepts |
def update_minmax(array, val_min, val_max, matrix, il, xl, ilines_offset, xlines_offset):
""" Get both min and max values in just one pass through array.
Simultaneously updates (inplace) matrix if the trace is filled with zeros.
"""
maximum = array[0]
minimum = array[0]
for i in array[1:]:
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def circunference(rad) -> float:
"""Returns the surface length of a circle with given radius."""
return 2 * math.pi * rad | bigcode/self-oss-instruct-sc2-concepts |
def known_words(word_list, lm_vocab):
"""
Filters out from a list of words the subset of words that appear in the vocabulary of KNOWN_WORDS.
:param word_list: list of word-strings
:return: set of unique words that appear in vocabulary
"""
return set(filter(lambda word: word in lm_vocab, word_lis... | bigcode/self-oss-instruct-sc2-concepts |
def minSize(split, mined):
"""
Called by combineCheck() to ensure that a given cleavage or peptide is larger than a given minSize.
:param split: the cleavage or peptide that is to have its size checked against max size.
:param mined: the min size that the cleavage or peptide is allowed to be.
:re... | bigcode/self-oss-instruct-sc2-concepts |
def simple_substitute(text, alphabet, code):
"""
Used to encode or decode the given text based on the provided alphabet.
PARAMS:
plaintext (string): The message you want to encode
alphabet (dictionairy[char] = char): Key is plaintext char, value is the substitute. Enter the same alphabet for... | bigcode/self-oss-instruct-sc2-concepts |
def func_ideal_length(target_position, no_probe_sites):
"""Finds the optimum length between insertion sites, based on the nucleotide length"""
length = target_position[-1] - target_position[0] #length of sequence available for probe sites
no_intervals = no_probe_sites - 1 #number of intervals between probe ... | bigcode/self-oss-instruct-sc2-concepts |
def var_replace(eq, var, new):
"""
Replace all instances of string var with string new.
This function differs from the default string replace method in
that it only makes the replace if var is not contained inside a
word.
Example:
eq = "-1j*kx*v*drho -drhodz*dvz -1.0*dz(dvz) - drho"
var... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def xgcd(a: int, b: int) -> Tuple[int, int, int]:
"""Extended Euclidean algorithm.
Finds :code:`gcd(a,b)` along with coefficients :code:`x`, :code:`y` such that
:code:`ax + by = gcd(a,b)`.
Args:
a: first number
b: second number
Returns:
gcd(a,b),... | bigcode/self-oss-instruct-sc2-concepts |
def get_line_starts(s):
"""Return a list containing the start index of each line in s.
The list also contains a sentinel index for the end of the string,
so there will be one more element in the list than there are lines
in the string
"""
starts = [0]
for line in s.split('\n'):
sta... | bigcode/self-oss-instruct-sc2-concepts |
def find_ns_subelements(element, subelement_name, ns_dict):
"""
retuns list of subelements with given name in any given namespace
Arguments:
- element (ElementTee.Element): main element to search in
- subelement_name (string): searched name of element
- ns_dict: dict of ... | bigcode/self-oss-instruct-sc2-concepts |
def all_params(params, funcs):
"""
Combined list of params + funcs, used in the test
"""
return params + funcs | bigcode/self-oss-instruct-sc2-concepts |
from operator import mul
def text_color(bg):
"""
Determine text color based off background color.
Parameters
----------
bg : tuple[int]
Background RGB color.
Returns
-------
tuple[int]
Foreground RGB color.
"""
luminance = sum(map(mul, (0.299, 0.587, 0.114), b... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_valid_input(service_name):
"""
Validate the input.
Args:
service_name (str): the name of the service. given as an argument to the module
Returns:
bool: True if the input is valid, else False.
"""
if re.match("^[A-Za-z0_]*$", service_name):
return True... | bigcode/self-oss-instruct-sc2-concepts |
def min_reconstruction_scale(ls_min, ls_max):
"""
Calculate the smallest scale in phi that can be reconstructed
successfully. The calculation is given by Eq. (9) in Cooray et al.
2020b.
Parameters
----------
ls_min : float
Lower limit of lamdba squared in the observed spectrum... | bigcode/self-oss-instruct-sc2-concepts |
def nogil(request):
"""nogil keyword argument for numba.jit"""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def applies_to_product(file_name, product):
"""
A OVAL or fix is filtered by product iff product is Falsy, file_name is
"shared", or file_name is product. Note that this does not filter by
contents of the fix or check, only by the name of the file.
"""
if not product:
return True
r... | bigcode/self-oss-instruct-sc2-concepts |
def drop_cols(data_frame, columns):
"""
Remove columns from data frame
"""
for col in columns:
data_frame = data_frame.drop([col], axis=1)
return data_frame | bigcode/self-oss-instruct-sc2-concepts |
def help_flag_present(argv: list[str], flag_name: str = 'help') -> bool:
"""
Checks if a help flag is present in argv.
:param argv: sys.argv
:param flag_name: the name, which will be prefixed with '-', that is a help flag. The default value is 'help'
:return: if the help flag is present
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_fraction(lsnp1, lsnp2):
"""Return the fraction of reads supporting region1."""
reg1_fraction = []
for index in range(len(lsnp1)):
sumdepth = lsnp1[index] + lsnp2[index]
if sumdepth == 0:
reg1_fraction.append(0)
else:
reg1_fraction.append(float(lsnp1[in... | bigcode/self-oss-instruct-sc2-concepts |
def bool_eval(token_lst):
"""token_lst has length 3 and format: [left_arg, operator, right_arg]
operator(left_arg, right_arg) is returned"""
return token_lst[1](token_lst[0], token_lst[2]) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def basic_logger(name, level):
"""
Returns a basic logger, with no special string formatting.
Parameters
----------
name : str
The name of the logger.
level : int
An integer, such as `logging.INFO`, indicating the desired severity
level. As in the `loggi... | bigcode/self-oss-instruct-sc2-concepts |
def get_headers(data, extra_headers=None):
"""
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
"""
response_headers = {
"Content-Length": str(len(data)),
}
if extra_headers:
response_... | bigcode/self-oss-instruct-sc2-concepts |
def unfold(vc: set, folded_verts: list):
"""
Compute final vc given the partial vc and list of folded vertices (unreversed)
:param vc: partial vc as a set
:param folded_verts: list of folded vertices as 3-tuples
:return: final vertex cover as a set
"""
final_vc = set(vc)
for u, v, w in f... | bigcode/self-oss-instruct-sc2-concepts |
def find_shops(index: dict, products: list) -> set:
"""
Find all the shops that contain all the products
:param index: Index of products
:param products: Products to match
:return: Set of all shops that sell all mentioned products
"""
try:
final_set = index[products[0]] # Initial in... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize_filename(filename: str) -> str:
"""
Make the given string into a filename by removing
non-descriptive characters.
:param filename:
:return:
"""
return re.sub(r'(?u)[^-\w.]', '', filename) | bigcode/self-oss-instruct-sc2-concepts |
def df_variant_id(row):
"""Get variant ID from pyvcf in DataFrame"""
if row['ID'] != '.':
return row['ID']
else:
return row['CHROM'] + ':' + str(row['POS']) | bigcode/self-oss-instruct-sc2-concepts |
def get_hd_domain(username, default_domain='default'):
"""Returns the domain associated with an email address.
Intended for use with the OAuth hd parameter for Google.
Args:
username: Username to parse.
default_domain: Domain to set if '@suchandsuch.huh' is not part of the
username. Defaults to ... | bigcode/self-oss-instruct-sc2-concepts |
def generate_term(n):
"""Generates nth term in the Fibonacci sequence"""
assert n >= 1
if n == 1:
return 1
elif n == 2:
return 2
else:
return generate_term(n-1) + generate_term(n-2) | bigcode/self-oss-instruct-sc2-concepts |
def abbr(name):
""" Return abbreviation of a given name.
Example:
fixed-effect -> f10t
per-member -> p8r
"""
return name if len(name) <= 2 else f"{name[0]}{len(name) - 2}{name[-1]}" | bigcode/self-oss-instruct-sc2-concepts |
def is_isogram(string):
"""Checks whether a given string is isogram or not. Returns a boolean."""
string = string.lower().replace(' ', '').replace('-', '')
return len(string) == len(set(string)) | bigcode/self-oss-instruct-sc2-concepts |
def parse_one_column_table(data_table):
"""Parse tables with only one column"""
output_list = []
data_rows = data_table.find_all("tr")[1:]
for data_row in data_rows:
data_cells = data_row.find_all("td")
for data_cell in data_cells:
try:
output_list.append(data... | bigcode/self-oss-instruct-sc2-concepts |
import shelve
def read_net_cp(namefile):
"""Read pre-computed network cp assignation."""
db = shelve.open(namefile)
cps = db['cps']
net = db['net']
methodvalues = db['methodvalues']
db.close()
return cps, net, methodvalues | bigcode/self-oss-instruct-sc2-concepts |
def dh_number_digest(g_val: int, p_val: bytes) -> int:
"""Determine hash value for given DH parameters.
Arguments:
g_val: the value g
p_val: the value p
Returns:
a hash value for the given DH parameters.
"""
return hash((g_val, p_val)) | bigcode/self-oss-instruct-sc2-concepts |
def time_to_str(delta_t, mode="min"):
"""Convert elapsed time to string representation
Parameters
--------
delta_t: time difference
Elapsed time
mode: str
Time representation manner, by "minitues" or "seconds".
Returns
--------
delta_str: str
Elapsed time string... | bigcode/self-oss-instruct-sc2-concepts |
def find_squeezenet_layer(arch, target_layer_name):
"""Find squeezenet layer to calculate GradCAM and GradCAM++
Args:
arch: default torchvision densenet models
target_layer_name (str): the name of layer with its hierarchical information. please refer to usages below.
target_layer_na... | bigcode/self-oss-instruct-sc2-concepts |
def is_word_guessed(secret_word, letters_guessed):
"""
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the le... | bigcode/self-oss-instruct-sc2-concepts |
import math
def sinh(x):
"""Get sinh(x)"""
return math.sinh(x) | bigcode/self-oss-instruct-sc2-concepts |
def norm_to_max(vals):
"""Normalizes items in vals relative to max val: returns copy."""
best = max(vals)
return [i/best for i in vals] | bigcode/self-oss-instruct-sc2-concepts |
def prefix_string() -> str:
"""Use string as prefix."""
return "test" | bigcode/self-oss-instruct-sc2-concepts |
def _abs(arg):
"""Returns the absolute value."""
return abs(arg) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def node_values_for_tests() -> List[Any]:
"""[summary]
Returns:
List[Any]: list of potential node values
"""
return [1, 2, 3, 4, 5, 6, 7, "spam", "sausage"] | bigcode/self-oss-instruct-sc2-concepts |
def add_chars() -> bytes:
"""Returns list of all possible bytes for testing bad characters"""
# bad_chars: \x00
chars = b""
chars += b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
chars += b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
chars += b"\x20\x21\x2... | bigcode/self-oss-instruct-sc2-concepts |
import math
def xy_yaw_from_quaternion(quat):
"""Calculate the yaw angle in the xy plane from a rotation quaternion.
:param quat: A unit quaternion representing the
:type quat: Any container that has numerical values in index 0, 1, 2 and 3
:return: The yaw angle in radians projected on the xy plane
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def option_selected(variable: Any, testvalue: Any) -> str:
"""
Returns ``' selected="selected"'`` if ``variable == testvalue`` else
``''``; for use with HTML select options.
"""
return ' selected="selected"' if variable == testvalue else '' | bigcode/self-oss-instruct-sc2-concepts |
def handle_args(pwb_py, *args):
"""Handle args and get filename.
@return: filename, script args, local args for pwb.py
@rtype: tuple
"""
fname = None
index = 0
for arg in args:
if arg.startswith('-'):
index += 1
else:
fname = arg
if not fn... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def is_active_user(user: Dict) -> bool:
"""
Returns true if the user is active and not the bot
:param user: the user to check
:return: boolean if user is active
"""
return (user is not None
and not user['deleted']
and not user['is_restricted']
... | bigcode/self-oss-instruct-sc2-concepts |
import types
def copy_func(f, name=None):
"""
Return a function with same code, globals, closure, and name (or provided name).
"""
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
# If f has been given attributes
fn.__dict__.upda... | bigcode/self-oss-instruct-sc2-concepts |
def __eq__(self, other):
"""Common `__eq__` implementation for classes which has `__slots__`."""
if self.__class__ is not other.__class__:
return False
return all(getattr(self, attr) == getattr(other, attr)
for attr in self.__slots__) | bigcode/self-oss-instruct-sc2-concepts |
def compute_delta(num_levels):
"""Computes the delta value from number of levels
Arguments
---------
num_levels : int
The number of levels
Returns
-------
float
"""
return num_levels / (2.0 * (num_levels - 1)) | bigcode/self-oss-instruct-sc2-concepts |
def _replace_slash(s, replace_with="__"):
"""Conda doesn't suppport slashes. Hence we have
to replace it with another character.
"""
return s.replace("/", replace_with) | bigcode/self-oss-instruct-sc2-concepts |
def _set_object_from_model(obj, model, **extra):
"""Update a DesignateObject with the values from a SQLA Model"""
for fieldname in obj.FIELDS:
if hasattr(model, fieldname):
if fieldname in extra.keys():
obj[fieldname] = extra[fieldname]
else:
obj[... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_class(cls_name: str) -> type:
"""
Converts a string into the class that it represents
NB: Code based on https://stackoverflow.com/questions/452969/does-python
-have-an-equivalent-to-java-class-forname
:param cls_name: The string representation of the desired class
:return: A pointer ... | bigcode/self-oss-instruct-sc2-concepts |
def rescol(rescol):
""" Comfirms that a give value is a valid results column and returns
the corresponding units column and results column.
"""
if rescol.lower() == 'concentration':
unitscol = 'units'
elif rescol.lower() == 'load_outflow':
unitscol = 'load_units'
else:
ra... | bigcode/self-oss-instruct-sc2-concepts |
def ContentTypeTranslation(content_type):
"""Translate content type from gcloud format to API format.
Args:
content_type: the gcloud format of content_type
Returns:
cloudasset API format of content_type.
"""
if content_type == 'resource':
return 'RESOURCE'
if content_type == 'iam-policy':
... | bigcode/self-oss-instruct-sc2-concepts |
def get_fk_model(model, fieldname):
"""returns None if not foreignkey, otherswise the relevant model"""
field_object, model, direct, m2m = model._meta.get_field_by_name(fieldname)
if direct and field_object.get_internal_type() in [
"ForeignKey",
"OneToOneField",
"ManyToManyField",
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_circuit_ordering(file):
"""Loads a circuit ordering (e.g. mapping from spin-orbitals to qubits) to a file.
Args:
file (str or file-like object): the name of the file, or a file-like object.
Returns:
ordering (list)
"""
if isinstance(file, str):
wi... | bigcode/self-oss-instruct-sc2-concepts |
def when_did_it_die(P0, days):
"""
Given a P0 and an array of days in which it was alive, censored or dead,
figure out its lifespan and the number of days it was alive'
Note, the lifespan is considered to last up to the last observation.
I.e., a worm that was observed to live 3 days, and died o... | bigcode/self-oss-instruct-sc2-concepts |
def op_to_dunder_unary(op: str) -> str:
"""Return the dunder method name corresponding to unary op."""
if op == '-':
return '__neg__'
elif op == '+':
return '__pos__'
elif op == '~':
return '__invert__'
else:
return op | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def int_version(name: str, version: str) -> List[int]:
"""splits the version into a tuple of integers"""
sversion = version.split('-')[0].split('+')[0].split('a')[0].split('b')[0].split('rc')[0]
#numpy
#scipy
#matplotlib
#qtpy
#vtk
#cpylog
#pyNastran
# '... | bigcode/self-oss-instruct-sc2-concepts |
def is_natural_number(*arr):
"""Check if the numbers are natural number (includes zero).
:param arr: number array
:return: True if are natural number, or False if not
"""
for n in arr:
if n < 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from typing import FrozenSet
def _overlap(set_a: FrozenSet, set_b: FrozenSet) -> bool:
"""Return True if there are overlapping items in set_a and set_b, otherwise return False.
# Passes as both sets have element 'b'
>>> _overlap(frozenset({'a', 'b'}), frozenset({'b', 'c'}))
True
# Fails as there... | bigcode/self-oss-instruct-sc2-concepts |
async def read_root():
"""Displays greeting message in homepage
Returns:
dict: a dictionary with greeting message
"""
return {"message": "✌"} | bigcode/self-oss-instruct-sc2-concepts |
def prefix(text: str): # NOTE: PEP 616 solved this in python version 3.9+
"""
Takes the first word off the text, strips excess spaces and makes sure to always return
a list containing a prefix, remainder pair of strings.
"""
segmented = text.split(' ', 1)
# ensure a list of 2 elements unpacked i... | bigcode/self-oss-instruct-sc2-concepts |
def ifexists(total_pages, page_no):
"""
This function checks whether the given page number is in the specified range
of total pages.
:param total_pages:
:param page_no:
:return: True or False
"""
if page_no <= total_pages:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def NoShifter(*args, **kwargs):
"""
Dummy function to create an object that returns None
Args:
*args: will be ignored
*kwargs: will be ignored
Returns:
None
"""
return None | bigcode/self-oss-instruct-sc2-concepts |
def hpa_to_mmhg(pressure: int) -> int:
"""
Converts pressure in hpa to mmhg
Args:
pressure: pressure to convert
Returns: pressure in mmhg
"""
return int(pressure * 0.75006156130264) | bigcode/self-oss-instruct-sc2-concepts |
def unemployment_rate(earning, earning_new, unemployment):
"""
Args:
earning: how much money the player earned last round
earning_new: how much money the player earned this round
unemployment: unemployment rate of the player had last round
Returns: unemplo... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def verify_assign_and_read(obj: Any, attr: str, value: Any) -> Any:
"""
Assign value to attribute, read and return result.
Assert that values can be mutated and read before and after mutation.
"""
try:
setattr(obj, attr, value)
except AttributeError:
rai... | bigcode/self-oss-instruct-sc2-concepts |
import tqdm
def find_stable_phases(all_compounds, criteria):
"""
find all compounds with e_above_hull within given range of zero
args:
all_compounds - returned from load_compounds (list of dicts)
criteria - criteria for a stable phase in meV
output:
list of dicts of stable phas... | bigcode/self-oss-instruct-sc2-concepts |
def parse_channal_response(channel=dict()):
"""
Parse channel dict to extract key metadata, including:
id, title, description, viewCount, videoCount, subscriberCount
:param channel: a dictionary containing all metadata of a channel
:return:
"""
result = {}
result['id'] = channel['id']
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def azimuthal_average(image, center=None):
# modified to tensor inputs from https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/
"""
Calculate the azimuthally averaged radial profile.
Requires low frequencies to be at the center of the image.
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def has_diff_value(dict_obj, key, value):
"""Returns True if dict_obj contains key, and its value is something other than value."""
return key in dict_obj and dict_obj[key] != value | bigcode/self-oss-instruct-sc2-concepts |
import re
def isolate_punctuation(text):
""" Isolate punctuation in a sentence.
>>> split_punctuation('Hi there!')
'Hi there !'
Args:
text (str): Input sentence
Returns:
str: Output sentence with isolated punctuation
"""
text = re.sub('([.,!?()])', r' \1 ', text)
tex... | bigcode/self-oss-instruct-sc2-concepts |
def integral(shift, op, elements, accumulator):
""" Inverse of derivative.
Scans a list of elements using an accumulator. Returns the integral of the elements and the final state of the accumulator.
----------
shift : Shift of -1 is an exclusive scan and a shift of 1 is an inclusive scan.
op : Opera... | bigcode/self-oss-instruct-sc2-concepts |
def get_scaled(x, y, radius, image):
"""Scales x y and raius whose values are from 0 to 1 to int values."""
scaled_x = int(x*image.shape[1])
scaled_y = int(y*image.shape[0])
scaled_radius = int(radius*max(image.shape[1], image.shape[0]))
return (scaled_x, scaled_y, scaled_radius) | bigcode/self-oss-instruct-sc2-concepts |
import fnmatch
def filename_match(filename, patterns, default=True):
"""Check if patterns contains a pattern that matches filename.
If patterns is not specified, this always returns True.
"""
if not patterns:
return default
return any(fnmatch.fnmatch(filename, pattern) for pattern in patt... | bigcode/self-oss-instruct-sc2-concepts |
import math
def truncate_floor(number, decimals):
"""Truncates decimals to floor based on given parameter
Arguments:
number {float} -- number to truncate
decimals {int} -- number of decimals
Returns:
float -- truncated number
"""
return math.floor(number * 10 ** decimals)... | bigcode/self-oss-instruct-sc2-concepts |
import random
def convkey(x, left=False, right=False):
"""Turns a numerical salary value into a string preserving comparison."""
assert not (left and right)
if left:
appendix = '0'
elif right:
appendix = '9'
else:
appendix = '5'
appendix += ''.join(chr(random.randrange(... | bigcode/self-oss-instruct-sc2-concepts |
def _return_features(data, features):
"""Select specific raw features from the data
:param data: The data set to manipulate.
:param features: A list of ISXC 2012 IDS specific features.
:return: List of data with just the chosen features in the order
they were requested.
"""
process... | bigcode/self-oss-instruct-sc2-concepts |
def return_module(module):
"""Mock for importlib.reload(). Returns argument."""
return module | bigcode/self-oss-instruct-sc2-concepts |
def predict_proba_model(model, X_score):
"""Uses a trained scikit-learn model to predict class probabilities for the
scoring data"""
return model.predict_proba(X_score)[:, 1] | bigcode/self-oss-instruct-sc2-concepts |
import pytz
def localize_date(date, city):
""" Localize date into city
Date: datetime
City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'..
"""
local = pytz.timezone(city)
local_dt = local.localize(date, is_dst=None)
return local_dt | bigcode/self-oss-instruct-sc2-concepts |
def set_common_keys(dict_target, dict_source):
""" Set a dictionary using another one, missing keys in source dictionary are reported"""
keys_missing=[]
for k in dict_target.keys():
if k in dict_source.keys():
dict_target[k]=dict_source[k]
else:
keys_missing.append(k)... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def accuracy(logits, labels):
"""
Compute accuracy of given forward pass through network.
Parameters:
- - - - -
logits: torch tensor
output of single network forward pass
labels: torch tensor
ground truth class of each sample
Returns:
- - - -
float s... | 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.