seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _DegreeDict(tris):
"""Return a dictionary mapping vertices in tris to the number of triangles
that they are touch."""
ans = dict()
for t in tris:
for v in t:
if v in ans:
ans[v] = ans[v] + 1
else:
ans[v] = 1
return ans | bigcode/self-oss-instruct-sc2-concepts |
def escape_path(path):
"""
Adds " if the path contains whitespaces
Parameters
----------
path: str
A path to a file.
Returns
-------
an escaped path
"""
if ' ' in path and not (path.startswith('"') and path.endswith('"')):
return '"' + path + '"'
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_json_value(value):
""" Get value as JSON. If value is not in JSON format return the given value """
try:
return json.loads(value)
except ValueError:
return value | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def get_columns(cxn, table):
"""Get a list of columns from a table"""
sql = f'PRAGMA table_info({table});'
cxn.row_factory = sqlite3.Row
columns = [r[1] for r in cxn.execute(sql)]
return columns | bigcode/self-oss-instruct-sc2-concepts |
def find_row(table, row):
"""
Return row index with row header in table
or -1 if row is not in table
"""
for idx in range(len(table)):
if table[idx][0] == row:
return idx
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def map_severity(meta_severity):
""" Map scanner severity to Carrier severity """
severity_map = {
"INFO": "Info",
"WARNING": "Medium",
"ERROR": "High",
}
return severity_map.get(meta_severity, "Info") | bigcode/self-oss-instruct-sc2-concepts |
def get_zip_perms(zipinfo):
"""Get file/dir permissions from zipinfo
Args:
zipinfo (zipfile.Zipinfo): information about one component file of a
zip-file
Returns:
int: file permissions for file in octal
"""
# Windows zip files with no permissions seem to sensibly default ... | bigcode/self-oss-instruct-sc2-concepts |
def imap(imap, vmin=None, vmax=None, cmap='YlGnBu_r', length_unit='cm'):
"""
Convenience base function to plot any IntensityMap2D instance
Parameters
----------
ratemap : IntensityMap2D
Intensity map to plot
cmap : Colormap or registered colormap name, optional
Colormap to use f... | bigcode/self-oss-instruct-sc2-concepts |
def weighted_average(values):
"""Calculates an weighted average
Args:
values (Iterable): The values to find the average as an iterable of
``(value, weight)`` pairs
Returns:
The weighted average of the inputs
Example:
>>> weighted_average([(1, 2), (2, 3)])
1... | bigcode/self-oss-instruct-sc2-concepts |
def set_staff_object(context, object):
"""
Assign an object to be the "main object" of this page.
Example::
{% set_staff_object page %}
"""
request = context["request"]
request.staff_object = object
return "" | bigcode/self-oss-instruct-sc2-concepts |
import math
def standard_deviation(times):
"""
Calculates the standard deviation of a list of numbers.
"""
mean = sum(times) / len(times)
# Sum the squares of the differences from the mean.
result = 0
for time in times:
result += (time - mean) ** 2
return math.sqrt(result / len(times)) | bigcode/self-oss-instruct-sc2-concepts |
import copy
def get_value_from_str_dotted_key(d, dotted_key):
"""Get value from python dict via dotted notation.
:param d: dictionary
:param dotted_key:
:return: str
"""
keys = dotted_key.split('.')
temp = copy.deepcopy(d)
try:
for key in keys:
temp = temp[key]
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def parse_headers(text):
"""Parse a string of headers (copied from Firefox) into a dict used in requests."""
return OrderedDict(line.split(': ') for line in text.splitlines() if line) | bigcode/self-oss-instruct-sc2-concepts |
def compose_key(instance):
"""Given an instance, returns a key
:arg instance: The model instance to generate a key for
:returns: A string representing that specific instance
.. Note::
This uses the id attribute of the model instance.
That's good enough for my needs, but we might need ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_bind_address(address, default=('localhost', 8080)):
"""
>>> parse_bind_address('80')
('localhost', 80)
>>> parse_bind_address('0.0.0.0')
('0.0.0.0', 8080)
>>> parse_bind_address('0.0.0.0:8081')
('0.0.0.0', 8081)
"""
if ':' in address:
host, port = addres... | bigcode/self-oss-instruct-sc2-concepts |
def to_identifier(key):
"""Converts given key to identifier, interpretable by TaskJuggler as a task-identifier
Args:
key (str): Key to be converted
Returns:
str: Valid task-identifier based on given key
"""
return key.replace('-', '_') | bigcode/self-oss-instruct-sc2-concepts |
def compute_kmp_fail(P):
"""Utility that computes and returns KMP 'fail' list."""
m = len(P)
fail = [0] * m # by default, presume overlap of 0 everywhere
j = 1
k = 0
while j < m:
if P[j] == P[k]: # k + 1 characters match thus far
fail[j] = k + 1... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_text(res, path):
"""Parsing text from response by path.
"""
value = None
node = res.find(path)
if node is not None:
value = node.text
value = value.strip()
return value | bigcode/self-oss-instruct-sc2-concepts |
def clean_texmath(txt):
"""
clean tex math string, preserving control sequences
(incluing \n, so also '\nu') inside $ $, while allowing
\n and \t to be meaningful in the text string
"""
s = "%s " % txt
out = []
i = 0
while i < len(s)-1:
if s[i] == '\\' and s[i+1] in ('n', 't'... | bigcode/self-oss-instruct-sc2-concepts |
import math
def days_frac_to_dhms(days_frac):
"""Convert a day float to integer days, hours, minutes and seconds.
Returns a tuple (days, hours, minutes, seconds).
>>> days_frac_to_dhms(2.5305)
(2, 12, 43, 55)
"""
days = math.floor(days_frac)
hms_frac = days_frac - days
hours = ma... | bigcode/self-oss-instruct-sc2-concepts |
def yes_or_no(question):
""" a utility tool to ask the user yes/no question
Parameters
----------
question : str
the text for the question
Returns
-------
value : bool
True or False
"""
while True:
answer = input(question + ' (y/n): ').lower().strip()
... | bigcode/self-oss-instruct-sc2-concepts |
def keyboard_data_signals_an_interrupt(
keyboard_data, stop_signal_chars=frozenset(['\x03', '\x04', '\x1b'])
):
"""The function returns a positive stop signal (1) if the character is in the
`stop_signal_chars` set.
By default, the `stop_signal_chars` contains:
* \x03: (ascii 3 - End of Text)
* \... | bigcode/self-oss-instruct-sc2-concepts |
def get_metric(mod, obs, fun, dim='time', verbose=False):
"""Calculate a metric along a dimension.
Metrics implemented: name
* correlation > corr
* mse > mse
* rmse > rmse
* mean percentage error > mpe
* stan... | bigcode/self-oss-instruct-sc2-concepts |
def remove_spaces(st):
""" Removes spaces from a string
:param st: (str) input string with spaces
:return: (str) string without any spaces
"""
return st.replace(' ', '') | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def Powerset(iterable):
"""powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)."""
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r)
for r in range(len(s)+1)) | bigcode/self-oss-instruct-sc2-concepts |
def update_leases(transform, persistence_service):
"""
Update the leases configuration in the persistence service.
:param transform: A function to execute on the currently configured
leases to manipulate their state.
:param persistence_service: The persistence service to which the
updat... | bigcode/self-oss-instruct-sc2-concepts |
def pkg_key(pkg, type_):
"""
generate a package key for a given type string
Generates a compatible "package key" for a unsanitized package name ``pkg``
of a specific key ``type``. The package string is "cleaned" to replaces
select characters (such as dashes) with underscores and becomes uppercase.
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def generate_node_id(node, data):
"""Generate a node ID from the node label, extracts data from: [$ID].
Return the extracted node ID and the label, without the ID part, so
it can be the expression if one isn't specified in the description."""
pat = r"\[(?P<node_id>\w+)\]"
m = re.search(... | bigcode/self-oss-instruct-sc2-concepts |
def normalize(msg):
"""
Normalizes the plain text removing all invalid characters and spaces
:param msg: Plain text to be normalized
:return: the normalized message without invalid chars
"""
return "".join([let.lower() for let in msg if let.isalpha() or let.isdigit()]) | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json(filename):
"""Load dictionary from JSON file."""
with open(filename, 'r') as f:
mybooks = json.load(f)
return(mybooks) | bigcode/self-oss-instruct-sc2-concepts |
def update_nested_dictionary(old, new):
"""
Update dictionary with the values from other dictionary. Recursively update
any nested dictionaries if both old and new values are dictionaries.
:param old: Old dictionary that will be updated
:type old: dict
:param new: New dictionary that contains t... | bigcode/self-oss-instruct-sc2-concepts |
def fisbHexErrsToStr(hexErrs):
"""
Given an list containing error entries for each FIS-B block, return a
string representing the errors. This will appear as a comment in either
the result string, or the failed error message.
Args:
hexErrs (list): List of 6 items, one for each FIS-B block. Each entry
... | bigcode/self-oss-instruct-sc2-concepts |
def wing(Sw,bw,cw,Nwr,t_cw,Nwer,nult,GW):
""" Compute weight of human-powered aircraft wing
Assumptions:
All of this is from AIAA 89-2048, units are in kg. These weight estimates
are from the MIT Daedalus and are valid for very lightweight
carbon fiber composite structures. This may n... | bigcode/self-oss-instruct-sc2-concepts |
def read_lines(file_name):
""" Read lines from given file and return as list """
with open(file_name, 'r') as fobj:
lines = fobj.readlines()
return lines | bigcode/self-oss-instruct-sc2-concepts |
def count_frequency(my_list):
"""
count the frequency of elements in a list using a dictionary
Args:
my_list (list): List
Returns:
dict: Dictionary containing unique item and frequency
Example::
>> my_list = ["happy", "neutral", "happy"]
>> count_frequency... | bigcode/self-oss-instruct-sc2-concepts |
def _ensure_list(item):
"""
Ensures that the given item is a list.
:param item:
:return:
"""
if item is None:
return []
if isinstance(item, list):
return item
if isinstance(item, tuple):
return list(item)
return [item] | bigcode/self-oss-instruct-sc2-concepts |
def header_exists(header_name, headers):
"""Check that a header is present."""
return header_name.lower() in (k.lower() for (k, _) in headers) | bigcode/self-oss-instruct-sc2-concepts |
def pre_process_expressions(expressions, variable_templates):
"""
This one is pretty simple - pass in a list of expressions which contain
references to templates and pass a dictionary of the templates themselves.
Strings will only be evaluated which are prepended with $.
Parameters
----------
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def neigh_square(position_diff: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""
Square-shaped neighborhood scaling function based on center-wise diff `position_diff` and radius `sigma`.
Parameters
----------
position_diff : torch.Tensor
The positional difference aroun... | bigcode/self-oss-instruct-sc2-concepts |
def join_strings(strings, glue=" AND "):
"""
Returns the non-empty strings joined together with the specified glue.
@param glue separator used as glue between strings
@return (joined string, number of strings actually used)
"""
strings = list(filter(None, strings))
return glue.joi... | bigcode/self-oss-instruct-sc2-concepts |
def custom(datacells, ncells, value):
"""Calculate percent of total"""
x = float(datacells.GetUnformattedValueAt(ncells-1,2)) # total
return float(value) / x | bigcode/self-oss-instruct-sc2-concepts |
def shape(x):
"""Change str to List[int]
>>> shape('3,5')
[3, 5]
>>> shape(' [3, 5] ')
[3, 5]
"""
# x: ' [3, 5] ' -> '3, 5'
x = x.strip()
if x[0] == '[':
x = x[1:]
if x[-1] == ']':
x = x[:-1]
return list(map(int, x.split(','))) | bigcode/self-oss-instruct-sc2-concepts |
def max_value(tab):
"""
Brief: computes the max with positiv value
Args:
tab: a liste of numeric value exepcts at least one positive valus, raise expection
Return: the max value
Raises :
ValueError if no positive value is found
"""
if not(isinstance(tab, list)):
rai... | bigcode/self-oss-instruct-sc2-concepts |
def calc(x, y, serial):
"""
Find the fuel cell's rack ID, which is its X coordinate plus 10.
Begin with a power level of the rack ID times the Y coordinate.
Increase the power level by the value of the grid serial number (your puzzle
input).
Set the power level to itself multiplied by the rack I... | bigcode/self-oss-instruct-sc2-concepts |
def make_snapshots(frame, ignore):
"""Extract a subset of atoms from a given frame."""
snapshot = {
'header': 'Removed.',
'box': frame['box'],
'residunr': [],
'residuname': [],
'atomname': [],
'atomnr': [],
'x': [],
'y': [],
'z': [],
}
... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_difference(dsm_array, dtm):
"""Calculate the difference between the dsm and dtm"""
dtm_array = dtm.read(1, masked = True)
difference = dsm_array - dtm_array
difference.data[difference < 0] = 0 # We set to 0 anything that might have been negative
return difference | bigcode/self-oss-instruct-sc2-concepts |
def norm_colname(colname):
"""Given an arbitrary column name, translate to a SQL-normalized column
name a la CARTO's Import API will translate to
Examples
* 'Field: 2' -> 'field_2'
* '2 Items' -> '_2_items'
Args:
colname (str): Column name that will be SQL normalized
Return... | bigcode/self-oss-instruct-sc2-concepts |
def makesafe(s):
"""Makes the given string "safe" by replacing spaces and lower-casing (less aggressive)"""
def rep(c):
if c.isalnum():
return c.lower()
else:
return '_'
ret = ''.join([rep(c) for c in s])
return ret | bigcode/self-oss-instruct-sc2-concepts |
def _get_empty_lines(text):
"""Get number of empty lines before and after code."""
before = len(text) - len(text.lstrip('\n'))
after = len(text) - len(text.strip('\n')) - before
return before, after | bigcode/self-oss-instruct-sc2-concepts |
def _get_db_table_for_model(model):
"""
Return table name in database server for passed model.
"""
return model._meta.db_table | bigcode/self-oss-instruct-sc2-concepts |
def INT_ICART(a, b, c):
"""Given a, b, and c, return a cartesian offset.
#define INT_ICART(a, b, c) (((((((a)+(b)+(c)+1)<<1)-(a))*((a)+1))>>1)-(b)-1)
"""
return ((((((a + b + c + 1) << 1) - a) * (a + 1)) >> 1) - b - 1) | bigcode/self-oss-instruct-sc2-concepts |
def walk(path, container):
"""
Recurse over the ActBlue JSON object, and get the values that we need,
based on the settings file.
Returns a single value for each path.
"""
if not container or isinstance(container, str):
return None
key = path[0]
if len(path) == 1:
if key... | bigcode/self-oss-instruct-sc2-concepts |
def sparse_mimmax(A, B, type="mim"):
"""Return the element-wise mimimum/maximum of sparse matrices `A` and `B`.
Parameters
----------
A:
The first sparse matrix
B:
The second sparse matrix
type:
The type of calculation, either mimimum or maximum.... | bigcode/self-oss-instruct-sc2-concepts |
def format_literal(raw):
"""Format a literal into a safe format. This is used to format the
flont:Literal IRI.
"""
return "_" + raw.replace(" ", "_") | bigcode/self-oss-instruct-sc2-concepts |
def make_PEM_filename(cert_id: str) -> str:
"""Create a filename for PEM certificate"""
return cert_id + '.pem' | bigcode/self-oss-instruct-sc2-concepts |
def is_in_list(num, lst):
"""
>>> is_in_list(4, [1, 2, 3, 4, 5])
True
>>> is_in_list(6, [1, 2, 3, 4, 5])
False
>>> is_in_list(5, [5, 4, 3, 2, 1])
True
"""
if not lst:
return False
else:
return lst[0] == num or is_in_list(num, lst[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def get_investigation_data(investigation_response):
"""Get investigation raw response and returns the investigation info for context and human readable.
Args:
investigation_response: The investigation raw response
Returns:
dict. Investigation's info
"""
investigation_data = {
... | bigcode/self-oss-instruct-sc2-concepts |
def wraps(wrapped, fun, namestr="{fun}", docstr="{doc}", **kwargs):
"""
Like functools.wraps, but with finer-grained control over the name and docstring
of the resulting function.
"""
try:
name = getattr(wrapped, "__name__", "<unnamed function>")
doc = getattr(wrapped, "__doc__", "") or ""
fun.__d... | bigcode/self-oss-instruct-sc2-concepts |
import re
def keyvault_name(name: str) -> bool:
"""Validate the name of the keyvault.
Args:
name (str): Name of the keyvault.
Returns:
bool: True or False depending on the name validity.
"""
regex = "^[a-zA-Z0-9-]{3,24}$"
pattern = re.compile(regex)
return pattern.match(... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def has_gpu() -> bool:
"""Detect if the runtime has GPU.
This function calls torch function underneath. To mask an
environment to have no GPU, you can set "CUDA_VISIBLE_DEVICES"
environment variable to empty before running the python script.
Returns:
bool:
True i... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def parse_device_list(device_list_str, key):
"""Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_analysis_files(pathnames):
"""Reads in simulation analysis files (as produced by pathsim_analysis.py).
Returns list of start times, end times, and statistics."""
start_time = None
end_time = None
compromise_stats = []
for pathname in pathnames:
with open(pat... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def _canonicalize_hostname(hostname):
"""Canonicalize hostname following MIT-krb5 behavior."""
# https://github.com/krb5/krb5/blob/d406afa363554097ac48646a29249c04f498c88e/src/util/k5test.py#L505-L520
af, socktype, proto, canonname, sockaddr = socket.getaddrinfo(
hostname, None, 0, 0... | bigcode/self-oss-instruct-sc2-concepts |
def drop_na_rows_from_datum(datum):
"""Drops rows from the pandas dataframe where all values are NA."""
datum_size = len(datum)
datum_type = datum['Type'][0]
dropped_datum = datum.dropna(axis=0, how='all')
dropped_datum_size = len(dropped_datum)
print(str(datum_size - dropped_datum_size) + " ro... | bigcode/self-oss-instruct-sc2-concepts |
import time
def timeit(callback, message):
"""Measure the time taken to execute a function.
This function measures the amount of time it takes to execute the
specified callback and prints a message afterwards regarding the
time taken. The `message` parameter provides part of the message,
e.g. if ... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_config_file(file_name):
"""Setup config parameters
Read and store configuration parameters
from given config file
"""
with open(file_name) as config_file:
config_values = {}
config = yaml.safe_load(config_file)
# get values from yaml
config_va... | bigcode/self-oss-instruct-sc2-concepts |
import re
def build_filter(pattern):
"""Function to return a filter function for scan_directories
Parameters
----------
pattern : str
Regex pattern to match
Returns
-------
function : a filter which returns true when a file matching
the pattern is present
... | bigcode/self-oss-instruct-sc2-concepts |
def rearrange_pandasdf_columns(df):
"""
Takes a pandas Dataframe with columns 'DateTime' and 'WorkerIndex' amongst others and places them at the front
:param df: The pandas Dataframe
:return: The column rearranged df
"""
new_columns = ['DateTime', 'WorkerIndex']
for c in df.columns:
... | bigcode/self-oss-instruct-sc2-concepts |
def compare_flavors(flavor_item):
"""
Helper function for sorting flavors.
Sorting order: Flavors with lower resources first.
Resource importance order: GPUs, CPUs, RAM, Disk, Ephemeral.
:param flavor_item:
:return:
"""
return (
flavor_item.get("Properties", {}).get("Accelerato... | bigcode/self-oss-instruct-sc2-concepts |
import json
def process_config(json_file):
"""Load configuration as a python dictionary.
Args:
json_file (str): Path to the JSON file.
Returns:
dict:
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_file:
co... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _filter_class_attributes(path, parent, children):
"""Filter out class attirubtes that are part of the PTransform API."""
del path
skip_class_attributes = {
"expand", "label", "from_runner_api", "register_urn", "side_inputs"
}
if inspect.isclass(parent):
children = [(name, child)... | bigcode/self-oss-instruct-sc2-concepts |
def make_list(arg):
"""Return a list with arg as its member or arg if arg is already a list. Returns an empty list if arg is None"""
return (arg
if isinstance(arg, list)
else ([arg]
if arg is not None
else [])) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
import pytz
def ns_to_datetime(ns):
"""
Converts nanoseconds to a datetime object (UTC)
Parameters
----------
ns : int
nanoseconds since epoch
Returns
-------
nanoseconds since epoch as a datetime object : datetime
"""
dt = datetime.utcf... | bigcode/self-oss-instruct-sc2-concepts |
def get_total_ramp_rate_violation(model):
"""Total ramp rate violation"""
ramp_up = sum(v.value for v in model.V_CV_TRADER_RAMP_UP.values())
ramp_dn = sum(v.value for v in model.V_CV_TRADER_RAMP_DOWN.values())
return ramp_up + ramp_dn | bigcode/self-oss-instruct-sc2-concepts |
def single_byte_xor(hex_string, single_byte: int) -> str:
"""XOR the hex_string with a single byte."""
return "".join((chr(letter ^ single_byte) for letter in bytes.fromhex(hex_string))) | bigcode/self-oss-instruct-sc2-concepts |
def _readSPARQLQuery(filename):
"""Read a SPARQL query from file and return the content as a string."""
content = ""
with open(filename, 'r') as reader:
content = reader.read()
return content | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def split_escaped_whitespace(text):
"""
Split `text` on escaped whitespace (null+space or null+newline).
Return a list of strings.
"""
strings = text.split('\x00 ')
strings = [string.split('\x00\n') for string in strings]
# flatten list of lists of strings to list of strin... | bigcode/self-oss-instruct-sc2-concepts |
import re
def axes_from_cmd(cmd, alt_names=None):
"""
Get axes name from command string
:param cmd: str
:param alt_names: dict {name_in_cmd: name_in_file}
:return: str
"""
alt_names = {} if alt_names is None else alt_names
cmd = cmd.split()
axes = cmd[1]
if axes in alt_names:
... | bigcode/self-oss-instruct-sc2-concepts |
def level_states_full_space(level, dimension):
"""
Creates a list of all states in ``level``.
Parameters
----------
level : int
Level of the state space.
dimension : int
Number of clonotypes.
Returns
-------
state_list : list
List of all states in level.
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def Extract_Numbers(string):
"""Function to extract the individual numbers form within a string """
List = [int(s) for s in re.findall(r'\d+', string)]
# Pythonic language for obtaining the integers that may appear in a string
return List
# Return the list of integers. Remianin... | bigcode/self-oss-instruct-sc2-concepts |
def read_group_string(experiment_sample):
"""
Generate a SAM header string for the read group.
Passed to bwa with escaped tabs.
"""
read_group_fields = [
'@RG',
'ID:'+experiment_sample.uid,
'PL:illumina',
'PU:'+experiment_sample.uid,
'LB:'+... | bigcode/self-oss-instruct-sc2-concepts |
def guess_n_initial_points(params): #96 (line num in coconut source)
"""Guess a good value for n_initial_points given params.""" #97 (line num in coconut source)
return max(len(params), min(len(params) * 2, 10)) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def ping(reply, cfg) -> str:
"""
Replies to the !ping command, and is used as a keep alive check
:param reply: Message object
:param cfg: See reply param
:return: The ping string, which in turn is given to Reddit's reply.reply()
"""
logging.info(f"Received ping from {reply.a... | bigcode/self-oss-instruct-sc2-concepts |
import base64
import json
def serialize(obj: object) -> str:
"""
Serializes a given object. It will find all the attributes of the
class that don't start with '__' and returns a base64 encoded json
string.
"""
final_dict = {}
for attr in dir(obj):
if not attr.startswith("__") and n... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def loadData(file_model):
"""
Load object from (pk) dump file
:param file_model: object file
:return: reconstructed object file
"""
object_file = None
try:
object_file = open(file_model, 'rb')
object_model = pickle.load(object_file)
object_file.close()... | bigcode/self-oss-instruct-sc2-concepts |
def dataset_len(tf_dataset, verbose=False):
"""
Compute the length of a TF dataset.
"""
tot = 0
for data, _ in tf_dataset.batch(128):
tot += data.shape[0]
if verbose: print('.', end='')
if verbose: print(flush=True)
return tot | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def argmax(array: List[float]) -> int:
"""Simple argmax implementation for lists of floats."""
index, value = max(enumerate(array), key=lambda x: x[1])
return index | bigcode/self-oss-instruct-sc2-concepts |
def check_exists(connection, path):
"""Check the file path in the SQL filepaths table.
:param connection:
:param path:
:return: path id"""
exists = '''SELECT EXISTS(SELECT 1 FROM filepaths
WHERE filepath = ?);'''
cursor = connection.cursor()
cursor.execute(exists, (path,))
return cursor.fetchone() | bigcode/self-oss-instruct-sc2-concepts |
def _round_to_interval(time, interval):
"""
:param time: in us
:return: time in us rounded to the earliest interval
"""
return time - time % interval | bigcode/self-oss-instruct-sc2-concepts |
def BMI_calculator(weight, height):
""" Function to calculate the BMI of an individual given their respective weight (lb) and height (in)"""
# Calculate BMI using lb / inches equation
bmi = ((weight)/(height * height)) * 703
return bmi | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def create_id() -> str: # pragma: no cover
"""Creates an uuid."""
return str(uuid.uuid4()) | bigcode/self-oss-instruct-sc2-concepts |
def ReadFileAsLines(filename):
"""Reads a file, removing blank lines and lines that start with #"""
file = open(filename, "r")
raw_lines = file.readlines()
file.close()
lines = []
for line in raw_lines:
line = line.strip()
if len(line) > 0 and not line.startswith("#"):
lines.append(line)
ret... | bigcode/self-oss-instruct-sc2-concepts |
def _formula_str(formula, sep='&'):
"""Returns a representation of 'formula' for prettyprinting"""
next_sep = '|' if sep == '&' else '&'
items = [item if (type(item) == str) else _formula_str(item, next_sep)
for item in formula]
return '({0})'.format(' {0} '.format(sep).join(items)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def as_list(ans: str, sep: str = ",") -> List[str]:
"""
Spits answer into list according to separator
"""
items = ans.strip().split(sep)
items = map(str.strip, items)
return list(items) | bigcode/self-oss-instruct-sc2-concepts |
def empty(level):
""" To generate empty space needed for shaping the tree"""
s = ""
for x in range(level):
s += " "
return s | bigcode/self-oss-instruct-sc2-concepts |
def is_python_file(filename):
"""
Return whether a file is a Python file or not
"""
return filename.endswith('.py') | bigcode/self-oss-instruct-sc2-concepts |
def partition(message):
"""
Takes in a decoded message (presumably passed through prepare()) and
returns a list of all contained messages. The messages are strings
Example:
>>> partition("5 Hello6 World!")
['Hello', 'World!']
"""
messages = []
while len(message) > 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def _date_long_form(date):
""" Displays a date in long form, eg 'Monday 29th April 2019'. """
second_last = (date.day // 10) % 10
last = date.day % 10
if second_last != 1 and last == 1:
ordinal = "st"
elif second_last != 1 and last == 2:
ordinal = "nd"
elif second_last != 1 and l... | bigcode/self-oss-instruct-sc2-concepts |
def _seconds_and_microseconds(timestamp):
"""
Split a floating point timestamp into an integer number of seconds since
the epoch, and an integer number of microseconds (having rounded to the
nearest microsecond).
If `_seconds_and_microseconds(x) = (y, z)` then the following holds (up to
the err... | bigcode/self-oss-instruct-sc2-concepts |
def _is_external(p):
"""Checks if the string starts with ../"""
return p[0:3] == '../' | 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.