seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def check_textgrid_duration(textgrid,duration):
"""
Check whether the duration of a textgrid file equals to 'duration'.
If not, replace duration of the textgrid file.
Parameters
----------
textgrid : .TextGrid object
A .TextGrid object.
duration : float
A given length of ti... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def checksum_sha256(file_path, block_size=65536):
"""Get sha256 checksum for a file"""
h = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(block_size), b""):
h.update(chunk)
return h.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def subset_BEA_Use(df, attr):
"""
Function to modify loaded BEA table based on data in the FBA method yaml
:param df: df, flowbyactivity format
:param attr: dictionary, attribute data from method yaml for activity set
:return: modified BEA dataframe
"""
commodity = attr['clean_parameter']
... | bigcode/self-oss-instruct-sc2-concepts |
def is_top_level(comment):
""" returns if the comment is top level (directly replied to the post) """
return comment.parent_id == comment.link_id | bigcode/self-oss-instruct-sc2-concepts |
def togrid(fen):
"""
Takes FEN (without extra information at end) and returns a grid
args: fen[0]
"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR"
returns: grid[0]
[['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], ['', '', '', '', '', '', '', ''], ['', ... | bigcode/self-oss-instruct-sc2-concepts |
def formatNumber(number):
"""Ensures that number is at least length 4 by
adding extra 0s to the front.
"""
temp = str(number)
while len(temp) < 4:
temp = '0' + temp
return temp | bigcode/self-oss-instruct-sc2-concepts |
def praw_to_user(user):
"""
Converts a PRAW user to a dict user.
Args:
user: :class:`praw.models.Redditor`
Note 1: accessing redditor attributes lazily calls reddit API
Note 2: if user.is_suspended is True, other attributes will not exist
Note 3: subreddit refers to a user profile (stored as a subredd... | bigcode/self-oss-instruct-sc2-concepts |
def df_drop_nan_rows(df, verbose=False):
"""Remove entries in dataframe where all rows (besides 'time')
have nan values.
"""
N_init = df.shape[0]
colnames = [c for c in df.columns if c not in ['time', 'turbid', 'index']]
df = df.dropna(axis=0, subset=colnames, how='all')
if verbose:
... | bigcode/self-oss-instruct-sc2-concepts |
def ansible_facts(ansible_module):
"""Return ansible_facts dictionary."""
return ansible_module.setup() | bigcode/self-oss-instruct-sc2-concepts |
def ApplyParsedXPathQuery(trees, xpath_query):
""" Apply a parsed XPath Query to a list (sequence) of `trees`."""
filtered_nodes = iter(trees[:])
for q in xpath_query:
filtered_nodes = q.Filter(filtered_nodes)
return filtered_nodes | bigcode/self-oss-instruct-sc2-concepts |
def ci_lookup(the_key, the_dict, default=None):
"""Case-insensitive lookup
Note that this will not work if keys are not unique in lower case
- it will match the last of the matching keys
>>> the_dict1 = {'Me': 'Andrew', 'You': 'Boris', 'Her': 'Natasha'}
>>> ci_lookup('heR', the_dict1)
... | bigcode/self-oss-instruct-sc2-concepts |
def _lookup_by_value(themap, value):
"""
Do a reverse lookup on a map (assumes 1-to-1)
"""
for k in themap:
if value == themap[k]:
return k
return None | bigcode/self-oss-instruct-sc2-concepts |
def rotated_array_search(nums, target):
"""
Find the index by searching in a rotated sorted array
Args:
nums(array), target(int): Input array to search and the target
Returns:
int: Index or -1
"""
# Binary search, O(n log n) in time and O(1) in space
lo, hi = 0, len(nums)-1
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import json
def deserialize_wikifier_config(uid: str, pid: str, region_filename: str) -> dict:
"""
This function reads and deserialize the wikifier config file
:param uid:
:param pid:
:param region_filename:
:return:
"""
file_path = str(Path.cwd() / "config" / ... | bigcode/self-oss-instruct-sc2-concepts |
def getHeadersFromSWIG (filename):
"""getHeadersFromSWIG (filename) -> (filename1, filename2, .., filenameN)
Reads the list of %include directives from the given SWIG (.i). The
list of C/C++ headers (.h) included is returned.
"""
stream = open(filename)
lines = stream.readlines()
stream.close()
line... | bigcode/self-oss-instruct-sc2-concepts |
def _build_var_list_str(var_names):
"""
Builds the string that contains the list of variables in the parameterized
variable format for SQL statements.
Args:
var_names ([str]): The list of var names, likely the keys in the dict
returned by `_prep_sanitized_vars()`.
Returns:
(str... | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(string: str) -> bool:
"""Checks is given string is palindrome.
Examples:
>>> assert is_palindrome("abccba")
>>>
>>> assert is_palindrome("123321")
>>>
>>> assert not is_palindrome("abccbX")
"""
if not isinstance(string, str):
raise TypeE... | bigcode/self-oss-instruct-sc2-concepts |
def _package_variables(variables, check_type):
""" Removes token and customer id and adds check type to dict data
Removes the token from the dictionary that will be sent to NodePing
in JSON format as well as the customer id since these aren't a part
of the check data. Also adds the check type.
:ty... | bigcode/self-oss-instruct-sc2-concepts |
def has_doc(f):
"""Check if function has doc string."""
return f.__doc__ is not None | bigcode/self-oss-instruct-sc2-concepts |
def key_in_kwargs(key, **kwargs):
""" Tests if a key is found in function kwargs | str, kwargs --> bool """
kwarg_dict = {**kwargs}
if key in kwarg_dict:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def embedding_dimension(vertices):
"""
Get the dimension of the space a simplex is embedded in.
:param vertices: Vertices of the simplex ((n + 1) x m matrix where row i contains the i:th vertex of the simplex).
:return: Dimension m of the space the simplex is embedded in.
:rtype: int
"""
re... | bigcode/self-oss-instruct-sc2-concepts |
def _nbcols(data):
""" retrieve the number of columns of an object
Example
-------
>>> df = pd.DataFrame({"a":np.arange(10),"b":["aa","bb","cc"]*3+["dd"]})
>>> assert _nbcols(df) == 2
>>> assert _nbcols(df.values) == 2
>>> assert _nbcols(df["a"]) == 1
>>> assert _nbcols(df["a"].valu... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def valid_after_from_network_statuses(network_statuses):
"""Obtain the consensus Valid-After datetime from the ``document``
attribute of a ``stem.descriptor.RouterStatusEntryV3``.
:param list network_statuses:
returns datetime:
"""
for ns in network_statuses:
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _check_simulator(simulator):
"""Checks that the simulator is callable and takes just two parameters
For the simulator to be functional within the IMNN it must have a specific
form where it takes a random number and a set of parameter values and
returns a simulation generated at tho... | bigcode/self-oss-instruct-sc2-concepts |
from click.testing import CliRunner
def runner(request):
"""Get a click.CliRunner instance."""
return CliRunner() | bigcode/self-oss-instruct-sc2-concepts |
def _is_sld(model_info, id):
"""
Return True if parameter is a magnetic magnitude or SLD parameter.
"""
if id.startswith('M0:'):
return True
if '_pd' in id or '.' in id:
return False
for p in model_info.parameters.call_parameters:
if p.id == id:
return p.type ... | bigcode/self-oss-instruct-sc2-concepts |
import six
def s(*l):
"""Join all members of list to a byte string. Integer members are converted to bytes"""
r = b''
for e in l:
e = six.int2byte(e)
r = r + e
return r | bigcode/self-oss-instruct-sc2-concepts |
def build_single(sequence, state_size, state):
"""
A small temporary model for lower order Markov Chains called during prediction when previously unseen state is
encountered.
:param sequence: Sequence to learn
:param state_size: Order of the Markov Chain
:param state: Current state
:return: Lower order Markov Ch... | bigcode/self-oss-instruct-sc2-concepts |
def to_vis_json_metagraph(metanodes, cross_edges):
"""Produce Vis.js formatted network data (for children metagraphs).
Args:
metanodes (dict): Metanodes of the metagraph.
cross_edges (dict): Edges running between metanodes.
Returns:
Vis.js formatted network data.
"""
nodes... | bigcode/self-oss-instruct-sc2-concepts |
def B1(tree):
"""
Returns the B1 statistic: the reciprocal of the sum of the maximum
number of nodes between each interior node and tip over all internal
nodes excluding root.
"""
b1 = 0.0
nd_mi = {}
for nd in tree.postorder_node_iter():
if nd._parent_node is None:
co... | bigcode/self-oss-instruct-sc2-concepts |
def _norm2x(xp, xrange, xcenter):
""" Convert normalized x in (-1, 1) back to data x unit
Arguments
xp: float | np1darray in (-1, 1)
xrange: float MHz
xcenter: float MHz
Returns
x: float | np1darray
"""
return xp / 2 * xrange + xcen... | bigcode/self-oss-instruct-sc2-concepts |
def get_confusion_matrix(classes: list, dataclasses: list):
"""
creates a confusion matrix
:param classes: is a one-dimensional list containing the class names
:param dataclasses: a 1-dimensional list containg the orignal and predicted class of each instance in data
:return: a 2-dimensional list wi... | bigcode/self-oss-instruct-sc2-concepts |
def rf_fit(rf, x_train, y_train):
"""
rf_fit will create the Random Forrest with the defined parameters and fit the model to the training data.
Parameters
----------
rf: sklearn.ensemble._forest.RandomForestClassifier
RandomForest which will be trained
x_train: numpy.ndarray
arr... | bigcode/self-oss-instruct-sc2-concepts |
def build_paths(base_path, partial_paths):
"""Build a list of full paths by concatenating each partial path
with the base path"""
paths = [base_path + partial_path for partial_path in partial_paths]
return paths | bigcode/self-oss-instruct-sc2-concepts |
def set_value_where_condition(df, value, col_val, value_cond1, col_cond1):
"""Set a value in a column where multiple conditions are fit
Args:
df (pd.DataFrame): Dataframe.
value (int, float, str): Value to set.
col_val (str): Column name for the set value
value_cond1 (int, f... | bigcode/self-oss-instruct-sc2-concepts |
def return_(value = None):
"""Create a return statement."""
if value is not None:
return [['return', value]]
else:
return [['return']] | bigcode/self-oss-instruct-sc2-concepts |
def hessian_vector_product_lr(label,ypred,x,v,C=0.03,has_l2=True,scale_factor=1.0):
"""Get implicit hessian-vector-products without explicitly building the hessian.
H*v = v + C *X^T*(D*(X*v))
"""
xv = x.dot(v)
D = ypred * (1 - ypred)
dxv = xv * D
if has_l2:
hvp = C * x.T.dot(dxv) + ... | bigcode/self-oss-instruct-sc2-concepts |
def sort_dict_by_vals(dictionary, reverse=True):
"""
Sort dictionary by values
:param dictiory: Dictionary object
:reverse(boolean): Set to True to sort the values in descending order
"""
return {key: value for key, value in
sorted(dictionary.items(), key=lambda item: item[1]... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def validate_ipv6(ip):
"""
Validate an ipv6 address
:param ip: The string with the ip
:return: True ip if it's valid for ipv6, False otherwise
"""
ip = str(ip)
try:
socket.inet_pton(socket.AF_INET6, ip)
except socket.error:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
async def assert_reply_contains(self, contents, substring):
""" Send a message and wait for a response. If the response does not contain
the given substring, fail the test.
:param str contents: The content of the trigger message. (A command)
:param str substring: The string to test against.
:return... | bigcode/self-oss-instruct-sc2-concepts |
def match_predictions(y_predicted, y_target_names, pred_node_predicted, pred_node_target_names):
"""Add final level node prediction results to final level-wide prediction result
This method matches the node prediction result, which is only a small fraction of the whole level prediction, with the level-wide
predict... | bigcode/self-oss-instruct-sc2-concepts |
def mround(x, base=5):
"""Round value x to nearest multiple of base."""
return int(base * round(float(x) / base)) | bigcode/self-oss-instruct-sc2-concepts |
def two_places_at_once(sequence):
"""
Demonstrates iterating (looping) through a sequence,
but examining TWO places in the sequence on the SAME ITERATION.
This particular example returns the number of items in the sequence
that are bigger than the previous item in the sequence.
For example, if ... | bigcode/self-oss-instruct-sc2-concepts |
def binarySearch(alist, item, start, end):
"""
Recursive Binary Search.
O(log(n)) time complexity.
:type alist of ordered values.
:type item to find
:type starting index
:type ending index
"""
if start > end:
return False
mid = (start + end) // 2
if alist[mid] == item:
return True
elif ... | bigcode/self-oss-instruct-sc2-concepts |
def feature_path(node):
"""Returns the feature path of a node."""
if node.is_group():
return [node.name()]
type = node.type()
if not type:
type = '?'
return feature_path(node.parent()) + [type] | bigcode/self-oss-instruct-sc2-concepts |
def emitter_injection_efficiency(i_en=0,i_e=1):
"""
The emitter injection efficiency measures the fraction
of the emitter current carried by the desired electrons
or holes in a NPN or PNP device. The default is for a
NPN device.
Parameters
----------
i_en : float, required
Elect... | bigcode/self-oss-instruct-sc2-concepts |
def count_number_of_this_labels(data_set_list:list,image_path_string:str):
"""
Assumption: that data_set_list has dictionary elements with a 'ImagePath' element
"""
return len([v for v in data_set_list if v["ImagePath"] == image_path_string]) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def FindClusters(xs, flags, active_flag_val):
"""Find repeated ranges of a certain value in a list.
Args:
xs: x coordinate of each value.
flags: values corresponding to each x-coordinate.
active_flag_val: the flag value we're searching for.
Example:
FindClusters([0, 1, 2, 3, 4... | bigcode/self-oss-instruct-sc2-concepts |
def is_complete(board: list[list[int]]) -> bool:
"""
Check if the board (matrix) has been completely filled with non-zero values.
>>> is_complete([[1]])
True
>>> is_complete([[1, 2], [3, 0]])
False
"""
return all(elem != 0 for row in board for elem in row) | bigcode/self-oss-instruct-sc2-concepts |
def solution(array): # O(N)
"""
Given n non-negative integers a1, a2, ..., an , where each represents
a point at coordinate (i, ai). n vertical lines are drawn such that the
two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which togeth... | bigcode/self-oss-instruct-sc2-concepts |
def power(value: float) -> float:
"""Compute power."""
return value ** 2 | bigcode/self-oss-instruct-sc2-concepts |
def bbox_for_point(point, size):
"""Calcs square bounding box for provided center and bounding box size.
:type point: list
:param point: bounding box center
:type size: float
:param size: size of square bounding box
:rtype: list
:return: new bounding box
"""
x0 = point[0] - size / 2.0
y0 = point[... | bigcode/self-oss-instruct-sc2-concepts |
def isInactive(edge):
"""Return 1 if edge is active, else return 0."""
if edge[2] >= len(edge[4]): return 1
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def object_kind(object_path):
"""
Parse the kind of object from an UDisks2 object path.
Example: /org/freedesktop/UDisks2/block_devices/sdb1 => device
"""
try:
return {
'block_devices': 'device',
'drives': 'drive',
'jobs': 'job',
}.get(object_path... | bigcode/self-oss-instruct-sc2-concepts |
def lstringstrip(s_orig, s_strip):
""" Left-strip a whole string, not 'any of these characters' like str.lstrip does """
if s_orig.startswith(s_strip):
return s_orig[len(s_strip):]
else:
return s_orig | bigcode/self-oss-instruct-sc2-concepts |
import threading
def background(f):
"""Threading decorator.
Use @background above the function you want to thread (run in the
background)."""
def bg_f(*a, **kw):
thread = threading.Thread(name=f.__name__, target=f, args=a, kwargs=kw)
thread.start()
return thread
return... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_id(size=16, chars=string.ascii_lowercase):
"""Return a random id string, default 16 characters long."""
return ''.join(random.choice(chars) for _ in range(size)) | bigcode/self-oss-instruct-sc2-concepts |
def apim_nv_delete(client, resource_group_name, service_name, named_value_id):
"""Deletes an existing Named Value. """
return client.named_value.delete(resource_group_name, service_name, named_value_id, if_match='*') | bigcode/self-oss-instruct-sc2-concepts |
def rectangle_points(pos, width, height):
"""Return the points of a rectangle starting at pos."""
x1, y1 = pos
x2, y2 = width + x1, height + y1
return [(x1, y1), (x1, y2), (x2, y2), (x2, y1)] | bigcode/self-oss-instruct-sc2-concepts |
def imcrop(image, crop_range):
""" Crop an image to a crop range """
return image[crop_range[0][0]:crop_range[0][1],
crop_range[1][0]:crop_range[1][1], ...] | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def _add_mlst(mlsts: dict) -> dict:
"""
Read through MLST results and create column each schema.
Args:
mlsts (dict): The MLST results associated with a sample
Returns:
dict: Per schema MLST hits
"""
results = OrderedDict()
for key, vals in m... | bigcode/self-oss-instruct-sc2-concepts |
def get_single_band(fnames,band_numbers,band_num):
"""
Function to return the file path for a single band, given a band number and
list of input file paths.
Parameters
----------
fnames : LIST
List of band file locations, as generated by get_filenames().
band_numbers : LIST
... | bigcode/self-oss-instruct-sc2-concepts |
def create_verifier_for_dsa(signature, hash_method, public_key,
image_properties):
"""Create verifier to use when the key type is DSA
:param signature: the decoded signature to use
:param hash_method: the hash method to use, as a cryptography object
:param public_key: the pu... | bigcode/self-oss-instruct-sc2-concepts |
def all_edges(G, nbunch=None, data=False):
"""
Get a list of all (both incoming and outgoing) edges of (Multi)DiGraph G
:param G: (Multi)DiGraph
:param nbunch: list of nodes whose adjacent edges we want to find
:param data: boolean: return list with or without nodes data
:return: corresponding l... | bigcode/self-oss-instruct-sc2-concepts |
def chance_of_missing(num_of_keys: int, num_of_draws: int, total_choices: int):
"""Given total number of choices, the number of keys among the
choices, and total number of draws, what are the chances of not
being to draw a single key in all the draws.
"""
r = 1
for _ in range(num_of_draws):
... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_delta_x(a: float, b: float, n: int) -> float:
"""
Calculate delta_x = (b - a) / n
n = data points samples
a = min x value of integral
b = max x value of intergal
"""
return (b - a) / n | bigcode/self-oss-instruct-sc2-concepts |
def precond_grad_kron(Ql, Qr, Grad):
"""
return preconditioned gradient using Kronecker product preconditioner
Ql: (left side) Cholesky factor of preconditioner
Qr: (right side) Cholesky factor of preconditioner
Grad: (matrix) gradient
"""
if Grad.shape[0] > Grad.shape[1]:
return Ql.... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_space(text):
"""
remove extra spaces and ending space if any
"""
text = re.sub('\s+', ' ', text)
text = re.sub('\s+$', '', text)
return text | bigcode/self-oss-instruct-sc2-concepts |
def is_leap(year: int) -> bool:
"""
Tests if the year is leap.
:param year: int. Year to be tested.
:return: bool. If the year is leap.
"""
if (year % 4) == 0:
if (year % 100) == 0:
return bool((year % 400) == 0)
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def file_create(path, content):
""" Create a new file at the given absolute path with the given content """
with open(path, 'w') as file_conf:
file_conf.write(content)
return path
return False | bigcode/self-oss-instruct-sc2-concepts |
def value_to_bit_matrix(a, s=(8, 8)):
""" convert a from n-bit wide value to
s[0] x s[1] bit matrix"""
bit_matrix = [[0] * s[1] for i in range(s[0])]
for i in range(s[0]):
for j in range(s[1]):
index = j + i * s[0]
bit = (a & (1 << index)) >> index
bit_mat... | bigcode/self-oss-instruct-sc2-concepts |
def BDEUnlockVolume(bde_volume, path_spec, key_chain):
"""Unlocks a BDE volume using the path specification.
Args:
bde_volume (pybde.volume): BDE volume.
path_spec (PathSpec): path specification.
key_chain (KeyChain): key chain.
Returns:
bool: True if the volume is unlocked, False otherwise.
"... | bigcode/self-oss-instruct-sc2-concepts |
def parse_rdp_assignment(line):
"""Returns a list of assigned taxa from an RDP classification line
"""
toks = line.strip().split('\t')
seq_id = toks.pop(0)
direction = toks.pop(0)
if ((len(toks) % 3) != 0):
raise ValueError(
"Expected assignments in a repeating series of (ran... | bigcode/self-oss-instruct-sc2-concepts |
def clean_link_text(link_text):
""" The link text sometimes contains new lines, or extrananeous spaces, we
remove them here. """
return link_text.strip().replace('\n', '').replace('\r', '') | bigcode/self-oss-instruct-sc2-concepts |
def get_entry(folder):
"""Find the name of the proof in the proof Makefile."""
with open('{}/Makefile'.format(folder)) as makefile:
for line in makefile:
if line.strip().lower().startswith('entry'):
return line[line.find('=')+1:].strip()
if line.strip().lower().s... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def chromium_third_party_googletest_repo_path(
chromium_verifier_repo: pathlib.Path) -> pathlib.Path:
"""Returns the path of third_party/googletest in chromium repo"""
return chromium_verifier_repo / 'third_party' / 'googletest' / 'src' | bigcode/self-oss-instruct-sc2-concepts |
def get_dict_info(dictionary, info_to_get):
"""Returns list containing data from given dictionary."""
return [dictionary.get(info) for info in info_to_get] | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_version_groups(csv_dir, pkm_versions):
"""Get the groups that classify games versions.
Args:
csv_dir (pathlib.Path): Path to csv directory.
pkm_versions (list): List of dict containing infos to build
pokediadb.models.Versionobject.
Returns
list: Ret... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def get_random_string(length:int) -> str:
"""Creates a random string from ascii letter characters"""
return ''.join(random.choice(string.ascii_letters) for x in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def depends_directly_on(dependencies):
"""Takes a dependency dictionary d and "inverts" it so that d[section] will return
the other sections which depend directly on that section"""
depends_on = {s: set() for s in dependencies.keys()}
for s, dependencies in dependencies.items():
for dep in depe... | bigcode/self-oss-instruct-sc2-concepts |
def _nonnull_dict(**kwargs):
"""Returns a dict containing all kwargs except thouse having a None value.
"""
return {key: value
for key, value in kwargs.items()
if value is not None} | bigcode/self-oss-instruct-sc2-concepts |
def double_stuff (things) :
""" Returns a new list with doubl ethe values than the previous list """
# accum list
new_list = []
# iterate over each item in the prev list
for thing in things :
# double each item
new_elem = thing * 2
# add to the new list
new_list.app... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
""" Generates a random string.
:param size: Length of random string.
:type size: Int
:param chars: Charectors used for random string generation.
:type chars: String
:return: String, random strin... | bigcode/self-oss-instruct-sc2-concepts |
def create_file(filename):
""" Create a file with write rights and UTF-8 encoding
Args:
param1 (string): Filename
Returns:
Return a file object
"""
return open(filename, mode="w", encoding="utf-8") | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def get_subsets(item_set, size):
"""Gets all the subsets of given size that can be formed from the itemset
Args:
item_set ((int, ...)): Set of items.
size (int):
Returns:
[(int,...), ...] All subsets of size `size`
"""
return itertools.combinations(item_s... | bigcode/self-oss-instruct-sc2-concepts |
def dequantize(x, scale_factor, num_levels=255):
"""
Reverse operation of quantize_to_int
Parameters:
- x: np.array(dtype=int), quantized vector in integer representation
- scale factor: float input will be mapped to this range
- num_levels: int: number of quantization levels, must be odd
... | bigcode/self-oss-instruct-sc2-concepts |
def full_shape(dim, shape, fill):
"""Returns a shape of at least dim dimensions"""
return ([fill] * (dim - len(shape))) + shape | bigcode/self-oss-instruct-sc2-concepts |
def make_normal_initializer(mean, std):
"""make normal initializer param of make_table_options
Args:
mean (float): A python scalar. Mean of the random values to generate.
std (float): A python scalar. Standard deviation of the random values to generate.
Returns:
dict: initializer p... | bigcode/self-oss-instruct-sc2-concepts |
def capitalize(s: str) -> str:
"""Capitalize the first character of a string."""
if s == '':
return ''
else:
return s[0].upper() + s[1:] | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
import random
async def task_coro(pid):
"""Coroutine non-deterministic task"""
await asyncio.sleep(random.randint(0, 2) * 0.1)
print('Task %s done' % pid)
return random.choice([True, False, False, False, False, False, False, False, False, False, False, False]) | bigcode/self-oss-instruct-sc2-concepts |
def is_job_config(config):
"""
Check whether given dict of config is job config
"""
try:
# Every job has name
if config['config']['job']['name'] is not None:
return True
except KeyError:
return False
except TypeError:
return False
except IndexError... | bigcode/self-oss-instruct-sc2-concepts |
import re
def select_structs(innerclass_list):
"""Select structures from innerclass list.
Args:
innerclass_list: raw list with unions and structures
extracted from Dogygen's xml file.
Returns:
Doxygen directives with structures selected from the list.
Not... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def get_routes(switchuser, switchpassword, url):
"""
Here's a function that takes in a common set of information, does one thing and then returns the result.
:param switchuser: A string that contains the username to access the device
:param switchpassword: A string that co... | bigcode/self-oss-instruct-sc2-concepts |
def _find_neighbors_relations(node, relations, nodes):
"""
Find all neighbors and relation for this node.
:param node: the node we search the neighbors and relations for
:param relations: a list of all relations
:param nodes: a list of all nodes
:return: a pair (neighbors, relations)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def _x_proto_matcher(art):
""" Is this artifact the x.proto file? """
return art['name'].endswith('.proto') | bigcode/self-oss-instruct-sc2-concepts |
def get_allegation_data(document):
"""
Parse an lxml document for allegations and return a list.
:param document:
:return:
"""
# Setup return structure
allegation_list = []
try:
# Find element and parse <li>s
allegation_div = document.find_class("view-allegations").pop(... | bigcode/self-oss-instruct-sc2-concepts |
def json_headers(app):
"""JSON headers."""
return [
('Content-Type', 'application/json'),
('Accept', 'application/json'),
] | bigcode/self-oss-instruct-sc2-concepts |
def icon_name(resolution):
"""Create file name from image resolution.
Args:
resolution (str): resolution of the image.
Returns:
icon_name (str): File name of an icon for .iconset.
"""
return 'icon_' + resolution + '.png' | bigcode/self-oss-instruct-sc2-concepts |
import operator
import itertools
def listadvanced_bool(lst, barr, bnot=False):
"""Advanced list indexing: boolean array
Args:
lst(list):
barr(array or bool): array of booleans
Returns:
list
"""
if bnot:
barr = map(operator.not_, barr)
return list(itertools.comp... | bigcode/self-oss-instruct-sc2-concepts |
def lerp(min, max, rat):
"""
Interpolate between `min` and `max` with the 0-1 ratio `rat`.
"""
return min+(max-min)*rat | 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.