seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def create_document1(args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<table>
<tbody style="border-collapse: collapse;border: 10px solid #d9d7ce; display: inline-block;padding: 6px 12px;line-height:50px;text-align: left;vertical-align: bottom;">
<tr>
<td colspan="2"><h1 style='text-align: left; color: black;'><u>DocuMap</u></h1></td>
</tr>
<tr>
<td colspan="2"><h2 style='text-align: left; color: black;'>{args["env_subject"]}</h2></td>
</tr>
<tr>
<td colspan="2" style="text-align: justify;"><pre><h3>{args["env_description"]}</h3></pre></td>
</tr>
<tr>
<td><b>Map URL: </b></td>
<td><h3 style="color:white;">**map_url**/</h3></td>
</tr>
<tr>
<td><b>Version: </b></td>
<td><span style="color:black;">{args["env_version"]}</span></td>
</tr>
<tr>
<td><b>Feedback: </b></td>
<td><span style="color:white;">**feedback**/</span></td>
</tr>
<tr style="line-height:80px;">
<td><b>Revision required ? : </b></td>
<td> Yes<span style="color:white;">**r1**/</span> No<span style="color:white;">**r2**/</span></td>
</tr>
<tr>
<td style="line-height:80px;"><b>Attach document: </b></td>
<td><span style="color:white;">**signer_attachment**/</span></td>
</tr>
<tr style="line-height:120px;">
<td><b>Agreed: </b></td>
<td><span style="color:white;">**signature_1**/</span></td>
</tr>
</tbody>
</table>
</body>
</html>
""" | bigcode/self-oss-instruct-sc2-concepts |
def source_to_locale_path(path):
"""
Return locale resource path for the given source resource path.
Locale files for .pot files are actually .po.
"""
if path.endswith("pot"):
path = path[:-1]
return path | bigcode/self-oss-instruct-sc2-concepts |
def is_arraylike(x):
"""
Determine if `x` is array-like. `x` is index-able if it provides the
`__len__` and `__getitem__` methods. Note that `__getitem__` should
accept 1D NumPy integer arrays as an index
Parameters
----------
x: any
The value to test for being array-like
Returns
-------
bool
`True` if array-like, `False` if not
"""
return hasattr(x, '__len__') and hasattr(x, '__getitem__') | bigcode/self-oss-instruct-sc2-concepts |
import random
import math
def roulette_index(n, random=random):
"""Randomly choose an index from 0...n-1. Choice has a weight of (index+1)."""
rouletteValue = random.randint(0, n * (n-1) // 2)
return math.ceil(-0.5 + math.sqrt(0.25 + 2 * rouletteValue)) | bigcode/self-oss-instruct-sc2-concepts |
def calculate_interval(start_time, end_time, deltas=None):
"""Calculates wanted data series interval according to start and end times
Returns interval in seconds
:param start_time: Start time in seconds from epoch
:param end_time: End time in seconds from epoch
:type start_time: int
:type end_time: int
:param deltas: Delta configuration to use. Defaults hardcoded if no
configuration is provided
:type deltas: dict(max time range of query in seconds: interval to use
in seconds)
:rtype: int - *Interval in seconds*
"""
time_delta = end_time - start_time
deltas = deltas if deltas else {
# 15 min -> 10s
900: 10,
# 30 min -> 30s
1800: 30,
# # 1 hour -> 1s
# 3600 : 1,
# # 1 day -> 30s
# 86400 : 30,
# 3 days -> 1min
259200: 60,
# 7 days -> 5min
604800: 300,
# 14 days -> 10min
1209600: 600,
# 28 days -> 15min
2419200: 900,
# 2 months -> 30min
4838400: 1800,
# 4 months -> 1hour
9676800: 3600,
# 12 months -> 3hours
31536000: 7200,
# 4 years -> 12hours
126144000: 43200,
}
for delta in sorted(deltas.keys()):
if time_delta <= delta:
return deltas[delta]
# 1 day default, or if time range > max configured (4 years default max)
return 86400 | bigcode/self-oss-instruct-sc2-concepts |
def flatten(x: dict, prefix="", grouped=True) -> dict:
"""Flattens dictionary by a group (one level only).
Arguments:
x {dict} -- Dictionary to be flattened.
Keyword Arguments:
prefix {str} -- Group prefix to flatten by. (default: {''})
grouped (bool) -- True if parameters are internally grouped by key. (default: {True})
Returns:
dict -- New flattened dictionary.
"""
output = {}
def flatten_inner(x: dict, output: dict, prefix: str):
for k, v in x.items():
output[f"{prefix}{k}"] = v
if grouped:
for k, v in x.items():
flatten_inner(v, output, prefix + k)
else:
flatten_inner(x, output, prefix)
return output | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
def _parse_columns(columns):
"""Expects a normalized *columns* selection and returns its
*key* and *value* components as a tuple.
"""
if isinstance(columns, Mapping):
key, value = tuple(columns.items())[0]
else:
key, value = tuple(), columns
return key, value | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
import re
def review_to_wordlist(review):
"""
Function to convert a document to a sequence of words.
Returns a list of words.
"""
# Remove HTML
review_text = BeautifulSoup(review).get_text()
#
# Remove non-letters
review_text = re.sub("[^a-zA-Z]"," ", review_text)
#
# Convert words to lower case and split them
words = review_text.lower().split()
return(words) | bigcode/self-oss-instruct-sc2-concepts |
def _IsNamedTuple(x):
"""Returns whether an object is an instance of a collections.namedtuple.
Examples::
_IsNamedTuple((42, 'hi')) ==> False
Foo = collections.namedtuple('Foo', ['a', 'b'])
_IsNamedTuple(Foo(a=42, b='hi')) ==> True
Args:
x: The object to check.
"""
return isinstance(x, tuple) and hasattr(x, '_fields') | bigcode/self-oss-instruct-sc2-concepts |
def MaybeAddColor(s, color):
"""Wrap the input string to the xterm green color, if color is set.
"""
if color:
return '\033[92m{0}\033[0m'.format(s)
else:
return s | bigcode/self-oss-instruct-sc2-concepts |
def _memory_usage(df):
"""Return the total memory usage of a DataFrame"""
return df.memory_usage(deep=True).sum() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def assert_empty_line_between_description_and_param_list(
docstring: List[str]
) -> List[str]:
"""
make sure empty line between description and list of params
find first param in docstring and check if there is description above it
if so, make sure that there is empty line between description and param list
:param docstring: list of lines in docstring
:return: list of lines in docstring
"""
prefixes = [":param", ":return", ":raises"]
start_of_param_list = -1
for i in range(len(docstring)):
line = docstring[i].strip()
# check if it starts with prefix
for prefix in prefixes:
if line.startswith(prefix) and i > 1:
start_of_param_list = i
break
if start_of_param_list != -1:
break
if start_of_param_list == -1:
return docstring
# remove all empty lines before param list and enter a single empty line before param list
while docstring[start_of_param_list - 1].strip() == "":
docstring.pop(start_of_param_list - 1)
start_of_param_list -= 1
docstring.insert(start_of_param_list, "")
return docstring | bigcode/self-oss-instruct-sc2-concepts |
def token_sub(request):
"""Returns the sub to include on the user token."""
return request.param if hasattr(request, 'param') else None | bigcode/self-oss-instruct-sc2-concepts |
def offset_error(x_gt, x_pred, loss_mask):
"""
masked offset error for global coordinate data.
inputs:
- x_gt: ground truth future data. tensor. size: (batch, seq_len, 2)
- x_pred: future data prediction. tensor. size: (batch, seq_len, 2)
- loss_mask: 0-1 mask on prediction range. size: (batch, seq_len, 1)
We now want mask like [0, 0, ..., 1, 1, ..,1, 0., 0] to work. And it works.
outputs:
- oe: (batch, seq_len)
"""
oe = (((x_gt - x_pred) ** 2.).sum(dim=2)) ** (0.5) # (batch, seq_len)
oe_masked = oe * loss_mask.squeeze(dim=2) # (batch, seq_len)
return oe_masked | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def is_default_route(ip):
"""
helper to check if this IP is default route
:param ip: IP to check as string
:return True if default, else False
"""
t = ipaddress.ip_address(ip.split("/")[0])
return t.is_unspecified and ip.split("/")[1] == "0" | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_class_that_defined_method(method):
"""
Returns the class that defined the method
Got implementation from stackoverflow
http://stackoverflow.com/a/25959545/3903832
"""
# for bound methods
if inspect.ismethod(method):
for cls in inspect.getmro(method.__self__.__class__):
if cls.__dict__.get(method.__name__) is method:
return cls.__name__
method = method.__func__ # fallback to __qualname__ parsing
# for unbound methods
if inspect.isfunction(method):
cls = getattr(inspect.getmodule(method),
method.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
if isinstance(cls, type):
return cls.__name__ | bigcode/self-oss-instruct-sc2-concepts |
def expand_noderange(value):
"""Expand a given node range like: '1-10,17,19'"""
ranges = value.split(',')
nodes = []
for r in ranges:
if '-' in r:
start, end = r.split('-')
nodes += [str(i) for i in range(int(start), int(end) + 1)]
else:
nodes.append(r.strip())
return nodes | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetimes_equal_minutes(dt1, dt2):
"""Assert that two datetimes are equal with precision to minutes."""
return datetime(*dt1.timetuple()[:5]) == datetime(*dt2.timetuple()[:5]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def replcDeid(s):
"""
replace de-identified elements in the sentence (date, name, address, hospital, phone)
"""
s = re.sub('\[\*\*\d{4}-\d{2}-\d{2}\*\*\]', 'date', s)
s = re.sub('\[\*\*.*?Name.*?\*\*\]', 'name', s)
s = re.sub('\[\*\*.*?(phone|number).*?\*\*\]', 'phone', s)
s = re.sub('\[\*\*.*?(Hospital|Location|State|Address|Country|Wardname|PO|Company).*?\*\*\]', 'loc', s)
s = re.sub('\[\*\*.*?\*\*\]', 'deidother', s)
return s | bigcode/self-oss-instruct-sc2-concepts |
def prep_words(name, word_list_ini):
"""Prep word list for finding anagrams."""
print("length initial word_list = {}".format(len(word_list_ini)))
len_name = len(name)
word_list = [word.lower() for word in word_list_ini if len(word) == len_name]
print("length of new word_list = {}".format(len(word_list)))
return word_list | bigcode/self-oss-instruct-sc2-concepts |
def _pathlib_compat(path):
"""
For path-like objects, convert to a filename for compatibility
on Python 3.6.1 and earlier.
"""
try:
return path.__fspath__()
except AttributeError:
return str(path) | bigcode/self-oss-instruct-sc2-concepts |
def _GetEnumValue(helper, name_or_value):
"""Maps an enum name to its value. Checks that a value is valid."""
if isinstance(name_or_value, int):
helper.Name(name_or_value) # Raises EnumError if not a valid value.
return name_or_value
else:
return helper.Value(name_or_value) | bigcode/self-oss-instruct-sc2-concepts |
def get_opacity(spectrum, mean):
"""
Calculate the opacity profile for the spectrum. This simply divides the
spectrum's flux by the mean.
:param spectrum: The spectrum to be processed
:param mean: The mean background flux, representing what the backlighting sources average flux.
:return: The opacity (e^(-tau)) at each velocity step.
"""
# print spectrum.flux
# print spectrum.flux/mean
return spectrum.flux/mean | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _rezise_targets(targets, height, width):
"""
Resize the targets to the same size of logits (add height and width channels)
"""
targets = torch.stack(targets) # convert list of scalar tensors to single tensor
targets = targets.view(
targets.size(0), targets.size(1), 1, 1, # add two dummy spatial dims
)
targets = targets.expand(
targets.size(0), targets.size(1), height, width # expand to spatial size of x
)
return targets | bigcode/self-oss-instruct-sc2-concepts |
import hmac
import hashlib
import base64
def get_uid(secret_key, email):
"""
This function calcualtes the unique user id
:param secret_key: APP's secret key
:param email: Github user's email
:return: unique uid using HMAC
"""
dig = hmac.new(bytes(secret_key.encode()), email.encode(), hashlib.sha256).digest()
uid = base64.b64encode(dig).decode()
return uid | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Tuple
def get_violations_count(individual: Sequence, queens_amount: int) -> Tuple[int]:
"""Get the amount of violations.
A violation is counted if two queens are placed in the same column or are in the same diagonal.
Args:
individual (deap.creator.SimpleIndividual): An individual
queens_amount (int): The amount of queens
Returns:
int: the amount of violations
"""
violations_amount = 0
for i in range(queens_amount):
for j in range(i+1, queens_amount):
if individual[i] == individual[j] or abs(i-j) == abs(individual[i]-individual[j]):
violations_amount += 1
return violations_amount, | bigcode/self-oss-instruct-sc2-concepts |
def custom_sort(x: str):
"""
All sorted lowercase letters are ahead of uppercase letters.
All sorted uppercase letters are ahead of digits.
All sorted odd digits are ahead of sorted even digits.
"""
return (
not str(x).isalpha(),
not str(x).islower(),
str(x).isdigit(),
int(x) % 2 == 0 if (str(x).isdigit()) else str(x),
str(x),
) | bigcode/self-oss-instruct-sc2-concepts |
def miles_to_kilometers(L_miles):
"""
Convert length in miles to length in kilometers.
PARAMETERS
----------
L_miles: tuple
A miles expression of length
RETURNS
----------
L_kilometers: float
The kilometers expression of length L_miles
"""
return 1.609344*L_miles | bigcode/self-oss-instruct-sc2-concepts |
import logging
def check_element_balance(elements, species, reaction, limit=1e-5):
"""Check the given reaction for their element balance."""
elm_sum = {key: 0.0 for key in elements.keys()}
for spc, spc_nu in reaction.reactants.items():
for key in species[spc].thermo.composition:
elm_sum[key] += species[spc].thermo.composition[key] * spc_nu
for spc, spc_nu in reaction.products.items():
for key in species[spc].thermo.composition:
elm_sum[key] -= species[spc].thermo.composition[key] * spc_nu
if any(abs(x) > limit for x in elm_sum.values()):
logging.warning('Element conservation violation: %s!', elm_sum)
return all(abs(x) <= limit for x in elm_sum.values()) | bigcode/self-oss-instruct-sc2-concepts |
def get_domain_class_attribute_names(ent):
"""
Returns all attribute names of the given registered resource.
"""
return ent.__everest_attributes__.keys() | bigcode/self-oss-instruct-sc2-concepts |
def load_descriptions(doc):
"""
Loads description (Captions)
:param doc: Caption text files
:return: Captions mapped to images
"""
mapping = dict()
# process lines
for line in doc.split('\n'):
# split line by white space
tokens = line.split()
if len(line) < 2:
continue
# take the first token as the image id, the rest as the description
image_id, image_desc = tokens[0], tokens[1:]
# extract filename from image id
image_id = image_id.split('.')[0]
# convert description tokens back to string
image_desc = ' '.join(image_desc)
# create the list if needed
if image_id not in mapping:
mapping[image_id] = list()
# store description
mapping[image_id].append(image_desc)
return mapping | bigcode/self-oss-instruct-sc2-concepts |
def batched_index_select_nd_last(t, inds):
"""
Index select on dim -1 of a >=2D multi-batched tensor. inds assumed
to have all batch dimensions except one data dimension 'n'
:param t (batch..., n, m)
:param inds (batch..., k)
:return (batch..., n, k)
"""
dummy = inds.unsqueeze(-2).expand(*inds.shape[:-1], t.size(-2), inds.size(-1))
out = t.gather(-1, dummy)
return out | bigcode/self-oss-instruct-sc2-concepts |
def gq_get_vertex_user(user):
"""Create the gremlin query that returns a Vertex for a user given
its uuid
"""
query = "g.V().hasLabel('user').has('uuid', '{}')".format(user.uuid)
return query | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates(list_with_duplicates):
"""
Removes the duplicates and keeps the ordering of the original list.
For duplicates, the first occurrence is kept and the later occurrences are ignored.
Args:
list_with_duplicates: list that possibly contains duplicates
Returns:
A list with no duplicates.
"""
unique_set = set()
unique_list = []
for element in list_with_duplicates:
if element not in unique_set:
unique_set.add(element)
unique_list.append(element)
return unique_list | bigcode/self-oss-instruct-sc2-concepts |
import torch
def negate_bounds(bounds: torch.Tensor, dim=-1) -> torch.Tensor:
"""Negate a bounds tensor: (1 - U, 1 - L)"""
return (1 - bounds).flip(dim) | bigcode/self-oss-instruct-sc2-concepts |
import glob
def get_all_file_path_in_dir(dir_name):
"""
dir内の全てのファイルのパスを取得する関数
Args:
dir_name (str): directory name
Returns:
All file path name str list
"""
all_file_path_list = [r for r in glob.glob(dir_name + '/*')]
return all_file_path_list | bigcode/self-oss-instruct-sc2-concepts |
import ast
def check_funcdefaultvalues(node):
"""
Returns if there are function definitions with default values.
"""
class Visitor(ast.NodeVisitor):
def __init__(self):
self.found = False
def visit_FunctionDef(self, node):
self.generic_visit(node)
if node.args.defaults:
self.found = True
visitor = Visitor()
visitor.visit(node)
return visitor.found | bigcode/self-oss-instruct-sc2-concepts |
def adjust_height(v1, height):
"""
Increases or decreases the z axis of the vector
:param v1: The vector to have its height changed
:param height: The height to change the vector by
:return: The vector with its z parameter summed by height
"""
return (v1[0],
v1[1],
v1[2] + height) | bigcode/self-oss-instruct-sc2-concepts |
import base64
def encode_array(array):
"""Encodes array to byte64
Args:
array (ndarray): array
Returns:
byte64: encoded array
"""
# Encoding of 3darray to save in database
encoded_array = base64.b64encode(array)
return encoded_array | bigcode/self-oss-instruct-sc2-concepts |
def _create_facilities(handler, facilities=None):
"""Initialize a facilities dictionary."""
if facilities is None:
facilities = dict()
for facility in handler.facility_names.keys():
if getattr(handler, 'LOG_%s' % facility.upper(), None) is not None:
facilities[facility] = handler.facility_names[facility]
return facilities | bigcode/self-oss-instruct-sc2-concepts |
def isRequest(code):
"""
Checks whether a code indicates a request.
:param code: code the code to check
:return: True if the code indicates a request
"""
return 1 <= code <= 31 | bigcode/self-oss-instruct-sc2-concepts |
import re
def uc_sequence(x: str)-> str:
"""
Input: String
Output: String
Check if there is any word exists with first alphabet uppercase and else lower case.
"""
c = re.findall("[A-Z][a-z]*",x)
if c:
return "Yes"
else:
return "No" | bigcode/self-oss-instruct-sc2-concepts |
def set_bit(a, order):
""" Set the value of a bit at index <order> to be 1. """
return a | (1 << order) | bigcode/self-oss-instruct-sc2-concepts |
def ensure_iterable(obj):
"""
Ensures that the object provided is a list or tuple and wraps it if not.
"""
if not isinstance(obj, (list, tuple)):
obj = (obj,)
return obj | bigcode/self-oss-instruct-sc2-concepts |
def gen_matchups(n):
"""
generate seed pairs for a round
>>> gen_matchups(4)
[(1, 4), (2, 3)]
"""
seeds = range(1, n+1)
games = []
for i in range(n/2):
low = seeds[i]
hi = seeds[-(i+1)]
games.append((low, hi))
return games | bigcode/self-oss-instruct-sc2-concepts |
import re
def regex_token_replace(sentence: str, token: str, replacement: str) -> str:
"""
replace all occurrences of a target token with its replacement
:param sentence: input sentence to be modified
:param token: target token to be replaced
:param replacement: replacement word for the target token
:return: sentence with the all occurrences of the target token substituted by its replacement
"""
replace_map = [
[token, replacement],
[token.capitalize(), replacement.capitalize()],
[token.upper(), replacement.upper()],
]
for j in range(len(replace_map)):
pattern = re.compile(
r"\b{}\b".format(replace_map[j][0])
) # \b indicates a word boundary in regex
sentence = re.sub(pattern, replace_map[j][1], sentence)
return sentence | bigcode/self-oss-instruct-sc2-concepts |
def has_common_element(a, b):
"""
Return True if iterables a and b have at least one element in common.
"""
return not len(set(a) & set(b)) == 0 | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def my_caller(up=0):
"""
Returns a FrameInfo object describing the caller of the function that
called my_caller.
You might care about these properties of the FrameInfo object:
.filename
.function
.lineno
The `up` parameter can be used to look farther up the call stack. For
instance, up=1 returns info about the caller of the caller of the function
that called my_caller.
"""
stack = inspect.stack()
return stack[up+2] | bigcode/self-oss-instruct-sc2-concepts |
def non_negative_int(s: str) -> int:
"""
Return integer from `s`, if `s` represents non-negative integer,
otherwise raise ValueError.
"""
try:
n = int(s)
if n < 0:
raise ValueError
return n
except ValueError:
raise ValueError('Must be non-negative integer') | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Sequence
def crop(data: torch.Tensor, corner: Sequence[int], size: Sequence[int], grid_crop: bool = False):
"""
Extract crop from last dimensions of data
Parameters
----------
data: torch.Tensor
input tensor [... , spatial dims] spatial dims can be arbitrary
spatial dimensions. Leading dimensions will be preserved.
corner: Sequence[int]
top left corner point
size: Sequence[int]
size of patch
grid_crop: bool
crop from grid of shape [N, spatial dims, NDIM], where N is the batch
size, spatial dims can be arbitrary spatial dimensions and NDIM
is the number of spatial dimensions
Returns
-------
torch.Tensor
cropped data
"""
_slices = []
ndim = data.ndimension() - int(bool(grid_crop)) # alias for ndim()
if len(corner) < ndim:
for i in range(ndim - len(corner)):
_slices.append(slice(0, data.shape[i]))
_slices = _slices + [slice(c, c + s) for c, s in zip(corner, size)]
if grid_crop:
_slices.append(slice(0, data.shape[-1]))
return data[_slices] | bigcode/self-oss-instruct-sc2-concepts |
def get_page_by_uid(uid, pages):
"""
Get a page by its UID
Args:
uid (str): The page UID to search for
pages (list of dict): list of pages
Returns:
dict: The matching page if any
"""
page_info = [page for page in pages if page["uid"] == uid]
if page_info:
return page_info[0] | bigcode/self-oss-instruct-sc2-concepts |
def union_contiguous_intervals(arr):
""" Union contiguous intervals.
arr = list of [(st,ed),...]
"""
arr = sorted(arr)
def _gen():
st0,ed0 = arr[0]
for st1,ed1 in arr[1:]:
if ed0 < st1: # ed1<st0 new interval
yield [st0,ed0]
st0,ed0 = st1,ed1
else: # overlapping/contiguous
ed0 = max(ed0, ed1)
yield [st0,ed0]
return [x for x in _gen()] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def compare_triplets(a: List[int], b: List[int]) -> Tuple[int, ...]:
"""
>>> compare_triplets((5, 6, 7), (3, 6, 10))
(1, 1)
"""
zip_ab = tuple(zip(a, b))
# alice, bob = 0, 0
# for x, y in zip_ab:
# if x > y:
# alice += 1
# elif x < y:
# bob += 1
alice, bob = sum(a > b for a, b in zip_ab), sum(a < b for a, b in zip_ab)
return alice, bob | bigcode/self-oss-instruct-sc2-concepts |
def is_client_error(code):
"""Return that the client seems to have erred."""
return 400 <= code <= 499 | bigcode/self-oss-instruct-sc2-concepts |
def cmd_resolve_strings(lresolver, resolve_strings):
"""Handle resolve-string command."""
for string in resolve_strings:
print(lresolver.resolve_string(string))
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def get_dims(shape, max_channels=10):
"""Get the number of dimensions and channels from the shape of an array.
The number of dimensions is assumed to be the length of the shape, as long as the shape of the last dimension is
inferior or equal to max_channels (default 3).
:param shape: shape of an array. Can be a sequence or a 1d numpy array.
:param max_channels: maximum possible number of channels.
:return: the number of dimensions and channels associated with the provided shape.
example 1: get_dims([150, 150, 150], max_channels=10) = (3, 1)
example 2: get_dims([150, 150, 150, 3], max_channels=10) = (3, 3)
example 3: get_dims([150, 150, 150, 15], max_channels=10) = (4, 1), because 5>3"""
if shape[-1] <= max_channels:
n_dims = len(shape) - 1
n_channels = shape[-1]
else:
n_dims = len(shape)
n_channels = 1
return n_dims, n_channels | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_shrink_board(
board: List[List[str]],
is_flatten: bool
) -> List:
"""
Get only the building placeholder.
(Note: In other word, remove the row and column header.)
Parameters
----------
board: List[List[str]]
2D array containing all the game detail, including column header, row header and placed buildings.
is_flatten: bool
A flag that indicate if the result need to be in flatten into 1d array.
Returns
-------
(Note: there are two possible scenario depending on {is_flatten})
placeholder_list: List[str]
A 1D array containing all the placeholder. (When is_flatten = True)
placeholder_list: List[List[str]]
A 2D array containing all the placeholder. (When is_flatten = False)
"""
if is_flatten:
return [board[r][c] for r in range(1, len(board)) for c in range(1, len(board[r]))]
else:
return [[board[r][c] for c in range(1, len(board[r]))] for r in range(1, len(board))] | bigcode/self-oss-instruct-sc2-concepts |
def same_lists(first, second):
"""Do the 2 input lists contain equivalent objects?"""
nobjs = len(first)
if len(second) != nobjs:
return False
# This is a bit of a brute-force approach since I'm not sure whether
# ExposureGroups will get ordered consistently by a sort operation if
# their internal ordering varies without defining the appropriate
# special methods, but no big deal. Equivalence *does* work where the
# internal ordering of ExposureGroups varies.
for obj1 in first:
found = False
for obj2 in second:
if obj1 == obj2:
found = True
break
if not found:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import _ast
def simpleAssignToName(node):
"""If a simple assignment to a name, return name, otherwise None."""
if isinstance(node, _ast.Assign) and len(node.targets) == 1:
targetNode = node.targets[0]
if isinstance(targetNode, _ast.Name):
return targetNode.id
else:
return None
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def request(url_request):
"""
Generate the URI to send to the THETA S. The THETA IP address is
192.168.1.1
All calls start with /osc/
"""
url_base = "http://192.168.1.1/osc/"
url = url_base + url_request
return url | bigcode/self-oss-instruct-sc2-concepts |
def parse_denormalized(line):
"""Parse one line of the original dataset into a (user, item, rating) triplet of strings."""
id_, rating = line.strip().split(',')
user, item = map(lambda x: x[1:], id_.split('_'))
return user, item, rating | bigcode/self-oss-instruct-sc2-concepts |
def printpath(P, u, w):
"""
Given modified path cost matrix (see floydwarshall) return shortest path
from i to j.
"""
path = [u]
while P[u][w][1] != -1:
path.append(P[u][w][1])
u = P[u][w][1]
return path | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_tags(html, tags):
"""Returns the given HTML with given tags removed.
``remove_tags`` is different from ``django.utils.html.strip_tags`` which
removes each and every html tags found.
``tags`` is a space separated string of (case sensitive) tags to remove.
This is backported from Django1.6:
https://docs.djangoproject.com/en/1.6/ref/utils/
"""
tags = [re.escape(tag) for tag in tags.split()]
tags_re = '(%s)' % '|'.join(tags)
starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
endtag_re = re.compile('</%s>' % tags_re)
html = starttag_re.sub('', html)
html = endtag_re.sub('', html)
return html | bigcode/self-oss-instruct-sc2-concepts |
def generate_colorbar_label(standard_name, units):
""" Generate and return a label for a colorbar. """
return standard_name.replace('_', ' ') + ' (' + units + ')' | bigcode/self-oss-instruct-sc2-concepts |
def safe_repr(x):
"""
A repr() that never fails, even if object has some bad implementation.
"""
try:
return repr(x)
except:
name = getattr(type(x), "__name__", "object")
return f"<{name} instance>" | bigcode/self-oss-instruct-sc2-concepts |
def read_tsp(path):
""" Read and parse TSP from given file path
Args:
path (string): location of *.tsp file
Returns:
data (dict): {city_index: {"x": xvalue, "y": yvalue}, ...}
"""
data = {}
with open(path, "r") as f:
# Specification block
for line in f:
if line.strip() == "NODE_COORD_SECTION":
break
# Data block
for line in f:
line = line.strip()
if line == "EOF":
# End of data block
break
try:
index, y, x = line.split(" ")
data[int(index)] = {"x": float(x), "y": float(y)}
except Exception as e:
print(e)
print("Can't parse data [{line}]")
return data | bigcode/self-oss-instruct-sc2-concepts |
def complete_graph(vertices_number: int) -> dict:
"""
Generate a complete graph with vertices_number vertices.
@input: vertices_number (number of vertices),
directed (False if the graph is undirected, True otherwise)
@example:
>>> print(complete_graph(3))
{0: [1, 2], 1: [0, 2], 2: [0, 1]}
"""
return {
i: [j for j in range(vertices_number) if i != j] for i in range(vertices_number)
} | bigcode/self-oss-instruct-sc2-concepts |
def is_hyponym(syn1, syn2):
""" Checks if syn1 is a child of syn2 """
while syn1 != syn2:
hypernyms = syn1.hypernyms()
if len(hypernyms) == 0:
return False
syn1 = hypernyms[0]
return True | bigcode/self-oss-instruct-sc2-concepts |
def api_date(a_datetime, time=False):
"""Return datetime string in Google API friendly format."""
if time:
return ('{0:%Y-%m-%d %H:%M:%S}'.format(a_datetime))
else:
return ('{0:%Y-%m-%d}'.format(a_datetime)) | bigcode/self-oss-instruct-sc2-concepts |
def Choose(index, *args):
"""Choose from a list of options
If the index is out of range then we return None. The list is
indexed from 1.
"""
if index <= 0:
return None
try:
return args[index-1]
except IndexError:
return None | bigcode/self-oss-instruct-sc2-concepts |
def ids_to_payload(ids: list[tuple[str, str]]) -> list[dict]:
"""
Convert a list of (type, id) tuples to a list of dicts that
can be used as payload for the kptncook api.
"""
payload = []
for id_type, id_value in ids:
if id_type == "oid":
payload.append({"identifier": id_value})
elif id_type == "uid":
payload.append({"uid": id_value})
return payload | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(pathname):
"""Read json from a file"""
with open(pathname) as data_file:
try:
json_data = json.load(data_file)
except:
print(f"Error reading file {pathname}")
return None
return json_data | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(d0, d1):
"""Create a new `dict` that is the union of `dict`s `d0` and `d1`."""
d = d0.copy()
d.update(d1)
return d | bigcode/self-oss-instruct-sc2-concepts |
def find_keys_with_duplicate_values(ini_dict, value_to_key_function):
"""Finding duplicate values from dictionary using flip.
Parameters
----------
ini_dict: dict
A dict.
value_to_key_function : function
A function that transforms the value into a hashable type.
For example if I have a list of int as value, I can transform the value in a int as follow:
lambda x: int("".join([str(i) for i in x])
Returns
-------
dict
a flipped dictionary with values as key.
"""
#
flipped = {}
for key, value in ini_dict.items():
value = value_to_key_function(value)
if value not in flipped:
flipped[value] = [key]
else:
flipped[value].append(key)
return flipped | bigcode/self-oss-instruct-sc2-concepts |
def get_cfg(cfg_label, cfg_dict):
"""
Get requested configuration from given dictionary or raise an exception.
:param cfg_label:
Label of configuration to get
:param dict cfg_dict:
Dictionary with all configurations available
:raises: At
:return: Config from given structure
:rtype: dict
"""
tmp_cfg = cfg_dict.get(cfg_label)
if tmp_cfg is None:
raise AttributeError("No configuration for '{}'".format(cfg_label))
return tmp_cfg | bigcode/self-oss-instruct-sc2-concepts |
def _get_improper_type_key(improper, epsilon_conversion_factor):
"""Get the improper_type key for the harmonic improper
Parameters
----------
improper : parmed.topologyobjects.Dihedral
The improper information from the parmed.topologyobjects.Angle
epsilon_conversion_factor : float or int
The epsilon conversion factor
Returns
----------
tuple, (improper_k_constant, improper_psi_o, improper_atom_1_type,
(improper_atom_2_type, improper_atom_3_type, improper_atom_4_type), improper_atom_1_res_type,
(improper_atom_2_res_type, improper_atom_3_res_type, improper_atom_4_res_type)
improper_k_constant : float
Harmonic k-constant or bond energy scaling factor
improper_psi_o : float
Harmonic equilbrium improper angle
improper_atom_1_type : str
The atom type for atom number 1 in the dihedral
improper_atom_2_type : str
The atom type for atom number 2 in the dihedral
improper_atom_3_type : str
The atom type for atom number 3 in the dihedral
improper_atom_4_type : str
The atom type for atom number 4 in the dihedral
improper_atom_1_res_type : str
The residue name for atom number 1 in the dihedral
improper_atom_2_res_type : str
The residue name for atom number 2 in the dihedral
improper_atom_3_res_type : str
The residue name for atom number 3 in the dihedral
improper_atom_4_res_type : str
The residue name for atom number 4 in the dihedral
"""
lj_unit = 1 / epsilon_conversion_factor
improper_k_constant = round(improper.type.psi_k * lj_unit, 8)
improper_psi_o = round(improper.type.psi_eq, 8)
improper_atom_1_type = improper.atom1.type
improper_atom_2_type = improper.atom2.type
improper_atom_3_type = improper.atom3.type
improper_atom_4_type = improper.atom4.type
improper_atom_1_res_type = improper.atom1.residue.name
improper_atom_2_res_type = improper.atom2.residue.name
improper_atom_3_res_type = improper.atom3.residue.name
improper_atom_4_res_type = improper.atom4.residue.name
return (
improper_k_constant,
improper_psi_o,
improper_atom_1_type,
(improper_atom_2_type, improper_atom_3_type, improper_atom_4_type),
improper_atom_1_res_type,
(
improper_atom_2_res_type,
improper_atom_3_res_type,
improper_atom_4_res_type,
),
) | bigcode/self-oss-instruct-sc2-concepts |
def _combine_counts(count1, count2):
""" Sum two counts, but check that if one is 'unknown',
both are 'unknown'. In those cases, return a single
value of 'unknown'. """
if count1 == 'unknown' or count2 == 'unknown':
assert(count1 == 'unknown' and count2 == 'unknown')
return 'unknown'
assert(type(count1) == int and type(count2) == int)
return count1 + count2 | bigcode/self-oss-instruct-sc2-concepts |
def formatDirPath(path):
"""Appends trailing separator to non-empty path if it is missing.
Args:
path: path string, which may be with or without a trailing separator,
or even empty or None
Returns:
path unchanged if path evaluates to False or already ends with a trailing
separator; otherwise, a / separator is appended
"""
if path and not path.endswith('/'):
path = path + '/'
return path | bigcode/self-oss-instruct-sc2-concepts |
def clean_thing_description(thing_description: dict) -> dict:
"""Change the property name "@type" to "thing_type" and "id" to "thing_id" in the thing_description
Args:
thing_description (dict): dict representing a thing description
Returns:
dict: the same dict with "@type" and "id" keys are mapped to "thing_type" and "thing_id"
"""
if "@type" in thing_description:
thing_description["thing_type"] = thing_description.pop("@type")
if "id" in thing_description:
thing_description["thing_id"] = thing_description.pop("id")
return thing_description | bigcode/self-oss-instruct-sc2-concepts |
def get_geo(twitter_msg):
"""
Generates GoogleMap link if msg has location data.
:param twitter_msg: Twitter Status Object
:return: string with gm link if possible or empty string otherwise
"""
try:
x, y = twitter_msg.place["bounding_box"]["coordinates"][0][0]
return "https://www.google.com/maps/place/{},{}".format(y, x)
except Exception as e:
return "" | bigcode/self-oss-instruct-sc2-concepts |
import math
def yield_strength(impactor_density_kgpm3):
"""
Yield strength equation for breakup altitude calculation. Only valid for density range 1000 to 8000.
:param impactor_density_kgpm3: Impactor density in kg/m^3
:returns: Yield Strength in Pascals.
:Reference: EarthImpactEffect.pdf, Equation 10
"""
return 10 ** (2.107 + (0.0624 * math.sqrt(impactor_density_kgpm3))) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def open_txt_doc(filename):
"""Opens texts in docs folder that go in front end of app"""
path = Path(__file__).parent / 'docs' / 'app' / filename
with open(path, 'r') as txtfile:
text = txtfile.read()
return text | bigcode/self-oss-instruct-sc2-concepts |
def combine_split_result(s):
"""Combines the result of a re.split splitting
with the splitters retained. E.g. ['I', '/', 'am']
-> ['I', '/am'].
"""
if len(s) > 1:
ss = [s[0]]
for i in range(1, len(s)//2+1):
ii = i-1
ss.append(s[i] + s[i+1])
return ss
else:
return s | bigcode/self-oss-instruct-sc2-concepts |
def clean_elements(orig_list):
"""Strip each element in list and return a new list.
[Params]
orig_list: Elements in original list is not clean, may have blanks or
newlines.
[Return]
clean_list: Elements in clean list is striped and clean.
[Example]
>>> clean_elements(['a ', '\tb\t', 'c; '])
['a', 'b', 'c']
"""
return [_.strip().strip(';') for _ in orig_list] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def load_bookmarks(bookmark_path: str) -> List[int]:
"""
VSEdit bookmark loader.
load_bookmarks(os.path.basename(__file__)+".bookmarks")
will load the VSEdit bookmarks for the current Vapoursynth script.
:param bookmark_path: Path to bookmarks file
:return: A list of bookmarked frames
"""
with open(bookmark_path) as f:
bookmarks = [int(i) for i in f.read().split(", ")]
if bookmarks[0] != 0:
bookmarks.insert(0, 0)
return bookmarks | bigcode/self-oss-instruct-sc2-concepts |
def _overall_output(ts, format_str):
"""Returns a string giving the overall test status
Args:
ts: TestStatus object
format_str (string): string giving the format of the output; must
contain place-holders for status and test_name
"""
test_name = ts.get_name()
status = ts.get_overall_test_status()
return format_str.format(status=status, test_name=test_name) | bigcode/self-oss-instruct-sc2-concepts |
def is_json(file_path):
"""
Checks if a certain file path is JSON.
:param file_path: The file path.
:return: True if it is JSON, False otherwise.
"""
return file_path.endswith('.json') | bigcode/self-oss-instruct-sc2-concepts |
def get_relation_id(relation):
"""Return id attribute of the object if it is relation, otherwise return given value."""
return relation.id if type(relation).__name__ == "Relation" else relation | bigcode/self-oss-instruct-sc2-concepts |
def get_sample_region_coverage(sample_tabix_object, region_dict):
"""
get_sample_region_coverage
==========================
Get the coverage values for a specific sample at a specific region interval.
A list containing per base coverage values will be returned.
Parameters:
-----------
1) sample_tabix_object: (psyam Object) A pysam tabix object representing the bed file of a sample
2) region_dict: (dict) A dictionary with region information. Required keys include "chrom", "start", and "end"
Returns:
+++++++
1) (list) A list of coverage values representing a per base coverage score
"""
coverage = []
## Iterate over the overlapping coverage intervals
for i, coverage_line in enumerate(
sample_tabix_object.fetch(
region_dict["chrom"], int(region_dict["start"]), int(region_dict["end"])
)
):
## Create a dict for the current line
cov_dict = dict(
zip(
["chrom", "start", "end", "coverage_value"],
coverage_line.strip().split("\t"),
)
)
## Add the coverage value for each position defined by the current interval
coverage.extend(
[
int(cov_dict["coverage_value"])
for x in range(int(cov_dict["end"]) - int(cov_dict["start"]))
]
)
return coverage | bigcode/self-oss-instruct-sc2-concepts |
import string
def case_iteration(header, iteration):
"""
Modifies a string to determine the correct
case for each individual character in the string.
A character will be uppercase if the bit representing it in
the iteration value is set to 1.
For example, the string "hello" with an iteration of 3 would
be return "HEllo".
The iteration value in looks like the following in binary:
00000011
Each char position the header string looks like the following in binary:
h = 00000001 (1<<0)
e = 00000010 (1<<1)
l = 00000100 (1<<2)
l = 00001000 (1<<3)
o = 00010000 (1<<4)
Each binary character position is compared to the iteration param using
a bitwise AND. Positive values are uppercased; zero values are lowercased.
Keyword arguments:
header -- a string containing the value to caseify
iteration -- a numeric value representing the binary mapping of characters
in the header string to uppercase.
"""
if iteration <= 0:
return header.lower()
chars = []
removed = []
# First create lists of workable and unworkable characters
for i, char in enumerate(header):
if char not in string.ascii_letters:
removed.append({"char": char, "pos": i})
else:
chars.append(char)
# Apply a binary map on the characters we can work with
for i, char in enumerate(chars):
pos = 1 << i
if pos & iteration:
chars[i] = char.upper()
else:
chars[i] = char.lower()
# Insert removed characters back into the correct positions
for item in removed:
chars.insert(item['pos'], item['char'])
return ''.join(chars) | bigcode/self-oss-instruct-sc2-concepts |
def get_ca_atoms(chain):
"""
Returns the CA atoms of a chain, or all the atoms in case it doesn't have CA atoms.
Arguments:
- chain - Bio.PDB.Chain, the chain to get the atoms
"""
result = []
if chain.child_list[0].has_id("CA"):
for fixed_res in chain:
if fixed_res.has_id("CA"):
result.append(fixed_res['CA'])
else:
result = list(chain.get_atoms())
return result | bigcode/self-oss-instruct-sc2-concepts |
def calculate_senate_bop(race, data):
"""
"total": The total number of seats held by this party.
Math: Seats held over (below) + seats won tonight
"needed_for_majority": The number of seats needed to have a majority.
Math: 51 (majority share) - total.
"total_pickups": The zero-indexed total number of pickups by this party.
Math: Add one for each pickup by this party.
"""
data['total'] += 1
majority = 51 - data['total']
if majority < 0:
majority = 0
data['needed_for_majority'] = majority
if race.has_flipped:
data['total_pickups'] += 1
return data | bigcode/self-oss-instruct-sc2-concepts |
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans, unanswerable_exists=False):
"""
Find the best threshold to determine a question is impossible to answer.
Args:
preds (dict): Dictionary with qa_id as keys and predicted answers as values.
scores (dict): Dictionary with qa_id as keys and raw evaluation scores (exact_match or
f1) as values.
na_probs (dict): Dictionary with qa_id as keys and unanswerable probabilities as values.
qid_to_has_ans (dict): Dictionary with qa_id as keys boolean values indicating if the
question has answer as values.
unanswerable_exists (bool, optional): Whether there is unanswerable questions in the data.
Defaults to False.
Returns:
tuple: score after applying best threshold, best threshold, (score for answerable
questions after applying best threshold, if unanswerable_exists=True)
"""
num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k])
# If na_prob > threshold, the question is considered as unanswerable by the prediction.
# Initially, the threshold is 0. All questions are considered as unanswerable by the
# predictions. So cur_score is the number of actual unanswerable questions (i.e. correctly
# predicted as unanswerable in the data.
cur_score = num_no_ans
best_score = cur_score
best_thresh = 0.0
# Sorted in ascending order
qid_list = sorted(na_probs, key=lambda k: na_probs[k])
for i, qid in enumerate(qid_list):
# When using the cur_na_prob as threshold, all predictions with na_prob > na_prob_cur are
# considered as unanswerable. Current question is considered answerable.
if qid not in scores:
continue
if qid_to_has_ans[qid]:
# Current question has ground truth answer, the prediction is correct. The raw score
# is added to cur_score
diff = scores[qid]
else:
# Current question doesn't have ground truth answer.
if preds[qid]:
# Prediction is not empty, incorrect. cur_score -= 1
diff = -1
else:
# Prediction is empty, correct, the original score 1 from num_no_ans is preserved.
diff = 0
cur_score += diff
if cur_score > best_score:
# When cur_score > best_score, the threshold can increase so that more questions are
# considered as answerable and fewer questions are considered as unanswerable.
# Imagine a PDF with two humps with some overlapping, the x axis is the na_prob. The
# hump on the left is answerable questions and the hump on the right is unanswerable
# questions.
# At some point, the number of actual answerable questions decreases, and we got more
# penalty from considering unanswerable questions as answerable than the score added
# from actual answerable questions, we will not change the threshold anymore and the
# optimal threshold is found.
best_score = cur_score
best_thresh = na_probs[qid]
if not unanswerable_exists:
return 100.0 * best_score / len(scores), best_thresh
else:
has_ans_score, has_ans_cnt = 0, 0
for qid in qid_list:
if not qid_to_has_ans[qid]:
continue
has_ans_cnt += 1
if qid not in scores:
continue
has_ans_score += scores[qid]
return 100.0 * best_score / len(scores), best_thresh, 1.0 * has_ans_score / has_ans_cnt | bigcode/self-oss-instruct-sc2-concepts |
def evaluate_prediction(y, y_hat):
"""
This is a function to calculate the different metrics based on the list of true label and predicted label
:param y: list of labels
:param y_hat: list of predictions
:return: (dict) ensemble of metrics
"""
true_positive = 0.0
true_negative = 0.0
false_positive = 0.0
false_negative = 0.0
tp = []
tn = []
fp = []
fn = []
for i in range(len(y)):
if y[i] == 1:
if y_hat[i] == 1:
true_positive += 1
tp.append(i)
else:
false_negative += 1
fn.append(i)
else: # -1
if y_hat[i] == 0:
true_negative += 1
tn.append(i)
else:
false_positive += 1
fp.append(i)
accuracy = (true_positive + true_negative) / (true_positive + true_negative + false_positive + false_negative)
if (true_positive + false_negative) != 0:
sensitivity = true_positive / (true_positive + false_negative)
else:
sensitivity = 0.0
if (false_positive + true_negative) != 0:
specificity = true_negative / (false_positive + true_negative)
else:
specificity = 0.0
if (true_positive + false_positive) != 0:
ppv = true_positive / (true_positive + false_positive)
else:
ppv = 0.0
if (true_negative + false_negative) != 0:
npv = true_negative / (true_negative + false_negative)
else:
npv = 0.0
balanced_accuracy = (sensitivity + specificity) / 2
results = {'accuracy': accuracy,
'balanced_accuracy': balanced_accuracy,
'sensitivity': sensitivity,
'specificity': specificity,
'ppv': ppv,
'npv': npv,
'confusion_matrix': {'tp': len(tp), 'tn': len(tn), 'fp': len(fp), 'fn': len(fn)}
}
return results | bigcode/self-oss-instruct-sc2-concepts |
def xi_func_theory(xi0, T, Tc, nu):
"""
Parameter
---------
xi0 : float
correlation length 0 (in m)
T : float
lattice constant of the cubic unit cell (in K)
Tc : float
critical temperature of the system (in K)
nu : float
critical exponent of the correlation length (nu = gamme_eff/2)
Return
------
xi : float
temperature dependent correlation length (in m)
"""
return xi0 * (T/Tc - 1.0)**(-nu) | bigcode/self-oss-instruct-sc2-concepts |
def sigma_z(state, site):
"""
Returns `(sign, state)` where `sign` is 1 or -1 if the `site`th bit of the int `state`
is 0 or 1 respectively. Can also accept numpy arrays of ints and gives numpy arrays back
"""
return (-1.0) ** ((state >> site) & 1), state | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def dateFormat(timestamp):
"""
Format timestamp (nb of sec, float) into a human-readable date string
"""
return datetime.fromtimestamp(
int(timestamp)).strftime('%a %b %d, %Y - %H:%M') | bigcode/self-oss-instruct-sc2-concepts |
def to_dict(key, resultset):
"""
Convert a resultset into a dictionary keyed off of one of its columns.
"""
return dict((row[key], row) for row in resultset) | bigcode/self-oss-instruct-sc2-concepts |
def get_language(file_path):
"""Return the language a file is written in."""
if file_path.endswith(".py"):
return "python3"
elif file_path.endswith(".js"):
return "node"
elif file_path.endswith(".rb"):
return "ruby"
elif file_path.endswith(".go"):
return "go run"
elif file_path.endswith(".c") or file_path.endswith(".cpp"):
return "gcc"
else:
return "Unknown language." | bigcode/self-oss-instruct-sc2-concepts |
def make_iter_method(method_name, *model_names):
"""Make a page-concatenating iterator method from a find method
:param method_name: The name of the find method to decorate
:param model_names: The names of the possible models as they appear in the JSON response. The first found is used.
"""
def iter_method(self, *args, **kwargs):
result = getattr(self, method_name)(*args, **kwargs)
# Filter the list of model names for those that are a key in the response, then take the first.
# Useful for backwards compatability if response keys might change
model_name = next((model_name for model_name in model_names if model_name in result), None)
# If there are no model names, return None to avoid raising StopIteration
if not model_name:
return
for model in result[model_name]:
yield model
while True:
if 'next' not in result.get('links', {}):
return
result = self._get(result['links']['next'])
for model in result[model_name]:
yield model
return iter_method | 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.