seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def propagation_level_end(start_point: tuple, shape: tuple) -> int:
"""
Returns the maximum propagation level where our data points will change
I.e. if start_point=(8, 8, 8) and shape=(16, 16, 16), then returns 8
If start_point=(1, 1, 3) and shape=(16, 16, 16) then returns 16-1=15
"""
max_val = ... | bigcode/self-oss-instruct-sc2-concepts |
def sum(mat, axis, target = None):
"""
Sum the matrix along the given dimension, where 0 represents the leading
dimension and 1 represents the non-leading dimension. If a target is
not prvided, a new vector is created for storing the result.
"""
return mat.sum(axis, target) | bigcode/self-oss-instruct-sc2-concepts |
def truncate_xticklabels(plot, stop_index=30):
"""
Truncate xtick labels with an ellipsis after `stop_index`
"""
for label in plot.get_xticklabels():
t = label.get_text()
if len(t) < stop_index:
continue
else:
label.set_text(t[:stop_index] + '...')
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def with_base_config(base_config, extra_config):
"""Returns dict with updates applied, helpful for one-liners"""
config = copy.deepcopy(base_config)
config.update(extra_config)
return config | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def replace_marker(text: str, marker: str, src_filename: str, replace_marker_with_src_file: bool = True) -> str:
""" replace a marker in the text with the content of a file, or with '' """
if replace_marker_with_src_file:
path_base_dir = pathlib.Path(__file__).parent
path_src_fi... | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def find_le(a, x):
"""Find rightmost value less than or equal to x"""
i = bisect.bisect_right(a, x)
if i:
return a[i-1]
raise ValueError | bigcode/self-oss-instruct-sc2-concepts |
def from_uint8_bytes(uint8: bytes) -> int:
"""Convert from uint8 to python int."""
return int.from_bytes(uint8, byteorder="little") | bigcode/self-oss-instruct-sc2-concepts |
def Precipitation(prec, temp, tt, rfcf, sfcf):
"""
========================================================
Precipitation (temp, tt, prec, rfcf, sfcf)
========================================================
Precipitaiton routine of the HBV96 model.
If temperature is lower than TT [degree C], ... | bigcode/self-oss-instruct-sc2-concepts |
import typing
import math
def triangle_ASA(alpha: float, c: float, beta: float) -> typing.Tuple[float, float, float]:
"""Given angle at A, included side A-B, angle at B of a plane triangle
this returns side A-C, angle at C, side C-B. Angles in radians.
See: https://en.wikipedia.org/wiki/Solution_of_triang... | bigcode/self-oss-instruct-sc2-concepts |
def is_runway_visibility(item: str) -> bool:
"""Returns True if the item is a runway visibility range string"""
return (
len(item) > 4
and item[0] == "R"
and (item[3] == "/" or item[4] == "/")
and item[1:3].isdigit()
) | bigcode/self-oss-instruct-sc2-concepts |
def E(expr):
"""
The notion of the expectation of random variables and the worst-case
expected values
Notes
-----
This function is used to denote
1. the expected value of an random variable when specifying the
uncertainty set of expectations.
2. the worst-case expected value of an a... | bigcode/self-oss-instruct-sc2-concepts |
def match_barcode_rule(trello_db, barcode):
"""Finds a barcode rule matching the given barcode.
Returns the rule if it exists, otherwise returns None."""
for rule in trello_db.get_all('barcode_rules'):
if rule['barcode'] == barcode:
return rule
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import TextIO
from typing import List
def parse_floats(io: TextIO) -> List[float]:
"""Parse first line of io to list of floats.
Parameters
----------
io :: TextIO
Object supporting `readline()`
Returns
-------
floats :: List[float]
A list of floats
Exampl... | bigcode/self-oss-instruct-sc2-concepts |
def hex2int(hex_str):
"""
Convert hex characters (e.g. "23" or "011a") to int (35 or 282)
:param hex_str: hex character string
:return: int integer
"""
return int(hex_str, 16) | bigcode/self-oss-instruct-sc2-concepts |
def determine_ambiguous_references(columns: set, definitions: set) -> set:
""" Return the set of reference names that exist as both a column and a definition. """
# get the diffs between the two sets
unambiguous_columns = columns - definitions
unambiguous_definitions = definitions - columns
# then... | bigcode/self-oss-instruct-sc2-concepts |
def get_repo_name(pull_request, key):
""" Extract repo name from a pull request dict. """
return pull_request[key]["repo"]["name"] | bigcode/self-oss-instruct-sc2-concepts |
import math
def gon_to_rad(angle: float) -> float:
"""Converts from gon (grad) to radiant.
Args:
angle: Angle in gon.
Returns:
Converted angle in rad.
"""
return angle * math.pi / 200 | bigcode/self-oss-instruct-sc2-concepts |
def decode_int(v):
"""Decodes integer value from hex string. Helper function useful when decoding data from contracts.
:param str v: Hexadecimal string
:return: Decoded number
:rtype: num
"""
if v[0:2] == '0x':
return int(v.replace('0x', ''), 16)
else:
return int(v) | bigcode/self-oss-instruct-sc2-concepts |
def closed_neighborhood(graph, v):
"""The closed neighborhood of a vertex in a graph
Args:
graph (networkx.classes.graph.Graph): graph
v: vertex in a graph
Returns:
The neighbors of v in graph, as a set.
Example:
>>> import networkx as nx
>>> from pycliques.dominated imp... | bigcode/self-oss-instruct-sc2-concepts |
def NP(record):
""" "No Process": the linked record is not processed.
This is the default behavior of EPICS links.
Example (Python source)
-----------------------
`my_record.INP = NP(other_record)`
Example (Generated DB)
----------------------
`field(INP, "other NPP")`
"""
retu... | bigcode/self-oss-instruct-sc2-concepts |
def camels_in_dest(camel_dict, destination):
"""Find the camels in the destination square
Parameters
----------
camel_dict : nested dict
Dictionary with current camel positions
destination : int
Square where camels are moving
Returns
-------
max_height_dest : int
... | bigcode/self-oss-instruct-sc2-concepts |
def _capability(interface,
version=3,
supports_deactivation=None,
cap_type='AlexaInterface'):
"""Return a Smart Home API capability object.
https://developer.amazon.com/docs/device-apis/alexa-discovery.html#capability-object
There are some additional fields ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def list_urls_from_string(text):
"""
From: https://stackoverflow.com/a/48769624/2907906
Modified to require the protocol (http:// or https://) to be present
It'll return a list of urls present in the string
"""
return re.findall("(?:(?:https?):\/\/)[\w/\-?=%.]+\.[\w/\-?=%.]+", text) | bigcode/self-oss-instruct-sc2-concepts |
def coords_zero(coords):
""" Return the origin for the coords """
return (0,) * len(coords) | bigcode/self-oss-instruct-sc2-concepts |
import json
def loads(kv_data):
"""
Decoding Key Value Json String
:param kv_data: [String] JSON String representing the Key Value information
:return: [Dictionary] Returns the JSON in dictionary form
"""
dict_kv = {}
if isinstance(kv_data, str):
kvs = json.loads(kv_data)
... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def decode(encoded_message):
"""
Decodes the message in base64
Args:
encoded_message (str): encoded message
Returns:
str: decoded message
"""
encoded_message_bytes = encoded_message.encode("ascii")
decoded_base64_bytes = base64.b64decode(encoded_message_byt... | bigcode/self-oss-instruct-sc2-concepts |
def is_unlimited(rate_limit):
"""
Check whether a rate limit is None or unlimited (indicated by '-1').
:param rate_limit: the rate limit to check
:return: bool
"""
return rate_limit is None or rate_limit == -1 | bigcode/self-oss-instruct-sc2-concepts |
def remove_arc(net, arc):
"""
Removes an arc from a Petri net
Parameters
---------------
net
Petri net
arc
Arc of the Petri net
Returns
-------------
net
Petri net
"""
net.arcs.remove(arc)
arc.source.out_arcs.remove(arc)
arc.target.in_arcs.re... | bigcode/self-oss-instruct-sc2-concepts |
def get_overlap_between_intervals(a, b):
"""
Finds the overlap between two intervals end points inclusive.
#Makes sure not to report overlap beyond either interval length.
# a=[10,20]; b=[10,20] --> f(a,b)=10 !(not 11)
# a=[10,20]; b=[20,30] --> f(a,b)=1
a=[10,20]; b=[15,30] --> f(a,b)=6
"""
#lena=abs(float(a... | bigcode/self-oss-instruct-sc2-concepts |
def _async_get_hass_provider(hass):
"""Get the Home Assistant auth provider."""
for prv in hass.auth.auth_providers:
if prv.type == 'homeassistant':
return prv
raise RuntimeError('No Home Assistant provider found') | bigcode/self-oss-instruct-sc2-concepts |
def split_train_test(X_all, y_all, frac_train):
"""
The first X% of X_all, y_all become the training set, the rest (1-X)% become the test set.
Note that this assumes that the samples are already shuffled or if not (e.g. if we were to split MNIST) that
this behavior is intended.
"""
num_total = X... | bigcode/self-oss-instruct-sc2-concepts |
def min_max_temp(cities_data):
"""Returns a list whose first and second elements are the min and the max temperatures of all the
cities in cities_data.
"""
temps = []
for r in cities_data:
temps.append(float(r['temperature']))
return [min(temps), max(temps)] | bigcode/self-oss-instruct-sc2-concepts |
def trim(msa, threshold=0.0):
"""Trim a MSA to its first and last non-gap containing columns."""
def gap_pct(msa, index):
return msa.column(index).count("-") / msa.count()
length = len(msa)
start, end = 0, length - 1
start_found, end_found = False, False
for i in range(length):
... | bigcode/self-oss-instruct-sc2-concepts |
def stray(arr):
"""
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
:param arr: an array of integers.
:return: the single different number in the array.
"""
a, b = set(arr)
return a if arr.count(a) == 1 else b | bigcode/self-oss-instruct-sc2-concepts |
def block_to_dict(block):
"""
Serialize a block as a dict.
"""
return {
"type": block.type,
"value": block.value
} | bigcode/self-oss-instruct-sc2-concepts |
def get_inside_outside_brackets(data, start_char, end_char, nested=True):
"""Split string into portions inside and outside delimiters
Args:
data: str
The string to parse
start_char: str
Character indicating the beginning of a delimited string
end_char: str
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_string(string):
""" return the md5 hash of a string"""
return hashlib.md5(string).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sample_from_latent_distribution(z_mean, z_logvar):
"""Samples from the Gaussian distribution defined by z_mean and z_logvar."""
e = torch.randn_like(z_mean)
return torch.add(
z_mean,
torch.exp(z_logvar / 2) * e,
) | bigcode/self-oss-instruct-sc2-concepts |
def valid_type(str_of_type):
"""Function for returning a pandas type given a string value representing that type
Args:
str_of_type (str): a python type in string form
Outputs:
the Pandas term for that type
"""
if str_of_type in ['int','integer']:
return('Int6... | bigcode/self-oss-instruct-sc2-concepts |
def file_id(file_query):
"""Returns an ID of the form `_file_$ID` to represent a [snoop.data.models.File][].
This ID is used to cross-link objects in the API.
"""
return f'_file_{file_query.pk}' | bigcode/self-oss-instruct-sc2-concepts |
def composeVideoMaskName(maskprefix, starttime, suffix):
"""
:param maskprefix:
:param starttime:
:param suffix:
:return: A mask file name using the provided components
"""
if maskprefix.endswith('_mask_' + str(starttime)):
return maskprefix + '.' + suffix
return maskprefix + '_m... | bigcode/self-oss-instruct-sc2-concepts |
def handler(context, inputs):
"""Set a name for a machine
:param inputs
:param inputs.resourceNames: Contains the original name of the machine.
It is supplied from the event data during actual provisioning
or from user input for testing purposes.
:param inputs.newName: The new mac... | bigcode/self-oss-instruct-sc2-concepts |
def make_dict(tokens):
"""Converts a parsed list of tokens to a dictionary."""
tokdict={}
for t in tokens:
tokdict[t[0]]=t[1:]
return tokdict | bigcode/self-oss-instruct-sc2-concepts |
def format_score(logpath, log, markup):
"""Turn a log file JSON into a pretty string."""
output = []
output.append('\nLog: ' + logpath)
if log['unrecognized']:
output.append('\nLog is unrecognized: {}'.format(log['unrecognized']))
else:
if log['flagged']:
output.append('\... | bigcode/self-oss-instruct-sc2-concepts |
def reply(f):
""" Mark f as a handler for mention notifications. """
f.reply = True
return f | bigcode/self-oss-instruct-sc2-concepts |
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = {}
index = 0
with open(vocab_file, "r", encoding="utf-8") as reader:
while True:
token = reader.readline()
if not token:
break
token = token.strip()
... | bigcode/self-oss-instruct-sc2-concepts |
def win_check(board, mark):
"""
function that takes in a board and checks to see if someone has won.
:param board: the board to check
:param mark: the last mark in placed in the board
:return: True if game is win or False otherwise
"""
return ((board[7] == mark and board[8] == mark and board... | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_random_coordinate(image):
"""
Example:
coordinates= get_random_coordinates() # gives random x-y coordinates inside image
Output:
return tupe (x,y).
"""
x,y,z=image.shape
return (random.randint(0,y),random.randint(0,x)) | bigcode/self-oss-instruct-sc2-concepts |
def contains(self, key):
"""
return True if key is in self, False otherwise
"""
try:
# pylint: disable=pointless-statement
self[key]
return True
except KeyError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def convert_seconds(seconds):
"""Converts the provided seconds value into days, hours, minutes, seconds and returns a tuple containing each of these values"""
# Converting seconds to a standard python float type to resolve the "negative 0 when using numpy.float64 type" issue .
seconds = float(seconds)
... | bigcode/self-oss-instruct-sc2-concepts |
def _hashable(x):
"""
Ensure that an point is hashable by a python dict.
"""
return tuple(map(float, x)) | bigcode/self-oss-instruct-sc2-concepts |
def make_sepset_node_name(node_a_name, node_b_name):
"""
Make a standard sepset node name using the two neighboring nodes.
:param str node_a_name: The one node's name.
:param str node_b_name: The other node's name.
:return: The sepset's name
:rtype: str
"""
return "sepset__" + "__".join... | bigcode/self-oss-instruct-sc2-concepts |
def readHysteresisDelayfromGUI(delay, timeZero):
"""
Read and create Hysteresis Delays from GUI. The values are given relative
to the timezero (so -20 means 20ps before the set t0).
The returned value is the absolute ps Delay for the setting of the stage.
:param delay, timeZero:
:return: delayV... | bigcode/self-oss-instruct-sc2-concepts |
def to_ascii(text):
"""Convert text to ascii."""
asciiText = ''.join([ch if ord(ch) < 128 else ' ' for ch in text])
return asciiText | bigcode/self-oss-instruct-sc2-concepts |
def SpanValue(span, arena):
"""Given an line_span and a arena of lines, return the string value.
"""
line = arena.GetLine(span.line_id)
c = span.col
return line[c : c + span.length] | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_direct_mention(message_text):
"""
Finds a direct mention (a mention that is at the beginning) in message text
and returns the user ID which was mentioned. If there is no direct mention, returns None
"""
matches = re.search("^<@(|[WU].+?)>(.*)", message_text)
# the f... | bigcode/self-oss-instruct-sc2-concepts |
def rpc_get_methods(client, current=None, include_aliases=None):
"""Get list of supported RPC methods.
Args:
current: Get list of RPC methods only callable in the current state.
include_aliases: Include aliases in the list with RPC methods.
"""
params = {}
if current:
params... | bigcode/self-oss-instruct-sc2-concepts |
import time
def rt_format_comment_time(t):
"""
Given a time struct representing the RT ticket's comment timestamp, this
returns a formatted, printable version of this timestamp.
:param t: the time struct of the RT ticket's comment timestamp
"""
return time.strftime("%a %b %d %H:%M:%S %Y UTC"... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def extended_euclidean(num_a: int, num_b: int) -> Tuple[int, int, int]:
"""
Perform the extended euclidean algorithm on the input numbers.
The method returns gcd, x, y, such that a*x + b*y = gcd.
:param num_a: First number a.
:param num_b: Second number b.
:return: Tu... | bigcode/self-oss-instruct-sc2-concepts |
def legacy_id_to_url_fn(id: str) -> str:
"""Generate an arxiv.org/archive URL given a paper ID."""
return 'https://arxiv.org/archive/' + id | bigcode/self-oss-instruct-sc2-concepts |
def feature_engineering(df):
"""Add statistics to raw data to analyze changes across time"""
# day-to-day change
df['result_count_absolute_change'] = df.groupby('keyword').results_count.diff().reset_index(drop=True) # day-to-day absolute change
df['result_count_relative_change'] = (df.result_count_ab... | bigcode/self-oss-instruct-sc2-concepts |
def confirm_proceed(prompt='Shall I proceed? (y/n)'):
"""
Prompts user for confirmation. Expects 'y' or 'n'.
"""
confirm = ''
while confirm not in ('y', 'Y', 'n', 'N'):
confirm = input(prompt)
if confirm in ('n', 'N'):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def reversepath(path):
"""
This function reverses a path.
"""
return path[::-1] | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_minimal(data):
"""Get JSON data in minimal form."""
return json.dumps(data, separators=(",", ":")) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def get_table_data(cursor, table_name, single_row=False, replace_none=False):
"""
Extract all the data of the table
Args:
cursor: the DB cursor
table_name: the name of the database
single_row: if True, returns a single row
replace_none: if True, replace ... | bigcode/self-oss-instruct-sc2-concepts |
def galois_multiply(a, b):
"""Galois Field multiplicaiton for AES"""
p = 0
while b:
if b & 1:
p ^= a
a <<= 1
if a & 0x100:
a ^= 0x1b
b >>= 1
return p & 0xff | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_node_distance(graph, node_1, node_2):
"""
Calculates distance between two nodes of graph,
Requires node attribute 'position' as shapely Point, e.g. Point(10, 15.2)
Parameters
-----------
graph : nx.graph
Graph object of networkx
node_1 : int
Node id of... | bigcode/self-oss-instruct-sc2-concepts |
def compareThresh(value,threshold,mode,inclusive, *, default=False):
"""Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False').
Accepted mode values are '<', '>', '<=' and '>='."""
#normalizing input
i... | bigcode/self-oss-instruct-sc2-concepts |
def filter_rule(_):
"""
No rule is needed
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
def calc_total_event(events_dict: dict) -> int:
"""各照射回数の合計を求める
Args:
events_dict (dict):
Returns:
int: cnt
"""
cnt = 0
for key in events_dict.keys():
n = int(events_dict[key])
cnt = cnt + n
return cnt | bigcode/self-oss-instruct-sc2-concepts |
def _compute_bands_from_cuts(cuts, sequence_length, linear=True):
"""Compute the size of the obtained bands from the position of cuts.
Returns a list of band sizes.
Parameters
----------
cuts
Location of the different cuts on the plasmid.
sequence_length
Length of the DNA molecule... | bigcode/self-oss-instruct-sc2-concepts |
import glob
def sorted_glob(pathname):#, cmp=None, key=None, reverse=None):
"""Returns a sorted list of file names matching glob pattern `pathname'.
Added here to accomodate older python that do not have sorted() function."""
rslt = glob.glob(pathname)
rslt.sort() #cmp=cmp, key=key, reverse=reverse)
return ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_valid_indices(shape, ix0, ix1, iy0, iy1):
"""Give array shape and desired indices, return indices that are
correctly bounded by the shape."""
ymax, xmax = shape
if ix0 < 0:
ix0 = 0
if ix1 > xmax:
ix1 = xmax
if iy0 < 0:
iy0 = 0
if iy1 > ymax:
iy1 = ym... | bigcode/self-oss-instruct-sc2-concepts |
def get_var(environ, keys, default=None):
"""Try each of the keys in turn before falling back on the default."""
for key in keys:
if environ.has_key(key):
return environ.get(key)
return default | bigcode/self-oss-instruct-sc2-concepts |
def sometrue(*args, **kwargs):
"""
Check whether some values are true.
Refer to `any` for full documentation.
See Also
--------
any : equivalent function; see for details.
"""
return any(*args, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def _label_str(block):
"""Returns a string by which the given block may be named, even if `None`."""
if block is None:
return 'exit'
else:
return block.label_str | bigcode/self-oss-instruct-sc2-concepts |
def react_polymer(polymer_string):
"""
Iterate through polymer_string, replacing all instances where two
adjacent characters are case-insensitive equal but not equal (i.e. A and a)
with the empty string
"""
# convert to a list since strings are immutable
polymer_list = [i for i in polymer_st... | bigcode/self-oss-instruct-sc2-concepts |
def graphql_mutation(
field_name, field_type, arguments={}, context_args=[],
description=None, is_deprecated=False, deprecation_reason=None):
"""Annotate a function as corresponding to a GraphQL mutation.
Decorator that annotates a function as corresponding to a GraphQL
mutation; i.e. a fie... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def check_disk_space(available_disk_space_percent_threshold):
""" Checks if disk space is above given threshold.
Args:
available_disk_space_percent_threshold(int): The disk space threshold
you want the root drive to be above.
Returns:
(Bool): Returns true if disk sp... | bigcode/self-oss-instruct-sc2-concepts |
def humanize_timedelta(td):
"""Pretty-print a timedelta in a human readable format."""
secs = int(td.total_seconds())
hours, secs = divmod(secs, 60 * 60)
mins, secs = divmod(secs, 60)
if hours:
return '%dh %dm' % (hours, mins)
if mins:
return '%dm' % mins
return '%ds' % secs | bigcode/self-oss-instruct-sc2-concepts |
def is_game_row_valid(game, lookup):
"""Returns whether all columns can be found in the game entry.
Parameters:
game: the entry for the game
lookup: a lookup for fields to indexes in columns
Returns:
true if valid row otherwise False
"""
for index in lookup.values():
... | bigcode/self-oss-instruct-sc2-concepts |
def format_syntax_error(e: SyntaxError) -> str:
""" Formats a SyntaxError. """
if e.text is None:
return "```py\n{0.__class__.__name__}: {0}\n```".format(e)
# display a nice arrow
return "```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```".format(
e, "^", type(e).__name__) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def diff_to_new_interesting_lines(unified_diff_lines: List[str]) -> Dict[int, str]:
"""
Extracts a set of 'interesting' lines out of a GNU unified diff format.
Format:
gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html
@@ from-li... | bigcode/self-oss-instruct-sc2-concepts |
def find_xpath(xpath, tree, namespaces={}, **kwargs):
"""
Find elements within an XML tree whose attributes match certain
values.
:param xpath: an xpath query string.
:param tree: `xml.etree.ElementTree` object.
:param namespaces: a dictionary of namespace prefixes.
:param kwargs: specifies... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def getPublicTypeMembers(type_, onlyValues=False):
"""
Useful for getting members from types (e.g. in enums)
>>> [_ for _ in getPublicTypeMembers(OS, True)]
['Linux', 'Windows']
"""
retVal = []
for name, value in inspect.getmembers(type_):
if not name.startswith("... | bigcode/self-oss-instruct-sc2-concepts |
def rolling_average(current_avg: float, new_value: float, total_count: int) -> float:
"""Recalculate a running (or moving) average
Needs the current average, a new value to include, and the total samples
"""
new_average = float(current_avg)
new_average -= new_average / total_count
new_average +... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def _process(proc_data: List[Dict]) -> List[Dict]:
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured to conform to t... | bigcode/self-oss-instruct-sc2-concepts |
def remove_specific_key(dictionary, key):
"""
Remove a specific named key from a dictionary.
Args:
dictionary: The dictionary to have a key removed
key: The key to be removed
Returns:
dictionary: The dictionary with the key removed
"""
if key in dictionary:
del ... | bigcode/self-oss-instruct-sc2-concepts |
def pulse_sink_port(sink, name_or_desc):
"""
Returns the PulseSinkInfo that matches the string, either against the name or the description.
:param sink: the PulseSinkObject to get the port from
:type sink: pulsectl.PulseSinkObject
:param name_or_desc: the name or description string to look for, use... | bigcode/self-oss-instruct-sc2-concepts |
def _group_list(items, lens):
"""
Unflat the list of items by lens
:param items: list of items
:param lens: list of integers
:return: list of list of items grouped by lengths
"""
res = []
cur_ofs = 0
for g_len in lens:
res.append(items[cur_ofs:cur_ofs+g_len])
cur_ofs ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def dump_bytes(*args, **kwargs):
"""Converts an object to JSON and returns the bytes."""
return json.dumps(*args, **kwargs).encode("ascii") | bigcode/self-oss-instruct-sc2-concepts |
import copy
def _GenerateInferredAshFlags(device_config):
"""Generate runtime-packed ash flags into a single device config.
Chrome flags are packed into /ui:serialized-ash-flags in the
resultant runtime-only configuration, as a string of null-terminated
strings.
Args:
device_config: transformed config... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def _should_ignore_markdown_cell(
source: Sequence[str],
skip_celltags: Sequence[str],
tags: Sequence[str],
) -> bool:
"""
Return True if the current cell should be ignored from processing.
Parameters
----------
source
Source from the notebook cell
... | bigcode/self-oss-instruct-sc2-concepts |
def station_locations(df, id_index):
"""
Creates a dictionary with station IDs as keys and locations as values.
Parameters
----------
df : pandas DataFrame
Bikeshare trip data.
id_index : dict
Maps station ID (arbitrary integer) to the range from 0 to number of stations
Ret... | bigcode/self-oss-instruct-sc2-concepts |
def camel_to_snake(s: str) -> str:
"""Converts "CamelCase" to "snake_case"."""
return "".join(f"_{c}" if c.isupper() else c for c in s).strip("_").lower() | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def npbytearray2hexstring(npbytearray, prefix="0x"):
"""Convert a NumPy array of uint8 dtype into a hex string.
Example:
npbytearray2hexstring(array([15, 1], dtype=uint8)) = "0x0f01"
"""
return prefix + binascii.hexlify(bytearray(npbytearray)).decode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
def update_halley(yvals, y0):
"""Calculate the variable increment using Halley's method.
Calculate the amount to increment the variable by in one iteration of
Halley's method. The goal is to find the value of x for which y(x) = y0.
`yvals` contains the values [y(x0), y'(x0), y''(x0), ...] of the functi... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def spatial_gradient(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Calculate gradients on single dimension of a tensor using central finite difference.
It moves the tensor along the dimension to calculate the approximate gradient
dx[i] = (x[i+1] - x[i-1]) / 2.
Adapted from:
... | bigcode/self-oss-instruct-sc2-concepts |
def convert_by_vocab(vocab, items, unk_info):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
if item in vocab:
output.append(vocab[item])
else:
output.append(unk_info)
return output | bigcode/self-oss-instruct-sc2-concepts |
def initialized(machine):
"""
Check to see if the given machine is initialized.
:param machine: Machine to check to see if default attributes are set
:return: `True` if the machine has its attributes set, `False` otherwise
"""
return all(hasattr(machine, attr) for attr in ('state', 'transition'... | 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.