seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import six
def find_dict(iterable, **rules):
"""Search for dict in iterable of dicts using specified key-value rules."""
for item in iterable:
# assert all key-value pairs from rules dict
ok = True
for k, v in six.iteritems(rules):
ok = ok and k in item and item[k] == v
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_field_by_name(model, field):
"""
Retrieve a field instance from a model by its name.
"""
field_dict = {x.name: x for x in model._meta.get_fields()} # noqa
return field_dict[field] | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_distance(i, j):
"""
Calculates the number of rounds before two songs would meet in a match.
If the songs would meet in the first round, returns 0. To determine a more
human-readable (1-indexed) round number for when two songs would meet (or,
the maximum number of rounds), call... | bigcode/self-oss-instruct-sc2-concepts |
def count_trees_in_path(matrix, start, slope):
"""Given a slice of a larger repeating matrix, and a slope for
a path through the matrix, count the number of trees in the path.
:param matrix: 2D array representing slice of larger matrix
:param start: tuple of starting position
:param slope: tuple of run/rise (rig... | bigcode/self-oss-instruct-sc2-concepts |
def scatter2D(ax,x,y,colorList,ec='black'):
"""
This function is to be called by makeScatter2D, creates a 2D scatter plot on a given axis with
colors determined by the given colorHandler or an optional override
:Arguments:
:type ax: matplotlib Axis2D
:param ax: Axis on which scatter... | bigcode/self-oss-instruct-sc2-concepts |
def _get_urls(driver):
"""Returns the list of URLs in tabs."""
urls = []
for w in driver.window_handles:
driver.switch_to.window(w)
urls.append(driver.current_url)
list.sort(urls)
return urls | bigcode/self-oss-instruct-sc2-concepts |
def get_micro_secs(real_str: str) -> int:
"""
If there is a decimal point returns fractional part as an integer in units
based on 10 to minus 6 ie if dealing with time; real_str is in seconds and any factional
part is returned as an integer representing microseconds. Zero returned if no factional part
... | bigcode/self-oss-instruct-sc2-concepts |
def idx_to_string(val):
"""Convert index to base pair
"""
idx_to_string = {0: "A",
1: "C",
2: "G",
3: "T"}
return idx_to_string[val] | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_username_valid(username):
"""
Check if a username is valid.
:param username: The username to validate.
:return: True if the username is valid; False otherwise.
"""
valid_username_regex = re.compile('^[a-zA-Z0-9\-_]+$')
return bool(re.match(valid_username_regex, username)) | bigcode/self-oss-instruct-sc2-concepts |
def batch_all(dataset, batch_size):
"""Batches all splits in a dataset into batches of size `batch_size`."""
return {
key: dataset[key].batch(batch_size)
for key in dataset.keys()
} | bigcode/self-oss-instruct-sc2-concepts |
def translate(rna_sequence):
"""
Compute the protein that will be produced by the given RNA sequence.
Parameters
----------
rna_sequence : string
The RNA strand we are evaluating.
Returns
-------
protein : string
The resulting protein from evaluating the codons in the R... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def build_schedule(lr: float, final_lr: float, n_epochs: int) -> Callable:
"""
Builds the schedule of which the learning rate decreases.
The schedule makes the learning rate decrease linearly.
:param lr: initial learning rate.
:param final_lr: final learning rate.
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def LoadNotebook(filename):
"""Read a IPython notebook (.ipynb).
Reads the file and parses it as JSON.
Args:
filename: The path to the .ipynb file.
Returns:
A parsed JSON object (dictionary).
"""
with open(filename) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def df_drop_duplicated_index(df):
"""Drop all duplicated indices in a dataframe or series"""
df2 = df.copy()
return df2[~df2.index.duplicated(keep='first')] | bigcode/self-oss-instruct-sc2-concepts |
def meanSubNormalize(cyDf, cyVars=None, compCommVars=None, meanVar=None):
"""Normalize cytokine columns by the log-mean for each patient, within each compartment.
The point is that if cytokine concentrations are generally high for one sample or another,
this might dominate the covariation of cytokines acros... | bigcode/self-oss-instruct-sc2-concepts |
def select(iterable, conditional):
"""
Looks through each value in the list, returning an array of all the values that pass a truth test (conditional).
params: conditional, iterable
iterable -> list, sequenece, set, dictionary, generator etc
conditional -> a lambda or function that takes ... | bigcode/self-oss-instruct-sc2-concepts |
def pad(names):
"""
Make all strings in list *names* the same size for f2py's benefit.
"""
return [ "%-16s"%v for v in names ] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def hflip_bboxes_helper(bbox: Tuple, **kwargs) -> Tuple:
"""
When the src image is horizontally flipped, the bounding box also gets horizontally
flipped
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
return (1 - right_factor, upper_factor, 1 - left_fa... | bigcode/self-oss-instruct-sc2-concepts |
def is_supported_english_translation(translation):
"""
A helper function to determine if the provided string is a supported English translation.
:param translation: Translation code
:type translation: str
:return: True = the translation is not supported, False = the translation is supported
:rt... | bigcode/self-oss-instruct-sc2-concepts |
def load_haiku(filename):
"""Open and return training corpus of haiku as a set."""
with open(filename) as in_file:
haiku = set(in_file.read().replace('-', ' ').split())
return haiku | bigcode/self-oss-instruct-sc2-concepts |
def isType(val, types):
"""
Check if val is of a type in types.
"""
for a_type in types:
if isinstance(val, a_type):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def int_to_rgb(rgb_int):
"""
Given an integer, converts to to RGB value. Any integer outside
the range of (0, 16777215) will raise an invalid
>>> int_to_rgb(-1)
Traceback (most recent call last):
...
ValueError: Integer must be in range [0, 16777215], got -1.
>>> int_to_rgb(0)
(0, 0,... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
from typing import Dict
from typing import Any
def ConfigParser_to_Dict(config: configparser.ConfigParser) -> Dict:
"""
Convert ConfigParser object to dictionary.
The resulting dictionary has sections as keys which point to a dict of the
section options as key => value pairs.
I... | bigcode/self-oss-instruct-sc2-concepts |
def timestamp(date_object):
"""Generate a trakt formatted timestamp from the given date object"""
fmt = '%Y-%m-%d:T%H:%M:%S.000Z'
return date_object.strftime(fmt) | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_sale(this_line):
"""Determine whether a given line describes a sale of cattle."""
has_price = re.search(r'[0-9]+', this_line)
is_not_succinct = len(re.split(r'\s{3,}',this_line)) > 3
return bool(has_price and is_not_succinct) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
def total_zones(endpoints: List[Dict[str, Dict[str, Any]]]) -> int:
"""
Returns the true unique number of zones, taking into account
that multiple endpoints can have the same zone name.
- us-west-1
- us-west-1 == 2 zones
... | bigcode/self-oss-instruct-sc2-concepts |
def get(isamAppliance, kdb_id, cert_id, check_mode=False, force=False):
"""
Retrieving a personal certificate from a certificate database
"""
return isamAppliance.invoke_get("Retrieving a personal certificate from a certificate database",
"/isam/ssl_certificates/{0}/p... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Any
def cast2lowercase(input: Union[list, tuple, str]) -> Any:
"""Cast input into lowercase.
Example:
>>> cast2lowercase('Hello World')
'hello world'
>>> cast2lowercase(['Hello', 'World'])
['hello', 'world']
"""
inputs = []
... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def get_random_string(n):
""" Create random string with len `n`
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=n)) | bigcode/self-oss-instruct-sc2-concepts |
def c_string_to_str(array) -> str:
"""
Cast C-string byte array to ``str``.
"""
return bytes(array).partition(b'\0')[0].decode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def etag_checksum(filename: str, chunk_size: int = 8 * 1024 ** 2) -> str:
"""\
Compute the `ETag` digest (which is not the `MD5` digest) of an object.
:param filename:
Path to file target file
:param chunk_size:
Chunk size to hash
:return:
`ETag` `hexdigest... | bigcode/self-oss-instruct-sc2-concepts |
def get_itim(tree, hart):
"""Get the ITIM associated with the hart"""
itim_ref = hart.get_field("sifive,itim")
if itim_ref:
itim = tree.get_by_reference(itim_ref)
return itim
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_sma(data, length):
""" Returns the simple moving average over a period of LENGTH """
if len(data) < length:
return "Not enough Data"
subset = data[-length:]
return sum(subset) / len(subset) | bigcode/self-oss-instruct-sc2-concepts |
def filter_timeseries_by_columns(data, columns):
"""
Filters features in multi-variate time series data
input (data): 3D numpy array with time series format
input (cols): array with columns (integer encoded) to be chosen
return (data): 3D numpy array with no. of featues = len(columns)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_n_bits(report):
"""Gets the number of bits that have each line from the input report.
Args:
report (list): Input report that contains a binary number for each line.
Returns:
int: How many bits have each binary number.
"""
return len(report[0])-1 | bigcode/self-oss-instruct-sc2-concepts |
def is_int(string):
"""
Check if `string` can be converted
into an int.
Parameters
----------
string : str
String to check.
Returns
-------
check : bool
True if `string` can be converted.
"""
try:
int(string)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def eval_expr(expr: str) -> str:
"""
Compute and return the result of *expr*.
>>> eval_expr("2 ^ 30")
'1073741824'
*expr* is sanitized and only a small range of characters are allowed:
>>> eval_expr("cat /etc/passwd") # doctest: +ELLIPSIS
Traceback (most recen... | bigcode/self-oss-instruct-sc2-concepts |
def get_var_val(key, ii, varDict):
"""Gets an input in the likes of ${var} and returns the corresponding var value from the dict
Parameters
----------
key: string
unparsed key of var
ii: int
current iteration idx
varDict: dict
variable dictionary
Returns
-------... | bigcode/self-oss-instruct-sc2-concepts |
import typing
from typing import Any
def repr_for_fp(fp: typing.IO[Any]) -> str:
"""
Helper to make a useful repr() for a file-like object.
"""
name = getattr(fp, "name", None)
if name is not None:
return repr(name)
else:
return repr(fp) | bigcode/self-oss-instruct-sc2-concepts |
import re
def ignore_timestamp(text):
"""
Remove a time stamp from a string to ease comparison.
This function removes timestamps generated using the following method::
time.strftime('%B %e, %Y at %H:%M')
This makes it easy to compare two strings for equality without even though
the embe... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _ceil_with_max(num, max_value):
"""
Ceil function that also takes a max value, to deal with possible rounding errors.
Rounding errors in floats can cause out of index errors when we index into an array.
"""
return min(math.ceil(num), max_value) | bigcode/self-oss-instruct-sc2-concepts |
def _string_parser(strip_whitespace):
"""Returns a parser function for parsing string values"""
def _parse_string_value(element_text, _state):
if element_text is None:
value = ''
elif strip_whitespace:
value = element_text.strip()
else:
value = element... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import re
def do_substitution(content: str, pattern_sub: list[Tuple[re.Pattern, str]]) -> str:
"""Do the substitution using pattern and sub."""
for pattern, sub in pattern_sub:
content = pattern.sub(sub, content)
return content | bigcode/self-oss-instruct-sc2-concepts |
def estimate_lm_score(sequence, ngrams):
"""
Compute the log score of a sequence according to given language model.
:param sequence: list of token ids
:param ngrams: list of dicts, as returned by `read_ngrams`
:return: log probability of `sequence`
P(w_3 | w_1, w_2) =
log_prob(w_1 w_2 w_... | bigcode/self-oss-instruct-sc2-concepts |
def remap_range(
val: float,
old_min: float,
old_max: float,
new_min: float,
new_max: float,
) -> float:
"""
Remaps a value from one range to another range.
Args:
val: A number form the old range to be rescaled.
old_min: The inclusive 'lower' bound of the old range.
... | bigcode/self-oss-instruct-sc2-concepts |
def _read_statements(filename):
"""
reads sql statements from file, where statements are separated using a single
newline
:param filename: path to ascii file contaning sql statements
:return: list of sql statements
"""
with open(filename, 'r') as f:
lines = f.readlines()
# on uni... | bigcode/self-oss-instruct-sc2-concepts |
def hashToBinary(hashValue):
"""Convert hashed value of type bytes32 into an array of binary digits in a string"""
tmp = bin(int(hashValue, 16))[2:];
prefix = '0' * (256 - len(tmp))
return prefix + tmp; | bigcode/self-oss-instruct-sc2-concepts |
def trim(string):
"""Trim a multi-line string (the idea is taken from PEP 257)."""
lines = string.splitlines()
indent = 0
while lines[1][indent] == ' ':
indent += 1
return lines[0] + '\n' + '\n'.join(line[indent:] for line in lines[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def insert_sil(phones):
"""
Insert silences.
Parameters
----------
phones : list
A list of phone sequence
Returns
-------
out : list
A list of new labels.
"""
out = []
for i,(s,e,p) in enumerate(phones):
if out:
if out[-1][... | bigcode/self-oss-instruct-sc2-concepts |
def get_file_source(filename):
# type: (str) -> str
"""Read the source of a file.
This convenience function is present to match the interface of get_module_source.
Args:
filename (str): the path of the file to read
Returns:
str: the contents of the file
"""
with open(filen... | bigcode/self-oss-instruct-sc2-concepts |
def compute_log_zT(log_rho, log_seebeck, log_kappa, log_temperature):
"""Returns the log of the thermoelectric figure of merit."""
return 2 * log_seebeck + log_temperature - log_rho - log_kappa | bigcode/self-oss-instruct-sc2-concepts |
def ret_normalized_vec(vec, length):
"""Normalize a vector in L2 (Euclidean unit norm).
Parameters
----------
vec : list of (int, number)
Input vector in BoW format.
length : float
Length of vector
Returns
-------
list of (int, number)
L2-normalized vector in Bo... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_discrete_classifier_point(instances, threshold):
"""
From a list of instances, calculate the coordinates for a discrete classifier
that uses the given threshold.
"""
TP = 0 # True positives
FP = 0 # False positives
P = 0 # Total positives
N = 0 # Total negatives
fo... | bigcode/self-oss-instruct-sc2-concepts |
def remote_prd_mock(url, request):
"""
Mock for remote PRD info.
"""
thebody = b'{"PRD-63999-999":{"curef":"PRD-63999-999","variant":"Snek","last_ota":"AAZ888","last_full":"AAZ999"}}'
return {'status_code': 200, 'content': thebody} | bigcode/self-oss-instruct-sc2-concepts |
def add_columns_with_default(event, field_and_default_dict):
""" Adds a column with the default value to every event where it's not already present
:param event: A dictionary
:param field_and_default_dict: A dictionary with keys and default values {field_1: default_for_field_1, field_2: default_for_field_2... | bigcode/self-oss-instruct-sc2-concepts |
import re
def modify_flexlogger_paths(s: str) -> str:
"""Modify flexlogger.* paths in the given string to hide implementation modules.
Examples:
>>> # Basic usage
>>> modify_flexlogger_paths("flexlogger.foo._abc.Abc")
'flexlogger.foo.Abc'
>>> # Modify all paths in the string
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_feed_by_path(path):
"""
This fetches the feed from a given path
:param path: Full path to file
:return: DiscoFeed as python object
"""
try:
with open(path, 'r') as fin:
return json.load(fin)
except:
raise Exception("Could not read file or rec... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _default_parse(raw_inp, choices, *args):
"""
Helper to parse default input to a node decorated with the node_list decorator on
the form l1, l 2, look 1, etc. Spaces are ignored, as is case.
Args:
raw_inp (str): Input from the user.
choices (list): List of available optio... | bigcode/self-oss-instruct-sc2-concepts |
def import_profile(database, species, loci_list):
"""Import all possible allele profiles with corresponding st's
for the species into a dict. The profiles are stored in a dict
of dicts, to easily look up what st types are accosiated with
a specific allele number of each loci.
"""
# Open allele p... | bigcode/self-oss-instruct-sc2-concepts |
def sortedSeasons(m):
"""Return a sorted list of seasons of the given series."""
seasons = m.get('episodes', {}).keys()
seasons.sort()
return seasons | bigcode/self-oss-instruct-sc2-concepts |
from typing import ByteString
from typing import Optional
def hexdump_line(_bytes: ByteString, length: Optional[int] = None) -> str:
"""Create a hexdump formatted line for supplied bytes.
If length is greater than len(_bytes), the line will be padded with ASCII
space characters to indicate no byte data i... | bigcode/self-oss-instruct-sc2-concepts |
def is_aware(dtime):
"""test if a datetime instance is timezone aware"""
if dtime.tzinfo is not None and dtime.tzinfo.utcoffset(dtime) is not None:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def bad_words_getter(occurences, occurences_min=2):
"""From a dictionnary, returns in a list all keys with lower value than the minimum given in input """
"""In the context: returns all words that appears less than the minimum given"""
bad_words = []
for key,value in occurences.items():
if value... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def dt_encode_topic(topic: str) -> str:
"""
Encode any string to be accepted by Digital Twin setSource. Use byte encoding and sha256-hashing.
:param topic: Topic name to be encoded.
:return: Hashed-encoded topic name
"""
return f"0x{hashlib.sha256(topic.encode('utf-8')).hexd... | bigcode/self-oss-instruct-sc2-concepts |
def merge_list(wordlists):
"""
this function merges all the wordlist(dictionary) into one, and return it
:param wordlists: an array contain all the wordlist(dictionary type)
:return: the merged word list (dictionary type)
"""
mergelist = {}
for wordlist in wordlists:
for key in word... | bigcode/self-oss-instruct-sc2-concepts |
def validate_float_value(float_value_input,
greater_than=None, less_than=None):
"""
The purpose of this function is to validate that a float value is valid.
The value, its range (either greater than or less than a number) may
also be tested. This function will bark if the valu... | bigcode/self-oss-instruct-sc2-concepts |
def repattr(obj, name, value):
"""Sets an attribute of a class/object. Returns the old value.
"""
old = getattr(obj, name)
setattr(obj, name, value)
return old | bigcode/self-oss-instruct-sc2-concepts |
def median(iterable, sort=True):
""" Returns the value that separates the lower half from the higher half of values in the list.
"""
s = sorted(iterable) if sort is True else list(iterable)
n = len(s)
if n == 0:
raise ValueError("median() arg is an empty sequence")
if n % 2 == 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def possible_moves(state: list) -> list:
"""
Returns list of all possible moves
For the given board position 'state' returns
list of all possible moves for the next turn
Parameters
----------
state : list
The board position to be evaluated
"""
moves = []
for x, row in ... | bigcode/self-oss-instruct-sc2-concepts |
import secrets
def passphrase(w, n):
"""
Generate passphrase
:param w: word list
:type w: list
:param n: number of words
:type n: int
:return: passphrase
:rtype: str
"""
# Store the random string
rd = ""
# Get n random words
for _ in range(n):
rd += secrets... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def predict_number_of_row_from_conf(conf):
"""
Precict the number of row of the fake data set generated by `fake_data_generator(conf)`
This is the product of number of values for each label
"""
num_uniques_by_label = [len(c.get('values', [])) for c in conf if c['type']... | bigcode/self-oss-instruct-sc2-concepts |
def inductive_split(g):
"""Split the graph into training graph, validation graph, and test graph by training
and validation masks. Suitable for inductive models."""
train_g = g.subgraph(g.ndata['train_mask'])
val_g = g.subgraph(g.ndata['train_mask'] | g.ndata['val_mask'])
test_g = g
return trai... | bigcode/self-oss-instruct-sc2-concepts |
def swap(array, idx_x, idx_y):
"""
Swap two values within an array. Mutates array!
:param array: array
:type array: list[any]
:param idx_x: index of a value
:type idx_x: int
:param idx_y: index of another value
:type idx_y: int
:return: array with swapped elements
"""
temp =... | bigcode/self-oss-instruct-sc2-concepts |
import time
def _get_expiration_time(expiry_seconds):
"""Return a timestamp |expiry_seconds| from now."""
return int(time.time() + expiry_seconds) | bigcode/self-oss-instruct-sc2-concepts |
def getGitRepositoryDownloadUrl(url: str) -> str:
"""
Takes a git repository url 'url' and returns the url to the master zip.
:param url: The url to a Github repository.
:return: The url to the master archive of the repository.
"""
return url + ('/' if url[-1] != '/' else '') + 'archive/master.... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Any
def join_any(sep: str, args: Sequence[Any]) -> str:
"""Joins multiple values together in a string using their `str` operator."""
return sep.join([ str(arg) for arg in args ]) | bigcode/self-oss-instruct-sc2-concepts |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
for i in range(0, len(seq)):
iMin = i
for j in range(i+1, len(seq)):
if seq[iMin... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def codeblock(block_str):
"""
Convinience function for defining code strings. Esspecially useful for
templated code.
"""
return textwrap.dedent(block_str).strip('\n') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
import fnmatch
def exclude_file(
exclude: Optional[List[str]] = None,
include: Optional[List[str]] = None,
filename: str = "",
) -> bool:
"""Check if the file should be included during any operations.
Process exclude list first than use include ... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def generate_identifier(size = 16, chars = string.ascii_uppercase + string.digits):
"""
Generates a random identifier (may be used as password) with
the provided constrains of length and character ranges.
This function may be used in the generation of random based
keys... | bigcode/self-oss-instruct-sc2-concepts |
def ec2_id_to_id(ec2_id):
"""Convert an ec2 ID (i-[base 16 number]) to an instance id (int)"""
return int(ec2_id.split('-')[-1], 16) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def xyxy2xywh(boxes):
""" xyxy -> xywh
(xmin,ymin,xmax,ymax) and (xcenter,ycenter,width,height)
Args:
boxes: torch.FloatTensor[N,4]
"""
w = boxes[:, 2] - boxes[:, 0] + 1
h = boxes[:, 3] - boxes[:, 1] + 1
# center
x = boxes[:, 0] + 0.5 * w
y = boxes[:, 1] + 0.5 ... | bigcode/self-oss-instruct-sc2-concepts |
import zlib
import struct
def CheckFCS(frame):
"""Return true when the FCS at the end of the frame is correct, i.e. the frame is not corrupted
"""
crc32 = zlib.crc32(frame[:-4])
fcs = struct.unpack('l', frame[-4:])[0]
return fcs == crc32 | bigcode/self-oss-instruct-sc2-concepts |
import array
def zeroByteArray(cb):
"""Returns an array with the given size containing 0."""
abArray = array.array('B', (0, ));
cb = cb - 1;
for i in range(cb): # pylint: disable=W0612
abArray.append(0);
return abArray; | bigcode/self-oss-instruct-sc2-concepts |
def default_setpoint_array(dataset, measured_name='measured'):
""" Return the default setpoint array for a dataset """
setpoint_array = dataset.default_parameter_array(measured_name).set_arrays[0]
return setpoint_array | bigcode/self-oss-instruct-sc2-concepts |
import json
def convert(x):
""" Convert a json string to a flat python dictionary
which can be passed into Pandas. """
ob = json.loads(x)
for k, v in ob.items():
if isinstance(v, list):
ob[k] = ",".join(v)
elif isinstance(v, dict):
for kk, vv in v.items():
... | bigcode/self-oss-instruct-sc2-concepts |
def day_to_int(day):
"""
day: a string representing the day of the week
Returns an integer
e.g. "MONDAY" -> 0, "TUESDAY" -> 1, etc.
"""
days = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
return days.index(day.upper()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def latern_fish_growth(laternfish, days, timer=8):
"""Models latern fish growth and returns number of fish after n days"""
tracker = Counter()
for i in range(timer + 1):
tracker[i] = 0
# starting values of each latern fish
for i in laternfish:
tracker[i... | bigcode/self-oss-instruct-sc2-concepts |
def tcl_findprd_prepd_start(prddict):
"""
Collect list of PRD entries.
:param prddict: Device:PRD dictionary.
:type prddict: dict(str: list)
"""
prda = []
for item in prddict.values():
prda.extend(item)
return prda | bigcode/self-oss-instruct-sc2-concepts |
def create_problem_instance(model, loaded_data):
"""
:param model: the AbstractModel Pyomo object with components added
:param loaded_data: the DataPortal object with the data loaded in and
linked to the relevant model components
:return: the compiled problem instance
Compile the problem ba... | bigcode/self-oss-instruct-sc2-concepts |
def human_format(num):
"""Make a nice human readable format for numbers."""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return "%.2f%s" % (num, ["", "K", "M", "B", "T", "P"][magnitude]) | bigcode/self-oss-instruct-sc2-concepts |
def is_file_empty(file_name) -> bool:
""" Check if file is empty by reading first character in it"""
# open ile in read mode
with open(file_name, 'r') as read_obj:
# read first character
one_char = read_obj.read(1)
# if not fetched then file is empty
if not one_char:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_phy_intfs(host_ans):
"""
@Summary: Get the physical interfaces (e.g., EthernetX) of a DUT
@param host_ans: Ansible host instance of this DUT
@return: Return the list of active interfaces
"""
intf_facts = host_ans.interface_facts()['ansible_facts']['ansible_interface_facts']
phy_intf... | bigcode/self-oss-instruct-sc2-concepts |
def divide_chunks(a_list, n):
"""Divide a list into chunks of size n.
:param a_list: an entry list.
:param n: size of each chunk.
:return: chunks in a list object.
"""
return [a_list[i:i + n] for i in range(0, len(a_list), n)] | bigcode/self-oss-instruct-sc2-concepts |
def find_balancing_cutoff_index(data, trials):
"""find the length of the shortest trial to balance the other experimental trials accordingly
Parameters
----------
data : dictionary
data dictionary consisting of trials from each subject
trials : list
list of experimental trials p... | bigcode/self-oss-instruct-sc2-concepts |
async def get_page(browser, url, selector):
"""Return a page after waiting for the given selector"""
page = await browser.newPage()
await page.goto(url)
await page.waitForSelector(selector)
return page | bigcode/self-oss-instruct-sc2-concepts |
def apply_mask(binary: str, mask: str) -> str:
"""Apply the parm mask to the parm binary number.
A 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged."""
result = ''
for place in range(36):
if mask[place] == 'X':
result += binar... | bigcode/self-oss-instruct-sc2-concepts |
def transpose_blocks(blocks, block_len):
"""
Returns a transposition of the elements in items.
E.g. ["AB","CD"] -> [["A", "C"], ["B", "D"]]
"""
transpositions = []
for i in range(block_len):
transpositions.append([block[i] for block in blocks])
return transpositions | bigcode/self-oss-instruct-sc2-concepts |
def frenchTextNull(frenchInputNull):
"""
This function returns true if input is empty
"""
if frenchInputNull == '':
return True | bigcode/self-oss-instruct-sc2-concepts |
def gen_mock_key(func_name, key):
# type: (str, str) -> str
"""
Concate function name and the key to store in the mock DB
"""
return '{0}-{1}'.format(func_name, key) | 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.