seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def are_all_elements_unique(elements):
"""Check if there are any repeated element in the list of elements. If yes return False otherwise return True."""
unique_elements = set()
for element in elements:
if element in unique_elements:
return False
unique_elements.add(element)
r... | bigcode/self-oss-instruct-sc2-concepts |
def is_buzz(replace_array, count):
"""
This function checks whether the count is a multiple of any of the numbers in replace_array[0] are replaces the
output with the text with the same index in replace_array[1]. If it is not a multiple with any of the numbers it
will return the number as a string.
... | bigcode/self-oss-instruct-sc2-concepts |
def copy_to_device(item, device, criterion_func):
"""
Return a copy of tensor on specified device.
Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts.
Parameters:
item: tensor to copy or (possibly nested) container of tensors to copy.
device: target dev... | bigcode/self-oss-instruct-sc2-concepts |
def aspect(df):
"""Return the aspect ratio of a Geopandas dataset"""
tb = df.total_bounds
return abs((tb[0] - tb[2]) / (tb[1] - tb[3])) | bigcode/self-oss-instruct-sc2-concepts |
def read_file(file_name):
"""Read file and return its contents."""
with open(file_name, "r") as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
import logging
def unwrap_state_dict(checkpoint, verbose=True):
"""Remove `module.` prefix for `state_dict`."""
with_wrapper = False
new_checkpoint = {}
for key, val in checkpoint.items():
if with_wrapper: # all keys consistent
assert key.startswith('module.')
if key.start... | bigcode/self-oss-instruct-sc2-concepts |
def getSZLen(abData, off):
"""
Get the length of a zero-terminated string field, in bytes.
Returns -1 if off is beyond the data packet or not properly terminated.
"""
cbData = len(abData);
if off >= cbData:
return -1;
offCur = off;
while abData[offCur] != 0:
offCur = off... | bigcode/self-oss-instruct-sc2-concepts |
def create_iam_policy(bindings_spec):
""" Create an IAM policy for the resource. """
return {
'gcpIamPolicy': {
'bindings': bindings_spec
}
} | bigcode/self-oss-instruct-sc2-concepts |
def cidr_mask_clears_minimum_size(cidrs: list, min_size: int):
"""
Verify all subnet masks in a list of CIDR blocks are larger than a minimum
Args:
cidrs: list of CIDR block strings
min_size: smallest size allowed for mask
Returns: bool
"""
return all([int(cidr.split("/")[1]) <... | bigcode/self-oss-instruct-sc2-concepts |
async def get_int_set(redis, key):
"""Get a set of integers on redis."""
str_set = await redis.smembers(key)
int_set = [int(i) for i in str_set]
return int_set | bigcode/self-oss-instruct-sc2-concepts |
def scale(x, copy=True):
"""Scale `x` to unity.
Subtract min and divide by (max-min).
Parameters
----------
x : array_like
copy : bool
copy `x` before scaling
Returns
-------
x_scaled
"""
xx = x.copy() if copy else x
xx = xx - xx.min()
xx /= xx.max()
re... | bigcode/self-oss-instruct-sc2-concepts |
def clone_task_definition(client, task_definition):
"""
Given a task definition ARN, clone the associated task.
Returns the new task definition ARN.
"""
resp = client.describe_task_definition(taskDefinition=task_definition)
taskDefinition = resp['taskDefinition']
# The task definition cont... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def move_file(source, destination):
"""Move a file"""
shutil.move(source, destination)
return True | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def unpackTimecode(timecode):
"""unpacks a timecode to minutes, seconds, and milliseconds"""
if "." in timecode:
x = datetime.strptime(timecode, '[%M:%S.%f]')
else:
x = datetime.strptime(timecode, '[%M:%S]')
minutes = x.minute
seconds = x.second
m... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def rGetJSON(url: str):
"""GET the contents of an URL and return its response as a JSON object"""
response = requests.get(url)
return response.json() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
import itertools
def build_vocab(sentences1, sentences2):
"""
Builds a vocabulary mapping from word to index based on the sentences.
Returns vocabulary mapping and inverse vocabulary mapping.
"""
# Build vocabulary
word_counts1 = Counter(itertools.chain(*sentences1))... | bigcode/self-oss-instruct-sc2-concepts |
def pers_name(data):
"""
extract text from TEI element <persName>
"""
try:
return data.find(".//persName", namespaces=data.nsmap).text
except AttributeError:
pass
return None | bigcode/self-oss-instruct-sc2-concepts |
def same_type(values, types):
"""Check if values are belongs to same type or type tuple.
:param collections.Iterable values: values to check type similarity
:param tuple|type types: type or tuple of types
"""
return all(map(lambda it: isinstance(it, types), values)) | bigcode/self-oss-instruct-sc2-concepts |
def calculate_cells(anchor_point_list_dict, cell_size_meters, utm_bounds=[]):
""" Calculate boundaries for image cells (chips) from anchor points.
This function takes the output from :func:`calculate_anchor_points` as well
as a desired cell size (`cell_size_meters`) and outputs
``(W, S, E, N)`` tuples ... | bigcode/self-oss-instruct-sc2-concepts |
def getWordPattern(word: str) -> str:
"""Get word pattern
Returns a string of the pattern form of the given word.
Args:
word: String containing word to convert into word pattern.
Example:
>>> import pythontutorials.books.CrackingCodes.Ch17.makeWordPatterns as makeWordPatterns
>>> make... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def read_links(path_to_csv, index):
"""
reads csv file for project links
:param path_to_csv: path to the csv file
:param index: index to keep data from
:return: list of parsed data
"""
link_list = []
skip = True # to skip the column headings
with open(path_to_csv, "r")... | bigcode/self-oss-instruct-sc2-concepts |
def solution(n: int = 1000) -> int:
"""
Returns ∑ r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
import pathlib
import imghdr
def sort_target_type(target_list: List[str]) -> Tuple[List[str], List[str], List[str]]:
"""sort input files by type
Args:
target_list (List[str]): list of pictures or movies or directories where pictures are stored
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def is_subseq(l1, l2):
"""is every element of l1 also in l2? (non-unique and order sensitive)"""
it = iter(l2)
return all(d in it for d in l1) | bigcode/self-oss-instruct-sc2-concepts |
def string_list_validator(value: str) -> str:
"""
Validate if value is a str
Arguments:
value {str} -- value to validate
Raises:
ValueError: value is not a type of str
ValueError: Value can't be a empty string
Returns:
str -- unchanged input value
"""
# ra... | bigcode/self-oss-instruct-sc2-concepts |
def location_to_hex(location):
"""convert location to hex for display"""
ret = "%08X" % int(location)
return ret | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import json
def from_json(s: str, **kwargs: Any) -> object:
"""
Convert a JSON string to an object representation. For usage, see json.loads(...).
"""
return json.loads(s, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def _should_process_segment(seg, segname):
"""Check if we should process the specified segment."""
return segname.endswith('__DATA_CONST.__mod_init_func') or \
segname == '__DATA.__kmod_init' | bigcode/self-oss-instruct-sc2-concepts |
from math import ceil # Biblioteca para arrendondamento do valor da média
def notas(*n, sit=False):
"""
-> Função de Analise: com Qdtde de notas, o valor maior; menor e média da turma.
:param n: uma ou mais notas dos alunos para analise.
:param sit: valor opcional para saber situação da média dos alu... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_atomtype(atomtype):
"""Removes extraneous charge info from atomtype
Atomtypes occasionally have charges such as O1+ or N1-. This function
uses regexps to replace these out.
atomtype: String
Raw atomtype extracted from PDB
"""
return re.sub(r'[0-9]+[+-]?', r'', atomtype) | bigcode/self-oss-instruct-sc2-concepts |
def _async_request_completed(payload):
"""Looks into an async response payload to see if the requested job has finished."""
if payload["status"] == "COMPLETED":
return True
if payload["status"] == "ERROR":
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def isSynchronous(key1, key2, mali, exons):
"""check if two transcripts are on synchronous positions.
Two transcripts are synchroneous, if their position in the
alignment and on the genomic sequence are both a < b.
Both front and end are taken into account. Note that they
can still be ... | bigcode/self-oss-instruct-sc2-concepts |
def get_assign_default_value_rule(variable_name: str, default_value_parameter_name: str):
"""
Returns a rule that sets a default value for a variable.
@param variable_name: The name of the variable whose default should be set (as a string)
@param default_value_parameter_name: The name of the parameter ... | bigcode/self-oss-instruct-sc2-concepts |
def get(lens, big):
"""
Get a value from `big` using `lens`.
"""
return lens.get(big) | bigcode/self-oss-instruct-sc2-concepts |
def convert_reference_json(reference_json, data_object):
"""
Converts the reference JSON download from DSS into the DOS message
and returns the DOS message.
:param reference_json:
:param data_object:
:return:
"""
# {u'content-type': u'application/octet-stream',
# u'crc32c': u'e2a2bc0... | bigcode/self-oss-instruct-sc2-concepts |
def none_if_na(s):
"""Return None if s == 'N/A'. Return s otherwise."""
return None if s == 'N/A' else s | bigcode/self-oss-instruct-sc2-concepts |
def encode_str(s):
"""Returns the hexadecimal representation of ``s``"""
return ''.join("%02x" % ord(n) for n in s) | bigcode/self-oss-instruct-sc2-concepts |
def _StaticValueInner(value, ctx, _): # pylint: disable=W0613
"""Returns a static value.
"""
return value | bigcode/self-oss-instruct-sc2-concepts |
def pct_max_weekly_submissions(quiz_df, quiz_meta_df):
"""
Helper function to compute student weekly submissions as a percentage of max # of submissions, and as a percentage of the highest number of student submissions that week.
:param quiz_df: pd.DataFrame of quiz submission data.
:param quiz_meta_df:... | bigcode/self-oss-instruct-sc2-concepts |
def dthandler(obj):
"""ISO formatting for datetime to be used in JSON.
"""
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError("Object can not be isoformatted.") | bigcode/self-oss-instruct-sc2-concepts |
def requires(modules):
"""Decorator to wrap functions with soft dependencies.
This function was inspired by the `requires` function of pysal,
which is released under the 'BSD 3-Clause "New" or "Revised" License'.
https://github.com/pysal/pysal/blob/master/pysal/lib/common.py
Parameters
------... | bigcode/self-oss-instruct-sc2-concepts |
def _get_edges(value, last_value, mask):
"""
Given two integer values representing a current and a past value,
and a bit mask, this function will return two
integer values representing the bits with rising (re) and falling (fe)
edges.
"""
changed = value ^ last_value
re = changed & value... | bigcode/self-oss-instruct-sc2-concepts |
def post_string(descr):
"""Constructs a http POST description string from dataset description"""
output = "dsid=ds%(dsid)s&rtype=S&rinfo=dsnum=%(dsid)s;\
startdate=%(startdate)s;enddate=%(enddate)s;parameters=%(parameters)s;\
level=%(level)s;product=%(product)s;grid_definition=%(grid_definition)s;ststep=%(... | bigcode/self-oss-instruct-sc2-concepts |
def FormatIssueRef(issue_ref_tuple, default_project_name=None):
"""Format an issue reference for users: e.g., 123, or projectname:123."""
if issue_ref_tuple is None:
return ''
project_name, local_id = issue_ref_tuple
if project_name and project_name != default_project_name:
return '%s:%d' % (project_nam... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sharded_bmm(args, kwargs, pg):
"""
Handles ``__torch_function__`` dispatch for the sharded_bmm op.
Warning: For now we only supports the case when both tensors are sharded
by dim 0 so that no local communication.
Args: same as ``torch.bmm``.
Return:
local_t... | bigcode/self-oss-instruct-sc2-concepts |
def asciify(text):
"""Translate non-ascii charaters to ascii equivalent.
**Example:**
>>> asciify('áéíóúÁÉÍÓÚñÑ')
'aeiouaeiounn'
"""
def translate(c):
if c in ['\u00C0', '\u00C1', '\u00C2', '\u00C3', '\u00C4',
'\u00C5', '\u00E0', '\u00E1', '\u00E2', '\u00E3',
... | bigcode/self-oss-instruct-sc2-concepts |
def input_as_string(filename:str) -> str:
"""returns the content of the input file as a string"""
with open(filename) as f:
return f.read().rstrip("\n") | bigcode/self-oss-instruct-sc2-concepts |
def jwt_auth_required(callable_obj):
"""A decorator that signs a callable object with an "auth_required"
attribute (True). We use this attribute to find which handler callbacks
require an authorized for protected access.
Args:
callable_obj (instance): A handler callable object.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def projection_simplex(u, r=1):
"""Project u unto the the r-simplex, i.e.
out = min_v || v - u ||_2^2, subject to sum(v_i)_i=1^n = r, v_i >= 0
Parameters
----------
u : torch.tensor
Vector to be projected of shape (n,).
r : positive float
Simplex constant.
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def create_cat_to_name_dict(filepath):
"""Return a dictionary containing category names and keys from a json file
Args:
filepath (str): Directory to a json file containing category names and keys for all data in train set
Returns:
dict: A python dictionary object mapping a key to each category i... | bigcode/self-oss-instruct-sc2-concepts |
def compute_gradient(tx, error_vector):
"""
Computes the gradient for the mean squared error loss function.
Args:
y: labels
error_vector: error vector computed for a specific data set and model
Returns:
gradient: the gradient vector computed according to its definition
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def remove_connected_component(cc, connected_components):
"""
Attempt to remove connected component and return the smaller set
:param Panel cc: connected component to remove
:param iterable connected_components: set of all connected components
:return: smaller set of connected componen... | bigcode/self-oss-instruct-sc2-concepts |
def obj_of(k, v):
"""Creates an object containing a single key:value pair"""
return {k: v} | bigcode/self-oss-instruct-sc2-concepts |
def get_by_path(dic, path):
"""
Gets a key (can be specified via dot notation) `path` in a nested `dic`
"""
parts = path.split('.')
loc = dic
for part in parts:
if part not in loc:
raise KeyError(path)
loc = loc[part]
return loc | bigcode/self-oss-instruct-sc2-concepts |
def _is_accepting(node):
"""Check if node is accepting."""
return node.get("type") == "Accepting" | bigcode/self-oss-instruct-sc2-concepts |
def map_base_attributes(cube, mapper_class, naming, locale=None):
"""Map all base attributes of `cube` using mapping function `mapper`.
`naming` is a naming convention object. Returns a tuple (`fact_name`,
`mapping`) where `fact_name` is a fact table name and `mapping` is a
dictionary of attribute refer... | bigcode/self-oss-instruct-sc2-concepts |
def rm_last(*args):
"""
Remove the last index from each list
"""
if len(args) == 1:
return args[:-1]
else:
return [a[:-1] for a in args]
return | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_final_path(output_path: Path, set_type: str, samp_name: str) -> Path:
"""Get path of output file
Arguments:
output_path {Path} -- root of output path
set_type {str} -- data set type
samp_name {str} -- name of sample
Returns:
Path -- comple... | bigcode/self-oss-instruct-sc2-concepts |
def parseStr(x):
"""
function to parse a string
Parameters
----------
x : str
input string
Returns
-------
int or float or str
parsed string
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def parse_tuple_latency(tl_file):
"""
Read the log of latencies and extract the relevant values for each time window,
returning an ordered dictionary of instant latencies per component.
"""
latencies = OrderedDict()
header = {}
ts = 0
for line in open(tl... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def vectorize(data, dtype=torch.uint8):
""" Vectorizes a tuple or int into a torch tensor. """
# Don't need to vectorize an int, its broadcasted
if isinstance(data, int):
return data
elif isinstance(data, tuple):
# If the elements are the same, there is be no need for this... | bigcode/self-oss-instruct-sc2-concepts |
import re
def human_sort_key(s):
"""
A key function to sort alpha-numerically, not by string
From http://nedbatchelder.com/blog/200712/human_sorting.html
This function can be used as the key for a sort algorithm to give it an understanding of numbers,
i.e. [a1, a2, a10], instead of the default (A... | bigcode/self-oss-instruct-sc2-concepts |
def site_center(sites):
"""
Find the geometric center of a collection of sites.
:param sites: Tuple of Site objects
:return: Array of the cartesian coordinates of the center of the sites
"""
return sum([site.coords for site in sites]) / len(sites) | bigcode/self-oss-instruct-sc2-concepts |
import re
def parseCrysolLog(logFileName):
"""Parse Crysol log file, obtain Chi2, Rg and eDens"""
# will not parse crysol_summary.txt, but the .log file
# created for each individual run
chi2 = 9999
Rg = -9999
eDens = -9999
position = -1
counter = 0
with open(logFileName, 'r') as... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def run_simulation(simulation):
"""
Fires of the simulation of a single game. Useful for the multiprocessing
map call.
Args:
simulation (Simulation): Instance of a single game simulation
Returns:
(Simulation) Completed simulation
"""
logging.info(f"Startin... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def random_uuid(use_uuid1: bool = False) -> uuid.UUID:
"""
Get a random UUID.
:param use_uuid1: Use UUID1 if True, else use UUID4.
:return: A random UUID.
"""
return uuid.uuid1() if use_uuid1 else uuid.uuid4() | bigcode/self-oss-instruct-sc2-concepts |
import ctypes
def _get_bytes_buffer(ptr, nbytes):
"""
Get a ctypes array of *nbytes* starting at *ptr*.
"""
if isinstance(ptr, ctypes.c_void_p):
ptr = ptr.value
arrty = ctypes.c_byte * nbytes
return arrty.from_address(ptr) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def harmonic(x, k, eq, order=[2]):
"""Harmonic term.
Parameters
----------
x : `torch.Tensor`, `shape=(batch_size, 1)`
k : `torch.Tensor`, `shape=(batch_size, len(order))`
eq : `torch.Tensor`, `shape=(batch_size, len(order))`
order : `int` or `List` of `int`
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def get_embeddings(model, data, device):
"""
Get best embeddings
Args
- model (torch object): best model
- data (Data object): dataset
- device (torch object): cpu or cuda
Return
- all_emb (tensor): best embedding for all nodes
"""
model.eval()
dat... | bigcode/self-oss-instruct-sc2-concepts |
def format_pytesseract_dict_results(ocr_res: dict) -> tuple:
"""Formats results from pytesseract.image_to_data(img, output_type=Output.DICT)
function.
Parameters
----------
ocr_res : dict
result of pytesseract.image_to_data(img, output_type=Output.DICT)
Returns
-------
tuple(li... | bigcode/self-oss-instruct-sc2-concepts |
def __cleanup_stdout(stdout):
"""Removes empty elements from the stdout/stderr list returned by run
param stdout: string output of subprocess stdout
returns: list of lines from stdout
"""
return list(filter(None, stdout.split('\n'))) | bigcode/self-oss-instruct-sc2-concepts |
import re
def boolean_to_upper(data):
"""Convert boolean operators to uppercase"""
ops = ['and', 'or', 'not']
for op in ops:
data = re.sub(r"\b%s\b" % (op), op.upper(), data)
return data | bigcode/self-oss-instruct-sc2-concepts |
def parse_style(style):
"""Parse a style string. The format is a space-separated list of
tokens, in order
<lineformat> <markerformat> <seriesformat>
Valid values:
lineformat: matplotlib line style, or dash sequence as
list of "-"-separated integers
m... | bigcode/self-oss-instruct-sc2-concepts |
def GetMavenGroupId(owner_domain):
"""Returns the maven group id for a given owner domain.
Args:
owner_domain: (str) The owner domain.
Returns:
(str) The group id.
"""
if owner_domain == 'google.com':
return 'com.google.apis'
else:
return '.'.join(reversed(owner_domain.split('.'))) | bigcode/self-oss-instruct-sc2-concepts |
def change1(line, old, new):
"""replace old with new if old in line. """
return line.replace(old, new) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def header_content_split(string: str, delimiter: str) -> List[str]:
"""
Take a string and split it according to the passed delimiter.
It will ignore delimiter if inside between double quote, inside a value, or in parenthesis.
The input string is considered perfectly formed. Thi... | bigcode/self-oss-instruct-sc2-concepts |
def increment_dictionary_with_dictionary(dict_a, dict_b):
"""
Function to add the values from one dictionary to the values from the same keys in another.
Args:
dict_a: First dictionary to be added
dict_b: Second dictionary to be added
Return:
The combined dictionary
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def DistributedWaitForReadyMidasTalker (midastalker_list, immediate_return,
timeout=None) :
""" Given a list of MidasTalkers, this returns a list of all 'ready'
MidasTalkers. Take the given timeout, distribute it evenly over all
MidasTalkers so that the maximum wait (if al... | bigcode/self-oss-instruct-sc2-concepts |
def is_ccw_xy(a, b, c, colinear=False):
"""Determine if c is on the left of ab when looking from a to b,
and assuming that all points lie in the XY plane.
Parameters
----------
a : sequence of float
XY(Z) coordinates of the base point.
b : sequence of float
XY(Z) coordinates of ... | bigcode/self-oss-instruct-sc2-concepts |
def original_error(err):
"""
Returns original exception from graphql exception wrappers.
graphql-core wraps exceptions that occurs on resolvers into special type
with ``original_error`` attribute, which contains the real exception.
"""
return err.original_error if hasattr(err, 'original_error')... | bigcode/self-oss-instruct-sc2-concepts |
def vDot(v, w):
""" Return the dot product of v . w """
return v[0]*w[0] + v[1]*w[1] + v[2]*w[2] | bigcode/self-oss-instruct-sc2-concepts |
def mels_len(mels):
"""Gets lenfth of log mel-spectrogram."""
return mels.shape[1] | bigcode/self-oss-instruct-sc2-concepts |
import re
def highlight(text, org):
"""
Highlights the company mention in the text presented during annotation
:param text: the text to be presented
:param org: the mention to be highlighted
:return: HTML object of text with highlighted company
"""
# Find locations of the company
occ... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def cnn_load(modelpath):
"""
Load the saved model
Input
=====
modelpath: str
Path to load the saved model
Output
======
model: dict
The dictonary that saved the network and functions.
"""
# Init
fp = open(modelpath, 'rb')
# load
mode... | bigcode/self-oss-instruct-sc2-concepts |
def one_of_k_encoding(x, allowable_set):
"""Converts input to 1-hot encoding given a set of allowable values."""
if x not in allowable_set:
raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set))
return list(map(lambda s: x == s, allowable_set)) | bigcode/self-oss-instruct-sc2-concepts |
def GetParameter(content, parameterName):
"""
Get one parameter from the header file
Arguments:
content -- content of the file
parameterName -- name of the parameter. Parameters available:
-- bands, lines, samples, framerate
Returns:
param -- curren... | bigcode/self-oss-instruct-sc2-concepts |
def __process_case_list(list_input, list_output):
"""
Process a case list and raise an exception in case of duplicate
entries.
"""
duplicate = ""
for item in list_input:
if item is None or item == "":
continue
elif item.lower() in list_output:
dup... | bigcode/self-oss-instruct-sc2-concepts |
def trim_comments(val):
"""
Remove in-line comments that begin with "#", and whitespace.
"""
return val.split("#")[0].strip() | bigcode/self-oss-instruct-sc2-concepts |
def generateOperation(length: int, amount: float) -> str:
"""
Generate an operation (operation = creation of a virtual credit card)
:param length: The duration of the virtual credit card in months
:type length: int
:param amount: The amount in Euros contained in the virtual credit card
:type am... | bigcode/self-oss-instruct-sc2-concepts |
def _has_rows(rows: list) -> bool:
"""
Determine if the table has rows.
Keyword arguments:
rows -- the rows to check
Returns: True if the table has rows, False otherwise
"""
return len(rows) > 0 | bigcode/self-oss-instruct-sc2-concepts |
def _can_walk(base, subdirectories):
"""
Determine if the first element of the 'subdirectories' list can be appended
to the 'base' path and still specify a directory.
"""
# Always consider the last part of the subdirectories the filename
if len(subdirectories) < 2:
return False
# All... | bigcode/self-oss-instruct-sc2-concepts |
def get_stable(res_file):
"""Returns whether the matching was found to be stable.
Args:
res_file: The file with IP results.
Returns:
Whether the matching was found to be stable.
"""
f = open(res_file, "r")
for line in f:
if 'stability_correct' in line:
return l... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def package_installed(pkg):
"""Check if package is installed"""
req = pkg_resources.Requirement.parse(pkg)
try:
pkg_resources.get_provider(req)
except pkg_resources.DistributionNotFound:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def levenshtein_distance(first,second):
""" Return the levenshtein distance between two strings.
http://rosettacode.org/wiki/Levenshtein_distance#Python
"""
if len(first) > len(second):
first, second = second, first
distances = range(len(first)+1)
for index2, char2 in enumerate(second):
new_distances = [i... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def format_mesh_terms(df):
"""
Removes unrequired columns and pivots the mesh terms data into a dictionary.
Args:
df (dataframe): mesh terms as returned from retrieve_mesh_terms
Returns:
(dict): document_id: list of mesh terms
"""
logging.info("Formatting mesh ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json_from_file(filename: str, encoding: str = 'utf-8') -> dict:
"""Load json configuration file.
:param filename:
Path to file.
:param encoding:
Encoding in which the file is read.
:return:
Loaded configuration as a dict.
"""
if not filename:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_object(arr, str_card):
""" Get Card Object using its User Input string representation
Args:
arr: array of Card objects
str_card: Card descriptor as described by user input, that is a 2 character
string of Rank and Suit of the Card. For example, KH for King of Hearts.
Returns:
object pointer corresp... | bigcode/self-oss-instruct-sc2-concepts |
def names_from_dct(spc_dct_i, tors_model):
""" Build the tors name list from a dictionary
"""
# Read names from dct
amech_ts_tors_names = ()
if 'amech_ts_tors_names' in spc_dct_i:
amech_ts_tors_names = spc_dct_i['amech_ts_tors_names']
if tors_model in ('1dhr', '1dhrf', '1dhrfa'):
... | bigcode/self-oss-instruct-sc2-concepts |
def list_messages(base, queue_name):
"""Utility function that lists messages in Zaqar queue."""
res = base.messaging_client.list_messages(queue_name)
if res['status'] != 200:
msg = 'Failed in listing messsages for Zaqar queue %s' % queue_name
raise Exception(msg)
return res['body']['me... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def accepts_args(func):
"""returns Bool if the func have *args else False"""
return 'args' in list(inspect.signature(func).parameters) | 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.