seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import time
import hmac
import hashlib
def verify_request(
*,
timestamp: str,
signature: str,
request_data: bytes,
signing_secret: str
) -> bool:
"""
This function validates the received using the process described
https://api.slack.com/docs/verifying-requests-from-slack and
using the code in https://github.com/slackapi/python-slack-events-api
Parameters
----------
timestamp: str
originates from headers['X-Slack-Request-Timestamp']
signature: str
originates from headers['X-Slack-Signature']
request_data: bytes
The originating request byte-stream; if using
Flask, then originates from request.get_data()
signing_secret : str
originates from the App config
Returns
-------
bool
True if signature is validated
False otherwise
"""
if abs(time.time() - int(timestamp)) > 60 * 5:
# The request timestamp is more than five minutes from local time.
# It could be a replay attack, so let's ignore it.
return False
req = str.encode('v0:' + str(timestamp) + ':') + request_data
request_hash = 'v0=' + hmac.new(
str.encode(signing_secret),
req, hashlib.sha256
).hexdigest()
return hmac.compare_digest(request_hash, signature) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def bytes_to_int(bindata):
"""Convert a sequence of bytes into a number"""
return reduce(lambda x,y: (x<<8) | y, map(ord,bindata), 0) | bigcode/self-oss-instruct-sc2-concepts |
import re
def word_filter(word):
""" The filter used for deleting the noisy words in changed code.
Here is the method:
1. Delete character except for digit, alphabet, '_'.
2. the word shouldn't be all digit.
3. the length should large than 2.
Args:
word
Returns:
True for not filtering, False for filtering.
"""
if word[:2] == '0x':
return False
if '=' in word:
return False
if '/' in word:
return False
if '.' in word:
return False
if '$' in word:
return False
word = re.sub("[^0-9A-Za-z_]", "", word)
if(word.isdigit()):
return False
if(len(word) <= 2):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import json
def get(event, context):
"""Handle the GET request and return the full lambda request event"""
return {
"statusCode": 200,
"body": json.dumps(event)
} | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def import_model(type_module, type_name):
"""
:param str type_module:
:param str type_name:
:return: Model type
:rtype: type
:raise ImportError: When the model cannot be found.
"""
try:
mod = importlib.import_module(type_module)
except ImportError as e:
raise ImportError("Import {}.{} failed; {}".format(type_module, type_name, e))
try:
type_ = getattr(mod, type_name)
except AttributeError:
raise ImportError("Import {0}.{1} failed; No class named {1}".format(type_module, type_name))
return type_ | bigcode/self-oss-instruct-sc2-concepts |
import re
def float_from_str(text):
"""
Remove uncertainty brackets from strings and return the float.
"""
return float(re.sub("\(.+\)", "", text)) | bigcode/self-oss-instruct-sc2-concepts |
import string
def capwords(value, sep=None):
"""
Split the argument into words using str.split(), capitalize each word using
str.capitalize(), and join the capitalized words using str.join(). If the
optional second argument sep is absent or None, runs of whitespace characters
are replaced by a single space and leading and trailing whitespace are
removed, otherwise sep is used to split and join the words.
"""
return string.capwords(value, sep=sep) | bigcode/self-oss-instruct-sc2-concepts |
def filter_OD(origins, destinations):
"""
takes lists of origins and destinations in (1D notation)
and returns list of tuples with OD coorinates
"""
if len(origins) == len(destinations):
return list(zip(origins, destinations))
else:
return [] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def do_instruction(current_position: int,
accumulator_value: int,
instruction: int,
instruction_value: int) -> Tuple[int, int]:
"""Perform instruction."""
if instruction == 0:
current_position += 1
elif instruction == 1:
accumulator_value += instruction_value
current_position += 1
elif instruction == 2:
current_position += instruction_value
return (current_position, accumulator_value) | bigcode/self-oss-instruct-sc2-concepts |
def get_vertex_names_from_indices(mesh, indices):
"""
Returns a list of vertex names from a given list of face indices
:param mesh: str
:param indices: list(int)
:return: list(str)
"""
found_vertex_names = list()
for index in indices:
vertex_name = '{}.vtx[{}]'.format(mesh, index)
found_vertex_names.append(vertex_name)
return found_vertex_names | bigcode/self-oss-instruct-sc2-concepts |
def add_articles_from_xml(thread, xml_root):
"""Helper function to create Article objects from XML input and add them to a Thread object."""
added_items = False
for item in xml_root.find('articles').findall('article'):
data = {
'id': int(item.attrib['id']),
'username': item.attrib['username'],
'link': item.attrib['link'],
'postdate': item.attrib['postdate'],
'editdate': item.attrib['editdate'],
'numedits': int(item.attrib['numedits']),
}
thread.add_article(data)
added_items = True
return added_items | bigcode/self-oss-instruct-sc2-concepts |
import base64
def decode(payload):
"""
https://en.wikipedia.org/wiki/Base64#URL_applications modified Base64
for URL variants exist, where the + and / characters of standard
Base64 are respectively replaced by - and _
"""
variant = payload.replace('-', '+').replace('_', '/')
return base64.b64decode(variant).decode() | bigcode/self-oss-instruct-sc2-concepts |
def BuildInstanceConfigOperationTypeFilter(op_type):
"""Builds the filter for the different instance config operation metadata types."""
if op_type is None:
return ''
base_string = 'metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.'
if op_type == 'INSTANCE_CONFIG_CREATE':
return base_string + 'CreateInstanceConfigMetadata'
if op_type == 'INSTANCE_CONFIG_UPDATE':
return base_string + 'UpdateInstanceConfigMetadata' | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _parse_publishing_date(string):
"""
Parses the publishing date string and returns the publishing date
as datetime.
Input example (without quotes): "Wed, 09 Nov 2016 17:11:56 +0100"
"""
return datetime.strptime(string,"%a, %d %b %Y %H:%M:%S +0100") | bigcode/self-oss-instruct-sc2-concepts |
def multiply(k, v1):
"""Returns the k*v1 where k is multiplied by each element in v1.
Args:
k (float): scale factor.
v1 (iterable): a vector in iterable form.
Returns:
iterable: the resultant vector.
"""
newIterable = [k * i for i in v1]
return tuple(newIterable) if type(v1) == tuple else newIterable | bigcode/self-oss-instruct-sc2-concepts |
import string
def is_valid_sha1(sha1: str) -> bool:
"""True iff sha1 is a valid 40-character SHA1 hex string."""
if sha1 is None or len(sha1) != 40:
return False
return set(sha1).issubset(string.hexdigits) | bigcode/self-oss-instruct-sc2-concepts |
def _is_projective(parse):
"""
Is the parse tree projective?
Returns
--------
projective : bool
True if a projective tree.
"""
for m, h in enumerate(parse):
for m2, h2 in enumerate(parse):
if m2 == m:
continue
if m < h:
if (
m < m2 < h < h2
or m < h2 < h < m2
or m2 < m < h2 < h
or h2 < m < m2 < h
):
return False
if h < m:
if (
h < m2 < m < h2
or h < h2 < m < m2
or m2 < h < h2 < m
or h2 < h < m2 < m
):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
def safe_power(x, exponent, *, epsilon=1e-6):
"""
Takes the power of each element in input with exponent and returns a tensor with the result.
This is a safer version of ``torch.pow`` (``out = x ** exponent``), which avoids:
1. NaN/imaginary output when ``x < 0`` and exponent has a fractional part
In this case, the function returns the signed (negative) magnitude of the complex number.
2. NaN/infinite gradient at ``x = 0`` when exponent has a fractional part
In this case, the positions of 0 are added by ``epsilon``,
so the gradient is back-propagated as if ``x = epsilon``.
However, this function doesn't deal with float overflow, such as 1e10000.
Parameters
----------
x : torch.Tensor or float
The input base value.
exponent : torch.Tensor or float
The exponent value.
(At least one of ``x`` and ``exponent`` must be a torch.Tensor)
epsilon : float
A small floating point value to avoid infinite gradient. Default: 1e-6
Returns
-------
out : torch.Tensor
The output tensor.
"""
# convert float to scalar torch.Tensor
if not torch.is_tensor(x):
if not torch.is_tensor(exponent):
# both non-tensor scalars
x = torch.tensor(x)
exponent = torch.tensor(exponent)
else:
x = torch.tensor(x, dtype=exponent.dtype, device=exponent.device)
else: # x is tensor
if not torch.is_tensor(exponent):
exponent = torch.tensor(exponent, dtype=x.dtype, device=x.device)
exp_fractional = torch.floor(exponent) != exponent
if not exp_fractional.any(): # no exponent has a fractional part
return torch.pow(x, exponent)
x, x_lt_0, x_eq_0, exponent, exp_fractional = torch.broadcast_tensors(
x, x < 0, x == 0, exponent, exp_fractional)
# deal with x = 0
if epsilon != 0:
mask = x_eq_0 & exp_fractional
if mask.any(): # has zero value
x = x.clone()
x[mask] += epsilon
# deal with x < 0
mask = x_lt_0 & exp_fractional
if mask.any():
x = x.masked_scatter(mask, -x[mask])
out = torch.pow(x, exponent)
out = out.masked_scatter(mask, -out[mask])
else:
out = torch.pow(x, exponent)
return out | bigcode/self-oss-instruct-sc2-concepts |
def fattr(key, value):
"""Decorator for function attributes
>>> @fattr('key', 42)
... def f():
... pass
>>> f.key
42
"""
def wrapper(fn):
setattr(fn, key, value)
return fn
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def unpickle_from_disk(filename):
"""Unpickle an object from disk.
Requires a complete filename
Passes Exception if file could not be loaded.
"""
# Warning: only using 'r' or 'w' can result in EOFError when unpickling!
try:
with open(filename, "rb") as pickle_file:
obj = pickle.load(pickle_file)
except UnicodeDecodeError as e:
with open(filename, "rb") as pickle_file:
obj = pickle.load(pickle_file, encoding='latin1')
except Exception as e:
print('Unable to load data ', filename, ':', e)
raise
return obj | bigcode/self-oss-instruct-sc2-concepts |
def merge_intervals(intervals):
""" Merge intervals in the form of a list. """
if intervals is None:
return None
intervals.sort(key=lambda i: i[0])
out = [intervals.pop(0)]
for i in intervals:
if out[-1][-1] >= i[0]:
out[-1][-1] = max(out[-1][-1], i[-1])
else:
out.append(i)
return out | bigcode/self-oss-instruct-sc2-concepts |
def _check_file(f, columns):
"""Return shell commands for testing file 'f'."""
# We write information to stdout. It will show up in logs, so that the user
# knows what happened if the test fails.
return """
echo Testing that {file} has at most {columns} columns...
grep -E '^.{{{columns}}}' {path} && err=1
echo
""".format(columns=columns, path=f.path, file=f.short_path) | bigcode/self-oss-instruct-sc2-concepts |
def find_if(cond, seq):
"""
Return the first x in seq such that cond(x) holds, if there is one.
Otherwise return None.
"""
for x in seq:
if cond(x): return x
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def _list_to_dict(items):
""" Convert a list of dicts to a dict with the keys & values aggregated
>>> _list_to_dict([
... OrderedDict([('x', 1), ('y', 10)]),
... OrderedDict([('x', 2), ('y', 20)]),
... OrderedDict([('x', 3), ('y', 30)]),
... ])
OrderedDict([('x', [1, 2, 3]), ('y', [10, 20, 30])])
"""
d = OrderedDict()
for item in items:
for k, v in item.items():
if k not in d:
d[k] = []
d[k].append(v)
return d | bigcode/self-oss-instruct-sc2-concepts |
def check(product, data):
"""Check if product does not exist in the data"""
if type(data) == dict:
data = data.values()
for d in data:
if product == d:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def _parse_cal_product(cal_product):
"""Split `cal_product` into `cal_stream` and `product_type` parts."""
fields = cal_product.rsplit('.', 1)
if len(fields) != 2:
raise ValueError(f'Calibration product {cal_product} is not in the format '
'<cal_stream>.<product_type>')
return fields[0], fields[1] | bigcode/self-oss-instruct-sc2-concepts |
def largest(a, b):
"""
This function takes two numbers
to determine which one is larger
"""
if a > b:
larger = a
else:
larger = b
return larger | bigcode/self-oss-instruct-sc2-concepts |
def extend_range(min_max, extend_ratio=.2):
"""Symmetrically extend the range given by the `min_max` pair.
The new range will be 1 + `extend_ratio` larger than the original range.
"""
mme = (min_max[1] - min_max[0]) * extend_ratio / 2
return (min_max[0] - mme, min_max[1] + mme) | bigcode/self-oss-instruct-sc2-concepts |
def build_risk_dataframe(financial_annual_overview):
"""Build risk dataframe
Notes:
Copies financial_annual_overview
Args:
financial_annual_overview (dataframe): An annual overview of financial data
Returns:
risk_dataframe (dataframe): An instance of a annual overview of financial data with a simulation of risk
"""
risk_dataframe = financial_annual_overview.copy()
return risk_dataframe | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import struct
def bytes_to_shortint(byteStream: bytes) -> Tuple[int]:
"""Converts 2 bytes to a short integer"""
# Ignore this in typing, as the 'H' will guarantee ints are returned
return struct.unpack('H', byteStream) | bigcode/self-oss-instruct-sc2-concepts |
def make_transparent(img, bg=(255, 255, 255, 255)):
"""Given a PIL image, makes the specified background color transparent."""
img = img.convert("RGBA")
clear = bg[0:3]+(0,)
pixdata = img.load()
width, height = img.size
for y in range(height):
for x in range(width):
if pixdata[x,y] == bg:
pixdata[x,y] = clear
return img | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def get_words(list_name: str):
"""
Reads the given word list from file into a list of capitalized words
"""
resource_package = __name__
resource_path = "/".join(("data", f"{list_name}.txt"))
word_list = pkg_resources.resource_string(resource_package, resource_path)
word_list = [word.decode("UTF-8") for word in word_list.split(b"\n")]
word_list = [w[:5].upper() for w in word_list]
return word_list | bigcode/self-oss-instruct-sc2-concepts |
def tree_prec_to_adj(prec, root=0):
"""Transforms a tree given as predecessor table into adjacency list form
:param prec: predecessor table representing a tree, prec[u] == v iff u is descendant of v,
except for the root where prec[root] == root
:param root: root vertex of the tree
:returns: undirected graph in listlist representation
:complexity: linear
"""
n = len(prec)
graph = [[prec[u]] for u in range(n)] # ajouter les prédécesseurs
graph[root] = []
for u in range(n): # ajouter les descendants
if u != root:
graph[prec[u]].append(u)
return graph | bigcode/self-oss-instruct-sc2-concepts |
def minutesToHours(minutes):
"""
(number) -> float
convert input minutes to hours;
return hours
>>> minutesToHours(60)
1.0
>>> minutesToHours(90)
1.5
>>>minutesToHours(0)
0.0
"""
hours = minutes / 60
hours = round(hours, 2)
return hours | bigcode/self-oss-instruct-sc2-concepts |
def url_to_be(url):
"""An expectation for checking the current url.
url is the expected url, which must be an exact match
returns True if the url matches, false otherwise."""
def _predicate(driver):
return url == driver.current_url
return _predicate | bigcode/self-oss-instruct-sc2-concepts |
def _get_ordered_keys(rows, column_index):
"""
Get ordered keys from rows, given the key column index.
"""
return [r[column_index] for r in rows] | bigcode/self-oss-instruct-sc2-concepts |
def _older_than(number, unit):
"""
Returns a query item matching messages older than a time period.
Args:
number (int): The number of units of time of the period.
unit (str): The unit of time: "day", "month", or "year".
Returns:
The query string.
"""
return f"older_than:{number}{unit[0]}" | bigcode/self-oss-instruct-sc2-concepts |
import fnmatch
from pathlib import Path
def generate_lists_of_filepaths_and_filenames(input_file_list: list):
"""For a list of added and modified files, generate the following:
- A list of unique filepaths to cluster folders containing added/modified files
- A set of all added/modified files matching the pattern "*/cluster.yaml"
- A set of all added/modified files matching the pattern "*/*.values.yaml"
- A set of all added/modified files matching the pattern "*/support.values.yaml"
Args:
input_file_list (list[str]): A list of files that have been added or modified
in a GitHub Pull Request
Returns:
list[str]: A list of unique filepaths to cluster folders
set[str]: A set of all files matching the pattern "*/cluster.yaml"
set[str]: A set of all files matching the pattern "*/*.values.yaml"
set[str]: A set of all files matching the pattern "*/support.values.yaml"
"""
patterns_to_match = ["*/cluster.yaml", "*/*.values.yaml", "*/support.values.yaml"]
cluster_filepaths = []
# Identify cluster paths amongst target paths depending on the files they contain
for pattern in patterns_to_match:
cluster_filepaths.extend(fnmatch.filter(input_file_list, pattern))
# Get absolute paths
cluster_filepaths = [Path(filepath).parent for filepath in cluster_filepaths]
# Get unique absolute paths
cluster_filepaths = list(set(cluster_filepaths))
# Filter for all added/modified cluster config files
cluster_files = set(fnmatch.filter(input_file_list, "*/cluster.yaml"))
# Filter for all added/modified helm chart values files
values_files = set(fnmatch.filter(input_file_list, "*/*.values.yaml"))
# Filter for all add/modified support chart values files
support_files = set(fnmatch.filter(input_file_list, "*/support.values.yaml"))
return cluster_filepaths, cluster_files, values_files, support_files | bigcode/self-oss-instruct-sc2-concepts |
def handle(string: str) -> str:
"""
>>> handle('https://github.com/user/repo')
'user/repo'
>>> handle('user/repo')
'user/repo'
>>> handle('')
''
"""
splt = string.split("/")
return "/".join(splt[-2:] if len(splt) >= 2 else splt) | bigcode/self-oss-instruct-sc2-concepts |
def proxy_result_as_dict(obj):
"""
Convert SQLAlchemy proxy result object to list of dictionary.
"""
return [{key: value for key, value in row.items()} for row in obj] | bigcode/self-oss-instruct-sc2-concepts |
def write_env(env_dict, env_file):
"""
Write config vars to file
:param env_dict: dict of config vars
:param env_file: output file
:return: was the write successful?
"""
content = ["{}={}".format(k, v) for k, v in env_dict.items()]
written = True
try:
with open(env_file, 'w') as file:
file.write('\n'.join(content))
except IOError:
written = False
return written | bigcode/self-oss-instruct-sc2-concepts |
def get_image(camera):
"""Captures a single image from the camera and returns it in PIL format."""
data = camera.read()
_, im = data
return im | bigcode/self-oss-instruct-sc2-concepts |
def _hashSymOpList(symops):
"""Return hash value for a sequence of `SymOp` objects.
The symops are sorted so the results is independent of symops order.
Parameters
----------
symops : sequence
The sequence of `SymOp` objects to be hashed
Returns
-------
int
The hash value.
"""
ssop = sorted(str(o) for o in symops)
rv = hash(tuple(ssop))
return rv | bigcode/self-oss-instruct-sc2-concepts |
def add_PDF_field_names(equiplist, type="NonEnc"):
"""Takes a list of items and their type and returns a dictionary with the items
as values and the type followed by a sequential number (type0, type1, etc.) as
keys. These are generally used to fill fields in a blank PDF, with keys
corresponding to field names.
"""
equipdict = {}
for index, item in enumerate(equiplist):
prefix = "".join((type, str(index)))
equipdict[prefix] = equiplist[index]
return equipdict | bigcode/self-oss-instruct-sc2-concepts |
def sclose(HDR):
"""input: HDR_TYPE HDR
output: [-1, 0]
Closes the according file.
Returns 0 if successfull, -1 otherwise."""
if HDR.FILE.OPEN != 0:
HDR.FILE.FID.close()
HDR.FILE.FID = 0
HDR.FILE.OPEN = 0
return 0
return -1
# End of SCLOSE
###########
# SREAD #
########### | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_yaml_file(file_path):
"""Parses yaml.
:param file_path: path to yaml file as a string
:returns: deserialized file
"""
with open(file_path, 'r') as stream:
data = yaml.safe_load(stream) or {}
return data | bigcode/self-oss-instruct-sc2-concepts |
def byte_to_string(byte):
"""
Converts an array of integer containing bytes into the equivalent string version
:param byte: The array to process
:return: The calculated string
"""
hex_string = "".join("%02x" % b for b in byte)
return hex_string | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_indent(str_):
"""
Find length of initial whitespace chars in `str_`
"""
# type: (str) -> int
match = re.search(r'[^\s]|$', str_)
if match:
return match.start()
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def get_acph2_m2_min(m1: float) -> float:
"""
Get minimum value of m2 (second moment) for ACPH(2) fitting.
According to [1], M2 has only lower bound since pow(CV, 2) should be
greater or equal to 0.5.
If m1 < 0, then `ValueError` is raised.
Parameters
----------
m1 : float
Returns
-------
m2_min : float
Minimum eligble value of the second moment.
"""
if m1 < 0:
raise ValueError(f"Expected m1 > 0, but m1 = {m1}")
return 1.5 * m1**2 | bigcode/self-oss-instruct-sc2-concepts |
def clamp(value, lower=None, upper=None):
""" Returns value no lower than lower and no greater than upper.
Use None to clamp in one direction only. """
if lower is not None:
value = max(value, lower)
if upper is not None:
value = min(value, upper)
return value | bigcode/self-oss-instruct-sc2-concepts |
def _finish_plot(ax, names, legend_loc=None, no_info_message="No Information"):
"""show a message in the axes if there is no data (names is empty)
optionally add a legend
return Fase if names is empty, True otherwise"""
if( not names ):
ax.text(0.5,0.5, no_info_message,
fontweight='bold', va='center', ha='center',
transform=ax.transAxes)
return False
if( legend_loc is not None ):
ax.legend(names, loc=legend_loc)
return True | bigcode/self-oss-instruct-sc2-concepts |
import json
import fnmatch
from pathlib import Path
def cmpmanifests(manifest_path_1, manifest_path_2, patterns=None, ignore=None):
"""Bit-accuracy test between two manifests.
Their format is {filepath: {md5, size_st}}"""
with manifest_path_1.open() as f:
manifest_1 = json.load(f)
with manifest_path_2.open() as f:
manifest_2 = json.load(f)
# print(manifest_1)
# print(manifest_2)
# print(set(manifest_1.keys()) & set(manifest_2.keys()))
if not patterns:
patterns = ['*']
if not ignore:
ignore = []
# print(patterns)
mismatch = set() # not the same
match = set() # the same
only_in_1 = set() # exists in dir_1 but not in dir_1
errors = set() # or errors accessing
for pattern in patterns:
pattern = f'*{pattern}'
for file_1_str, meta_1 in manifest_1.items():
if not fnmatch.fnmatch(file_1_str, pattern):
continue
file_1 = Path(file_1_str)
if any(fnmatch.fnmatch(file_1.name, i) for i in ignore):
continue
if file_1_str in manifest_2:
is_same = meta_1['md5'] == manifest_2[file_1_str]['md5']
if not is_same:
mismatch.add(file_1)
else:
match.add(file_1)
else:
only_in_1.add(file_1)
return {
"mismatch": list(mismatch),
"match": list(match),
"only_in_1": list(only_in_1),
"errors": list(errors),
} | bigcode/self-oss-instruct-sc2-concepts |
import random
def rand_uniform(a, b):
"""
Returns a sample from a uniform [a, b] distribution.
"""
return random.random() * (b - a) + a | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterator
from typing import ByteString
from typing import Any
from typing import Union
def hash_a_byte_str_iterator(
bytes_iterator: Iterator[ByteString], hasher: Any, as_hex_str: bool = False
) -> Union[ByteString, str]:
"""
Get the hash digest of a binary string iterator.
https://stackoverflow.com/a/3431835/105844
Parameters
----------
bytes_iterator : Iterator[ByteString]
The byte iterator
hasher : Any
The hash function from `hashlib`
as_hex_str : {'False','True'}, optional
Return the digest as bytes, or a hexidecimal string, by default False
Returns
-------
Union[ByteString, str]
The digest of the input bytes, as bytes or a hexidcimal string, by default bytes.
"""
for block in bytes_iterator:
hasher.update(block)
return hasher.hexdigest() if as_hex_str else hasher.digest() | bigcode/self-oss-instruct-sc2-concepts |
def recursive_config_join(config1: dict, config2: dict) -> dict:
"""Recursively join 2 config objects, where config1 values override config2 values"""
for key, value in config2.items():
if key not in config1:
config1[key] = value
elif isinstance(config1[key], dict) and isinstance(value, dict):
config1[key] = recursive_config_join(config1[key], value)
return config1 | bigcode/self-oss-instruct-sc2-concepts |
def iterativeFactorial(num):
"""assumes num is a positive int
returns an int, num! (the factorial of n)
"""
factorial = 1
while num > 0:
factorial = factorial*num
num -= 1
return factorial | bigcode/self-oss-instruct-sc2-concepts |
def remove_code_parameter_from_uri(url):
"""
This removes the "code" parameter added by the first ORCID call if it is there,
and trims off the trailing '/?' if it is there.
"""
return url.split("code")[0].strip("&").strip("/?") | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import List
from typing import Dict
import time
def get_dir_data(path: Path) -> List[Dict[str, str]]:
"""Returns list of files and folders in given directory sorted by type and by name.
Parameters
----------
path : Path
Path to directory which will be explored.
Returns
-------
List[Dict[str, str]]
List of dicts that contain file/folder attributes: name, type (file/folder/unknown),
last modification time.
"""
output_list = []
for item in path.iterdir():
if item.is_dir():
item_type = "folder"
elif item.is_file():
item_type = "file"
else:
item_type = "unknown"
output_list.append(
{
"name": item.name,
"type": item_type,
"time": time.ctime(item.stat().st_mtime),
}
)
output_list.sort(key=lambda x: (x["type"], x["name"]))
return output_list | bigcode/self-oss-instruct-sc2-concepts |
def decide_compiler(config):
"""确定使用的编译器
如果设置中使用的是clang,则使用设置中的编译器
否则使用默认的clang++
"""
if 'clang'in config:
return config
else:
return 'clang++' | bigcode/self-oss-instruct-sc2-concepts |
def map_to_45(x):
"""
(y-y1)/(x-x1) = (y2-y1)/(x2-x1) ---> x1 = 1, x2 = 5, y1 = 1, y2 = 4.5
output = output_start + ((output_end - output_start) / (input_end - input_start)) * (input - input_start)
"""
input_start = 1
input_end = 5
output_start = 1
output_end = 4.5
if x >= 5:
return 4.5
return output_start + ((output_end - output_start) / (input_end - input_start)) * (x - input_start) | bigcode/self-oss-instruct-sc2-concepts |
import struct
def read_unsigned_var_int(file_obj):
"""Read a value using the unsigned, variable int encoding."""
result = 0
shift = 0
while True:
byte = struct.unpack(b"<B", file_obj.read(1))[0]
result |= ((byte & 0x7F) << shift)
if (byte & 0x80) == 0:
break
shift += 7
return result | bigcode/self-oss-instruct-sc2-concepts |
def phrase(term: str) -> str:
"""
Format words to query results containing the desired phrase.
:param term: A phrase that appears in that exact form. (e.q. phrase "Chicago Bulls" vs. words "Chicago" "Bulls")
:return: String in the format google understands
"""
return '"{}"'.format(term) | bigcode/self-oss-instruct-sc2-concepts |
def clear_tier_dropdown(_):
"""
whenever a new cluster is in focus reset
the tier dropdown to empty again
Parameters
----------
_ : str
reactive trigger for the process
Returns
-------
str
empty string
"""
return '' | bigcode/self-oss-instruct-sc2-concepts |
import json
def format_report(jsn):
""" Given a JSON report, return a nicely formatted (i.e. with indentation) string.
This should handle invalid JSON (as the JSON comes from the browser/user).
We trust that Python's json library is secure, but if the JSON is invalid then we still
want to be able to display it, rather than tripping up on a ValueError.
"""
if isinstance(jsn, bytes):
jsn = jsn.decode('utf-8')
try:
return json.dumps(json.loads(jsn), indent=4, sort_keys=True, separators=(',', ': '))
except ValueError:
return "Invalid JSON. Raw dump is below.\n\n" + jsn | bigcode/self-oss-instruct-sc2-concepts |
import json
def readfile(filename):
""" Read JSON from file and return dict """
try:
with open(filename, 'r') as f:
return json.load(f)
except IOError:
print('Error while reading from file') | bigcode/self-oss-instruct-sc2-concepts |
def signed_leb128_encode(value: int) -> bytes:
"""Encode the given number as signed leb128
.. doctest::
>>> from ppci.utils.leb128 import signed_leb128_encode
>>> signed_leb128_encode(-1337)
b'\xc7u'
"""
data = []
while True:
byte = value & 0x7F
value >>= 7 # This is an arithmatic shift right
# Extract the current sign bit
sign_bit = bool(byte & 0x40)
# Check if we are done
if (value == 0 and not sign_bit) or (value == -1 and sign_bit):
# We are done!
data.append(byte)
break
else:
data.append(byte | 0x80)
return bytes(data) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generage_sha1(text: str) -> str:
"""Generate a sha1 hash string
Args:
text (str): Text to generate hash
Returns:
str: sha1 hash
"""
hash_object = hashlib.sha1(text.encode('utf-8'))
hash_str = hash_object.hexdigest()
return hash_str | bigcode/self-oss-instruct-sc2-concepts |
def flatten_list(nested_list, list_types=(list, tuple), return_type=list):
"""Flatten `nested_list`.
All the nested lists in `nested_list` will be flatten, and the elements
in all these lists will be gathered together into one new list.
Parameters
----------
nested_list : list | tuple
The (maybe) nested list to be flatten.
list_types : tuple[type]
Types to be regarded as lists. (default is `(list, tuple)`)
return_type : type
The returning list type. (default is `list`)
"""
ret = []
stack = [nested_list]
while stack:
top = stack.pop()
if isinstance(top, list_types):
stack.extend(reversed(top))
else:
ret.append(top)
return return_type(ret) | bigcode/self-oss-instruct-sc2-concepts |
def encrypt(msg, a, b, k):
""" encrypts message according to the formula l' = a * l + b mod k """
encrypted_message = ""
for letter in msg:
if letter == " ":
encrypted_message += " "
else:
encrypted_letter_index = (a * (ord(letter) - ord('a')) + b) % k
encrypted_message += chr(encrypted_letter_index + ord('a'))
return encrypted_message | bigcode/self-oss-instruct-sc2-concepts |
def decimal_to_base(n, base):
"""Convert decimal number to any base (2-16)"""
chars = "0123456789ABCDEF"
stack = []
is_negative = False
if n < 0:
n = abs(n)
is_negative = True
while n > 0:
remainder = n % base
stack.append(remainder)
n = n // base
result = ""
while stack:
result = result + chars[stack.pop()]
if is_negative:
return "-"+result
else:
return result | bigcode/self-oss-instruct-sc2-concepts |
def split_output(cmd_output):
"""Function splits the output based on the presence of newline characters"""
# Windows
if '\r\n' in cmd_output:
return cmd_output.strip('\r\n').split('\r\n')
# Mac
elif '\r' in cmd_output:
return cmd_output.strip('\r').split('\r')
# Unix
elif '\n' in cmd_output:
return cmd_output.strip('\n').split('\n')
# If no newline
return cmd_output | bigcode/self-oss-instruct-sc2-concepts |
def _parse_bool(value):
"""Parse a boolean string "True" or "False".
Example::
>>> _parse_bool("True")
True
>>> _parse_bool("False")
False
>>> _parse_bool("glorp")
Traceback (most recent call last):
ValueError: Expected 'True' or 'False' but got 'glorp'
"""
if value == 'True':
return True
if value == 'False':
return False
raise ValueError("Expected 'True' or 'False' but got {!r}".format(value)) | bigcode/self-oss-instruct-sc2-concepts |
import struct
def one_byte_array(value):
"""
Convert Int to a one byte bytearray
:param value: value 0-255
"""
return bytearray(struct.pack(">B", value)) | bigcode/self-oss-instruct-sc2-concepts |
def get_column_widths(columns):
"""Get the width of each column in a list of lists.
"""
widths = []
for column in columns:
widths.append(max([len(str(i)) for i in column]))
return widths | bigcode/self-oss-instruct-sc2-concepts |
def filter_arglist(args, defaults, bound_argnames):
"""
Filters a list of function argument nodes (``ast.arg``)
and corresponding defaults to exclude all arguments with the names
present in ``bound_arguments``.
Returns a pair of new arguments and defaults.
"""
new_args = []
new_defaults = []
required_args = len(args) - len(defaults)
for i, arg in enumerate(args):
if arg.arg not in bound_argnames:
new_args.append(arg)
if i >= required_args:
new_defaults.append(defaults[i - required_args])
return new_args, new_defaults | bigcode/self-oss-instruct-sc2-concepts |
import string
def clean_string(s):
"""Function that "cleans" a string by first stripping leading and trailing
whitespace and then substituting an underscore for all other whitepace
and punctuation. After that substitution is made, any consecutive occurrences
of the underscore character are reduced to one occurrence.
Finally, the string is converted to lower case.
Returns the cleaned string.
Input Parameters:
-----------------
s: The string to clean.
"""
to_sub = string.whitespace + string.punctuation
trans_table = str.maketrans(to_sub, len(to_sub) * '_')
fixed = str.translate(s.strip(), trans_table)
while True:
new_fixed = fixed.replace('_' * 2, '_')
if new_fixed == fixed:
break
fixed = new_fixed
return fixed.lower() | bigcode/self-oss-instruct-sc2-concepts |
def error_dict(error_message: str):
"""Return an error dictionary containing the error message"""
return {"status": "error", "error": error_message} | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
def listing(zip_path):
"""Get list of all the filepaths in a ZIP.
Args:
zip_path: path to the ZIP file
Returns: a list of strings, the ZIP member filepaths
Raises:
any file i/o exceptions
"""
with zipfile.ZipFile(zip_path, "r") as zipf:
return zipf.namelist() | bigcode/self-oss-instruct-sc2-concepts |
import math
def all_possible_combinations_counter(subset_size,
set_size):
"""
Return a number (int) of all possible combinations of elements in size
of a subset of a set.
Parameters
-------
subset_size: int
Size of the subset.
set_size: int
Size of the whole set.
Returns
-------
int
Number of all combinations.
"""
f = math.factorial
return f(set_size) / f(subset_size) / f(set_size - subset_size) | bigcode/self-oss-instruct-sc2-concepts |
def read_weights(nnf_path):
"""
Format: c weights PW_1 NW_1 ... PW_n NW_n
:param nnf_path: Path to NNF file
:return: list of weights
"""
weight_str = None
with open(nnf_path, "r") as ifile:
for line in ifile.readlines():
if "c weights " in line:
weight_str = line[10:].strip()
break
if weight_str is None:
return None
weight_strs = weight_str.split(" ")
weights = [float(w) for w in weight_strs]
return weights | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def validate_id_is_uuid(input_id, version=4):
"""Validates provided id is uuid4 format value.
Returns true when provided id is a valid version 4 uuid otherwise
returns False.
This validation is to be used only for ids which are generated by barbican
(e.g. not for keystone project_id)
"""
try:
value = uuid.UUID(input_id, version=version)
except Exception:
return False
return str(value) == input_id | bigcode/self-oss-instruct-sc2-concepts |
import copy
def with_base_config(base_config, extra_config):
"""Returns the given config dict merged with a base agent conf."""
config = copy.deepcopy(base_config)
config.update(extra_config)
return config | bigcode/self-oss-instruct-sc2-concepts |
def get_subtext(soup):
"""Gets the subtext links from the given hacker news soup."""
subtext = soup.select(".subtext")
return subtext | bigcode/self-oss-instruct-sc2-concepts |
def players_in_tournament(t_body):
"""Get number of players in a tournament
Args:
t_body (element.tag) : tourn table body. Child of ResponsiveTable
Returns:
number of players
"""
players = t_body.find_all("tr", class_="Table__TR Table__even")
if players is not None:
num_players = len(players)
return num_players | bigcode/self-oss-instruct-sc2-concepts |
def PyEval_GetBuiltins(space):
"""Return a dictionary of the builtins in the current execution
frame, or the interpreter of the thread state if no frame is
currently executing."""
caller = space.getexecutioncontext().gettopframe_nohidden()
if caller is not None:
w_globals = caller.get_w_globals()
w_builtins = space.getitem(w_globals, space.newtext('__builtins__'))
if not space.isinstance_w(w_builtins, space.w_dict):
w_builtins = w_builtins.getdict(space)
else:
w_builtins = space.builtin.getdict(space)
return w_builtins # borrowed ref in all cases | bigcode/self-oss-instruct-sc2-concepts |
def map_hostname_info(hostname, nmap_store):
"""Map hostname if there is one to the database record."""
if hostname is not None:
nmap_store["hostname"] = hostname.get('name')
return nmap_store
nmap_store["hostname"] = None
return nmap_store | bigcode/self-oss-instruct-sc2-concepts |
def sum_ascii_values(text: str) -> int:
"""Sum the ASCII values of the given text `text`."""
return sum(ord(character) for character in text) | bigcode/self-oss-instruct-sc2-concepts |
from typing import MutableMapping
from typing import Any
def get_dict_item_with_dot(data: MutableMapping, name: str) -> Any:
"""Get a dict item using dot notation
>>> get_dict_item_with_dot({'a': {'b': 42}}, 'a')
{'b': 42}
>>> get_dict_item_with_dot({'a': {'b': 42}}, 'a.b')
42
"""
if not name:
return data
item = data
for key in name.split('.'):
item = item[key]
return item | bigcode/self-oss-instruct-sc2-concepts |
def _has_exclude_patterns(name, exclude_patterns):
"""Checks if a string contains substrings that match patterns to exclude."""
for p in exclude_patterns:
if p in name:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def max_multiple(divisor, bound):
"""
Finds the largest dividable integer that is lower than bound.
:param divisor: positive integer.
:param bound: positive integer.
:return: the largest integer N, such that, N is divisible by divisor, N is less
than or equal to bound, and N is greater than 0.
"""
return bound - (bound % divisor) | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_count(json_filepath):
"""Reads the count from the JSON file and returns it"""
with open(json_filepath) as json_file:
data = json.load(json_file)
try:
return data["count"]
except KeyError:
return None | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
import six
def _convert_toc(wiki_html):
"""Convert Table of Contents from mediawiki to markdown"""
soup = BeautifulSoup(wiki_html, 'html.parser')
for toc_div in soup.findAll('div', id='toc'):
toc_div.replaceWith('[TOC]')
return six.text_type(soup) | bigcode/self-oss-instruct-sc2-concepts |
import re
import logging
def check_edge(graph, edge_label):
"""
Parameters
----------
graph : nx.DiGraph
A graph.
edge_label : str
Edge label.
Returns
-------
int
Counts how many edges have the property `label` that matches `edge_label`.
"""
edge_label = re.compile(edge_label)
filtered = [triple for triple in graph.edges.data('label') if edge_label.search(triple[2])]
for v, u, label in filtered:
logging.info(f"{graph.nodes[v]['label']}.{label} -> {graph.nodes[u]['label']}")
return len(filtered) | bigcode/self-oss-instruct-sc2-concepts |
def _str_to_bytes(s):
"""Convert str to bytes."""
if isinstance(s, str):
return s.encode('utf-8', 'surrogatepass')
return s | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def _pydantic_dataclass_from_dict(dict: dict, pydantic_dataclass_type) -> Any:
"""
Constructs a pydantic dataclass from a dict incl. other nested dataclasses.
This allows simple de-serialization of pydentic dataclasses from json.
:param dict: Dict containing all attributes and values for the dataclass.
:param pydantic_dataclass_type: The class of the dataclass that should be constructed (e.g. Document)
"""
base_model = pydantic_dataclass_type.__pydantic_model__.parse_obj(dict)
base_mode_fields = base_model.__fields__
values = {}
for base_model_field_name, base_model_field in base_mode_fields.items():
value = getattr(base_model, base_model_field_name)
values[base_model_field_name] = value
dataclass_object = pydantic_dataclass_type(**values)
return dataclass_object | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def load_module(mod):
"""Load a python module."""
module = importlib.import_module(mod)
print(module, mod)
return module | bigcode/self-oss-instruct-sc2-concepts |
def gcd(a, b):
"""Returns the greatest common divisor of a and b, using the Euclidean
algorithm."""
if a <= 0 or b <= 0:
raise ValueError('Arguments must be positive integers')
while b != 0:
tmp = b
b = a % b
a = tmp
return a | bigcode/self-oss-instruct-sc2-concepts |
def find_server(dbinstance, params):
"""
Find an existing service binding matching the given parameters.
"""
lookup_params = params.copy()
for srv in dbinstance.servers:
# Populating srv_params must be in sync with what lookup_target()
# returns
srv_params = {}
for attr in ("host", "cluster", "service_address",
"address_assignment", "alias"):
value = getattr(srv, attr, None)
if value:
srv_params[attr] = value
if lookup_params == srv_params:
return srv
return None | bigcode/self-oss-instruct-sc2-concepts |
def __is_global(lon, lat):
"""
check if coordinates belong to a global dataset
Parameters
----------
lon : np.ndarray or xarray.DataArray
lat : np.ndarray or xarray.DataArray
Returns
-------
bool
"""
if lon.max() - lon.min() > 350 and lat.max() - lat.min() > 170:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def correctPR(text):
"""
Remove the trailing space in the PR avlues.
:param text:
:return: corrected PR
"""
return text.replace(" ", "") | 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.