seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def preprocess(text_string):
"""
Accepts a text string and replaces:
1) urls with URLHERE
2) lots of whitespace with one instance
3) mentions with MENTIONHERE
This allows us to get standardized counts of urls and mentions
Without caring about specific people mentioned
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def to_query_str(params):
"""Converts a dict of params to afaln actual query string.
Args:
params: dict of simple key-value types, where key is a string and
value is a string or something that can be converted into a
string. If value is a list, it will be converted to a comma-
... | bigcode/self-oss-instruct-sc2-concepts |
def writexl_new_content_types_text(db):
"""
Returns [Content_Types].xml text
:param pylightxl.Database db: database contains sheetnames, and their data
:return str: [Content_Types].xml text
"""
# location: [Content_Types].xml
# inserts: many_tag_sheets, tag_sharedStrings
# note calcCh... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def import_object(string: str):
"""Import an object from a string.
The object can be a function, class or method.
For example: `'keras.layers.Dense.get_weights'` is valid.
"""
last_object_got = None
seen_names = []
for name in string.split("."):
seen_names.append(... | bigcode/self-oss-instruct-sc2-concepts |
def time_in_range(start, end, x):
"""
Return true if x is in the range [start, end]
"""
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end | bigcode/self-oss-instruct-sc2-concepts |
import posixpath
def extract_version(module_name):
"""
extract the version number from the module name provided.
:param module_name: <str> the module to find version in.
:return: <int> version number.
"""
# module_name_v0000.py --> module_name, _v0000.py --> _v0000
return posixpath.splitex... | bigcode/self-oss-instruct-sc2-concepts |
def indices(lst, element):
""" A function that searches for all occurrences of an element in a list """
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset + 1)
except ValueError:
return result
result.append(offset) | bigcode/self-oss-instruct-sc2-concepts |
def next_greatest_letter(letters: list[str], target: str) -> str:
"""Returns the the smallest element in the list that is larger than the given target
Args:
letters:
A list of sorted characters drawn from the lowercase latin
alphabet that also wraps around. For example, if the t... | bigcode/self-oss-instruct-sc2-concepts |
import math
def floatToJson(x):
"""Custom rule for converting non-finite numbers to JSON as quoted strings: ``"inf"``, ``"-inf"``, and ``"nan"``.
This avoids Python's bad habit of putting literal ``Infinity``, ``-Infinity``, and ``NaN``
in the JSON (without quotes)."""
if x in ("nan", "inf", "-inf"):... | bigcode/self-oss-instruct-sc2-concepts |
def points_to_vec(pt1, pt2, flip = False):
"""
Converts the coordinate of two points (pt1 > pt2) to a vector
flip: bool, default = False
If the coordinate system should be flipped such that higher y-coords
are lower (e.g. needed when working with images in opencv).
"""
vx = pt2[0]... | bigcode/self-oss-instruct-sc2-concepts |
def rbits_to_int(rbits):
"""Convert a list of bits (MSB first) to an int.
l[0] == MSB
l[-1] == LSB
0b10000
| |
| \\--- LSB
|
\\------ MSB
>>> rbits_to_int([1])
1
>>> rbits_to_int([0])
0
>>> bin(rbits_to_int([1, 0, 0]))
'0b100'
>>> bin(rbits_to... | bigcode/self-oss-instruct-sc2-concepts |
def esi_Delta(Delta, q):
"""
Calculate equivalent step index (esi) Delta for a graded-index fiber.
Args:
Delta : relative refractive index [-]
Returns:
equivalent relative refractive index [-]
"""
return q * (2 + q) / (1 + q)**2 * Delta | bigcode/self-oss-instruct-sc2-concepts |
def read_worksheet(worksheet_name, workbook):
"""Read worksheet table to list of dicts
"""
output = []
try:
data = workbook[worksheet_name].values
except KeyError:
print("Worksheet {} not found".format(worksheet_name))
return output
keys = next(data)
data = list(data... | bigcode/self-oss-instruct-sc2-concepts |
def generate_macs_args(flags):
"""
This is a helper function that takes the sim options and outputs the start the macs_args
:param flags:
:return macs_args:
"""
macs_args = None
if '-macs_file' in flags:
macs_args = [flags['-macs_file'][0][0], flags['-length'][0][0], "-I", flags['-I... | bigcode/self-oss-instruct-sc2-concepts |
def _expand(dict_in):
""" Convert {key1: list1, key2: list2} to
{list1[0]: key1, list1[1]: key1, list2[0]: key2 etc}
"""
dict_out = {}
for key in dict_in:
for item in dict_in[key]:
dict_out[item] = key
return dict_out | bigcode/self-oss-instruct-sc2-concepts |
def replacer(svgFile, toReplace, newData):
"""
Searches through SVG file until it finds a toReplace, once found, replaces it with newData
"""
for count in range(0,len(svgFile)):
found = svgFile[count].find(toReplace) #Check if the current line in the SVG file has the required string
if n... | bigcode/self-oss-instruct-sc2-concepts |
def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None):
"""Given a list, returns a string representation of that list with specified delimiter and optional string chars
_list -- the list or tuple to stringify
delimiter -- the the character to sepe... | bigcode/self-oss-instruct-sc2-concepts |
def get_yaml(path):
"""
Return the Yaml block of a post and the linenumbers of it.
"""
end = False
yaml = ""
num = 0
with open(path, 'r', encoding='utf-8') as f:
for line in f.readlines():
if line.strip() == '---':
if end:
break
... | bigcode/self-oss-instruct-sc2-concepts |
def bitcount(num):
"""
Count the number of bits in a numeric (integer or long) value. This
method is adapted from the Hamming Weight algorithm, described (among
other places) at http://en.wikipedia.org/wiki/Hamming_weight
Works for up to 64 bits.
:Parameters:
num : int
The ... | bigcode/self-oss-instruct-sc2-concepts |
def _pad_binary(bin_str, req_len=8):
"""
Given a binary string (returned by bin()), pad it to a full byte length.
"""
bin_str = bin_str[2:] # Strip the 0b prefix
return max(0, req_len - len(bin_str)) * '0' + bin_str | bigcode/self-oss-instruct-sc2-concepts |
def income3(households):
"""
Dummy for for income group 3
"""
return (households['income_category'] == 'income group 3').astype(int) | bigcode/self-oss-instruct-sc2-concepts |
def _deep_flatten(items): # pylint: disable=invalid-name
"""Returns a list of objects, flattening sublists/subtuples along the way.
Example: _deep_flatten([1, (2, 3, (4, 5), [6, 7]), [[[8]]]]) would return
the list [1, 2, 3, 4, 5, 6, 7, 8].
Args:
items: An iterable. If elements of this iterable are lists... | bigcode/self-oss-instruct-sc2-concepts |
def depth2inv(depth):
"""
Invert a depth map to produce an inverse depth map
Parameters
----------
depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Depth map
Returns
-------
inv_depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Inverse depth map
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_unit_string_from_comment(comment_string):
"""return unit string from FITS comment"""
bstart = comment_string.find("[")
bstopp = comment_string.find("]")
if bstart != -1 and bstopp != -1:
return comment_string[bstart + 1: bstopp]
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import torch
def _size_repr(key: str, item: Any) -> str:
"""String containing the size / shape of an object (e.g. a tensor, array)."""
if isinstance(item, torch.Tensor) and item.dim() == 0:
out = item.item()
elif isinstance(item, torch.Tensor):
out = str(list(item.si... | bigcode/self-oss-instruct-sc2-concepts |
def _strip(json_str):
"""Strip //-prefixed comments from a JSON string."""
lines = []
for line in json_str.split('\n'):
pos = line.find('//')
if pos > -1:
line = line[:pos]
lines.append(line)
return '\n'.join(lines) | bigcode/self-oss-instruct-sc2-concepts |
def load_yolo_predictions(txt_path, classes=None):
"""Return a list of records from YOLO prediction file.
Each record is a list `[label, box, score]`, where the box contains
coordinates in YOLOv5 format. `score` can be None if text file does
not contain scores, and `label` is either integer, or string ... | bigcode/self-oss-instruct-sc2-concepts |
def group_changes(changes):
"""Consolidate same-position insertions and deletions into single changes.
"""
insertions = [c for c in changes if c.change_type == 'insert']
deletions = [c for c in changes if c.change_type == 'delete']
mutations = [c for c in changes if c.change_type == 'mutate']
in... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hashstring(s: str) ->str:
"""
Generating an "unique" user id from the sha224 algorithm.
"""
return hashlib.sha224(s.encode('ascii')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import re
def deNumerize(text:str) -> str:
"""Removes numbers from strings"""
regex_pattern = re.compile(pattern = r'[0-9]', flags=re.UNICODE)
return regex_pattern.sub(r'', text) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def get_schema_type(arg_schema: Dict[str, Any]) -> str:
"""Returns the schema type for an argument.
Args:
arg_schema: dict(str, *). Schema for an argument.
Returns:
str. Returns schema type by extracting it from schema.
"""
return ar... | bigcode/self-oss-instruct-sc2-concepts |
def extractScopeLFN(scope_lfn):
""" Extract the scope and LFN from the scope_lfn string """
# scope_lfn = scope:lfn -> scope, lfn
_dummy = scope_lfn.split(':')
return _dummy[0], _dummy[1] | bigcode/self-oss-instruct-sc2-concepts |
def set_style(style,
text_color='white',
highlight_hover=True,
mini_zoom=False,
th_mini_font_size=6,
enforce_size=False,
td_width=15,
td_height=15):
"""Imposes some styling options on a DataFrame.style object."""
prope... | bigcode/self-oss-instruct-sc2-concepts |
def _hasfield(model_fields, field_name):
"""
Check if field name exists in list of model fields
:param list model_fields: List of Django Model object fields
:param string field_name: attribute string, dotted or dunderscored.
example: 'user.first_name' or 'user__first_name'
:returns: Field obje... | bigcode/self-oss-instruct-sc2-concepts |
def enum_solutions(node):
"""
>>> node = {'entry': {'lemma': u'EOS'}}
>>> enum_solutions(node)
[[u'EOS']]
>>> node = {
... 'entry': {'lemma': u'これ'},
... 'next': [
... {
... 'entry': {'lemma': u'は'},
... 'next': [
... {... | bigcode/self-oss-instruct-sc2-concepts |
def postprocess(var_list):
"""수집한 환자수 후처리
Args:
var_list: 후처리 할 문자열 list
Returns:
(list) var_list 순서대로 후처리된 결과
"""
result = []
for var in var_list:
var = var.replace(',', '').strip()
if '.' in var:
var = float(var)
elif var == '-':
... | bigcode/self-oss-instruct-sc2-concepts |
def edit_distance(left_word: str, right_word: str) -> int:
""" The difference between same-length words in number of edits
The result is the edit distance of the two words (number of
substitutions required to tranform left_word into right_word).
Args:
left_word: One word to compare
rig... | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_undirected(G):
"""Return a new undirected representation of the graph G."""
return G.to_undirected() | bigcode/self-oss-instruct-sc2-concepts |
def make_tuple(input):
"""
returns the input as a tuple. if a string is
passed, returns (input, ). if a tupple is
passed, returns the tupple unmodified
"""
if not isinstance(input, (tuple, list)):
input = (input,)
return input | bigcode/self-oss-instruct-sc2-concepts |
def rawformat(x, pos):
"""
Generic number formatter to help log plot look nice
"""
if (x < 1000): return '%1.0f' % x
if (x < 10000): return '%1.1fK' % (x/1000.0)
if (x < 1000000): return '%1.0fK' % (x/1000.0)
if (x < 1e9): return '%1.1fM' % (x/1.0e6)
if (x < 1e12): return '%1.1fB' % (x/... | bigcode/self-oss-instruct-sc2-concepts |
def get_nested_attr(obj, attr, default=None):
"""Get nested attributes of an object."""
attrs = attr.split(".")
for a in attrs:
try:
obj = getattr(obj, a)
except AttributeError:
if default:
return default
else:
raise
ret... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def validate_proof(previous_proof, proof):
"""
Validates the new proof.
:param int previous_proof: Proof of the previous block
:param int proof: Potential proof of the next block
:return bool: True if the new proof is valid, False if not
"""
attempt = f'{previous_proof}{pr... | bigcode/self-oss-instruct-sc2-concepts |
def split_barcode(barcode, return_gg=False):
"""Splits a barcode sequence into part A, part C, and part B sequences."""
split = barcode.split("-")
if len(split) == 2:
# Remove the gem group from the barcode
barcode, gem_group = split
else:
gem_group = None
assert len(barcode)... | bigcode/self-oss-instruct-sc2-concepts |
import math
def compute_idfs(documents):
"""
Given a dictionary of `documents` that maps names of documents to a list
of words, return a dictionary that maps words to their IDF values.
Any word that appears in at least one of the documents should be in the
resulting dictionary.
"""
# Slig... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def _readcsv(file):
"""Read a CSV file into a multidimensional array of rows and columns."""
rows = []
with open(file, newline='') as csvfile:
reader = csv .reader(csvfile, delimiter=',', quotechar='"')
headers = next(reader, None) # headers
for row in reader:
... | bigcode/self-oss-instruct-sc2-concepts |
def format_txt_desc(node):
"""
Formats a XML node into a plain text format.
"""
desc_buf = ''
for desc in node.childNodes:
if desc.nodeName == "#text":
desc_buf += desc.data + "\n"
elif desc.nodeName == "p":
desc_buf += desc.firstChild.data + "\n"
for chld in desc.childNodes:
if chld.nodeName ==... | bigcode/self-oss-instruct-sc2-concepts |
def sum_attributes(triplet):
"""
return the sum of the attributes of a triplet
ie: triplet = (((2, 2, 2, 2), (3, 3, 3, 3), (1, 2, 3, 1)))
returns [6, 7, 8, 6] <- [2+3+1, 2+3+2, 2+3+3, 2+3+1]
"""
return [sum(a) for a in zip(*triplet)] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Iterable
from typing import Any
def flatten_to_list(obj: Union[Iterable[Any], Any]) -> Union[list[Any], Any]:
"""
Flattens iterable to a non-nested list
Function ignores strings and treats as non-iterable
:param obj: iterable of nested iterables
:retur... | bigcode/self-oss-instruct-sc2-concepts |
def clean_team_name(team_names):
"""Take a list of team_names, modify the names to match the format specified in br_references, and return a new list
Args:
team_names: a list of team_names to be checked for validity, and if needed, modified
"""
new_team_names = []
for team in team_names:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Callable
def any_matches(iterable: Iterable, cond_fn: Callable = bool) -> bool:
"""
Returns `True` if `cond_fn` is `True`
for one or more elements in `iterable`.
Parameters
----------
iterable : Iterable
The iterable to be checked
con... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def get_valid_name_permutations(param_name: str) -> Set[str]:
"""Get all underscore permutations for provided arg name"""
return {
"_",
param_name,
f"_{param_name}",
f"{param_name}_",
} | bigcode/self-oss-instruct-sc2-concepts |
def add_arguments(parser, create_group=True):
"""A helper function to add standard command-line options to make an API
instance.
This adds the following command-line options:
--btn_cache_path: The path to the BTN cache.
Args:
parser: An argparse.ArgumentParser.
create_group: Wh... | bigcode/self-oss-instruct-sc2-concepts |
def import_object(module_name, attribute_name):
"""Import an object from its absolute path.
Example:
>>> import_object('datetime', 'datetime')
<type 'datetime.datetime'>
"""
module = __import__(module_name, {}, {}, [attribute_name], 0)
return getattr(module, attribute_name) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_prefix(curie):
"""Get prefix from CURIE."""
match = re.fullmatch(r'([a-zA-Z.]+):\w+', curie)
if match is None:
raise ValueError(f'{curie} is not a valid CURIE')
return match[1] | bigcode/self-oss-instruct-sc2-concepts |
def cross(v1, v2):
"""
Returns the cross product of the given two vectors
using the formulaic definition
"""
i = v1[1] * v2[2] - v2[1] * v1[2]
j = v1[0] * v2[2] - v2[0] * v1[2]
k = v1[0] * v2[1] - v2[0] * v1[1]
return [i, -j, k] | bigcode/self-oss-instruct-sc2-concepts |
def iterable(item):
"""If item is iterable, returns item. Otherwise, returns [item].
Useful for guaranteeing a result that can be iterated over.
"""
try:
iter(item)
return item
except TypeError:
return [item] | bigcode/self-oss-instruct-sc2-concepts |
def xy_to_uv76(x, y): # CIE1931 to CIE1976
""" convert CIE1931 xy to CIE1976 u'v' coordinates
:param x: x value (CIE1931)
:param y: y value (CIE1931)
:return: CIE1976 u', v' """
denominator = ((-2 * x) + (12 * y) + 3)
if denominator == 0.0:
u76, v76 = 0.0, 0.0
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def parent(n: int) -> int:
"""Return the index of the parent of the node with a positive index n."""
return (n - 1) // 2 | bigcode/self-oss-instruct-sc2-concepts |
import collections
import itertools
def find_repeat(data):
"""You notice that the device repeats the same frequency change list over and
over. To calibrate the device, you need to find the first frequency it
reaches twice.
>>> find_repeat([+1, -1])
0
>>> find_repeat([+3, +3, +4, -2, -4])
... | bigcode/self-oss-instruct-sc2-concepts |
def _next_power_of_two(value):
"""Return the first power of 2 greater than or equal to the input."""
power = 1
while power < value:
power *= 2
return power | bigcode/self-oss-instruct-sc2-concepts |
import math
def Tan(num):
"""Return the tangent of a value"""
return math.tan(float(num)) | bigcode/self-oss-instruct-sc2-concepts |
def _read_file(path):
"""Default read() function for use with hash_files()."""
with open(path,"rb") as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
def string_is_comment(a_string):
"""Is it a comment starting with a #."""
return a_string[0] == "#" | bigcode/self-oss-instruct-sc2-concepts |
def wrap(item):
"""Wrap a string with `` characters for SQL queries."""
return '`' + str(item) + '`' | bigcode/self-oss-instruct-sc2-concepts |
def recvn(sock, n):
"""
Read n bytes from a socket
Parameters
----------
sock - socket.socket
The socket to read from
n - int
The number of bytes to read
"""
ret = b''
read_length = 0
while read_length < n:
tmp = sock.recv(n - read_length)
... | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(n):
"""Returns True if integer n is a palindrome, otherwise False"""
if str(n) == str(n)[::-1]:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def prepare_description(report):
"""Constructs a description from a test report."""
raw = report['description']
# Wrap to at most 80 characters.
wrapped = textwrap.wrap(raw, 80)
description = wrapped[0]
if len(wrapped) > 1:
# If the text is longer than one line, add a... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def select_nms_index(scores: torch.Tensor,
boxes: torch.Tensor,
nms_index: torch.Tensor,
batch_size: int,
keep_top_k: int = -1):
"""Transform NMS output.
Args:
scores (Tensor): The detection scores of sha... | bigcode/self-oss-instruct-sc2-concepts |
def dict_from_cursor(cursor):
"""
Convert all rows from a cursor of results as a list of dicts
:param cursor: database results cursor
:return: list of dicts containing field_name:value
"""
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for r... | bigcode/self-oss-instruct-sc2-concepts |
def parse_rmc_status(output, lpar_id):
"""
Parses the output from the get_rmc_status() command to return the RMC
state for the given lpar_id.
:param output: Output from IVM command from get_rmc_status()
:param lpar_id: LPAR ID to find the RMC status of.
:returns status: RMC status for the given... | bigcode/self-oss-instruct-sc2-concepts |
def miles_to_kilometers(miles):
"""Convert miles to kilometers
PARAMETERS
----------
miles : float
A distance in miles
RETURNS
-------
distance : float
"""
# apply formula
return miles*1.609344 | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _get_timestamped_path(
parent_path: Path,
middle_path,
child_path='',
timestamp='',
create=True,
):
"""
Creates a path to a directory by the following pattern:
parent_path / middle_path / [child_path] / [timestamp]
:param parent_pat... | bigcode/self-oss-instruct-sc2-concepts |
def node2code(nodes, with_first_prefix=False):
"""
convert a node or a list of nodes to code str, e.g.
" import paddle" -> return "import paddle"
" import paddle" -> return "import paddle"
"""
if not isinstance(nodes, list):
nodes = [nodes]
code = ''
is_first_leaf =... | bigcode/self-oss-instruct-sc2-concepts |
def is_int(int_string: str):
"""
Checks if string is convertible to int.
"""
try:
int(int_string)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _get_course_marketing_url(config, course):
"""
Get the url for a course if any
Args:
config (OpenEdxConfiguration): configuration for the openedx backend
course (dict): the data for the course
Returns:
str: The url for the course if any
"""
for course_run in course.... | bigcode/self-oss-instruct-sc2-concepts |
def try_get_value(obj, name, default):
"""
Try to get a value that may not exist.
If `obj.name` doesn't have a value, `default` is returned.
"""
try:
return getattr(obj, name)
except LookupError:
return default | bigcode/self-oss-instruct-sc2-concepts |
def count_null_urls(conn):
""" Queries the sqlite3 table unpaywall and finds the number of Nones in pdf_url"""
cur = conn.cursor()
query = """
SELECT count(*)
FROM unpaywall
WHERE pdf_url IS NOT NULL """
cur.execute(query)
return cur.fetchone()[0] | bigcode/self-oss-instruct-sc2-concepts |
def check_win(secret_word, old_letters_guessed):
"""
this function checks whether the player was able to guess the secret word and thus won the game
:param secret_word: the word the player has to guess
:param old_letters_guessed: all the characters the player has already guessed
:type secret_word:... | bigcode/self-oss-instruct-sc2-concepts |
def Axes_Set_Breakaxis(bottom_ax,top_ax,h,v,direction='v'):
"""
Remove the spines for between the two break axes (either in vertical
or horizontal direction) and draw the "small break lines" between
them.
Parameters:
-----------
direction: the direction of the two break axes, could ... | bigcode/self-oss-instruct-sc2-concepts |
def islistoflists(arg):
"""Return True if item is a list of lists.
"""
claim = False
if isinstance(arg, list):
if isinstance(arg[0], list):
claim = True
return claim | bigcode/self-oss-instruct-sc2-concepts |
def date_to_str(ts):
"""
Convert timestamps into strings with format '%Y-%m-%d %H:%M:%S'.
Parameters
----------
ts : pd.timestamp
Timestamp.
Returns
-------
str
Strings with format '%Y-%m-%d %H:%M:%S'.
"""
return ts.strftime('%Y-%m-%d %H:%M:%S') | bigcode/self-oss-instruct-sc2-concepts |
def list_to_tuple(x):
""" Make tuples out of lists and sets to allow hashing """
if isinstance(x, list) or isinstance(x, set):
return tuple(x)
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
import gzip
import pickle
import logging
def load_obj(filename):
"""
Load saved object from file
:param filename: The file to load
:return: the loaded object
"""
try:
with gzip.GzipFile(filename, 'rb') as f:
return pickle.load(f)
except OSError:
logging.getLogge... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def b64urlencode(message):
"""
This function performs url safe base64 encoding.
:param message: Message to encode,
:return: Encoded string.
"""
return base64.urlsafe_b64encode(message) | bigcode/self-oss-instruct-sc2-concepts |
def lesser(tup,value):
"""
Returns the number of elements in tup strictly less than value
Examples:
lesser((5, 9, 1, 7), 6) returns 2
lesser((1, 2, 3), -1) returns 0
Parameter tup: the tuple to check
Precondition: tup is a non-empty tuple of ints
Parameter value: the value to... | bigcode/self-oss-instruct-sc2-concepts |
def problem_19_1(x, y):
""" Write a function to swap a number in place without temporary variables. """
# Bit-wise operations.
#x = x ^ y
#y = x ^ y
#x = x ^ y
#return (x, y)
# Arithmetic operations.
x = x - y
y = y + x
x = y - x
return (x, y) | bigcode/self-oss-instruct-sc2-concepts |
def generate_bs_pointers(bs_lengths, bs_size):
"""
It generates the pointers (i.e. time indexes) of each modified sax word into the original time-series data
:param bs_lengths: list of modified sax words
:type bs_lengths: list of str
:param bs_size: window size (in the original time-series) of a si... | bigcode/self-oss-instruct-sc2-concepts |
def upper_first(text: str) -> str:
"""
Capitalizes the first letter of the text.
>>> upper_first(text='some text')
'Some text'
>>> upper_first(text='Some text')
'Some text'
>>> upper_first(text='')
''
>>> upper_first(text='_some text')
'_some text'
:param text: to be cap... | bigcode/self-oss-instruct-sc2-concepts |
def parse(line):
"""Parses HH:MM:SS text -> (time,text)"""
parts = line.strip().split(" ")
return (parts[0], " ".join(parts[1:]) ) | bigcode/self-oss-instruct-sc2-concepts |
def last(mention):
""" Compute the last token of a mention.
Args:
mention (Mention): A mention.
Returns:
The tuple ('last', TOKEN), where TOKEN is the (lowercased) last token
of the mention.
"""
return "last", mention.attributes["tokens"][-1].lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Iterable
def elem(n: Any, it: Iterable[Any]) -> bool:
"""
Determine if iterable object contains the given element
Args:
n: Value to validate
it: Iterable object
Examples:
>>> fpsm.elem(2, range(10))
True
>>> fpsm.elem(... | bigcode/self-oss-instruct-sc2-concepts |
def to_camel(string):
"""Convert a snake_case string to CamelCase"""
return "".join(word.capitalize() for word in string.split("_")) | bigcode/self-oss-instruct-sc2-concepts |
def get_temperature_number(temp_str):
"""
Given a temperature string of the form "48.8 °C", return the first number
(in this example, 48). Also handles strings of the form "48,8 °C" that
apparently can exist (at least when reading the response from a file)
:param temp_str: Temperature string
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def squish(text):
"""Turn any run of whitespace into one space."""
return re.sub(r"\s+", " ", text) | bigcode/self-oss-instruct-sc2-concepts |
def compute_union_of_regions( regions ):
"""Compute a non-overlapping set of regions covering the same position as the input regions.
Input is a list of lists or tuples [ [a1,b1], ... ]
Output is a similar list. All regions are assumed to be closed i.e. to contain their endpoints"""
result = []
reg... | bigcode/self-oss-instruct-sc2-concepts |
def get_grid_coupling_list(width, height, directed=True):
"""Returns a coupling list for nearest neighbor (rectilinear grid) architecture.
Qubits are numbered in row-major order with 0 at the top left and
(width*height - 1) at the bottom right.
If directed is True, the coupling list includes both [a, b... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_month_number(month):
"""
Get the month in numeric format or 'all'
Parameters
----------
month : int or str
Returns
-------
n_month : int or 'all'
Month in numeric format, or string 'all'
"""
if isinstance(month, str):
if ... | bigcode/self-oss-instruct-sc2-concepts |
def name_matches(texnode, names):
"""
Returns True if `texnode`'s name is on one of the names in `names`.
"""
if hasattr(texnode, 'name') and texnode.name in names:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
async def absent(
hub,
ctx,
name,
zone_name,
resource_group,
record_type,
connection_auth=None,
**kwargs,
):
"""
.. versionadded:: 1.0.0
Ensure a record set does not exist in the DNS zone.
:param name:
Name of the record set.
:param zone_name:
Name ... | bigcode/self-oss-instruct-sc2-concepts |
import socket
import errno
def check_port_is_available(host, port):
"""Check if a given port it's available
Parameters
----------
host : str
port : int
Returns
-------
available : bool
"""
available = True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
... | 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.