seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import inspect
import ctypes
def cdll_with_spec(lib_path, spec):
"""
Open a shared library using ctypes.CDLL and apply the given spec class'
type annotations to the argtypes and restype attributes of the shared
library's functions.
The spec is a stub class with type annotations for the argument a... | bigcode/self-oss-instruct-sc2-concepts |
def remote_addr_from_request(request):
"""
Returns the correct remote address from the request object. If the
request was proxied, this correct information is in HTTP_X_FORWARDED_FOR
"""
if not request:
raise TypeError("No request passed to function")
if 'HTTP_X_FORWARDED_FOR' in request... | bigcode/self-oss-instruct-sc2-concepts |
def create_choice_attribute(creator_type, value, choice_entry):
"""Create an instance of a subclass of ChoiceAttributeMixin for the given value.
Parameters
----------
creator_type : type
``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value``
class-meth... | bigcode/self-oss-instruct-sc2-concepts |
def intervalcheckstrict(a,b,c):
"""
Returns whether a < b < c is True or False
"""
if a<b and b<c:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def generate500response(error: str) -> dict:
""" A function that generates a '500-Internal Server Error' message and returns it as a dict """
return {
"status": 500,
"message": "Internal Server Error",
"error": error
} | bigcode/self-oss-instruct-sc2-concepts |
def add_integers(a: int, b: int):
"""Sum two integers
Args:
a (int):
b (int):
Returns:
int: sum of the integer inputs a and b
"""
return a + b | bigcode/self-oss-instruct-sc2-concepts |
def standardize_input(score):
"""
Converts the score input of either a str, int, or float into the desired
input for percentage_to_gpa.
I don't care about some being int and some being float, still works all the same.
>>> standardize_input('95%')
95.0
>>> standardize_input(95)
95
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_yearly_logical_year(year, month, day):
# type: (int, int, int) -> int
"""Retrieves the logical year for a yearly frequency."""
return year | bigcode/self-oss-instruct-sc2-concepts |
def GetAttemptString(attempts):
"""
Creates the string used to display the current attempt.
"""
match attempts:
case 1:
return "1st"
case 2:
return "2nd"
case 3:
return "3rd"
case _:
return "{}th".format(attempts) | bigcode/self-oss-instruct-sc2-concepts |
def _describe_obj(obj):
"""
Prints the name of the object, and any qualifiers.
- if an item with count > 1, appends the count
"""
if obj.item and obj.item.count > 1:
return obj.name + ' (x' + str(obj.item.count) + ')'
else:
return obj.name | bigcode/self-oss-instruct-sc2-concepts |
import functools
def dirichlet(boundary_values_fn):
"""Wrapper for Dirichlet boundary conditions to be used in PDE solvers.
Example: the boundary value is 1 on both boundaries.
```python
def lower_boundary_fn(t, location_grid):
return 1
def upper_boundary_fn(t, location_grid):
return 0
solver ... | bigcode/self-oss-instruct-sc2-concepts |
def create_tags(ec2_client, ec2_instance_id, event_detail):
"""
Given an EC2 Instance ID, and event['detail'] from an ECS Container
Instance State Change, updates EC2 Instance tags with clusterArn &
containerInstanceArn
Returns the SDK response to the create_tags call.
"""
cluster_arn = ev... | bigcode/self-oss-instruct-sc2-concepts |
def human_readable(bytes):
"""
Return a human-readable representation of the provided number of bytes.
"""
for n, label in enumerate(['bytes', 'KiB', 'MiB', 'GiB', 'TiB']):
value = bytes / (1024 ** n)
if value < 1024:
return f'{round(value, 2)} {label}'
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_base64(text: str) -> bool:
"""Guess whether text is base64-encoded."""
return bool(
re.match(
r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$",
text.replace("\n", ""),
)
) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def top_k_logits(logits, k, probs=False):
"""
Masks everything but the k top entries as -infinity (1e10).
Used to mask logits such that e^-infinity -> 0 won't contribute to the
sum of the denominator.
"""
if k == 0:
return logits
else:
values = torch.topk(logit... | bigcode/self-oss-instruct-sc2-concepts |
def getCommands(args):
"""Split (if needed) and obtain the list of commands that were sent into Skelebot"""
commands = []
command = []
for arg in args:
if arg == "+":
commands.append(command)
command = []
else:
command.append(arg)
commands.append(... | bigcode/self-oss-instruct-sc2-concepts |
def build_srcdict(gta, prop):
""" Build a dictionary that maps src to a property """
o = {}
for s in gta.roi.sources:
o[s.name] = s[prop]
return o | bigcode/self-oss-instruct-sc2-concepts |
def getValues(currentValues, current, total):
"""
Return either the current values (for this horizon) or all computed results
Parameters
----------
currentValues : Boolean
True: return 'current', False: return 'total'
current : Pointer
Pointer to the current values
total : ... | bigcode/self-oss-instruct-sc2-concepts |
def _GetInsertTime(operation):
"""Finds the insertTime property and return its string form.
Args:
operation: A messages.Operation instance.
Returns:
The time the operation started in string form.
"""
properties = operation.metadata.additionalProperties
for prop in properties:
if prop.key == 'i... | bigcode/self-oss-instruct-sc2-concepts |
def processFrame(frame):
"""Simulate a left and right sensor output (from 0 to 1) given the input image."""
# The pixels are grey-scale values from 0-255 - white = 255, black = 0
# We want to turn the image into two values, one for the left "sensor" and one for the right.
# There are many possible ways ... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def unixts_to_dt_obj(unixts):
"""
Convert unix timestamp to naive datetime object in UTC time zone.
:param float/int/str unixts: unix timestamp
:returns: datetime object in UTC timezone
"""
if isinstance(unixts, str):
try:
unixts = int(unixts)... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
import re
def parse_lxml_form(text):
""" Parse lxml form into a dictionary of name:value based on the 'input' tags in text"""
soup = BeautifulSoup(text, features="lxml")
form = {}
for inputtag in soup.find_all(re.compile("(INPUT|input)")):
name = inputtag.get("nam... | bigcode/self-oss-instruct-sc2-concepts |
def orbputx(orb, srcname, time, packet, nbytes):
"""Put a packet on an orb, returning the pktid of the output packet"""
return orb.putx(srcname, time, packet, nbytes) | bigcode/self-oss-instruct-sc2-concepts |
def make_slim_provenance_dict(model_type, slim_generation,
stage='late', spatial_dimensionality='', spatial_periodicity='',
separate_sexes=False, nucleotide_based=False):
"""
Returns a dictionary encoding provenance information for a SLiM tree sequence.
"""
document = {
"schema_v... | bigcode/self-oss-instruct-sc2-concepts |
def MAX(src_column):
"""
Builtin maximum aggregator for groupby
Example: Get the maximum rating of each user.
>>> sf.groupby("user",
... {'rating_max':tc.aggregate.MAX('rating')})
"""
return ("__builtin__max__", [src_column]) | bigcode/self-oss-instruct-sc2-concepts |
def builder_support(builder):
"""Return True when builder is supported. Supported builders output in
html format, but exclude `PickleHTMLBuilder` and `JSONHTMLBuilder`,
which run into issues when serializing blog objects."""
if hasattr(builder, 'builder'):
builder = builder.builder
not_sup... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
import copy
def get_object_camera_target(bullet_odicts: List[Dict], oidx: int):
"""Computes the position of the target for the camera to look at, for a
given object index.
Args:
bullet_odicts: A list of object dictionaries.
oidx: The object ... | bigcode/self-oss-instruct-sc2-concepts |
def get_content_of_sliding_window(image, abs_center, width, height, count=0):
"""Returns a width x height window where abs_center is the center."""
y_bottom = image.shape[0] - height*count
y_top = y_bottom - height
if y_top < 0:
return None
x_left = abs_center - round(width/2)
x_right ... | bigcode/self-oss-instruct-sc2-concepts |
def ctop(width, height, zx_coord, zy_coord, zxoff, zyoff, zoom):
"""
Converts complex space coordinates to actual pixel coordinates
(zxoff, zyoff are always the complex offsets).
"""
x_coord = (zx_coord + zxoff) * zoom * width / 2 / (width / height)
y_coord = (zy_coord + zyoff) * zoom * height ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def dont_document_data(config, fullname):
"""Check whether the given object should be documented
Parameters
----------
config: sphinx.Options
The configuration
fullname: str
The name of the object
Returns
-------
bool
Whether the data of `fullname` s... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _distance_matrix(x: torch.Tensor, eps_factor=1e2) -> torch.Tensor:
"""Naive dense distance matrix calculation.
Parameters
----------
x : torch.Tensor
Dense [n, d] tensor containing the node attributes/embeddings.
eps_factor : [type], optional
Factor to be multipli... | bigcode/self-oss-instruct-sc2-concepts |
def box(text: str, lang: str = "") -> str:
"""Get the given text in a code block.
Parameters
----------
text : str
The text to be marked up.
lang : `str`, optional
The syntax highlighting language for the codeblock.
Returns
-------
str
The marked up text.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def set_true_for_empty_dict(d):
"""
Recursively set value of empty dicts from a dictionary.
For some of entity G Suite API return {} (blank dictionary) which indicates some actions on resource.
Eg. Here, new or upload indicates resource is newly created or uploaded on the server.
{
"new": {}, /... | bigcode/self-oss-instruct-sc2-concepts |
def add_three(a):
"""Return a + 3.
"""
return a + 3 | bigcode/self-oss-instruct-sc2-concepts |
def get_line_msg(line):
"""Return message part of a line."""
return line.split()[2] | bigcode/self-oss-instruct-sc2-concepts |
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:ret... | bigcode/self-oss-instruct-sc2-concepts |
def check_interval_intersection(t1a, t1b, t2a, t2b):
"""
Determine if the intervals (t1a, t1b) and (t2a, t12b) intersect.
"""
if min(t1a, t1b) < t2a and max(t1a, t1b) > t2a:
return True
elif min(t1a, t1b) < t2b and max(t1a, t1b) > t2b:
return True
elif min(t2a, t2b) < t1b and max... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _parse_frame_name(fname: str) -> Tuple[int, int]:
"""Use the name of a frame file to infer its initial timestamp and length
Expects frame names to follow a standard nomenclature
where the name of the frame file ends {timestamp}-{length}.gwf
Args:
fname:
... | bigcode/self-oss-instruct-sc2-concepts |
def is_velocity_transitions(filename):
"""
Tests whether the given file is a velocity histogram file.
:param str filename: Name of the file to check.
:return: Whether the file is a velocity histogram file.
:rtype: bool
"""
with open(filename, "rb") as file:
return file.read(4) =... | bigcode/self-oss-instruct-sc2-concepts |
def opAll(operator, *numbers):
"""opAll(op, numbers) --> Based on the first arg operator, the function applies to the given set of numbers.
Parameters:
op: Operator: + or - or * or /
numbers: Any length of numbers
Returns:
A floating point number
"""
numbers = list(numbers)
res = ... | bigcode/self-oss-instruct-sc2-concepts |
def padlist(list_to_pad, padlen, pad_token=0):
"""
Pads a list with pad_token
Args:
list_to_pad: a list of str / int / float, each entry represents the token / token id
padlen: int, max length of the expected list, list_to_pad would either be truncated or padded to this length
pad_to... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def find_extension_file() -> Path:
"""Find the packaged extension file."""
paths = list(Path("web-ext-artifacts/").glob("*.zip"))
if len(paths) < 1:
raise ValueError("Can't find extension file. Run `yarn build`.")
elif len(paths) > 1:
raise ValueError("Found mu... | bigcode/self-oss-instruct-sc2-concepts |
def cnt_ovlp_occur(string, sub):
"""
Count overlapping occurrence of `sub` in `string`. E.g. `cnt_ovlp_occur("CCC", "CC")` would return 2.
Python's `str.count(word)` function does NOT count overlapping occurrence. E.g. "CCC".count("CC") only returns 1.
:param string:
:param sub:
:return:
"... | bigcode/self-oss-instruct-sc2-concepts |
def clamp(value, parameter):
""" Clamp value to parameter's min and max values
"""
value = parameter.min if value < parameter.min else value
value = parameter.max if value > parameter.max else value
return value | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_async_def_coroutine(what):
"""
Returns true for any coroutine produced by an ``async def`` function.
"""
return inspect.iscoroutine(what) | bigcode/self-oss-instruct-sc2-concepts |
def readlines(var, skip_empty_lines = True):
"""Read the lines from a file"""
ret = []
with open(var) as fvar:
for line in fvar:
line = line.rstrip('\n\r')
if not line and skip_empty_lines:
continue
ret.append(line)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def polyMulti( x, y ):
"""
Provede vzájemné pronásobení dvou polynomů reprezentovaných jako pole.
Například [1, 1] značí polynom x + 1.
Parametry:
----------
x: list
První polynom
y: list
Druhý polynom
Vrací:
------
list
V... | bigcode/self-oss-instruct-sc2-concepts |
from passlib.hash import sha256_crypt
def create_elog_password_hash(password):
"""Create a SHA256 encrypted password for ELOGs."""
return sha256_crypt.encrypt(password, salt="", rounds=5000)[4:] | bigcode/self-oss-instruct-sc2-concepts |
def date_to_string(date):
"""
Convert datetime object to string in %Y-%m-%d format.
"""
return date.strftime('%Y-%m-%d') | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pack_sequence_for_linear(inputs, lengths):
"""
:param inputs: [B, T, D]
:param lengths: [B]
:return: [sum(batch lengths), D]
"""
batch_list = []
for i, l in enumerate(lengths.tolist()):
batch_list.append(inputs[i, :l])
packed_sequence = torch.cat(batch_list... | bigcode/self-oss-instruct-sc2-concepts |
def separate_channels(x):
"""
Separates the two channel of the tensor passed as argument into two different tensors
"""
x1 = x[:, 0:1, :, :]
x2 = x[:, 1:2, :, :]
return x1, x2 | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_characters_again(string: str) -> str:
"""Returns string with all recurring characters removed."""
return ''.join(set(string.lower())) | bigcode/self-oss-instruct-sc2-concepts |
def normalize(columns_values):
""" Normalize the column values from 0 to 1. """
max_val = max(columns_values)
min_val = min(columns_values)
if max_val == min_val: # Avoid dividing by zero
return columns_values
return [(val-min_val) / (max_val-min_val) for val in columns_values] | bigcode/self-oss-instruct-sc2-concepts |
import functools
def dot(v1, v2):
"""Dot product(inner product) of v1 and v2
v1, v2 - python list
Return v1 dot v2
"""
elementwise_multiply = list(map((lambda x, y: x * y), v1, v2))
return functools.reduce((lambda x, y: x + y), elementwise_multiply) | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_params_from_signature(f):
"""
Fetches the params tuple list from the given function's signature.
"""
sig = inspect.signature(f)
return list(sig.parameters.values()) | bigcode/self-oss-instruct-sc2-concepts |
def _check_if_user_role_exists(client, user_id):
"""Returns True if User with user_id already exists."""
key = client.key("UserRole", user_id)
entity = client.get(key)
return entity is not None | bigcode/self-oss-instruct-sc2-concepts |
def boundaries2d(q, g, form="periodic"):
"""
Apply boundary conditions
Parameters
----------
q : array of float
The solution, correct in the interior
g : Grid
Information about the grid
form : string, optional
The type of boundary condition to impose. The default is ... | bigcode/self-oss-instruct-sc2-concepts |
def easyCommand(function, args):
"""
Easy wrapper to create a string representation of function calls
:param function: the function should be called
:param args: list of all the arguments for the function
:returns: str -- string representation to be passed to *exec*
"""
text = str(function... | bigcode/self-oss-instruct-sc2-concepts |
def get_node_type_key(op):
"""Get node_def type key."""
ntype = None
if 'T' in op.node_def.attr:
ntype = 'T'
if 'Tidx' in op.node_def.attr:
ntype = 'Tidx'
return ntype | bigcode/self-oss-instruct-sc2-concepts |
def fullname(clazz):
"""
Return fully qualified name of the given class.
>>> from collections import Counter
>>> fullname(Counter)
'collections.Counter'
"""
clazz_name = clazz.__name__ if hasattr(clazz, '__name__') else clazz._name
return f'{clazz.__module__}.{clazz_name}' | bigcode/self-oss-instruct-sc2-concepts |
import torch
def logistic(x):
"""
The logistic, inverse logit, or sigmoid link function given by
$$ y = \\frac{1}{1 + e^{-x}} $$
"""
return 1.0/(1.0+torch.exp(-x)) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def Sha1Checksum(payload):
"""Returns the SHA1 checksum of the given byte sequence.
Args:
payload: bytes
Returns:
str
"""
m = hashlib.sha1()
m.update(payload)
return m.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_indentation(text, spaces):
"""
Remove at most n leading spaces from each line.
>>> remove_indentation('foo\\n bar\\n baz\\n barbaz', 2)
'foo\\nbar\\nbaz\\n barbaz'
"""
if spaces == 0:
return text
else:
return re.sub(f'^[ ]{{1,{spaces}}}(.*?)$', '\\... | bigcode/self-oss-instruct-sc2-concepts |
def has_duplicates(n):
""" Check if the given list has unique elements
Uses the property of sets:
If converted into a set it is guaranteed to have unique elements.
-> Compare number of elements to determine if the list contains duplicates
"""
if type(n) is not list:
raise Ty... | bigcode/self-oss-instruct-sc2-concepts |
import struct
import binascii
def make_chunk(type, data):
"""Create chunk with @type and chunk data @data.
It will calculate length and crc for you. Return bytes.
@type is str and @data is bytes.
"""
out = struct.pack("!I", len(data))
data = type.encode("latin-1") + data
crc32 = binascii... | bigcode/self-oss-instruct-sc2-concepts |
def longest_bar_len(bars_in_frames):
"""
DEPRECATED
Returns the size of the longest bar among all, in number of frames.
Parameters
----------
bars_in_frames : list of tuples of integers
The bars, as tuples (start, end), in number of frames.
Returns
-------
max_len : integer... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def md5sum(file):
"""Calculate the md5 checksum of a file-like object without reading its
whole content in memory.
>>> from io import BytesIO
>>> md5sum(BytesIO(b'file content to hash'))
'784406af91dd5a54fbb9c84c2236595a'
"""
m = hashlib.md5()
while True:
d = fi... | bigcode/self-oss-instruct-sc2-concepts |
def _transform_literal_to_expression(expression, node, context):
"""Transform a Literal compiler expression into its SQLAlchemy expression representation.
Args:
expression: expression, Literal compiler expression.
node: SqlNode, the SqlNode the expression applies to.
context: Compilatio... | bigcode/self-oss-instruct-sc2-concepts |
def _midi_to_hz(midi_note, tuning_deviation):
"""Function to convert MIDI to Hz with certain tuning freq
Args:
midi_note (float): note represented in midi value
tuning_deviation (float): deviation in cents with respect to 440Hz
Returns:
(float): note in Hz considering the new tunin... | bigcode/self-oss-instruct-sc2-concepts |
def counter_to_list(counter):
"""
Convert a Counter object to a list of elements. For each entry (element, count), the element 'element' is added
'count' times to the list.
:counter: The Counter object.
:return: The list of elements.
"""
return list(counter.elements()) | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_yaml_file(path):
"""Open a YAML file, read it and return its contents."""
with open(path) as fh:
return yaml.safe_load(fh) | bigcode/self-oss-instruct-sc2-concepts |
def job_has_params(job_url):
"""
Determin weather a Jenkins job accepts build parameters
"""
name = job_url.rstrip("/").rsplit("/")[-1]
if name in (
"pr-docs",
"pr-lint",
"pr-pre-commit",
):
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def topic_name(project, name):
"""Get topic name."""
return 'projects/{project}/topics/{name}'.format(project=project, name=name) | bigcode/self-oss-instruct-sc2-concepts |
import copy
def apply_PI_params(model, fitted, input_matrix, output_matrix, target, exog, forecast_horizon):
"""
Calculate custom prediction interval --> Confidence intervals are used as model parameters.
Intervals are added to the forecast.
Parameters
----------
model : statsmodels.tsa.state... | bigcode/self-oss-instruct-sc2-concepts |
def create_task_descriptor( name, arguments ):
"""
Decouples the structure of a task descriptor from code outside this
module. Don't count on the returned object having a consistent type or
format.
@param name Task identifier
@param arguments Arguments to pass to the task
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def check_unique(item, array: list) -> bool:
"""Returns True if an item is not in a list
:parameter item: Checks item against a list
:type item: any
:parameter array: List to be checked against
:type array: list
:return: True if an item is not in a list
:rtype: bool
... | bigcode/self-oss-instruct-sc2-concepts |
def insertion_sort(arr):
"""
The function insertion_sort() sorts the given list using insertion sort algorithm.
The function returns the list after sorting it.
Arguments
arr : An unsorted list.
"""
for x in arr[1:]:
for y in arr[arr.index(x)-1::-1]:
if x < y:
... | bigcode/self-oss-instruct-sc2-concepts |
def _build_atom_unique_id(atom_line):
"""Returns a unique identifying tuple from an ATOM line"""
# unique_id: (name, altloc, resi, insert, chain, segid)
unique_id = (atom_line[12:16],
atom_line[16],
int(atom_line[22:26]),
atom_line[26], atom_line[21],
... | bigcode/self-oss-instruct-sc2-concepts |
def rr(y_true):
"""Return the reciprical rank of the first positive candidate."""
for index in range(0, len(y_true)):
if y_true[index]:
return 1.0 / (index + 1)
return 0.0 | bigcode/self-oss-instruct-sc2-concepts |
import re
def shallow_word_segment(phrase):
"""segments the words and numbers from a string phrase. Does a shallow word segmentation method using regex
Examples: u'ãbacon_abcd $123g' -> [u'ãbacon', u'abcd', u'123g']
Args:
phrase (str): phrase that has multiple words
Returns:
([str]): ... | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates(li):
"""Removes duplicates of a list but preserves list order
Parameters
----------
li: list
Returns
-------
res: list
"""
res = []
for e in li:
if e not in res:
res.append(e)
return res | bigcode/self-oss-instruct-sc2-concepts |
import re
def camelCase(string: str) -> str:
"""Convert a string into camel case
Args:
string (str): the string to convert
Returns:
str: the camel case version of the string
"""
string = re.sub(r"(_|-|\.)+", " ", string).title().replace(" ", "")
return string[0].lower() + st... | bigcode/self-oss-instruct-sc2-concepts |
def surround(string):
"""Surrounds a string with curly brackets, square brackets, and a space.
:param string: String to be surrounded
:type string: str
:return: Surrounded string
:rtype: str"""
return "{[ " + string + " ]}" | bigcode/self-oss-instruct-sc2-concepts |
def argsort(seq):
""" Stable version of argsort """
# http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3382369#3382369
return sorted(range(len(seq)), key=seq.__getitem__) | bigcode/self-oss-instruct-sc2-concepts |
def iterable(obj) -> bool:
"""
Determines if this object satisfies the iterable interface, which
requires it to support either ``__iter__`` or ``__getitem__``.
"""
return hasattr(obj, '__iter__') or hasattr(obj, '__getitem__') | bigcode/self-oss-instruct-sc2-concepts |
def apply_permutation(cm, perm):
"""
Apply permutation to a matrix.
Examples
--------
>>> cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
>>> perm = np.array([2, 0, 1])
>>> apply_permutation(cm, perm)
array([[8, 6, 7],
[2, 0, 1],
[5, 3, 4]])
"""
return cm[... | bigcode/self-oss-instruct-sc2-concepts |
def datetime64_to_inttime(var):
"""
Return an "inttime" representing a datetime64.
For example, 2016-09-29 as an "inttime" would be 20160929
An 'inttime' is used in statistics which return an actual
observation to represent the date that observation happened.
It is a relatively compact represen... | bigcode/self-oss-instruct-sc2-concepts |
def is_leap_year(year):
"""
Returns whether a year is a leap year
- Leap years are any year that can be exactly divided by 4
- Except if it can be divided exactly by 100 then it isn't
- But if it can be divided exactly by 400 then it is a leap year
"""
if (year % 4 == 0 and year ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def coerce_to_number(ticket_value):
"""Coerce the input into a number.
If the input is a number, return itself. Otherwise parses input strings of two forms.
'SERVER-12345' and '12345' will both return 12345'.
"""
if isinstance(ticket_value, int):
return ticket_value
ticket_... | bigcode/self-oss-instruct-sc2-concepts |
def linmag(vali, magstart, magend, dur):
"""
funciton for generating a ramp of values that is linear in magnification
vali: initial value (globally)
magstart: magnification at the start of the ramp
magend: magnification at the end of the ramp
dur: number of steps (duration)
"""
out = []
... | bigcode/self-oss-instruct-sc2-concepts |
def mask_characters(expression, search_text, target_text, mask_char):
"""Mask characters found by a regular expression with mask character. Mask characters will equal length of masked
string.
A different target text to search text may be used, but the developer must ensure that they are compatible.
This... | bigcode/self-oss-instruct-sc2-concepts |
def get_version(path):
"""Get __version__ from Python file."""
with open(path, "rt") as f:
for line in f:
if line.startswith("__version__ = "):
return line.strip().split(" = ")[1].strip("\"'") | bigcode/self-oss-instruct-sc2-concepts |
def get_assist_turnover_ratio(assists, turnovers):
"""
Calculates the ratio of assists to turnovers.
:param assists: Number of assists.
:param turnovers: Number of turnovers.
:return: The ratio
:rtype: float
"""
try:
ratio = float(assists) / turnovers
except ZeroDivisionErro... | bigcode/self-oss-instruct-sc2-concepts |
def _GetMachineInfoPlistValue(key):
"""Returns value of given key in the machineinfo plist, or '' if not found."""
return '' | bigcode/self-oss-instruct-sc2-concepts |
def is_active(obj, now):
"""Determine if an object is active."""
if not obj.start or obj.start <= now:
if not obj.end or obj.end >= now:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def fmt_datetime(datestr):
"""
Reformats a date/time string so that it avoids any special characters.
:param datestr: a string representing a date/time in 'YYYY-mm-dd HH:MM:SS'
or 'YYYY-mm-ddTHH:MM:SS' format
:returns: a string representing a date/time... | bigcode/self-oss-instruct-sc2-concepts |
def filter_username(username) -> str:
"""
Removes '/u/' and 'u/' from a username.
:return: The filtered username.
"""
return username.replace("/u/", "").replace("u/", "") | bigcode/self-oss-instruct-sc2-concepts |
def format(self, ndigit="", ftype="", nwidth="", dsignf="", line="",
char="", **kwargs):
"""Specifies format controls for tables.
APDL Command: /FORMAT
Parameters
----------
ndigit
Number of digits (3 to 32) in first table column (usually the node
or element number). In... | bigcode/self-oss-instruct-sc2-concepts |
import posixpath
def normalize(path):
"""We use posixpath.normpath to support cross-platform path format.
However, it doesn't handle None input. So we wrap it up."""
if path is None:
return None
return posixpath.normpath(path) | bigcode/self-oss-instruct-sc2-concepts |
import time
from functools import wraps
import logging
def retry(ExceptionToCheck, tries=4, delay_s=1, backoff=2):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/Pyt... | 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.