content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _get_yearly_logical_year(year, month, day):
# type: (int, int, int) -> int
"""Retrieves the logical year for a yearly frequency."""
return year | 28e7e5a9554bf3d572f976238a8d65553435fb22 | 634,393 |
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) | 9efa9da631de0eb9cb65fff53748f0fba51dd927 | 634,394 |
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 | 4c63286304337d9384da638217d5970d6254fc88 | 634,397 |
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 ... | 099e96005ddac741b031ed28995f8becf02c0e4b | 634,398 |
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... | eda636232ae3d37feeb1d290e76fb795a061189b | 634,399 |
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:
... | e0e0c4e780b2384e622428d0f883b1d4435ae74e | 634,402 |
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", ""),
)
) | f3be6a0e77e84715317d7233523b01ff5de92ce5 | 634,407 |
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... | 2e24f430629fb00baf0723c7f03147c19b484e67 | 634,409 |
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(... | 84387d61b982a569e8a45f635a3da308833a6bf0 | 634,410 |
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 | bcbd50e9917a9000b46a98c16287a183f4e00cd3 | 634,413 |
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 : ... | ff067d3307a0d2d9849ff32de5954c3ff7b8a5ed | 634,415 |
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... | 9b7294f0ff94b6c375012fbcbb62bd4ea7698f64 | 634,417 |
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 ... | 35b3b302df17c151cfef2a942c1d81cb50baad94 | 634,418 |
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)... | 8e57c4e467ab2b5f8c388156752a02e03037d959 | 634,419 |
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... | 6f7e89f096718984c0a74130e26b530cd58c8467 | 634,424 |
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) | e15a39566aefdefd703272d7478c647078f9b32f | 634,428 |
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... | a1e1788dcb22ed2c593d8df7c604e165236a32f6 | 634,433 |
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]) | 59d030a07fafb6f254149d264b3a4feb9431ed28 | 634,434 |
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... | 3194c89ec2b4b86bf67ce7cb0deaefe832024b88 | 634,437 |
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 ... | 66075dc5447a45861612b710864c557cca6d2e42 | 634,440 |
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 ... | 44d773f1cce8576682ba75c89bc210dd111ca75e | 634,441 |
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 ... | 9b39dd13232b50725e59105d168d5e82f8c814c6 | 634,444 |
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... | dfe56e6cad36ecb978d2973efa0a313e4b75587e | 634,446 |
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... | bafe4c182101bbf161745aba11de549412bbbbfa | 634,449 |
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.
"""
... | fbea21841bd02ef627370c9d5541b01dce695492 | 634,450 |
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": {}, /... | a96a22ba7c725c13f4ce1b7210f755f9e8e603b9 | 634,453 |
def add_three(a):
"""Return a + 3.
"""
return a + 3 | b4cd93f76ef768578a9f81dfa9f17d163dac0a84 | 634,458 |
def get_line_msg(line):
"""Return message part of a line."""
return line.split()[2] | 7b0b98cf487b58ebe2da9ee2b422a54dab44f3e0 | 634,459 |
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... | 38a3ab5d6684174429d21474b9f5f7ee9bee86f9 | 634,461 |
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... | b6ed55eea625fbcc9e4787338d83cedc274c0f3a | 634,462 |
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:
... | 990b03cb1f20dbbb63724dc6e19f59c7787fa194 | 634,469 |
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) =... | c635049d3117b5414e62641e4c3d5f4cf46ce681 | 634,471 |
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 = ... | b4703303f33ce1b25e7d11101ffce431ed0b088e | 634,473 |
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... | 175b32a8457db6089625326465ea1d939c126b2b | 634,483 |
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... | bb56a4e823372cd62c841f657a4cd28b2d2705eb | 634,484 |
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:
"... | c862245c03c591cfecacc093b9bf2ca1cf426663 | 634,485 |
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 | 7bd154e9221c288810ab9470e37beca9cb58b068 | 634,490 |
import inspect
def is_async_def_coroutine(what):
"""
Returns true for any coroutine produced by an ``async def`` function.
"""
return inspect.iscoroutine(what) | c8528289e7ff707736f0d64683c7cb4e4372202f | 634,496 |
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 | 2bccf9f7313cdd588f737980f0f2fca8ccb0abad | 634,500 |
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... | f8ca4895d34d2996a06a39476fbe0affb41de314 | 634,501 |
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:] | c5bb119fd35fd98888d9d0681fb06915174f518b | 634,502 |
def date_to_string(date):
"""
Convert datetime object to string in %Y-%m-%d format.
"""
return date.strftime('%Y-%m-%d') | 258cc45caeacfc8d59a59f0a998383402bb2dcad | 634,505 |
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... | e8ff486a4a8689e1e6ad4eca8cfc2bab20c07d2a | 634,507 |
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 | 63b1ec6acc0c1d4d063e915b61391c3760cc9a96 | 634,510 |
def get_unique_characters_again(string: str) -> str:
"""Returns string with all recurring characters removed."""
return ''.join(set(string.lower())) | 164af772c826b8572daaac455424d8a0be9fd6df | 634,511 |
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] | 63b00822a177ffe25739b222af8771cd320c151e | 634,513 |
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) | f4cf8d461cc27fe8b8eb57be1b6f1e3e62aa4c24 | 634,514 |
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()) | 5524185e3989c1ec2663bfdb2baa37c3b9fba489 | 634,515 |
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 | 0105351792ae08d6d50ecf6193464345f353cdfe | 634,517 |
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 ... | 358305df256171e23cabc7d66870cf97797057f5 | 634,518 |
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... | 6e459b4153c88dcc59b5d14c458fe17dbc27d31a | 634,520 |
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 | c1e4693e7f59610c70dfd238d85b4570cc1ca643 | 634,521 |
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}' | 35262e7c2f9e5428745054aa3f0b4ff7107a7ef1 | 634,522 |
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)) | 07661305755174cda0afa240d5814d00c8bd121b | 634,523 |
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() | 669572e0a91b452c0ea54a63a3b48c6b0a510dec | 634,526 |
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}}}(.*?)$', '\\... | 5946e7c6129341250dd5599354b76fc6d5b351b6 | 634,527 |
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... | 64db6a2da62432ce2fe9de3a29764a6c5f5b58a0 | 634,530 |
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... | 37c1c7e3b5bd4fb07f0ff24cee6938e1a6b36d6d | 634,531 |
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... | a74625b3c6e2712a6db9d86244609c68f5eba7ee | 634,533 |
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... | 3152afac5f3b9c3013cf48687f09378505d38fa1 | 634,534 |
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... | e29cd6c6b4d704c2492dbcdc46099cc5c02b41d1 | 634,535 |
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... | d911675f25492a447b85d2caed77253f04d9bda0 | 634,537 |
import typing
def _generate_datetime_placeholder(schema: dict, path: typing.List[str]) -> typing.Union[dict, None]:
"""
Generates a placeholder datetime object based on an object schema.
:param schema: the sampledb object schema
:param path: the path to this subschema
:return: the generated objec... | 3d349a66446ff4cd9e477bd2810de9558c2717f1 | 634,539 |
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()) | 92b1c1113bda053140f62e02af28fc985f149851 | 634,540 |
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) | 97b7e310b6d195d80f766b9413eafe955d2e866c | 634,543 |
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 | 2247109e5e0d8815f3b1fca7be0fccd07d5d7c83 | 634,550 |
def topic_name(project, name):
"""Get topic name."""
return 'projects/{project}/topics/{name}'.format(project=project, name=name) | 0a0e04b0896624a1e6271a834815857309c043fe | 634,555 |
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... | e4b21be27f4f560e47eddd8811664e40087d167d | 634,557 |
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
"""
... | 0422c9f62c2d19890bbe8465c28ceb47f842a59c | 634,561 |
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
... | c4c08c4e63958f6a131cedcb6b20d07dad50be96 | 634,568 |
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:
... | 0c2df7b9ad7bd72f5f7ba26c5b1bc3babe6b30f6 | 634,569 |
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],
... | 8eca206b237fd4eecf6010306adb85c45af17c52 | 634,570 |
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 | cd666ba049649b9905ca96031c62478d1faa7726 | 634,571 |
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]): ... | 478791a0bfd460dc3a044c6f6ca2a52e5ea3f3fc | 634,576 |
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 | e74de8e6817dcab7e800b6d264a29a871245e8f7 | 634,577 |
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... | 71005731197cd54f9d0a905ba673d06d9f8ef36c | 634,579 |
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 + " ]}" | 1c1b2dad0231a4b663ce303b164ff645956d47b5 | 634,580 |
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__) | 9ccd0f2c3267dcec10db7c9e7668d5f3574050ea | 634,582 |
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__') | adcc62d32d488fe39449a7ba6d4d40ac28693af9 | 634,583 |
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[... | 6dc35a54da4970e86506e2215411957ebfcd1d6f | 634,584 |
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... | ba8d9ec2b76f52b581039226955321215a936251 | 634,585 |
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 ... | 23d850d2fa3a6c0ce430227569765e473a9d637a | 634,586 |
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_... | 4804a574f1830ee5410de6fda0e904ff13bc974e | 634,588 |
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 = []
... | 43cb211aafa36fd8cbc15649f4c2a092bec909e5 | 634,590 |
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... | 6f2ee6b799b4ff774f9850be6561e0e3a61e2deb | 634,591 |
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("\"'") | 7895c07653132fba7a62bc24c77e5050d584de7c | 634,595 |
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... | 6304ad6eadcbad71aff9efb89f3376f419390b77 | 634,597 |
def _GetMachineInfoPlistValue(key):
"""Returns value of given key in the machineinfo plist, or '' if not found."""
return '' | ce8a857607ca7cc22b54f788e46495b9f507da3d | 634,600 |
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 | 845300fb218de73385843141c0f30a8a15354f56 | 634,604 |
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... | f83fac1b253a910f86938036bf79ea4c3ecee489 | 634,608 |
def filter_username(username) -> str:
"""
Removes '/u/' and 'u/' from a username.
:return: The filtered username.
"""
return username.replace("/u/", "").replace("u/", "") | 95c548c30bfa8892063928c441ccc05cd94c40c7 | 634,613 |
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... | 4c01afdccc4066005a4db7d523ef1d13ccf74b36 | 634,616 |
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) | 15da149a56a98d1493e8730b1a3a772ef273a10b | 634,617 |
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... | a6aed596d7e2c2017bf33ff42a8ef44d7a85c265 | 634,618 |
def generate_artifact_link(owner: str, name: str) -> str:
"""Generate link for downloading artifacts
:param owner: Github repo owner name
:type owner: str
:param name: Github repo name
:type name: str
:returns: Link to api to download artifacts
:rtype: str
"""
return f"https://api.... | 5451141bd8905be6447f82224621580b8f3d3606 | 634,619 |
def get_route_edge_attributes(
G, route, attribute=None, minimize_key="length", retrieve_default=None
):
"""
Get a list of attribute values for each edge in a path.
Parameters
----------
G : networkx.MultiDiGraph
input graph
route : list
list of nodes IDs constituting the pa... | 2d3b8aeab2aebcbffc3fcbe177e139b30ae6e63f | 634,622 |
def compute_acc(pred, truth):
""" Compute accuracy """
return pred.max(dim=1)[1].eq(truth).sum() / len(pred) | a51015bf209bc9628314ab553b9e591fe7074106 | 634,623 |
def is_sorted(lst, le_cmp=None):
""" Check if a list is sorted
Args:
lst (:obj:`list`): list to check
le_cmp (:obj:`function`, optional): less than equals comparison function
Returns
:obj:`bool`: true if the list is sorted
"""
if le_cmp:
return all(le_cmp(a, b) for ... | cf7b0aae21238876641031be15fae40012b4bf08 | 634,627 |
def _get_column_width(max_value, decimals=5):
"""Get width of column to pass to :func:`numpy.savetxt`, accounting
for the decimal point and a sign +/-.
"""
return len(str(int(max_value // 1))) + decimals + 2 | c6330b5e7e579dbea360a7e77705b60a453c1a76 | 634,629 |
import torch
def cosine_similarity(v1, v2):
"""Cosine similarity [-1, 1].
Parameters
----------
v1, v2 : Tensor
Tensor with the same shape [batch_size, n_feature].
References
----------
- `Wiki <https://en.wikipedia.org/wiki/Cosine_similarity>`__.
"""
return torch.sum(t... | 09e179274e00ef29d83e5ba93077de5d02db86bb | 634,631 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.