seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def create_files_dict(file_name, metadata_content, bitstream_content):
"""Create dict of files to upload to S3."""
package_files = [
{
"file_name": f"{file_name}.json",
"file_content": metadata_content,
},
{
"file_name": f"{file_name}.pdf",
... | bigcode/self-oss-instruct-sc2-concepts |
def supra_adjacency_matrix(net,includeCouplings=True):
"""Returns the supra-adjacency matrix and a list of node-layer pairs.
Parameters
----------
includeCoupings : bool
If True, the inter-layer edges are included, if False, only intra-layer
edges are included.
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def expand_wildcards(paths: Union[str, Path]) -> list:
"""Expand the wildcards that may be present in Paths."""
path = Path(paths).expanduser()
parts = path.parts[1:] if path.is_absolute() else path.parts
return [f for f in Path(path.root).glob(str(Pat... | bigcode/self-oss-instruct-sc2-concepts |
def test_arg_index_attrs() -> None:
"""Accessing argument index and attributes."""
assert "{0.real}, {0.imag}".format(3 - 5j) == "3.0, -5.0"
class Point:
"""Point with x-y coordinates."""
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def validate(model, testloader, criterion):
"""Validate the model
Arguments:
model -- The network to validate
testloader -- Test data
criterion -- Loss function to use
"""
test_loss = 0
accuracy = 0
for images, targets in testloader:
images.resize_... | bigcode/self-oss-instruct-sc2-concepts |
def add_integers(*args: int) -> int:
"""Sum integers.
Arguments:
*args: One or more integers.
Returns:
Sum of integers.
Raises:
TypeError: No argument was passed or a passed argument is not of type
`int`.
Example:
>>> add_integers(3, 4)
7
"... | bigcode/self-oss-instruct-sc2-concepts |
def select_by_year(year, D):
"""Select year from specification given in dictionary or list of ranges.
Examples:
>>> spec = {(..., 1990): 'foo',
... 1991: 'bar',
... (1992, 2000): 'foobar',
... (2001, ...): 'blah'}
>>> select_by_year(1990, sp... | bigcode/self-oss-instruct-sc2-concepts |
import re
def md(MD_tag):
"""
Given MD tag and a sequence, find the number of matched, deletion, and substitution bps
Return: 1-level dictionary
"""
#matchLens = re.sub("\D"," ",MD_tag).split() #replace non-digit chars by blanks
#matchLens = map(int, matchLens) #length of the matches before... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sqlite_md5(text):
"""
md5 - Returns the md5 of the text
"""
if (text!=None):
hash = hashlib.md5()
hash.update(text.encode("utf-8"))
return hash.hexdigest()
return None | bigcode/self-oss-instruct-sc2-concepts |
import random
def MERB_config(BIM):
"""
Rules to identify a HAZUS MERB configuration based on BIM data
Parameters
----------
BIM: dictionary
Information about the building characteristics.
Returns
-------
config: str
A string that identifies a specific configration wi... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_accuracy(logits, ys_ref, pad):
"""Compute teacher-forcing accuracy.
Args:
logits (FloatTensor): `[B, T, vocab]`
ys_ref (LongTensor): `[B, T]`
pad (int): index for padding
Returns:
acc (float): teacher-forcing accuracy
"""
pad_pred = logits... | bigcode/self-oss-instruct-sc2-concepts |
def length(iterable):
"""
Return number of items in the iterable.
Attention: this function consumes the whole iterable and
can never return if iterable has infinite number of items.
:Example:
>>> length(iter([0, 1]))
2
>>> length([0, 1, 2])
3
"""
try:
return len(itera... | bigcode/self-oss-instruct-sc2-concepts |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the pgdb Connection
constructor.
"""
dsn['password'] = dsn['passwd']
del dsn['passwd']
dsn['database'] = dsn['db']
del dsn['db']
return [], dsn | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_request(url: str, headers: dict, path: str)->dict:
"""
Perform an HTTP GET request
:param url: the url to request
:param headers: a dict containing the ZT Auth header
:param path: the path at the url to request
:return: a dict representing the returned JSON object.
... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_iso_8601(dt):
"""Format a datetime as an iso 8601 string - YYYY-MM-DDTHH:MM:SS with optional timezone +HH:MM."""
if dt:
return dt.replace(microsecond=0).isoformat()
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import List
def get_key_mapping(inverse_mapping: Dict[Any, List[str]]) -> Dict[str, Any]:
"""Returns the key mapping from the inverse mapping.
Args:
inverse_mapping: A mapping from the mapped input to the list of keys.
Returns:
a mapping from ... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def combos(indices):
""" Return all combinations of indices in a list of index sublists.
Arguments:
indices: list of int lists
List of index lists.
"""
return list(itertools.product(*indices)) | bigcode/self-oss-instruct-sc2-concepts |
def setDefaults(configObj={}):
""" Return a dictionary of the default parameters
which also been updated with the user overrides.
"""
gain = 7 # Detector gain, e-/ADU
grow = 1 # Radius around CR pixel to mask [default=1 for 3x3 for non-NICMOS]
ctegrow = 0... | bigcode/self-oss-instruct-sc2-concepts |
def init_comm(base_comm, grid_shape):
"""Create an MPI communicator with a cartesian topology."""
return base_comm.Create_cart(grid_shape, len(grid_shape) * (False,),
reorder=False) | bigcode/self-oss-instruct-sc2-concepts |
def is_test(obj) -> bool:
"""Is the object a test, i.e. test_func()?"""
assert hasattr(obj, "__name__")
obj_name = obj.__name__.lower()
patterns = ("test", "_test", "__test")
return any(obj_name.startswith(pattern) for pattern in patterns) | bigcode/self-oss-instruct-sc2-concepts |
def harm(x,y):
"""Harmonic mean of x and y"""
return x*y/(x+y) | bigcode/self-oss-instruct-sc2-concepts |
def remove_dups(lst):
"""
Inputs:
lst - A list object
Outputs:
Returns a new list with the same elements in lst,
in the same order, but without duplicates. Only
the first element of each replicated element will
appear in the output.
"""
result = []
dups = set()
... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_service_argument(argument):
"""
normalize service name and set type: $object, $variable$
Examples:
>>> normalize_service_argument('$Mongodb')
['Mongodb', 'object']
>>> normalize_service_argument('%batch_size%')
['batch_size', 'variable']
"""
if isinstanc... | bigcode/self-oss-instruct-sc2-concepts |
import re
def camel_to_snake(camel):
"""
make a camelcase from a snakecase
with a few things thrown in - we had a case where
we were parsing a spreadsheet and using the headings as keys in an object
one of the headings was "Who Uploads?"
"""
camel = camel.strip()
camel = re.sub(' ', ''... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def format_board(board: List[str]) -> str:
"""Return the board formatted for output"""
out_board = ''
for i in range(0, len(board)):
if i == 0 or i % 3 == 0:
out_board += '\n' + '-------------' + '\n|'
tic = board[i] if board[i] in 'XO' else i + 1
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _include_exclude(
dictionary: dict,
include_pattern: str,
exclude_pattern: str,
) -> bool:
"""
Filters the items of a dictionary based on a include / exclude regexp pair.
Returns `True` if the size of the dictionary changed.
"""
incl, excl = re.compile(include_pattern), r... | bigcode/self-oss-instruct-sc2-concepts |
def fruity_file(models_path):
"""Return fruity sample data file as a Path object."""
return models_path.joinpath("fruity.txt") | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _modified_date(f: Path) -> str:
"""Get the modified date of the file"""
return str(f.stat().st_mtime) | bigcode/self-oss-instruct-sc2-concepts |
def separate_gradients(gradients, weight_vars, input_vars):
"""
split the gradient dictionary up into one for input and one for weights.
Parameters
----------
gradients: dict:
dictionary of gradients. Should be str, list[Objective] key/value pairs.
input_vars: list:
the input va... | bigcode/self-oss-instruct-sc2-concepts |
import re
def subject_id_of(path) -> str:
"""
Returns the subject ID closest to the end of the input string or Path.
Inputs
------
path : str or Path
String or Path containing the subject ID.
Returns
-------
str
Subject ID found in the filename
Raises
------
... | bigcode/self-oss-instruct-sc2-concepts |
import logging
import inspect
def get_file_logger(
log_file=None,
log_filemode='a',
log_level=logging.INFO,
log_msg_fmt='%(asctime)s %(levelname)s %(message)s',
log_date_fmt='%a, %d %b %Y %H:%M:%S',
log_prefix=None
):
"""
Purpose:
Get Logger to file
Args:
log_level ... | bigcode/self-oss-instruct-sc2-concepts |
def class_name(obj):
""" Returns the class name of an object"""
return obj.__class__.__name__ | bigcode/self-oss-instruct-sc2-concepts |
def Split(string,n):
"""Split a string into lines of length n with \n in between them"""
N =len(string)//n
return '\n'.join([string[i*n:(i+1)*n] for i in range(N)]+[string[N*n:]]) | bigcode/self-oss-instruct-sc2-concepts |
def molm2_to_molec_cm2(spc_array):
"""
Convert moles/m2 to molec/cm2
"""
avo_num = 6.0221409e23
molec_per_m2 = spc_array * avo_num
molec_per_cm2 = molec_per_m2 * 1e4
return molec_per_cm2 | bigcode/self-oss-instruct-sc2-concepts |
def dms2dd(dms):
"""
DMS to decimal degrees.
Args:
dms (list). d must be negative for S and W.
Return:
float.
"""
d, m, s = dms
return d + m/60. + s/3600. | bigcode/self-oss-instruct-sc2-concepts |
def br(value):
""" Replaces newlines with HTML-style <br>'s """
return value.replace("\n", "<br>") | bigcode/self-oss-instruct-sc2-concepts |
import math
def binary_entropy(p):
"""
Uses the binary entropy function denoted H(p) in information theory/statistics
Computes the entropy of a Bernoulli process with probability of success p
When p = .5, entropy is at its max value (unbiased bit, most common unit of information entropy)
@param ... | bigcode/self-oss-instruct-sc2-concepts |
def quantify(iterable, pred=bool):
"""Count how many times the predicate is true.
:param iterable: source of values
:param pred: the predicate whose result is to be quantified when applied to
all values in iterable. Defaults to bool()
"""
# quantify([2, 56, 3, 10, 85], lambda x: x... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_all_tokens_exist(input_tokens, output_tokens, include_joiner_token,
joiner):
"""Adds all tokens in input_tokens to output_tokens if not already present.
Args:
input_tokens: set of strings (tokens) we want to include
output_tokens: string to int dictionary mappi... | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
def async_return(result):
"""Mock a return from an async function."""
future = asyncio.Future()
future.set_result(result)
return future | bigcode/self-oss-instruct-sc2-concepts |
def get_ttylog_lines_from_file(ttylog):
"""Read from ttylog. If lines have '\r' at end, remove that '\r'. Return the read lines"""
ttylog_file = open(ttylog,'r',errors='ignore', newline='\n',encoding='utf-8')
ttylog_read_data = ttylog_file.read()
#Replace escaped double qoutes with qoutes
ttylog_rea... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def read_input_file(input_file_path):
""" read the input file and convert the contents
to a list of ints """
p = Path(input_file_path)
with p.open() as f:
data = list(map(int, f.readlines()))
return data | bigcode/self-oss-instruct-sc2-concepts |
def variable_to_jsonpath(p):
"""Converts a expression variable into a valid JSON path starting with $."""
# replace JSON_ with $ and _ with .
return p.var.replace('JSON_', '$').replace('_', '.') | bigcode/self-oss-instruct-sc2-concepts |
def remove_bottom(pnts, gt_box, bottom):
"""
Args:
* `pnts`: Lidar Points
* `gt_box`: The 3D bounding box of the object
* `bottom`: A height threshold, deciding which points to keep\n
Return:
`pnts` whose heights are larger than -dz/2 + bottom, where dz is from the `gt_box`.
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _convert_to_datetime(unix_timestamp):
"""
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
"""
try:
unix_timestamp = float(uni... | bigcode/self-oss-instruct-sc2-concepts |
def _extract_username(request):
"""
Look for the "username" in a request. If there is no valid username we
will simply be throttling on IP alone.
"""
return request.POST.get("username", "notfound").lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import time
def tmp_path(base: str, _time_stamp: List[int] = []) -> str:
"""Get a temporary path containing a time stamp."""
if not _time_stamp:
_time_stamp.append(int(time.time()))
return f"{base}{_time_stamp[0]}" | bigcode/self-oss-instruct-sc2-concepts |
def is_error_response(res):
"""
check the status code of http response
:param res: http response
:return: True if the status code less than 200 or larger than 299;
False if the status code is between 200 and 299
"""
if res is None:
return True
if res.status_code < 200 or... | bigcode/self-oss-instruct-sc2-concepts |
def get_content(*filename:str) -> str:
""" Gets the content of a file or files and returns
it/them as a string
Parameters
----------
filename : (str)
Name of file or set of files to pull content from
(comma delimited)
Returns
-------
str:
Content from the fi... | bigcode/self-oss-instruct-sc2-concepts |
def get_index(fields, keys):
""" Get indices of *keys*, each of which is in list *fields* """
assert isinstance(keys, list)
assert isinstance(fields, list)
return [fields.index(k) for k in keys] | bigcode/self-oss-instruct-sc2-concepts |
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
num1:
The first number to find the lcm for
num2:
The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bi... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def find_type_object(type_name):
"""Try to find the type object given the name of the type.
Deals with cases such as `argparse.ArgumentParser` where a module needs to
be imported before we can find the correct type object. If the type object
cannot be found, a `NameError` is raised.
... | bigcode/self-oss-instruct-sc2-concepts |
def add(x, y):
"""Add two coordinate pairs."""
return (x[0] + y[0], x[1] + y[1]) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def get_permutations(a):
"""
get all permutations of list a
"""
p = []
for r in range(len(a)+1):
c = list(itertools.combinations(a,r))
for cc in c:
p += list(itertools.permutations(cc))
return p | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def fm_string(dt_string, millisecond=False):
"""
Input a date string and returns a datetime object.
"""
if millisecond:
return datetime.strptime(
dt_string, '%Y/%m/%d %H:%M:%S.%f')
else:
return datetime.strptime(
dt_string, '%Y/... | bigcode/self-oss-instruct-sc2-concepts |
def _is_weekend(date):
"""Returns whether the date is a weekend."""
return date.isoweekday() in (6, 7) # Saturday, Sunday | bigcode/self-oss-instruct-sc2-concepts |
import math
def _selection_size_heuristic(num_samples):
"""Return size of mini-batch, given size of dataset."""
# Incrase size of mini-batch gradually as number of samples increases,
# with a soft cap (using log).
# But do not return size larger than number of samples
return min(num_samples,
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_md5(unicode):
"""
Generate an MD5 hash
Args:
unicode (bytes): Unicode bytes representing the string you want to be hashed
Returns:
str: An MD5 hash (hex characters)
"""
hasher = hashlib.md5()
hasher.update(unicode)
return hasher.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import math
def factors_of(x):
"""Returns a set of tuples of factors of x.
Examples
--------
>>> factors_of(12)
{(1, 12), (2, 6), (3, 4)}
>>> factors_of(20)
{(1, 20), (2, 10), (4,5)}
"""
factors = set()
sqrt_x = math.sqrt(x)
if sqrt_x == int(sqrt_x):
factors.add... | bigcode/self-oss-instruct-sc2-concepts |
import math
def uv(sped, drct2):
"""Convert to u,v components."""
dirr = drct2 * math.pi / 180.00
s = math.sin(dirr)
c = math.cos(dirr)
u = round(-sped * s, 2)
v = round(-sped * c, 2)
return u, v | bigcode/self-oss-instruct-sc2-concepts |
def getfmt(n,dtype ="d"):
"""
Generates the binary format n dtype
defualts to double
@param n: number of particles
@param dtype: data type
returns the format string used to decode the binary data
"""
fmt = ""
fmt += dtype
for i in range(n):
... | bigcode/self-oss-instruct-sc2-concepts |
def clean_timestamp(timestamp, format=False):
"""
used to remove unwanted characters from the overly long timestamp in the json data of a tweet
eg: timestamp comes in as 'Thu Dec 17 13:44:24 +0000 2020' and for now we only want 'Thu Dec 17 13:44'
"""
cleaned_timestamp_list = str(timestamp).split(' ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def transform_tensor_by_dict(tensor, map_dict, device="cpu"):
"""
Given a tensor of any shape, map each of its value
to map_dict[value].
:param tensor: input tensor
:param map_dict: value mapping dict. Both key and value are numbers
:return: mapped tensor, type is FloatTensor
... | bigcode/self-oss-instruct-sc2-concepts |
def connection_callback(isolation_level=None,
read_only=None,
deferrable=None,
application_name=None,
inherit=None):
"""
Decorator for functions used in :meth:`IConnectionManager.open_and_call`.
When the functio... | bigcode/self-oss-instruct-sc2-concepts |
def _generate_variable_name(variable_counter):
"""
Generates a unique variable name.
"""
return "v{}".format(variable_counter.next()) | bigcode/self-oss-instruct-sc2-concepts |
def null_padded(string, length):
"""
Force a string to a given length by right-padding it with zero-bytes,
clipping the initial string if neccessary.
"""
return bytes(string[:length] + ('\0' * (length - len(string))), 'latin1') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def get_border_width(width: int) -> Dict[str, int]:
"""Replicates border_width parameter from Gtk3, by producing a dict equivalent margin parameters
Args:
width (int): the border width
Returns:
Dict[str, int]: the dict with margin parameters
"""
return dic... | bigcode/self-oss-instruct-sc2-concepts |
def filter_dataframe(df, column, value):
"""Filter DataFrame for a column and a value or a list of value
Parameters
----------
df: DataFrame
DataFrame to filter
column: str
column name
value: list or 1dim value
values
Returns
-------
DataFrame: filtered Data... | bigcode/self-oss-instruct-sc2-concepts |
def phi(T):
"""
:param T: [°C] Temperatura
:return: Factor que cuantifica la rapidez de cambios en los canales iónicos debido a la temperatura (T).
"""
Q_10 = 3 # Radio de las tasas por un incremento de temperatura de 10 °C
T_base = 6.3 # Temperatura base [°C]
return Q_10 ** ((T -... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_rgb(int_):
"""Integer to RGB conversion"""
red = (int_ >> 24) & 255
green = (int_ >> 16) & 255
blue = (int_ >> 8) & 255
return red, green, blue | bigcode/self-oss-instruct-sc2-concepts |
def model_uname(value):
"""Returns a model name such as 'baking_oils'"""
words = value._meta.verbose_name.lower().replace("&", "").split()
return "_".join(words) | bigcode/self-oss-instruct-sc2-concepts |
import re
def chunk_paf(paf_record):
""" Takes a PafRecord object or a full cs string and returns a list of fields from its cs string """
if type(paf_record) == str:
cs = paf_record
else:
cs = paf_record.tags["cs"]
separable_cs = re.sub(r'(?<!\A)([-:*+])', r',\1', cs)
return separa... | bigcode/self-oss-instruct-sc2-concepts |
def heatmap_figsize(nrow, ncol=None):
"""Generate size tuple for heatmap based on number of rows and columns"""
if ncol is None:
ncol = nrow
return ncol * 0.3 + 3, nrow * 0.3 | bigcode/self-oss-instruct-sc2-concepts |
def getBit(val, idx: int) -> int:
"""Gets a bit."""
return 1&(val>>idx) | bigcode/self-oss-instruct-sc2-concepts |
def flatten_list(nested_list):
"""
Given a list of lists, it flattens it to a single list.
:param nested_list: list of lists
:return: Single list containing flattened list.
"""
return [item for sub_list in nested_list for item in sub_list] | bigcode/self-oss-instruct-sc2-concepts |
def rn_sub(a, b):
"""
a - b
uses rn_sum and rn_neg to get the difference like a + (-b)
:param a: RN object
:param b: RN object
:return: difference array
"""
return a + (-b) | bigcode/self-oss-instruct-sc2-concepts |
def split_sig(params):
"""
Split a list of parameters/types by commas,
whilst respecting brackets.
For example:
String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3]
=> ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]']
"""
result = []
current = ''
level = 0
f... | bigcode/self-oss-instruct-sc2-concepts |
def sum_factorial_digits(x):
"""
Returns the sum of the factorials of the digits of x
"""
factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
sum_factorial_digits_ = 0
for i in str(x):
sum_factorial_digits_ += factorials[int(i)]
return(sum_factorial_digits_) | bigcode/self-oss-instruct-sc2-concepts |
import random
import time
def retry(initial_delay,
max_delay,
factor=2.0,
jitter=0.25,
is_retriable=None):
"""Simple decorator for wrapping retriable functions.
Args:
initial_delay: the initial delay.
factor: each subsequent retry, the delay is multiplied by this v... | bigcode/self-oss-instruct-sc2-concepts |
def fixup_acl(acl: str) -> str:
"""
Replace standard ip/mask entries with "none" and "any" if present
"""
if acl is None:
acl = "none"
if acl == '':
acl = "none"
if acl == "255.255.255.255/32":
acl = "none"
if acl == "0.0.0.0/0":
acl = "any"
return acl | bigcode/self-oss-instruct-sc2-concepts |
import aiohttp
import base64
async def render(eqn: str, **kwargs) -> bytes:
"""
Render LaTeX using Matthew Mirvish's "TeX renderer slave microservice thing".
Returns raw image data or raises ValueError if an error occurred.
"""
kwargs["source"] = eqn
async with aiohttp.request("POST", "http:/... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize(s):
""" Remove escape codes and non ASCII characters from output
"""
ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
s = ansi_escape.sub('', s)
mpa = dict.fromkeys(range(32))
return s.translate(mpa).strip().replace(' ', '') | bigcode/self-oss-instruct-sc2-concepts |
def get_max_region(regions, field='area'):
"""Return the region from the list that maximizes the field."""
max_region = regions[0]
for i in range(1, len(regions)):
if regions[i][field] > max_region[field]:
max_region = regions[i]
return max_region | bigcode/self-oss-instruct-sc2-concepts |
def get_bucket_config(config, bucket_name):
"""
Pulls correct bucket config from application config based on name/alias.
Args:
config(dict)
bucket_name(string): bucket name or bucket reference name
Returns:
dict | None: config for bucket or None if not f... | bigcode/self-oss-instruct-sc2-concepts |
def _has_dns_message_content_type(flow):
"""
Check if HTTP request has a DNS-looking 'Content-Type' header
:param flow: mitmproxy flow
:return: True if 'Content-Type' header is DNS-looking, False otherwise
"""
doh_content_types = ['application/dns-message']
if 'Content-Type' in flow.request... | bigcode/self-oss-instruct-sc2-concepts |
def cast_to_str(labels, nested=False):
""" Convert every label to str format.
If nested is set to True, a flattened version of the input
list is also returned.
Args:
labels: list
Input labels
nested: bool
Indicate if the input list ... | bigcode/self-oss-instruct-sc2-concepts |
def binary_string_to_int(s):
"""
Convert a string of a binary representation to a number
:param s: a binary representation as a string
:return: an integer
"""
return int(s,2) | bigcode/self-oss-instruct-sc2-concepts |
def optimal_merge_pattern(files: list) -> float:
"""Function to merge all the files with optimum cost
Args:
files [list]: A list of sizes of different files to be merged
Returns:
optimal_merge_cost [int]: Optimal cost to merge all those files
Examples:
>>> optimal_merge_pattern([2... | bigcode/self-oss-instruct-sc2-concepts |
def total_mass(particles):
"""
Returns the total mass of the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(3)
>>> particles.mass = [1.0, 2.0, 3.0] | units.kg
>>> particles.total_mass()
quantity<6.0 kg>
"""
return particles.mass.sum() | bigcode/self-oss-instruct-sc2-concepts |
def _str_to_int(_str):
"""Convert the input str to an int if possible
:param _str: input string
:return: integer if text is a digit, else string
"""
return int(_str) if _str.isdigit() else _str | bigcode/self-oss-instruct-sc2-concepts |
def proto_to_bytes(proto):
""" Converts a proto object to a bytes array """
return proto.SerializeToString() | bigcode/self-oss-instruct-sc2-concepts |
def gen_key_i(i, kappa, K):
"""
Create key value where key equals kappa, except:
key_(i mod n) = kappa_(i mod n) XOR K_(i mod n)
Parameters:
i -- integer in [0,n-1]
kappa -- string
K -- string
Return:
key -- list of bool
"""
# Transform string into list of booleans
kappa = list(kappa)
kappa = [boo... | bigcode/self-oss-instruct-sc2-concepts |
def get_intent_queries(infold, intent_names, mode):
""" Get list of queries with their corresponding intent number. """
intent_queries = ['sentence\tlabel\n']
for index, intent in enumerate(intent_names):
queries = open(f'{infold}/{mode}set/{intent}.csv', 'r').readlines()
for query in queri... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def irot(x: int, y: int, deg: int, origin: Tuple[int, int] = (0, 0)) -> Tuple[int, int]:
"""
Rotate an integer point by `deg` around the `origin`. Only works when deg % 90 == 0.
"""
transformed_x = x - origin[0]
transformed_y = y - origin[1]
assert deg % 90 == 0
fo... | bigcode/self-oss-instruct-sc2-concepts |
def lsearch(l,pattern):
""" Search for items in list l that have substring match to pattern. """
rvals = []
for v in l:
if not v.find(pattern) == -1:
rvals.append(v)
return rvals | bigcode/self-oss-instruct-sc2-concepts |
def parse_to_short_cmd(command):
"""Takes any MAPDL command and returns the first 4 characters of
the command
Examples
--------
>>> parse_to_short_cmd('K,,1,0,0,')
'K'
>>> parse_to_short_cmd('VPLOT, ALL')
'VPLO'
"""
try:
short_cmd = command.split(',')[0]
return ... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def md5sum(path):
"""Return the MD5 hash of the file contents.
"""
BUF_SIZE = 1024 * 64
buf = bytearray(BUF_SIZE)
mv = memoryview(buf)
md5 = hashlib.md5()
with open(path, 'rb') as fh:
while True:
num_bytes = fh.readinto(buf)
md5.update(mv[:num... | bigcode/self-oss-instruct-sc2-concepts |
def allowed_file(filename, extensions):
"""
chceck if file extension is in allowed extensions
:param filename: name of file
:param extensions: allowed files extensions
:return: True if extension is correct else False
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in extens... | bigcode/self-oss-instruct-sc2-concepts |
def parse_bool(val):
"""
Parse bool value from cli.
Must be represented by integer number 0 or 1.
Return: (bool) True/False
"""
try:
val = int(val)
assert val == 0 or val == 1, 'Wrong value: {}'.format(val)
except:
raise ValueError('Cannot parse flag {}. It must an ... | bigcode/self-oss-instruct-sc2-concepts |
def is_list_or_tuple(x):
"""Return True if list or tuple."""
return isinstance(x, tuple) or isinstance(x, list) | 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.