seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_distances(clusters):
"""Extract distances as intermediate values between 2 clusters"""
distances = []
for idx, _ in enumerate(clusters[:-1]):
clst_0 = float(clusters[idx])
clst_1 = float(clusters[idx + 1])
distances.append((clst_1 - clst_0) / 2 + clst_0)
return tuple(dist... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_encoding(encoding):
""" Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing undersc... | bigcode/self-oss-instruct-sc2-concepts |
def alignment_patterns_table() -> dict[int, list[int]]:
"""A dictionary that contains the positions of the alignment patterns.
Returns:
dict[int, list[int]]: Returns a list of positions.
"""
table = {
2: [18],
3: [22],
4: [26],
5: [30],
6: [34],
7... | bigcode/self-oss-instruct-sc2-concepts |
def title_case(text: str) -> str:
"""Convert the text to title case.
Args:
text: The text to convert to title case.
Returns:
str: The text converted to title case.
"""
return text.title() | bigcode/self-oss-instruct-sc2-concepts |
def cut_to_specific_word(dataframe, specific_word, part_in_bid):
"""
Takes in a dataframe and a column, and then creates a new dataframe containing only
the rows from the original dataframe that had the search word in that column
:params: a dataframe, a specific_word to look for, and a column name relat... | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_line(line):
"""Parse a JSON string into a Python object."""
try:
line = line.strip()
return json.loads(line)
except json.decoder.JSONDecodeError:
return None | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import logging
def _check_file_existence(file_path: str) -> bool:
"""
Validates the existence of a file
"""
path = Path(file_path)
if not path.exists():
logging.error('Provided file cannot be found.')
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def piecewise_linear_continuous(x, x_b, m_1, b_1, m_2):
"""
Eq. 10. 2-Part Piecewise Linear Continuous Function
Used to fit D18O_cc-w fractionation versus drip rate.
Describes two lines that intersect at x_b.
Parameters
----------
x : numpy array
independent variable
x_b : ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def prj_vtx_pth(vtx, pose, cam_K):
"""
project 3D vertices to 2-dimensional image plane using pytorch
:param vtx: (N, 3), vertices, tensor
:param pose: (3, 4), tensor
:param cam_K: (3, 3), intrinsic camera parameter, tensor
:return: pts_2D: (N, 2), pixel coordinates, tensor; z: (N... | bigcode/self-oss-instruct-sc2-concepts |
def repeat_to_length(string_to_expand, length):
"""Repeats string_to_expand to fill up a string of the provided length.
Args:
string_to_expand: string to repeat
length: length of string to return
Returns: generated string of provided length
"""
return (string_to_expand * (int(leng... | bigcode/self-oss-instruct-sc2-concepts |
def select_rows_by_regex(df, column_name,
regex_str):
"""Returns pandas dataframe rows matching regex in a specific column.
Returns a dataframe with a subset of rows where the value in the column
contains the regex.
Args:
df: A pandas dataframe.
column_name: Name of the column... | bigcode/self-oss-instruct-sc2-concepts |
def with_lock(method):
"""
Execute method with lock. Instance should have lock object in lock attribute.
"""
def wrapper(self, *args):
with self.lock:
return method(self, *args)
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
def sql_file(tmp_path):
""" Construct a file containing a SQL statement """
directory = tmp_path / "sql"
directory.mkdir()
file = directory / "sql.txt"
file.write_text("SELECT\n 1 as foo;")
return file.absolute() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import hashlib
def transport_channel_id(transport, is_server: bool, channel_id_type: Optional[str] = None) -> bytes:
"""
Application-layer user authentication protocols are vulnerable to generic
credential forwarding attacks, where an authentication credential sent by
a cli... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import List
def _split_pbn(file_path: Path) -> List[List[str]]:
"""
Read in the entire PBN file. Split on lines consisting of '*\n' into a list of strings per board
:param file_path: path to PBN file
:return:
"""
with open(file_path, "r") as pbn_file:
... | bigcode/self-oss-instruct-sc2-concepts |
def is_finite_ordinal(n):
"""
Return True if n is a finite ordinal (non-negative int).
"""
return isinstance(n, int) and n >= 0 | bigcode/self-oss-instruct-sc2-concepts |
def _EnableTypoCorrection( flags ):
"""Adds the -fspell-checking flag if the -fno-spell-checking flag is not
present"""
# "Typo correction" (aka spell checking) in clang allows it to produce
# hints (in the form of fix-its) in the case of certain diagnostics. A common
# example is "no type named 'strng' in n... | bigcode/self-oss-instruct-sc2-concepts |
import six
def _get_column_pairs(columns, require_qualifier=False):
"""Turns a list of column or column families into parsed pairs.
Turns a column family (``fam`` or ``fam:``) into a pair such
as ``['fam', None]`` and turns a column (``fam:col``) into
``['fam', 'col']``.
:type columns: list
... | bigcode/self-oss-instruct-sc2-concepts |
def fix2range(vals, minval, maxval):
"""
A helper function that sets the value of the array or number `vals` to
fall within the range `minval` <= `vals` <= `maxval`.
Values of `vals` that are greater than `maxval` are set to
`maxval` (and similar for `minval`).
Parameters
----------
va... | bigcode/self-oss-instruct-sc2-concepts |
def maker_file_path_fromidx(digits=1, levels=1):
"""
Creates a method that returns a file path for the given number of leading digits and levels.
Args:
digits: minimum number of digits to use for the path, any number with less digits will have leading zeros
added.
levels: how to ... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def query_to_json(query):
"""Query with requests and return response as json
Parameters
----------
query : string
query
Returns
-------
json
response
"""
return requests.get(query).json() | bigcode/self-oss-instruct-sc2-concepts |
async def files_for_PR(gh, pull_request):
"""Get files for a pull request."""
# For some unknown reason there isn't any files URL in a pull request
# payload.
files_url = f'{pull_request["url"]}/files'
data = []
async for filedata in gh.getiter(files_url): # pragma: no branch
data.appen... | bigcode/self-oss-instruct-sc2-concepts |
import math
def create_geographic_chunks(longitude=None, latitude=None, geographic_chunk_size=0.5):
"""Chunk a parameter set defined by latitude, longitude, and a list of acquisitions.
Process the lat/lon/time parameters defined for loading Data Cube Data - these should be
produced by dc.list_acquisition... | bigcode/self-oss-instruct-sc2-concepts |
def check(checkRow, checkColumn):
"""checks if this row and column is valid, used when looking at possible piece movement"""
if 0 <= checkRow <= 7 and 0 <= checkColumn <= 7:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def doc_template(object_name: str, body: str)->str:
"""Returns an html page
:param object_name: name of the object
:param body: body of the page
:return: the page
"""
doc = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>""" + object_name + """</title>
<m... | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def fetch_swimmer_urls(url):
"""Fetch all of the swimmers and urls from a team url"""
# Download/parse the pages
page = requests.get(url)
soup = BeautifulSoup(page.content, features="html.parser")
# The last table in the page contains all the swimmer... | bigcode/self-oss-instruct-sc2-concepts |
def _copy_with_ignore(dct, keep, ignore=()):
"""
Copy the entries in the given dict whose keys are in keep.
Parameters
----------
dct : dict
The dictionary to be copied.
keep : set-like
Set of keys for entries we want to keep.
ignore : set or tuple
Don't issue a warn... | bigcode/self-oss-instruct-sc2-concepts |
def coordinates(width, height):
""" Returns coordinates [x1, y1, x2, y2] for a centered box of width, height
"""
with open('/sys/class/graphics/fb0/virtual_size', 'r') as res:
screenx, screeny = map(int, res.read().strip('\n').split(','))
posx = (screenx/2) - (width/2)
posy = (screeny/2) -... | bigcode/self-oss-instruct-sc2-concepts |
def evaluate_ser(entity, outputs):
"""
Get all correct and incorrect queries. Correct means all entities are identified correctly
with exact span
:param entity: list of (start_index, end_index, label) tuples for EACH query
:param outputs: PARSED mallard/duckling responses
:return: Two lists of ... | bigcode/self-oss-instruct-sc2-concepts |
def target_gene_indices(gene_names,
target_genes):
"""
:param gene_names: list of gene names.
:param target_genes: either int (the top n), 'all', or a collection (subset of gene_names).
:return: the (column) indices of the target genes in the expression_matrix.
"""
if is... | bigcode/self-oss-instruct-sc2-concepts |
def extract_modified_bs_sequence(sax_sequence):
"""
This functions extracts the modified Behaviour Subsequence (BS) sequence list, which is the original sax word
sequence where every consecutive pairs of sax words are equal are fused into the same sax word.
:param sax_sequence: list of original sax wor... | bigcode/self-oss-instruct-sc2-concepts |
def build_ols_query(ontology_uri: str) -> str:
"""Build a url to query OLS for a given ontology uri."""
return "https://www.ebi.ac.uk/ols/api/terms?iri={}".format(ontology_uri) | bigcode/self-oss-instruct-sc2-concepts |
import re
def transform_col_in_line(line, col_transformations):
"""Given a line in a table definition, transform any column names
for which a transformation is defined in `col_transformations`.
"""
col_patterns = [
"^\s*`([a-zA-Z0-9_]+)`.*,$", # fields
"^\s*PRIMARY KEY \(`([a-zA-Z0-9... | bigcode/self-oss-instruct-sc2-concepts |
def factors_list(n):
"""Return a list containing all the numbers that divide `n`
evenly, except for the number itself. Make sure the list is in
ascending order.
>>> factors_list(6)
[1, 2, 3]
>>> factors_list(8)
[1, 2, 4]
>>> factors_list(28)
[1, 2, 4, 7, 14]
"""
all_factors ... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def create_soup(url):
"""
Create soup object from url
"""
try:
html_report_part1 = open(url,'r')
soup = BeautifulSoup( html_report_part1, "html.parser")
return soup
except Exception as e:
print("[ERROR] Error occurred in requesting html... | bigcode/self-oss-instruct-sc2-concepts |
def to_list(dataseq):
"""Converts a ``ctypes`` array to a list."""
return list(dataseq) | bigcode/self-oss-instruct-sc2-concepts |
def write(content, path):
"""
Write string to utf-8 pure text file
"""
with open(path, "wb") as f:
return f.write(content.encode("utf-8")) | bigcode/self-oss-instruct-sc2-concepts |
def _append_if_error(errors, sentence_id, test, explanation, token=None):
"""
If a test fails, append an error/warning dictionary to errors.
Args:
errors: a list of errors
sentence_id: ID of the sentence this applies to
test: boolean from a checked expression
explanation: us... | bigcode/self-oss-instruct-sc2-concepts |
def get_url_path(url):
"""Return a list of all actual elements of a url, safely ignoring
double-slashes (//) """
return filter(lambda x: x != '', url.split('/')) | bigcode/self-oss-instruct-sc2-concepts |
def textblock(text, indent=0):
"""
Indent textblock by specified number of spaces.
.. code-block:: pycon
>>> block = 'one\ntwo'
>>> print(textblock(block))
one
two
>>> print(textblock(block), 4)
one
two
"""
if indent:
return ('\n' + ' ' * indent).join(... | bigcode/self-oss-instruct-sc2-concepts |
def g2N(T):
"""
Converting gram to Newton
"""
return [0.00980665 * i for i in T] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def get_syntax(selected: Dict[str, Any], cmd: str) -> str:
"""Returns the syntax for a given command
Parameters
----------
selected : Dict[str, Any]
The command object
cmd : str
The command that was attempted
Returns
--------... | bigcode/self-oss-instruct-sc2-concepts |
def predict_model_gen(session, style_dataset, sample_count):
"""Create a generator function that emits style images.
Args:
session: tf.Session, the session that contains subgraph to load the traning
dataset
style_dataset: tf.data.Dataset that contains training style images.
sample_count: int, num... | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(array, elem, first, last):
"""
Search for an element in an array using binary search
:param array: array to look for element
:param elem: the lement to look for
:param first: the index of the first position in the array
:param last: the index of the last position in the array
... | bigcode/self-oss-instruct-sc2-concepts |
def string_time_from_ms(time_in_ms: int, hours: bool = False) -> str:
"""
Convert timestamp in millisecond in a string with the format mm:ss.xxx
If hours is true the format will be hh:mm:ss.xx
"""
# if no time time_in_ms is equal to the maximum value of a 32bit int
if time_in_ms == 2147483647 o... | bigcode/self-oss-instruct-sc2-concepts |
def format_timedelta(timedelta):
"""Formats a timedelta object to a string by throwing off the microsecond
part from the standard timedelta string representation.
"""
whole_repr = str(timedelta) + '.'
return whole_repr[:whole_repr.find('.')] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import math
def calculate_raster_coordinate(longitude: float, latitude: float, origin: List[int], pixel: List[int]):
""" From a given longitude and latitude, calculate the raster coordinate corresponding to the
top left point of the grid surrounding the given geographic coordinate.
... | bigcode/self-oss-instruct-sc2-concepts |
def escape(string):
"""Escape strings to be SQL safe"""
if '"' in string:
raise Exception("Can't escape identifier {} because it contains a backtick"
.format(string))
return '"{}"'.format(string) | bigcode/self-oss-instruct-sc2-concepts |
def _region_to_coords(region):
"""Split GATK region specification (chr1:1-10) into a tuple of chrom, start, end
"""
chrom, coords = region.split(":")
start, end = coords.split("-")
return (chrom, int(start), int(end)) | bigcode/self-oss-instruct-sc2-concepts |
def edges_iter(G,nbunch=None):
"""Return iterator over edges adjacent to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
"""
return G.edges_iter(nbunch) | bigcode/self-oss-instruct-sc2-concepts |
def _ConditionHelpText(intro):
"""Get the help text for --condition."""
help_text = """
{intro}
*expression*::: (Required) Expression of the condition which
evaluates to True or False. This uses a subset of Common Expression
Language syntax.
*title*::: (Required) Title for the expression, i.e. a short string
desc... | bigcode/self-oss-instruct-sc2-concepts |
def configsection(config, section):
"""
gets the list of keys in a section
Input:
- config
- section
Output:
- list of keys in the section
"""
try:
ret = config.options(section)
except:
ret = []
return ret | bigcode/self-oss-instruct-sc2-concepts |
def _py2vim_scalar(value, null, true, false):
"""Return the given Python scalar translated to a Vim value.
None, True, and False are returned as the (Vim) sentinel values 'null',
'true', and 'false', respectively; anything else is returned untouched.
"""
if value is None:
return null
if... | bigcode/self-oss-instruct-sc2-concepts |
def Y_i(i,A,X):
"""
Calculate band `i` of the coordinate rotation described in equation 8 of
Lyzenga 1978.
Parameters
----------
i : int
The band number of `Y` to calculate.
A : np.array
The coordinate system rotation parameters calculated by the method
`Aij` and des... | bigcode/self-oss-instruct-sc2-concepts |
def degree_max_repetition(recpat_bag:list):
"""
Computes the degree of maximal repetition from a bag of
recurring patterns -- a list of ngram tuples.
"""
return max([len(recpat) for recpat in recpat_bag]) | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_cog(cog):
"""Validates course over ground
Arguments
---------
cog : float
Course over ground
Returns
-------
True if course over ground is greater than zero and less than 360 degrees
"""
return cog >= 0 and cog < 360 | bigcode/self-oss-instruct-sc2-concepts |
def IsGlobalTargetGrpcProxiesRef(target_grpc_proxy_ref):
"""Returns True if the target gRPC proxy reference is global."""
return target_grpc_proxy_ref.Collection() == 'compute.targetGrpcProxies' | bigcode/self-oss-instruct-sc2-concepts |
def divide(num, den):
"""
Divide num by den in a template, returns 'NaN' if denominator is 0.
"""
return (float(num) / float(den)) if float(den)!=0 else 'NaN' | bigcode/self-oss-instruct-sc2-concepts |
def _get_all_objects(objs):
"""
Helper function to get all objects of a 'Network' along with their
corresponding ``contained_objects``.
Parameters
----------
objs : Iterable
List or set of objects
Returns
-------
all_objects : set
A set of all Network's objects and ... | bigcode/self-oss-instruct-sc2-concepts |
def is_empty(df):
"""Tests if a pd.DataFrame is empty or not"""
return len(df.index) == 0 | bigcode/self-oss-instruct-sc2-concepts |
def bytes2human(n: int) -> str:
"""Convert `n` bytes into a human readable string.
>>> bytes2human(10000)
'9.8K'
>>> bytes2human(100001221)
'95.4M'
"""
# http://code.activestate.com/recipes/578019
symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
prefix = {}
for i, s in enumera... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def extend_batch(batch, dataloader, batch_size):
"""
If the batch size is less than batch_size, extends it with
data from the dataloader until it reaches the required size.
Here batch is a tensor.
Returns the extended batch.
"""
while batch.shape[0] != batch_size:
data... | bigcode/self-oss-instruct-sc2-concepts |
def queue_to_list(queue):
"""Convert a Queue to a list."""
result = []
while queue.qsize() != 0:
result.append(queue.get())
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_value(json, attr):
"""Get the value from the json."""
if attr in json:
return json[attr][0]
return "" | bigcode/self-oss-instruct-sc2-concepts |
def run_async(coro):
"""Execute a coroutine until it's done."""
values = []
result = None
while True:
try:
values.append(coro.send(None))
except StopIteration as ex:
result = ex.args[0] if ex.args else None
break
return values, result | bigcode/self-oss-instruct-sc2-concepts |
def get_log_prob_unigram(masked_token_ids, token_ids, mask_idx, lm):
"""
Given a sequence of token ids, with one masked token, return the log probability of the masked token.
"""
model = lm["model"]
tokenizer = lm["tokenizer"]
log_softmax = lm["log_softmax"]
mask_token = lm["mask_token"... | bigcode/self-oss-instruct-sc2-concepts |
def num_region_obs(count_arr, lon_idxs, lat_idxs):
"""
Given lon/lat indices and array of GOSAT counts, determine number of
observations in the region as defined by the indices.
Parameters:
count_arr (np arr) : array of counts (Mx72x46), M num months
lon_idxs (np arr) : array of longit... | bigcode/self-oss-instruct-sc2-concepts |
def get_uid_from_action_name(action_name, uid_string=None):
"""
Extract id from action name by splitting at "__", because this marks the start of id in action name.
If uid string is in action name, remove it
:param action_name: full action name of processor (e.g. "{action_type}_{aName}_{id}[uid_string}]... | bigcode/self-oss-instruct-sc2-concepts |
def metaclass_name_for_class(classname):
"""Return the name of the C++ metaclass for the given class."""
if '::' in classname:
return None
return classname + '::MetaClass' | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def file_exists(
path,
exception=ValueError,
emsg="`path` is not a file or does not exist",
):
"""
Assert if file exist.
Parameters
----------
path : str or pathlib.Path
The file path.
exception : Exception
The Exceptio... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def b64e(b):
"""Base64 encode some bytes.
Uses the url-safe - and _ characters, and doesn't pad with = characters."""
return base64.urlsafe_b64encode(b).rstrip(b"=") | bigcode/self-oss-instruct-sc2-concepts |
import torch
def tensor_abs(inputs):
"""Apply abs function."""
return torch.abs(inputs) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def parse_camera_id(metadata: Dict[str, Any]):
"""
Determine the camera the photograph was taken with from its EXIF data.
:param metadata: EXIF data to find the camera from.
:returns: The camera id, if it could be determined. If not, returns ``'Unknown'``.
"""
f... | bigcode/self-oss-instruct-sc2-concepts |
def key2freq(n: int) -> float:
"""
Gives the frequency for a given piano key.
Args:
n: The piano key index
Returns:
The Frequency
"""
return 440 * 2 ** ((n - 49) / 12) | bigcode/self-oss-instruct-sc2-concepts |
def order(sentence: str) -> str:
"""
Sorts a given string by following rules:
1. Each word in the string will contain a single number.
This number is the position the word should have in the result.
2. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
3. I... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def setupcfg_has_metadata(setup_cfg_filename='setup.cfg'):
"""Parse the setup.cfg and return True if it has a metadata section"""
config = configparser.ConfigParser()
config.read(setup_cfg_filename)
if 'metadata' in config.sections():
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def isnumber(word):
""" Checks if a string is a string of a number.
Parameters
----------
word : string
String of the possible number.
Returns
-------
Boolean.
"""
try:
float(word)
except (ValueError, TypeError):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def md5(filepath, blocksize=65536):
"""Generate MD5 hash for file at `filepath`"""
hasher = hashlib.md5()
fo = open(filepath, 'rb')
buf = fo.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fo.read(blocksize)
return hasher.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Optional
def resolve_absolute_offset(
dataset_path: Path, offset: str, target_path: Optional[Path] = None
) -> str:
"""
Expand a filename (offset) relative to the dataset.
>>> external_metadata_loc = Path('/tmp/target-metadata.yaml')
>>> resolve_absolut... | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_json(data):
"""Return a JSON string representation of data.
If data is a dictionary, None is replaced with 'null' in its keys and,
recursively, in the keys of any dictionary it contains. This is done to
allow the dictionary to be sorted by key before being written to JSON.
"""... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _calculate_target_load(num_reqs: int, rate: float = 100, baseline: int = 0) -> int:
""" Given the rate and number of URLs in data set, calculate how many URLs to send in this load"""
if baseline:
target_num_reqs = baseline * (rate / 100)
else:
target_num_reqs = num_reqs * (... | bigcode/self-oss-instruct-sc2-concepts |
def format_name(name: str) -> str:
"""Formats a string for displaying to the user
Examples
--------
>>> format_name("manage_messages")
'Manage Messages'
>>> format_name("some_name")
'Some Name'
Parameters
----------
name : str
the raw name
Returns
-------
s... | bigcode/self-oss-instruct-sc2-concepts |
def string_to_int_list(line) -> list[int]:
"""
Given a line containing integers, return a list of ints.
Return list[int]: A list of integers from the string.
>>> string_to_int_list('22 13 17 11 0')
[22, 13, 17, 11, 0]
>>> string_to_int_list('22,13,17,11,0')
[22, 13, 17, 11, 0]
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_push_size(op):
"""Get push side increment for given instruction or register."""
ins = op.lower()
if ins == 'pushq':
return 8
elif ins == 'pushl':
return 4
else:
raise RuntimeError("push size not known for instruction '%s'" % (ins)) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_number_of_asa_service_groups(asa):
"""
Returns the number of service object-groups the given ASA object has configured.
:param asa: ASA device to count network object-groups.
:return: Integer which describes how many object-groups is found on ASA.
"""
url = asa.url() + ... | bigcode/self-oss-instruct-sc2-concepts |
def zeros(n: int) -> int:
"""Return the number of trailing zeros in the binary representation of n.
Return 0 if n == 0."""
result = 0
while n & 1 == 0:
n = n // 2
result += 1
return result | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_nb_query_params(nb_url_search: str) -> dict:
"""
Get the url query parameters from the search string.
Arguments:
nb_url_search {str} -- The URL search string
Returns:
dictionary of the query string parameters.
"""
nb_params = {}
query_string_match = re.... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Iterator
def _exponential_backoff(
retries: int = 10,
delay: float = 2,
backoff: float = 2,
max_delay: float = 60) -> Callable:
"""
Customizable exponential backoff strategy.
Args:
retries (int): Maximum number of times... | bigcode/self-oss-instruct-sc2-concepts |
def find_zeroes_2(f, a, b, epsilon=1e-10):
"""
A formulation of the recursive version of find_zeroes that does not do explicit recursion on the stack.
:param f: The function.
:param a: The lower bound of the interval.
:param b: The upper bound of the interval.
:param epsilon: The stopping toler... | bigcode/self-oss-instruct-sc2-concepts |
def find_scenario_string_from_number(scenario):
"""
Find a string to represent a scenario from it's number (or None in the case of baseline).
Args:
scenario: The scenario value or None for baseline
Returns:
The string representing the scenario
"""
if scenario == 0:
retu... | bigcode/self-oss-instruct-sc2-concepts |
import io
def load_data(dataset_path):
"""
load data from a file
:param dataset_path:
:return: a list of all the items in the file
"""
items = []
with io.open(dataset_path, "r", encoding="utf8") as f:
for line in f:
items.append(line.rstrip())
return items | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_clusters_from_labels(texts: List[str], labels: List[int]) -> List[List[str]]:
"""Given a series of texts and their labels (as produced during clustering), reconstructs the clusters"""
return [[text for text, lab in zip(texts, labels) if lab == label] for label in set(labels) i... | bigcode/self-oss-instruct-sc2-concepts |
def parsing_explore_lines(explore_list, loc_list):
"""
This function parses a list of explore lines into a grouped structure of explore lines.
:param explore_list: the list representing raw explore file.
:type explore_list: list
:param loc_list: the list of dividers, each divider is the number of... | bigcode/self-oss-instruct-sc2-concepts |
def names_to_labels(names, depth=1, sep='.'):
"""
convert names to grouping labels
Parameters
----------
names : [str]
account names in form of 'Foo.Bar.Baz'
depth : int, optional
returned label depth. The default is 1.
sep : char, optional
Separator character. The d... | bigcode/self-oss-instruct-sc2-concepts |
def apply_filter(x, W):
"""
Applies a filter on the mixture. Just corresponds to a matrix
multiplication.
Parameters
----------
x: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)]
STFT of the signal on which to apply the filter.
W: np.ndarray [shape=(nb_frames, nb_bins, nb_chan... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def merge_dict(a, b):
"""Merge the fields of a and b, the latter overriding the former."""
res = copy.deepcopy(a) if a else {}
copyb = copy.deepcopy(b) if b else {}
for key in copyb:
res[key] = copyb[key]
return res | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance_between_points(x, y):
"""
distance between two points with the coordinates (x1, y1) and (x2, y2).
D=√(x2−x1)2+(y2−y1)2
"""
all_distances = []
zipped = zip(x,y)
for z in zipped:
z1, z2 = z
all_distances.append((z1-z2)**2)
return math.sqrt(sum(all... | bigcode/self-oss-instruct-sc2-concepts |
def GetGlueCpp(idl_file):
"""Gets the name of the glue implementation file.
Args:
idl_file: an idl_parser.File, the source IDL file.
Returns:
the name of the implementation file.
"""
if 'npapi_cpp' in idl_file.__dict__:
return idl_file.npapi_cpp
else:
return idl_file.basename + '_glue.cc' | bigcode/self-oss-instruct-sc2-concepts |
def register_event(event_type, include_subclasses=False):
"""
Register a method to handle a specific `opsdroid.events.Event` object.
Args:
event_type (Event): The event class this method can handle.
include_subclasses (bool): Allow the function to trigger on subclasses of the registered
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def CryptRandInt(length=10):
"""Get random integer in range"""
#byte = os.urandom(100)
#rand = int(byte.hex(),16)
r = random.SystemRandom()
rndint = r.randrange( length )
return rndint | 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.