seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def for_each_in(cls, f, struct):
""" Recursively traversing all lists and tuples in struct, apply f to each
element that is an instance of cls. Returns structure with f applied. """
if isinstance(struct, list):
return map(lambda x: for_each_in(cls, f, x), struct)
elif isinstance(struct, tupl... | bigcode/self-oss-instruct-sc2-concepts |
import collections
def get_sectors(n_con):
"""
INPUTS:
n_con (mysql) - A "normal" pymysql database connection
OUTPUT:
Dictionary with sectors as keys, and lists of ticker_id's as values
"""
sectors = collections.defaultdict(list)
with n_con.cursor() as n_cur:
n_cur.exec... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def unaccent(string):
"""
Receives a string and return it without accents
:param string: accented string
:return: unaccented string
"""
text = unicodedata.normalize('NFD', string)
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
return str(text... | bigcode/self-oss-instruct-sc2-concepts |
def _recover_uid(good_id) -> int:
"""
Get the uid part of the good id.
:param str good_id: the good id
:return: the uid
"""
uid = int(good_id.split("_")[-2])
return uid | bigcode/self-oss-instruct-sc2-concepts |
def rgba2int(r, g, b, a):
""" rgba2int: Converts an RGBA value into an integer
:param r The red value (0-255)
:param g The green value (0-255)
:param b The blue value (0-255)
:param a The alpha value (0-255)
:returns: The RGBA value compact into a 4 byte integer.
"""
return (r << 24) ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def findurls(text):
"""
Finds all urls in a string
"""
urls = re.findall('href="(.*?)"', text)
return urls | bigcode/self-oss-instruct-sc2-concepts |
def table(
caption="",
thead="",
tbody="",
striped=True,
bordered=False,
hover=True,
condensed=False,
span=False):
"""
*Generate a table - TBS style*
**Key Arguments:**
- ``caption`` -- the table caption
- ``thead`` -- the tabl... | bigcode/self-oss-instruct-sc2-concepts |
def get_order(order):
"""
All the orders they create look something like this:
"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
Their preference is to get the orders as a nice clean string
with spaces and capitals like so:
"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milksha... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(name=__name__, level=logging.INFO):
"""
This pattern prevents creates implicitly creating a root logger by creating the sub-logger named __name__
Also by default sets level to INFO
"""
logger = logging.getLogger(name)
logger.setLevel(level)
return logger | bigcode/self-oss-instruct-sc2-concepts |
def bit_invert(value, width=32):
"""! @brief Return the bitwise inverted value of the argument given a specified width.
@param value Integer value to be inverted.
@param width Bit width of both the input and output. If not supplied, this defaults to 32.
@return Integer of the bitwise inversion of @... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def get_fillin_graph2(old_graph, peo):
"""
Provided a graph and an order of its indices, returns a
triangulation of that graph corresponding to the order.
The algorithm is copied from
"Simple Linear Time Algorithm To Test Chordality of Graph"
by R. E. Tarjan and M. Yannakakis
... | bigcode/self-oss-instruct-sc2-concepts |
def isint(val):
"""
check if the entry can become an integer (integer or string of integer)
Parameters
----------
val
an entry of any type
Returns
-------
bool
True if the input can become an integer, False otherwise
"""
try:
int(val)
return Tru... | bigcode/self-oss-instruct-sc2-concepts |
def update_vocab(vocab):
"""Add relevant special tokens to vocab."""
vocab_size = len(vocab)
vocab["<unk>"] = vocab_size
vocab["<s>"] = vocab_size + 1
vocab["</s>"] = vocab_size + 2
return vocab | bigcode/self-oss-instruct-sc2-concepts |
def json_for_user(user, session_id):
""" Convert the provided user to a dictionary (for JSON)
Args:
user: the User object
Returns:
An object containing user details
"""
return {
"user_id": user.user_id,
"name": user.name,
"title": user.title,... | bigcode/self-oss-instruct-sc2-concepts |
def parse_vec(s, size = 3):
"""Parse a vector and return it as a list of values. Upon failure, return a
vector containing all 0s.
"""
if s.count(" ") < size - 1:
return [0] * size
try:
return [float(value) for value in s.split(" ")]
except ValueError:
return [0] * size | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def _integrate(function: Callable[[float, ], float],
start: float, end: float, n: int) -> float:
"""
Calculate defined integral of given `function` in range of
[start, end]
:param function: Function to integrate
:param start: Left bound
:param end: R... | bigcode/self-oss-instruct-sc2-concepts |
def reject(position_store, particles, random_particle):
"""Reject the move and return the particle to the original place.
Parameters
----------
position_store: float, array_like
The x and y positions previously held by the particle that has moved.
particles: util.particle.dt, array_like
... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def factors(n):
"""
Decomposes a number into its factors.
:param n: Number to decompose.
:type n: int
:return: List of values into which n can be decomposed.
:rtype: list
"""
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(... | bigcode/self-oss-instruct-sc2-concepts |
import traceback
def atomic_method(method):
""" Decorator to catch the exceptions that happen in detached thread atomic tasks
and display them in the logs.
"""
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].exceptionq.put("A... | bigcode/self-oss-instruct-sc2-concepts |
def _font_pt_to_inches(x):
"""Convert points to inches (1 inch = 72 points)."""
return x / 72. | bigcode/self-oss-instruct-sc2-concepts |
def dimcolor(rgb, prop):
"""
Dims a given rgb color to prop, which should be in the interval 0.0 - 1.0.
"""
return tuple(map(lambda x: int(round(x * prop)), rgb)) | bigcode/self-oss-instruct-sc2-concepts |
import struct
import binascii
def hex2double(s):
"""Convert Ephemeris Time hex string into double."""
return struct.unpack('d', binascii.unhexlify(s))[0] | bigcode/self-oss-instruct-sc2-concepts |
def decode_edges(edges):
"""
Decodes the specified integer representing edges in Cortex graph. Returns
a tuple (forward, reverse) which contain the list of nucleotides that we
append to a kmer and its reverse complement to obtain other kmers in the
Cortex graph.
"""
bases = ["A", "C", "G", "... | bigcode/self-oss-instruct-sc2-concepts |
def query_default(param, args):
"""
Allow for a parameter to be queried, and return defaults for those not provided.
Parameters
----------
param : str
The parameter being queried
args : object
Namespace object
Returns
-------
Queried value or default
"""
va... | bigcode/self-oss-instruct-sc2-concepts |
def lookup(name, namespaces=None, modules=None):
"""
Look up the given name and return its binding. Return `None` if not
found.
namespaces:
Iterable of namespaces / dictionaries to search.
modules:
Iterable of modules / objects to search.
"""
if namespaces is not None:
... | bigcode/self-oss-instruct-sc2-concepts |
def metadata_to_dict(metadata):
"""
Takes metadata as specified in seperate_metadata_and_content() documentation and\
converts it to a dictionary.
Note that white space on either side of the metadata tags and values will be stripped; \
also, if there are any duplicate metadata key names, the value o... | bigcode/self-oss-instruct-sc2-concepts |
def max_sequence_length_from_log(log):
"""
Returns length of the longest sequence in the event log.
:param log: event log.
:return: max_seq_length.
"""
max_seq_length = 0
for sequence in log:
max_seq_length_temp = 0
for activity_ in sequence:
max_seq_length_temp... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_duplicate_spacing(text):
"""Replace multiple spaces by one space"""
pattern = r'[\s]+'
return re.sub(pattern, " ", text)
pass | bigcode/self-oss-instruct-sc2-concepts |
def point_in_box(bbox, point):
"""check if a point falls with in a bounding box, bbox"""
LB = bbox[0]
RU = bbox[1]
x = point[0]
y = point[1]
if x < LB[0] or x > RU[0]:
return False
elif y < LB[1] or y > RU[1]:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def manhattan(coord_1: Tuple[int, int], coord_2: Tuple[int, int]) -> int:
"""
Returns the manhattan distance between 2 coordinates.
"""
return abs(coord_1[0] - coord_2[0]) + abs(coord_1[1] - coord_2[1]) | bigcode/self-oss-instruct-sc2-concepts |
def parse_lines(s):
"""
parser for line-separated string fields
:s: the input string to parse, which should be of the format
string 1
string 2
string 3
:returns: tuple('string 1', ...)
"""
return tuple(map(lambda ss: ss.strip... | bigcode/self-oss-instruct-sc2-concepts |
def gen_namespace(dbname, collname):
""" Generate namespace.
"""
return '%s.%s' % (dbname, collname) | bigcode/self-oss-instruct-sc2-concepts |
def calculate_score(given_answers: dict, correct_answers: dict) -> int:
"""Returns the number of correct answers.
given_answers: {"question1": "X",
"question2": "Y",
...
"questionN": "Z"}
correct_answers: {"question1": "A",
"... | bigcode/self-oss-instruct-sc2-concepts |
def multiply(a, b):
"""Function to multiply two numbers.
Parameters
----------
a: float
First number of the multiplication.
b: float
Second number of the multiplication.
Returns
-------
float
The product of a and b, a*b.
"""
return a * b | bigcode/self-oss-instruct-sc2-concepts |
def get_mnsp_period_collection_attribute(data, attribute, func) -> dict:
"""
Get MNSP period collection attribute
Parameters
----------
data : dict
NEMDE case file dictionary
attribute : str
Name of attribute to extract
func : function
Function used to parse extrac... | bigcode/self-oss-instruct-sc2-concepts |
def box(keyword):
"""Validation for the ``<box>`` type used in ``background-clip``
and ``background-origin``."""
return keyword in ('border-box', 'padding-box', 'content-box') | bigcode/self-oss-instruct-sc2-concepts |
def sort_keypoints_by_response_and_get_n_best(keypoint_list, n=500):
"""
Sorts keypoint list by "response" field and returns the first n best keypoints.
If the length of the list is smaller than n, than return the whole list.
input: keypoint_list - list of keypoints
n - no of keypoints to be... | bigcode/self-oss-instruct-sc2-concepts |
def dirac_measure(a,b):
"""
Returns 1 iff a=b and 0 otherwise.
"""
if a==[] or b==[]:
return 0.0
return float(a==b) | bigcode/self-oss-instruct-sc2-concepts |
def anchor(post):
"""Return anchor string for posts that arepage sections."""
if post.section:
return '#' + post.section
else:
return '' | bigcode/self-oss-instruct-sc2-concepts |
import re
def _ParseFixed(fixed_or_percent_str):
"""Retrieves int value from string."""
if re.match(r'^\d+$', fixed_or_percent_str):
return int(fixed_or_percent_str)
return None | bigcode/self-oss-instruct-sc2-concepts |
import math
def __calculateGridAxis(length, local):
"""
Calculates the grid axis.
Parameters
----------
length : int.
Global length.
local : int.
Local size.
Returns
-------
grid : int
Calculated grid size.
"""
return int(math.ceil(float(length) ... | bigcode/self-oss-instruct-sc2-concepts |
import copy
import logging
def MergeConfigs(default_config, override_config, warn_new_key=False):
"""Merges the override config into the default config.
This function will recursively merge two nested dicts.
The override_config represents overrides to the default_config dict, so any
leaf key/value pairs whic... | bigcode/self-oss-instruct-sc2-concepts |
def SampleZipped(sample_file, input_api):
"""Return True if the zipfile that should contain |sample_file| is in
this change.
"""
sample_path = sample_file.LocalPath()
for af in input_api.AffectedFiles():
root, ext = input_api.os_path.splitext(af.LocalPath())
if ext == '.zip' and sample_path.startswith... | bigcode/self-oss-instruct-sc2-concepts |
def _find_traces(traces, trace_type, item_id):
"""Find traces for a script or automation."""
return [
trace
for trace in traces
if trace["domain"] == trace_type and trace["item_id"] == item_id
] | bigcode/self-oss-instruct-sc2-concepts |
def GenerateTableHtml(items, keys_to_print, display_index=True):
"""Given a list of object values and keys to print, make an HTML table.
Args:
items: Items to print an array of dicts.
keys_to_print: (key, display_fn). `key` is a key in the object. i.e.
items[0][key] should exist. display_fn is the ma... | bigcode/self-oss-instruct-sc2-concepts |
def polyToBox(poly:list):
""" Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. """
xmin = 1e10
xmax = -1e10
ymin = 1e10
ymax = -1e10
for poly_comp in poly:
for i in range(len(poly_comp) // 2):
x = poly_comp[2*i + 0]
y = poly_comp[2*i + 1]
xmin = min(x, xmin)
xma... | bigcode/self-oss-instruct-sc2-concepts |
import re
def char_tokenizer(sentence):
"""Cut the sentence into the format we want:
- continuous letters and symbols like back-slash and parenthese
- single Chinese character
- other symbols
"""
regex = []
# English and number part for type name.
regex += [r'[0-9a-zA-Z\\+()\-<>]+']
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def match_pattern(file, pattern):
""" Continue reading file line by line and look for regular expression pattern.
Returns True if the pattern was found, False if not. """
for line in file:
if re.search(pattern, line):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def GetTimestampEventName(process):
""" Returns the name of the events used to count frame timestamps. """
event_name = 'BenchmarkInstrumentation::DisplayRenderingStats'
for event in process.IterAllSlicesOfName(event_name):
if 'data' in event.args and event.args['data']['frame_count'] == 1:
return event... | bigcode/self-oss-instruct-sc2-concepts |
import math
def radial_decay(r_nmi, rmax_nmi):
"""
Calculates the radial decay factor for a given radius.
Rmax_nmi < r_nmi: NWS 23 pdf page 53, page 27, Figure 2.12, empirical fit
Rmax_nmi > r_nmi: NWS 23 pdf page 54, page 28, Figure 2.13, empirical fit (logistic regression)
:param r_nmi: int Poin... | bigcode/self-oss-instruct-sc2-concepts |
import time
def get_date(basename):
"""Return date object representing date of M3 observation"""
return time.strptime(basename[3:11], "%Y%m%d") | bigcode/self-oss-instruct-sc2-concepts |
def subset(data: list, default_length: int):
"""
Get a subset of a list
:param data: list
:param default_length: default length of list
:return: list
"""
# Stop if nothing was found:
if len(data) == 0:
return []
# Select some IDs
length = default_length if len(data) > d... | bigcode/self-oss-instruct-sc2-concepts |
def _MakeOptional(property_dict, test_key):
"""Iterates through all key/value pairs in the property dictionary. If the "test_key" function
returns True for a particular property key, then makes that property optional. Returns the
updated property dict.
"""
for key, value in property_dict.items():
if test_... | bigcode/self-oss-instruct-sc2-concepts |
def find_index_of_minimum(arr):
"""Returns the index of the minimum number
Arguments:
arr {list} -- the input list
Returns:
int -- the index of the minimum number
"""
minimum = arr[0]
index_of_minimum = 0
for index, item in enumerate(arr):
if item < minimum:
... | bigcode/self-oss-instruct-sc2-concepts |
def stars(number_of_stars, max_stars):
"""
For a given number of stars, will return number of stars.
:param int number_of_stars: number of stars
:param int max_stars: max number of stars
:return: a string
"""
star_true = "★"
star_false = "☆"
return star_true * number_of_stars + star... | bigcode/self-oss-instruct-sc2-concepts |
def _get_match_groups(ping_output, regex):
"""
Get groups by matching regex in output from ping command.
"""
match = regex.search(ping_output)
if not match:
raise Exception('Invalid PING output:\n' + ping_output)
return match.groups() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
import sqlite3
def is_database_locked(db: Union[str, Path]) -> bool:
"""Checks is database locked
Notice:
This function will block the thread for a while (the timeout is set to 0)
"""
conn = sqlite3.connect(str(db), timeout=0)
try:
conn.e... | bigcode/self-oss-instruct-sc2-concepts |
def _need_loop(v):
"""
if a variable should loop to concat string
:param v: any variable
:return: Boolean
"""
return isinstance(v, list) or isinstance(v, dict) or isinstance(v, tuple) | bigcode/self-oss-instruct-sc2-concepts |
def struct2spglib(st):
"""Transform :class:`~pwtools.crys.Structure` to spglib input tuple (cell,
coords_frac, znucl).
"""
return st.get_spglib() | bigcode/self-oss-instruct-sc2-concepts |
def get_partners(bam, bams):
"""
Returns the partner bam files having the same ID
"""
partners = []
for bam_iter in bams:
if bam in bam_iter:
partners.append(bam_iter)
return partners | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def _generate_random_string(N: int = 6) -> str:
"""
Generate some random characers to use in the captcha.
Parameters
----------
N : int
Number of characters to generate.
Returns
-------
str
A pseudo-random sequence of lowercase letters and ... | bigcode/self-oss-instruct-sc2-concepts |
def decrease(raw_table, base_index):
""" Convert decrease flag to english """
if raw_table[base_index] == 0:
return "stop"
else:
return "lowering" | bigcode/self-oss-instruct-sc2-concepts |
from passlib.context import CryptContext
def make_passwordmanager(schemes=None):
"""
schemes contains a list of replace this list with the hash(es) you wish
to support.
this example sets pbkdf2_sha256 as the default,
with support for legacy bcrypt hashes.
:param schemes:
:return: CryptCon... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def predict_fn(input_data, model):
""" Predict stock prices
Parameters:
----------
input_data(num of samples, lookback): input data
model: trained model
Returns:
--------
output (num of samples, output_size): predictions
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def missing_metadata_field() -> str:
"""Return a schema with missing metadata key."""
return """{
"type": "struct",
"fields": [
{ "type": "string", "nullable": true,
"name": "name", "metadata": {} },
{ "type": "integer", "nullable": true,
"... | bigcode/self-oss-instruct-sc2-concepts |
def after_space(s):
"""
Returns a copy of s after the first space
Parameter s: the string to slice
Precondition: s is a string with at least one space
"""
return s[s.find(' ') + 1:] | bigcode/self-oss-instruct-sc2-concepts |
def binom(n, k):
"""
*DESCRIPTION OF FUNCTION*
Parameters
----------
n : int
First number in the binomial coefficient. Can be thought of as the set being drawn from
k : int
Second number in the binomial coefficient. Can be thought of as being the nuber of items drawn from the se... | bigcode/self-oss-instruct-sc2-concepts |
def no_duplicates(route):
"""
This function removes duplicate nodes that may be present in a route, ensuring it can be plotted.
Parameters
----------
route : list
list of nodes traversed by route, in order
Returns
-------
route : list
list of nodes traversed by route, i... | bigcode/self-oss-instruct-sc2-concepts |
def single_function_to_run(batch, function_to_run):
"""
apply a list of functions on a batch of data
"""
for fn in function_to_run:
batch = fn(batch)
return batch | bigcode/self-oss-instruct-sc2-concepts |
import re
def de_camel(s: str, separator: str = "_", _lowercase: bool = True) -> str:
""" Returns the string with CamelCase converted to underscores, e.g.,
de_camel("TomDeSmedt", "-") => "tom-de-smedt"
de_camel("getHTTPResponse2) => "get_http_response2"
"""
s = re.sub(r"([a-z0-9])([A-Z])",... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def wordpiece_tokens_to_normalized_text(wordpiece_tokens: Sequence[str]) -> str:
"""Concatenates wordpiece tokens to a normalized text and cleans up.
The wordpiece tokens are results from BERT tokenization. They may contain
symbols of '##' or ' ##' and some extra whitespaces. The fu... | bigcode/self-oss-instruct-sc2-concepts |
def get_string_by_card(all_strings, card=None, string_number=None):
"""Reduce the boundary_strings dataframe to a single card type or
a single string number
Args:
all_strings: dataframe
AdhSimulation.BoundaryCondition.boundary_strings dataframe
card: string
String ca... | bigcode/self-oss-instruct-sc2-concepts |
def which_percentile(value, d):
"""
Returns the percentile of 'value' in 'd's distribution.
:param value: The value whose percentile is required
:param d: A pandas.Series or Numpy array which represents the distribution
:return: int
"""
if len(d) == 0:
return 0
return sum(d < va... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Callable
def solve_volume_based_compartments(
compartments: List[Dict[str, float]], volume_nomo: Callable
) -> List[Dict[str, float]]:
"""Traverse a series of volume-based nomographs from the bottom compartment (retention)
to the top compa... | bigcode/self-oss-instruct-sc2-concepts |
import re
def build_key_pattern(genus):
"""Build a regex pattern for the genus key
Parameters:
genus - the genus of the file (a string)
The pattern has one subgroup: the genus and species name
"""
# --- Species name from index line ---
#
# Relies on the assumption that index lin... | bigcode/self-oss-instruct-sc2-concepts |
def first(t):
"""Return first item in array or None."""
return t[0] if t else None | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Optional
def torch_huber(
y_true: torch.Tensor,
y_pred: torch.Tensor,
sample_weight: Optional[torch.Tensor] = None,
a: float = 0.9,
):
"""Computes Mean Huber Error.
Args:
y_true: true target values.
y_pred: predicted target values.
sampl... | bigcode/self-oss-instruct-sc2-concepts |
def date_to_json(value, obj):
"""Serialize a Date value."""
if value is None:
return value
else:
return value.strftime('%Y-%m-%dT%H:%M:%S.%f') | bigcode/self-oss-instruct-sc2-concepts |
def _html_template(site_name, author, js_snippet, css_snippet):
"""Create a HTML Template given a site name,
author, snippet to include JS files and CSS files
"""
template_data = {
'site_name': site_name,
'author': author,
'js': js_snippet,
'css': css_snippet
}
wi... | bigcode/self-oss-instruct-sc2-concepts |
def import_default(module_name, force=False, default=None):
"""
Provide an implementation for a class or function when it can't be imported
or when force is True.
This is used to replicate Pandas APIs that are missing or insufficient
(thus the force option) in early pandas versions.
"""
i... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_distance_2points(p1: tuple, p2: tuple):
"""
uses the hypothenus method to calculate the straight line distance between two given points on a 2d cartesian plane.
:param p1: point 1
:param p2: point 2
:return:
"""
return math.hypot(p2[0] - p1[0], p2[1] - p1[1]) | bigcode/self-oss-instruct-sc2-concepts |
import time
def format_timestamp(secs):
"""Format a UNIX timestamp using ISO 8601 format.
Args:
secs: the number of seconds since the Epoch to convert into a timestamp
Returns:
an ISO 8601 compliant timestamp of the form "yyyy-mm-ddThh:mm:ssZ"
"""
return time.strftime("%Y-%m-%dT%H... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_table(table_lines):
"""Parse lines into a table.
Table example:
```txt
ID# Name Designation IAU/aliases/other
------- ---------------------------------- ----------- -------------------
0 Solar System Barycenter ... | bigcode/self-oss-instruct-sc2-concepts |
def getBucketName(year, month, day, radar):
""" Get the name of a specific bucket where radar data is stored.
Args:
year: Year as an integer.
month: Month as an integer.
day: Day as an integer.
radar: The 4 letter name of the radar, a string.
Returns:
The bucket nam... | bigcode/self-oss-instruct-sc2-concepts |
import math
def __get_pooled_standard_deviation(s1: float, s2: float,
n1: int, n2: int) -> float:
"""Calcultes pooled standard deviation
Args:
s1 (float): standard deviation of sample 1
s2 (float): standard deviation of sample 2
n1 (int): no observa... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def status_from_analysis(line):
"""
Utility method to obtain the process status boolean flags from the relative line in the final analysis output
text file.
:param line: string from log file
:return: list of boolean status flags
"""
line = line.strip().split('\t')
return [a... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import glob
import torch
def read_expert_trajectories(folder_path):
"""
reads expert features found in folder_path.
:return: torch tensor of all features of all expert trajectories.
:rtype: torch float tensor, shape of (num of total features x feature length)
"""
fea... | bigcode/self-oss-instruct-sc2-concepts |
def add_parser_arguments(parser):
"""Add arguments to an `argparse.ArgumentParser`."""
parser.add_argument(
'--data',
type=str,
help='path to AnnData object with "spliced", "unspliced", "ambiguous" in `.layers`',
)
parser.add_argument(
'--out_path',
type=str,
... | bigcode/self-oss-instruct-sc2-concepts |
def manage_addBooleanIndex(self, id, extra=None,
REQUEST=None, RESPONSE=None, URL3=None):
"""Add a boolean index"""
return self.manage_addIndex(
id, 'BooleanIndex', extra=extra,
REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL3) | bigcode/self-oss-instruct-sc2-concepts |
def combineLabels(timexLabels, eventLabels, OLabels=[]):
"""
combineTimexEventLabels():
merge event and timex labels into one list, adding instance ids
@param timexLabels: list of timex labels for entities.
@param eventLabels: list of event labels for entities. Includes no instances labeled as ... | bigcode/self-oss-instruct-sc2-concepts |
def is_image(tensor):
"""
Check if a tensor has the shape of
a valid image for tensorboard logging.
Valid image: RGB, RGBD, GrayScale
:param tensor: (np.ndarray or tf.placeholder)
:return: (bool)
"""
return len(tensor.shape) == 3 and tensor.shape[-1] in [1, 3, 4] | bigcode/self-oss-instruct-sc2-concepts |
def slice_parents(parent1, parent2):
"""
Crossover method 1:
====================
Slices the seeds of both parents in the middle and combines them.
Retruns the combines new seeds.
"""
length = len(parent1) // 2
child_seeds = parent1[:length] + parent2[length:]
return child_seeds | bigcode/self-oss-instruct-sc2-concepts |
def file_to_ids(file_path):
"""Read one line per file and assign it an ID.
Args:
file_path: str, path of file to read
Returns: dict, mapping str to ID (int)
"""
str2id = dict()
with open(file_path) as file:
for i, line in enumerate(file):
str2id[line.strip()] = i
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def is_close(
actual: Union[int, float], expected: Union[int, float], threshold: Union[int, float]
) -> bool:
"""Compare the difference between two input numbers with specified threshold."""
return abs(round(actual, 2) - round(expected, 2)) <= threshold | bigcode/self-oss-instruct-sc2-concepts |
def replace_consts_with_values(s, c):
"""
Replace the constants in a given string s with the values in a list c.
:param s: A given phenotype string.
:param c: A list of values which will replace the constants in the
phenotype string.
:return: The phenotype string with the constants replaced... | bigcode/self-oss-instruct-sc2-concepts |
import random
def calculate_countdown__random(count: int, index: int, duration: int) -> int:
"""
把周期任务通过随机数的方式平均分布到 duration 秒 内执行,用于削峰
:param count: 任务总数
:param index: 当前任务索引
:param duration: 执行周期
:return: 执行倒计时(s)
"""
return random.randint(0, max(duration - 1, 1)) | bigcode/self-oss-instruct-sc2-concepts |
def _retrieve_door_state(data, lock):
"""Get the latest state of the DoorSense sensor."""
return data.get_door_state(lock.device_id) | bigcode/self-oss-instruct-sc2-concepts |
def read_file(filename):
"""Reads a file.
"""
try:
with open(filename, 'r') as f:
data = f.read()
except IOError as e:
return (False, u'I/O error "{}" while opening or reading {}'.format(e.strerror, filename))
except:
return (False, u'Unknown error opening or re... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
import yaml
from pathlib import Path
def read_yaml_file(filename: str) -> Dict[str, Any]:
"""Reads a YAML file, safe loads, and returns the dictionary"""
cfg: Dict[str, Any] = yaml.safe_load(Path(filename).read_text())
return cfg | bigcode/self-oss-instruct-sc2-concepts |
import torch
def mask_center(x: torch.Tensor, mask_from: int, mask_to: int) -> torch.Tensor:
"""
Initializes a mask with the center filled in.
Args:
mask_from: Part of center to start filling.
mask_to: Part of center to end filling.
Returns:
A mask with the center filled.
... | 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.