seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_facts(device):
"""
Determines ifd_style fact based on the personality.
"""
ifd_style = "CLASSIC"
if device.facts["personality"] == "SWITCH":
ifd_style = "SWITCH"
elif device.facts["personality"] == "JDM":
ifd_style = None
return {
"ifd_style": ifd_style,
... | bigcode/self-oss-instruct-sc2-concepts |
def left_part_of(txt, sub_txt, n=1):
"""
Return the left part before the nth of sub_txt appeared in txt.
:param txt: text
:param sub_txt: separate text
:param n: the nth of sub_txt(default:1)
"""
parts = txt.split(sub_txt)
return sub_txt.join(parts[:n]) | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_query(allkeys, revealed):
"""Selects a uniform random range to query."""
(a,ac), (b,bc) = sorted(random.sample(allkeys, 2))
revealed.add(ac)
revealed.add(bc)
return a, b + 0.01 | bigcode/self-oss-instruct-sc2-concepts |
def str_to_bool(s: str):
"""Return a boolean for the given string, follows the same semantics systemd does."""
if s.lower() in ('1', 'yes', 'true', 'on'):
return True
elif s.lower() in ('0', 'no', 'false', 'off'):
return False
else:
raise NotImplementedError(f"Unknown boolean val... | bigcode/self-oss-instruct-sc2-concepts |
def clamp(n, minn, maxn):
"""
Clamp a value 'n' within the range 'minn' and 'maxn'.
:param n: value to be clamped
:param minn: lower bound of clamp
:param maxn: upper bound of clamp
:returns:
* **clamped_val** - value within the range of 'minn' and 'm... | bigcode/self-oss-instruct-sc2-concepts |
import json
import dataclasses
import pytz
from datetime import datetime
def put_release(client, bucket, key, release):
"""
Upload a new release to S3.
Arguments:
client (botocore.client.S3): client for AWS S3.
bucket (str): bucket's name.
key (str): object's key.
release ... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def rename_file(source: Path, destination_path: Path):
"""
Helper function that renames file to reflect new path. If a file of the same
name already exists in the destination folder, the file name is numbered and
incremented until the filename is unique (prevents overwriting f... | bigcode/self-oss-instruct-sc2-concepts |
def clean(synonyms):
"""
Returns the deduped, sorted list of synonyms
"""
deduped_synonyms = list(set([s.strip() for s in synonyms]))
deduped_synonyms.sort()
return deduped_synonyms | bigcode/self-oss-instruct-sc2-concepts |
def get_imag(input, input_type="linear", channels_axis=1):
"""Returns the imaginary components of the complex-valued input.
Arguments
---------
input : torch.Tensor
Input tensor.
input_type : str,
(convolution, linear) (default "linear")
channels_axis : int.
Default 1.
... | bigcode/self-oss-instruct-sc2-concepts |
def smooth(scalars, weight):
"""Smooth scalar array using some weight between [0, 1]. This is the tensorboard implementation
For comparison with @ewma, see https://github.com/theRealSuperMario/notebook_collection
Parameters
----------
scalars : np.array
array of scalars
weight : fl... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string(choose_from=None, length=8):
"""
Return a random sequence of characters
Args:
choose_from (Sequence): he set of eligible characters - by default
the set is string.ascii_lowercase + string.digits
length (int): the length of the sequ... | bigcode/self-oss-instruct-sc2-concepts |
def to_upper(word: str):
"""
Make the 'word' parameter uppercase
:param word: string to be uppercase
:return: uppercase string
"""
return word.upper() | bigcode/self-oss-instruct-sc2-concepts |
def dnsDomainLevels(host):
"""
:param str host: is the hostname from the URL.
:return: the number (integer) of DNS domain levels (number of dots) in the hostname.
:rtype: int
"""
return host.count('.') | bigcode/self-oss-instruct-sc2-concepts |
def extract_mentioned_users(text_string, remove_users=True):
"""
Extracts mentioned_users from a text_string
:param text_string: String of text you wish to extract mentioned_users from
:param remove_users: Boolean, if True it will remove the mentioned_users from the text_string
:return: text_sting... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def send_telegram_message(msg):
""" Utility to send message to telegram groups """
base_url = "https://api.telegram.org/bot589160362:AAHEeNBIeh3m3RA07lANaDHovy874xNFi1g/sendMessage"
chat_id_one = "-294841384" # Signal Testing
chat_id_two = "-464227511" # Signal Development
msg ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def isPropVar(s):
"""
Check, whether the string s can be interpreted as a propositional variable.
"""
return re.fullmatch('[A-Za-z][A-Za-z0-9<>,]*', s) | bigcode/self-oss-instruct-sc2-concepts |
def is_bool(x):
"""Tests if something is a boolean."""
return isinstance(x, bool) | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_config(config_file=None):
"""
Read a set of JSON formatted configs and store as dictionary
:param config_file: location of file with JSON formatted config
:return: dictionary with messages/statuses
"""
config = {}
if not config_file:
return config
buf = o... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def flatten_feature_map(feature_map):
"""
Flatten input tensor from [batch, y, x, f] to [batch, y*x*f]
Args:
feature_map: tensor with shape [batch, y, x, f]
Returns:
reshaped_map: tensor with shape [batch, y*x*f]
"""
map_shape = feature_map.get_shape()
if(map_... | bigcode/self-oss-instruct-sc2-concepts |
def reverseComplement(read):
"""
Returns the reverse complemnt of read
:param read: a string consisting of only 'A', 'T', 'C', 'G's
"""
complementDict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
return ''.join([complementDict[c] for c in read[::-1]]) | bigcode/self-oss-instruct-sc2-concepts |
def convert(tree,fileName=None):
"""
Converts input files to be compatible with merge request #460:
- Removes "all" node
- Sets default variable names
@ In, tree, xml.etree.ElementTree.ElementTree object, the contents of a RAVEN input file
@ In, fileName, the name for the raven input file
@O... | bigcode/self-oss-instruct-sc2-concepts |
def _get_nodes_mac_addresses(task, node):
"""Get all mac addresses for a node."""
for r in task.resources:
if r.node.id == node['id']:
return [p.address for p in r.ports] | bigcode/self-oss-instruct-sc2-concepts |
import time
def timestamp_2_datetime(timestamp, fmt):
""" 将时间戳转换成指定格式的日期字符串
:param timestamp: 原始时间戳
:param fmt: 时间格式
"""
return time.strftime(fmt, time.localtime(timestamp)) | bigcode/self-oss-instruct-sc2-concepts |
def user_directory_path(instance, filename):
"""
Obtain the upload path, including the filename. File will be uploaded to
settings.MEDIA_ROOT/<username>/<filename> if user is authenticated, and
to settings.MEDIA_ROOT/anon_usr/<filename> otherwise.
instance: An instance of the model where the FileF... | bigcode/self-oss-instruct-sc2-concepts |
def client(app):
"""return an instance of the application's test client"""
return app.test_client() | bigcode/self-oss-instruct-sc2-concepts |
import logging
def log_aucs(**aucs):
"""Log and tabulate AUCs given as nested dictionaries in the format '{model: {label: auc}}'"""
def dashes(n): return '-' * n
header = "{:<35} {:<20} {:<15}"
row = "{:<35} {:<20} {:<15.10f}"
width = 85
logging.info(dashes(width))
for auc_name, auc_value... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_string(length):
"""Return a random string of a certain length."""
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
for _ in range(length)
) | bigcode/self-oss-instruct-sc2-concepts |
def slice_name_to_components( slice_name ):
"""
Decomposes a slice name into a map of its unique components. This is the
inverse of build_slice_name(). Also handles slice_name's which have been
converted into a path or URL as a prefix.
Takes 1 argument:
slice_name - String specifying the s... | bigcode/self-oss-instruct-sc2-concepts |
import ssl
import asyncio
import aiohttp
async def get(session, url):
"""Wrapper for session.get() that returns None if the HTTP GET call failed.
Args:
session:
url:
Returns:
2-tup
status_code: int
body_str: str
"""
try:
async with session.... | bigcode/self-oss-instruct-sc2-concepts |
import re
def text_cleanup(text):
"""
1. Replace HTML tags with punctuations
2. Remove digits in given text as they would interfere
3. Remove single characters in given text
4. Reduce multiple spaces in given text to single space
:param text: Raw article text
:return: preprocessed art... | bigcode/self-oss-instruct-sc2-concepts |
def generate_valid_queue_entry(**overrides):
"""
This functions generate a valid queue entry.
If you want to override the value, provide an object with the same property names
"""
return {
"studentName": "Frinze",
"studentNumber": "22711649",
"unitCode": "CITS3403",
"... | bigcode/self-oss-instruct-sc2-concepts |
def mkt_cap_format(x):
"""
Formats number to millions of dollars.
Params:
x (numeric, like int or float) the number to be formatted
Example:
mkt_cap_format(3000000)
mkt_cap_format(4490000)
"""
return "${:.1f}M".format(x/1000000) | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def read_from_config_file(filepath: str):
"""
Read from the generated configparser file path, return the settings and the configparser object
Parameters
----------
filepath
absolute filepath to the configparser object
Returns
-------
configparser.ConfigPar... | bigcode/self-oss-instruct-sc2-concepts |
def check_detection_overlap(gs, dd):
"""
Evaluates if two detections overlap
Paramters
---------
gs: list
Gold standard detection [start,stop]
dd: list
Detector detection [start,stop]
Returns
-------
overlap: bool
Whether two events overlap.
"""
ov... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid(sg, logger, args):
"""
Validate our args.
:param sg: Shotgun API handle.
:param logger: Logger instance.
:param args: Any additional misc arguments passed through this plugin.
:returns: True if plugin is valid, None if not.
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
import re
def list_files(url, tag=''):
"""
Function to create a list of the NetCDF data files in the THREDDS catalog created by a request to the M2M system.
:param url: URL to user's THREDDS catalog specific to a data request
:param tag: regex pattern used... | bigcode/self-oss-instruct-sc2-concepts |
import random
def qubit_shot(i_mean: float, q_mean: float, i_std: float, q_std: float):
"""Creates a random IQ point using a Gaussian distribution.
Args:
i_mean: mean of I distribution
q_mean: mean of Q distribution
i_std: standard deviation of I distribution
q_std: standard d... | bigcode/self-oss-instruct-sc2-concepts |
def _get_ndims(x):
"""Returns the number of dimensions of a TensorFlow Tensor or a numpy array like object.
Both objects have a different method to get the number of dimensions. Numpy arrays have a .ndim attribute,
whereas TensorFlow tensors have a .shape.ndims and a .rank attribute.
Args:
x: ... | bigcode/self-oss-instruct-sc2-concepts |
def MergeResultsFromMultipleFiles(results_by_file, info_levels):
"""Merge multiple results to show occurrences in files and range of values.
Args:
results_by_file: A dict of check results indexed by file name.
info_levels: A list of report levels to merge. E.g., ['warning', 'error']
Returns:
A dict ... | bigcode/self-oss-instruct-sc2-concepts |
def print_adjacent_bases(bases, sequence):
"""
Print a summary of the bases preceding removed adapter sequences.
Print a warning if one of the bases is overrepresented and there are
at least 20 preceding bases available.
Return whether a warning was printed.
"""
total = sum(bases.values())
if total == 0:
ret... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def deque_slice(deque, start, end=-1):
""" return a sliced part of a deque as a list """
if end == -1:
end = len(deque)
return list(itertools.islice(deque, start, end)) | bigcode/self-oss-instruct-sc2-concepts |
import functools
def get_n_trainable_parameters(model):
"""This funtion calculates the number of trainable parameters
of the model
Arguments:
model {nn.Module} -- model
Returns:
int -- the number of trainable parameters of the model
"""
cnt = 0
for param in list(... | bigcode/self-oss-instruct-sc2-concepts |
def is_even(number: int) -> bool:
"""
Test if a number is a even number.
:param number: the number to be checked.
:return: True if the number is even, otherwise False.
>>> is_even(-1)
False
>>> is_even(-2)
True
>>> is_even(0)
True
>>> is_even(3)
False
>>> is_even(4)
... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def introduction(request):
""" Return a configuration for contributing examples to the
Demo application.
Parameters
----------
request : dict
Information provided by the demo application.
Currently this is a placeholder.
Returns
-------
response :... | bigcode/self-oss-instruct-sc2-concepts |
def read_stopwords(path):
"""
Loads stop words.
:param path: path to file containing the smart stop words
:return: set containing all stop words
"""
stopwords = set()
with open(path, "r") as file_stopwords:
for line in file_stopwords:
line = line.rstrip()
if l... | bigcode/self-oss-instruct-sc2-concepts |
def strip_whitespaces(tpl):
""" Strip white spaces before and after each item """
return [item.strip() for item in tpl] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
from typing import Any
def is_nested(dictionary: Mapping[Any, Any]) -> bool:
"""Returns if passed 'contents' is nested at least one-level.
Args:
dictionary (dict): dict to be tested.
Returns:
bool: indicating whether any value in the 'contents' is also a
... | bigcode/self-oss-instruct-sc2-concepts |
def to_sparse_fillna(df, mean):
"""fills Nan's in sparse df with mean of df, returns dataframe"""
df_filled = df.fillna(mean)
return df_filled | bigcode/self-oss-instruct-sc2-concepts |
def textual_list(items, join_word="or", empty="(nothing)"):
"""Lists items in humanized list form.
e.g.
>>> textual_list(['foo', 'bar', 'baz'])
'foo', 'bar' or 'baz'
"""
if not items:
return empty
items = list(items)
last_item = items.pop()
items_list = ", ".join("'{}'".for... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def getsha512(filename):
"""
This function computes the SHA512 sum of a file
:param filename: path+filename of file to compute SHA512 sum for
:return: hexidecimal sha512 sum of file.
"""
sha512_hash = hashlib.sha512()
with open(filename,"rb") as f:
# Read and update... | bigcode/self-oss-instruct-sc2-concepts |
def devilry_multiple_users_verbose_inline(users):
"""
Returns the provided iterable of user objects HTML formatted.
Perfect for formatting lists of users inline, such as when showing examiners
or candidates on a group.
"""
return {
'users': users
} | bigcode/self-oss-instruct-sc2-concepts |
def type_error_message(func_name: str, expected: str, got: str) -> str:
"""Return an error message for function func_name returning type got,
where the correct return type is expected."""
return ('{0} should return a {1}, but returned {2}' +
'.').format(func_name, expected, got) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import typing
def is_non_empty_dir(expected_dir: Path) -> typing.List[str]:
"""Assert that directory exists, and that it's not empty.
Returns:
A list of errors found, or empty if successful.
"""
errs = []
if expected_dir.is_dir():
for child in expected_dir.iterdir():
... | bigcode/self-oss-instruct-sc2-concepts |
def check_issubset(to_check, original):
"""
Check that contain of iterable ``to_check`` is among iterable ``original``.
:param to_check:
Iterable with elements to check.
:param original:
Iterable with elements to check to.
:return:
Boolean.
"""
s = set()
# Need th... | bigcode/self-oss-instruct-sc2-concepts |
def get_name_frame_code(GOP_struct, idx_code):
"""
Return a list of name (frame_i) with all frames that have
coding_order = <idx_code> in the given GOP structure <GOP_struct>.
"""
name_frame_code = []
for f in GOP_struct:
if GOP_struct.get(f).get('coding_order') == idx_code:
... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_string(output):
"""Removes unwanted characters from output string."""
return output.replace("\t", " ") | bigcode/self-oss-instruct-sc2-concepts |
def __digit(value):
"""
Converts hex to digit
"""
return int(value, 16) | bigcode/self-oss-instruct-sc2-concepts |
def _get_filepath_components(filepath):
"""
Splits filepath to return (path, filename)
"""
components = filepath.rsplit("/", 1)
if len(components) == 1:
return (None, components[0])
return (components[0], components[1]) | bigcode/self-oss-instruct-sc2-concepts |
def ship_name(fleet, designated_no):
"""Return ship's name for specified designated number
from the fleet."""
# has dictionary a key? Use syntax: key in dictionary
if designated_no in fleet:
return fleet[designated_no] | bigcode/self-oss-instruct-sc2-concepts |
def normalize_tag(tag):
"""
Drops the namespace from a tag and converts to lower case.
e.g. '{https://....}TypeName' -> 'TypeName'
"""
normalized = tag
if len(tag) >= 3:
if tag[0] == "{":
normalized = tag[1:].split("}")[1]
return normalized.lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def anagrams_cntr(str1, str2):
"""This function takes two strings and compares if they are Anagram using Counter."""
return Counter(str1.lower()) == Counter(str2.lower()) | bigcode/self-oss-instruct-sc2-concepts |
def approx_first_derivative(fun, x, h):
"""
Function to approximate the first derivative through central differences
args:
fun (function): function that will be approximated
x (float): value where the function will be centered
h (float): finite step that will be taken... | bigcode/self-oss-instruct-sc2-concepts |
def strZip(list1, list2, string):
""" Return a list of strings of the form x1stringx2 where x1
and x2 are elements of list1 and list2 respectively.
"""
result = []
for x1, x2 in zip(list1, list2):
result.append(str(x1)+string+str(x2))
return result | bigcode/self-oss-instruct-sc2-concepts |
def palindrome(word):
"""Return True if the given word is a palindrome."""
return word == word[::-1] | bigcode/self-oss-instruct-sc2-concepts |
import aiohttp
async def text_callback(resp: aiohttp.ClientResponse) -> str:
"""Returns the response result as text.
Mostly useful for endpoints that returns just text on its output. Some
examples::
$ curl ifconfig.me/ip
123.123.123.123
$ curl 'wttr.in/?format=%t'
+31°C
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_activity_masks(df):
"""Split activities into three groups depending if other activities.
Tell if activity is first (trip end), intermediate (can be deleted), or last (trip starts).
First and last are intended to overlap.
Parameters
----------
df : DataFrame
DataFrame with bool... | bigcode/self-oss-instruct-sc2-concepts |
def delta(n_1, n_2) -> int:
"""Kronicka-delta function, yields 1 if indexing is the same, else zero."""
if n_1 == n_2:
return 1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def parse_arn(arn):
"""
Parses an ARN (Amazon Resource Identififier).
:param arn: The arn as a string
:returns: A dictionary with all as entries
"""
parts = arn.split(':')
sections = {
'owner': parts[1],
'service': parts[2],
'region': parts[3],
'account_id': ... | bigcode/self-oss-instruct-sc2-concepts |
def copy_grid(grid):
"""Copy grid."""
return [row[:] for row in grid] | bigcode/self-oss-instruct-sc2-concepts |
def flatten(l):
"""Flatten a singly nested list.
Examples
--------
>>> flatten([[0,1,2], [4,5]])
[0, 1, 2, 4, 5]
"""
return [item for sublist in l for item in sublist] | bigcode/self-oss-instruct-sc2-concepts |
def _includes(opt):
"""
Return the #include directives for the user-defined list of include files.
"""
includes = []
if opt.include_files is not None and len(opt.include_files) > 0:
for include_file in opt.include_files:
if include_file[0] == '"' or include_file[0] == '<':
... | bigcode/self-oss-instruct-sc2-concepts |
def _var2numpy(var):
"""
Make Variable to numpy array. No transposition will be made.
:param var: Variable instance on whatever device
:type var: Variable
:return: the corresponding numpy array
:rtype: np.ndarray
"""
return var.data.cpu().numpy() | bigcode/self-oss-instruct-sc2-concepts |
def make_help_cmd(cmd, docstring):
"""
Dynamically define a twill shell help function for the given
command/docstring.
"""
def help_cmd(message=docstring, cmd=cmd):
print('=' * 15)
print('\nHelp for command %s:\n' % cmd)
print(message.strip())
print()
print('=... | bigcode/self-oss-instruct-sc2-concepts |
def is_connectable(bnode, cnode):
"""
>>> bnode = {'entry': {'pos': 'N'}}
>>> cnode = {'entry': {'pos': 'J-K'}}
>>> is_connectable(bnode, cnode)
True
>>> bnode = {'entry': {'pos': 'V-Y'}}
>>> cnode = {'entry': {'pos': 'V-S'}}
>>> is_connectable(bnode, cnode)
False
"""
ctable ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _add_docstring_to_top_level_func(line: str, docstring: str) -> str:
"""
Add docstring to the top-level function line string.
Parameters
----------
line : str
Target function line string.
e.g., `def sample_func(a: int) -> None:`
docstring : str
... | bigcode/self-oss-instruct-sc2-concepts |
def bool_to_str(bool_val):
"""convert boolean to strings for YAML configuration"""
if not isinstance(bool_val, bool):
raise TypeError("The bool_val is required to be boolean type")
return "true" if bool_val else "false" | bigcode/self-oss-instruct-sc2-concepts |
import slugify
def create_slug(s: str) -> str:
"""Convert a plain string into a slug.
A slug is suitable for use as a URL. For instance, passing ``A new world``
to this function will return ``a-new-world``.
"""
return slugify.slugify(s) | bigcode/self-oss-instruct-sc2-concepts |
def get_boundaries(bucket_names):
"""
Get boundaries of pandas-quantized features.
>>> bucket_names = ["whatever_(100.0, 1000.0)", "whatever_(-100.0, 100.0)"]
>>> get_boundaries(bucket_names)
[(100.0, 1000.0), (-100.0, 100.0)]
"""
boundaries = []
for bucket_name in bucket_names:
... | bigcode/self-oss-instruct-sc2-concepts |
def _normalize_vendor(vendor):
"""Return a canonical name for a type of database."""
if not vendor:
return "db" # should this ever happen?
if "sqlite" in vendor:
return "sqlite"
if "postgres" in vendor or vendor == "psycopg2":
return "postgresql"
return vendor | bigcode/self-oss-instruct-sc2-concepts |
def days_in_minutes(days):
"""
Returns int minutes for float DAYS.
"""
return days * 60 * 24 | bigcode/self-oss-instruct-sc2-concepts |
def splice_data(data: str, width: int, height: int) -> list[str]:
"""Splice a data chunk into a number of layers
:param data: Image pixels
:param width: Image width in pixels
:param height: Image height in pixels
:return: List of layer of pixels
"""
layer_length = width * height
assert ... | bigcode/self-oss-instruct-sc2-concepts |
def split_by_indel_size(df):
""" Sort 1-nt and >1-nt indels
Args:
df (pandas.DataFrame)
Returns:
df_mono (pandas.DataFrame): df for 1-nt indels
df_non_mono (pandas.DataFrame): df for >1-nt indels
"""
df_mono = df[df["indel_size"] == 1]
df_non_mono = df[df["indel_size"] > ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def jacobian(f, x, out_dim):
"""Computes Jacobian of a vector-valued function.
Given f: batch_size x input_dim -> batch_size x output_dim
Computes Jacobian Matrix J: batch_size x output_dim x input_dim
By passing a gradient matrix to the backward call of the output tensor
NOTE:
... | bigcode/self-oss-instruct-sc2-concepts |
def check_op(op):
"""
:param op: op to be checked
:return: op if acceptable, raise error if not
"""
acceptable_op = ["=", ">=", "<=", "CONTAINS", "!!=", ">", "<", "<>", "IS NULL", "IS NOT NULL"]
if op not in acceptable_op:
raise KeyError("'op' sent ('%s') not acceptable. Please check yo... | bigcode/self-oss-instruct-sc2-concepts |
def get_model_image(model_name, image_name: str = ""):
"""
Auxiliary function to get the image of the model
:param model_name: model name
:param image_name: image name
:return: image path
:rtype: str
"""
path_name = (
f"images/{model_name}/{model_name}.png"
if not image_n... | bigcode/self-oss-instruct-sc2-concepts |
def build_group_dict(groups:list) -> dict:
"""Build a dict of groups, code -> group."""
group_dict = {}
for group in groups:
group_dict[group.code] = group
return group_dict | bigcode/self-oss-instruct-sc2-concepts |
def seconds_to_hms(seconds: int) -> str:
"""
Returns string like "23:01:59" or "297:59:03" from seconds.
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d}" | bigcode/self-oss-instruct-sc2-concepts |
def to_latlon_for_days(dataframe):
"""For each day get list of typles with lat lon that is needed
for api call
params:
dataframe: dataframe with colums lat, lon, time
returns:
dict(key:date, value: list of tuples with latlon)
"""
result = dict()
... | bigcode/self-oss-instruct-sc2-concepts |
def bin_title(bin):
"""The title of a Bin instance in text representations"""
return 'Sample @ ' + bin.iso8601time | bigcode/self-oss-instruct-sc2-concepts |
def _get_relationships(notation):
"""
Return the list of orthology relationships to keep.
ENSEMBL homology relationships are defined in:
https://www.ensembl.org/info/genome/compara/homology_types.html
Posible values to this function are '1:1', '1:n' and 'm:n'.
>>> _get_relationships('1:1')
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def gaussian(x, mean, sdev):
""" Computes a gaussian """
first, second = 0, 0
if sdev > 0:
first = 1 / (math.sqrt(2 * math.pi) * sdev)
second = math.e ** (-((x - mean) ** 2) / (2 * (sdev ** 2)))
return first * second | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Union
def parse_int(v: Any) -> Union[int, None]:
"""Tries to parse to int
:param v: Value to parse to int
:param type: Any
:return: Parsed int or None if error occured
:rtype: Union[int, NoneType]
"""
try:
return int(v)
except ValueEr... | bigcode/self-oss-instruct-sc2-concepts |
import re
def grep(pattern, string=None, filename=None):
""" simulate linux grep command
return lines matching a pattern in a string or a file.
Parameters:
pattern: regular expression string
Usage examples:
result = grep('keyword', filename='a.txt' )
for i in result:
... | bigcode/self-oss-instruct-sc2-concepts |
def api_route(api_path, method="GET"):
"""Decorate a function as API route/command."""
def decorate(func):
func.api_path = api_path
func.api_method = method
return func
return decorate | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def platform() -> Dict[str, Any]:
"""
Returns:
The schema for the `platform` block
"""
data = {
"type": "list",
"schema": {
"type": "dict",
"schema": {
"name": {"type": "string", "required": ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from functools import reduce
def dgetattr(obj: Any, attr: str, default: Any) -> Any:
""" getattr with dot seperated attribute list """
try:
return reduce(getattr, attr.split("."), obj)
except AttributeError:
return default | bigcode/self-oss-instruct-sc2-concepts |
def pretty_html(html: str) -> str:
"""
Add padding at the beginning of code and span
elements to format the HTML output
Args:
html (str): the HTML output string
"""
format_html = html
format_html = format_html.replace("<code", "\n{}<code".format(" " * 12))
format_html = format_h... | bigcode/self-oss-instruct-sc2-concepts |
def my_circle(my_radius):
"""Calculates the area of a circle given its radius.
Keyword arguments:
my_radius (float) -- Radius of the circle.
Returns:
Float -- Area of the circle.
"""
return (3.14 * my_radius * my_radius) | bigcode/self-oss-instruct-sc2-concepts |
def minmax_scale(img, scale_range=(0, 1), orig_range=(0, 255)):
"""Rescale data values from original range to specified range
:param img: (numpy array) Image to be scaled
:param scale_range: Desired range of transformed data.
:param orig_range: Original range of input data.
:return: (numpy array) S... | bigcode/self-oss-instruct-sc2-concepts |
def vec2str(a, fmt='{}', delims='()', sep=', '):
"""
Convert a 3-sequence (e.g. a numpy array) to a string, optionally
with some formatting options. The argument `a` is also allowed to
have the value `None`, in which case the string 'None' is returned.
The argument `delims` can be used to specify d... | 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.