content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def status_request(token):
"""Create ACME "statusRequest" message.
:param unicode token: Token provided in ACME "defer" message.
:returns: ACME "statusRequest" message.
:rtype: dict
"""
return {
"type": "statusRequest",
"token": token,
} | eb63269820aff9ef84cb67ef3348d1121be051f5 | 383,637 |
import pathlib
import click
def get_filenames_from_template(photo, filename_template, original_name):
""" get list of export filenames for a photo
Args:
photo: a PhotoInfo instance
filename_template: a PhotoTemplate template string, may be None
original_name: boolean; if True, use pho... | ce392d636262a59f8bc7cb6f14948c9bdb4f0acc | 393,387 |
from pathlib import Path
def path_join(*other):
"""Add each of other argumetns to path in turn"""
return Path().joinpath(*other) | b1c71ddf423dd2852cb3de4f368761415a584be7 | 524,314 |
def first(element):
"""
A wrapper around element[0].
params:
element: an element that implements __getitem__
"""
return element[0] | e6014c95616e4a95644833deeed01a670649cc94 | 377,105 |
import typing
def trace_lines_model_checking_mode(stdout) -> typing.List[typing.List[str]]:
"""
Returns list of lists. Each sublist is a list of lines
that make a trace.
Args:
stdout : stdout of TLC execution run in model checking mode
"""
ret = []
lines = stdout.split("\n")
h... | 26b57ee29370a764b51961d672c5969050dccb85 | 680,500 |
import click
def format_options(original_function=None, headers=None):
"""Shared output format options."""
def _format_options(f):
f = click.option('--format', '-f', 'fmt', default=None,
type=click.Choice(['simple', 'table', 'csv']),
help="Output form... | c4caed905f16e570abda4893b6c49e9296991c73 | 261,502 |
def bbox_to_list(bbox_string):
"""
Convert bounding box passed in as string such as:
"[0.536007, 0.434649, 0.635773, 0.543599]" to list of floats
"""
bbox = bbox_string.strip('][').split(', ')
bbox = [float(x) for x in bbox]
return bbox | a1d24730dad42312c9ef9f7541cbf906885202ca | 266,406 |
def mydub(a):
"""Double a
"""
return a * 2 | bf039316d510db53264ab435e5092477bd57e397 | 648,533 |
def R_curv(deltaT_sub, r_min, radius, Q_drop):
""" thermal resistance due drop curvature
Parameters
----------
deltaT_sub: float
temperature difference to the cooled wall in K
r_min: float
minimum droplet radius in m
radius: float
... | 176520b43184e879bb25bcecc50e64e6dabaa6cc | 10,754 |
import torch
import logging
def get_device() -> torch.device:
"""Gets device to use for PyTorch.
Returns:
Device.
"""
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
logging.info("Model device: %s", device)
return device | 587c03df06dc38fe4cd939faa42aeb92377234ed | 451,064 |
def _host_absolute(name):
"""
Ensure that hostname is absolute.
Prevents us from making relative DNS records by mistake.
"""
if not name.endswith("."):
name = name + "."
return name | 0569be8577063cbbecbed9bc860f686e2080c92b | 209,694 |
def lookup_password(words, uhpd):
"""
lookup_password(words, (user, host, port, database)) -> password
Where 'words' is the output from pgpass.parse()
"""
user, host, port, database = uhpd
for word, (w_host, w_port, w_database, w_user) in words:
if (w_user == '*' or w_user == user) and \
(w_host == '*' or w... | 33f68e19e18faeef461c0e9c24f7df680c8b0945 | 112,122 |
def is_eligible_for_exam(mmtrack, course_run):
"""
Returns True if user is eligible exam authorization process. For that the course must have exam
settings and user must have paid for it.
Args:
mmtrack (dashboard.utils.MMTrack): a instance of all user information about a program.
course... | 2ee804ac8f338186bd543584b207cde440a109c5 | 678,337 |
def invert_mapping(kvp):
"""Inverts the mapping given by a dictionary.
:param kvp: mapping to be inverted
:returns: inverted mapping
:rtype: dictionary
"""
return {v: k for k, v in list(kvp.items())} | 62c16608b83d9a10fe30930add87b8d73ba5e1cd | 63,516 |
def get_armstrong_value(num):
"""Return Armstrong value of a number, this is the sum of n**k
for each digit, where k is the length of the numeral.
I.e 54 -> 5**2 + 4**2 -> 41.
Related to narcisstic numbers and pluperfect digital invariants.
"""
num = str(num)
length = len(num)
armstrong_... | fd0692566ab0beffb785c1ac4fbd4aa27893cfbf | 41,523 |
def get_element_text(element):
"""Builds the element text by iterating through child elements.
Parameters
----------
element: lxml.Element
The element for which to build text.
Returns
-------
text: str
The inner text of the element.
"""
text = ''.join(element.iterte... | 41409e83a23927a5af0818c5f3faace0ca117751 | 17,234 |
def rc4(buffer, key):
"""
Encrypt / decrypt the content of `buffer` using RC4 algorithm.
Parameters
----------
buffer : bytes
The bytes sequence to encrypt or decrypt.
key : bytes
The key to be used to perform the cryptographic operation.
Returns
-------
A by... | d6b737e74c1ed04f45f783781307e1f5aca58509 | 145,167 |
import math
def floor(quantity, units):
"""Compute the floor of a quantity with units.
:param quantity: the quantity to take the ceiling of
:param units: the units to convert to before taking the ceiling, and of the result
:returns: the ceiling of quantity, measured in units
"""
number = quan... | 723e4f2816c375b481b2fcf32be627a5f786d114 | 324,770 |
def case_sort(string):
"""
Here are some pointers on how the function should work:
1. Sort the string
2. Create an empty output list
3. Iterate over original string
if the character is lower-case:
pick lower-case character from sorted string to place in output list
else:
... | 70391df1faaba08f0d596a6bd401c80d30fa8923 | 547,452 |
def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop'])
return status.split(None, 1)[0].lower() in mutating | 76c45a300773afe1313c1be36c07bc23b37c06f3 | 448,047 |
def merge(dict1,dict2):
"""
Returns a new dictionary merging (joining keys) dict1
and dict2.
If a key appears in only one of dict1 or dict2, the
value is the value from that dictionary. If it is in
both, the value is the sum of values.
Example: merge({'a':1,'b':2},{'b':3,'c':4}) returns
... | e542c33d84611485c8c18087d5bdad71e052749b | 140,572 |
def _remove_lines_starting_with(string, start_char):
"""
Utility function that removes line starting with the given character in the
provided str.
:param data: the str to remove lines.
:param start_char: the character to look for at the begining of a line.
:returns: the string without the line... | 59092b26601fe2b1e0038c21b1fc827dc8ce0fb8 | 60,458 |
def _default_converter(cls, value):
"""A default converter method that tries to deserialize objects."""
if isinstance(value, dict):
return cls.from_jsonld(value)
return value | 12be1c65e413e2670e82a78dde096bb3a94f5078 | 552,935 |
def add_separator_argument(parser):
"""Add argument for setting table separator comma or tab
"""
parser.add_argument(
'-s', '--sep', choices=['TAB', ','], default='TAB',
help="Specify the field separator character in the library metadata file"
)
return parser | ba90c3bfa746329d6f42ee4d5ba48eddfe1f9ac6 | 394,814 |
def get_log_extra_item(log, item):
"""Returns an extra item from the logging object."""
return log.extra.get(item, 'unknown') | 6e60d685eb28c7a37984043e1bb28d546303aab7 | 285,275 |
import requests
def gce_get_metadata(path):
"""Queries the GCE metadata server the specified value."""
return requests.get(
'http://metadata/computeMetadata/v1/{}'.format(path),
headers={
'Metadata-Flavor': 'Google'
}
).text | 4cc6952275e27ee1317f9b6a7c70fadf155235af | 394,381 |
def luminance_newhall1943(V, **kwargs):
"""
Returns the *luminance* :math:`R_Y` of given *Munsell* value :math:`V`
using *Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd (1943)*
method.
Parameters
----------
V : numeric
*Munsell* value :math:`V`.
\*\*kwargs : \*\*, optio... | 3806a6957aaca700f3f3477eaa33746b37c33249 | 671,322 |
import typing
from typing import TypeGuard
import asyncio
def is_async_iterator(obj: typing.Any) -> TypeGuard[typing.AsyncIterator[object]]:
"""Determine if the object is an async iterator or not."""
return asyncio.iscoroutinefunction(getattr(obj, "__anext__", None)) | 160d1dd2d5f1c9d6d2637e6006ae0ef268c7810f | 32,050 |
import functools
import time
def profile(func):
"""Record the runtime of the decorated function"""
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start = time.perf_counter_ns()
value = func(*args, **kwargs)
stop = time.perf_counter_ns()
print(f'{func.__name__} :... | d8b1d92c033a3033fd4171c5a3dda1087a7643f0 | 354,819 |
def ctof(temp_c):
"""Convert temperature from celsius to fahrenheit"""
return temp_c * (9/5) + 32 | 4357cb6d355d14c11b21bfe0bd4efc5c1e3b4703 | 49,167 |
def human_readable_size(filesize=0):
"""
Converts number of bytes from *filesize* to human-readable format.
e.g. 2048 is converted to "2 kB".
# Parameters:
filesize (int): The size of file in bytes.
# Return:
str: Human-readable size.
"""
for unit in ["", "k", "M", "G", "T", "P"]:... | 37e54c9622394114c91059ed7c9236a8403c6a2f | 144,217 |
def _create_database_sql(database_name):
"""Return a tuple of statements to create the database with the given name.
:param database_name: Database name
:type: str
:rtype: tuple
"""
tmpl = "create database {} with owner = dcc_owner template = template0 " \
"encoding = 'UTF8' lc_collat... | 48fc179d282750d162eb7544cf4b594d0e2f0729 | 645,176 |
import logging
def logger() -> logging.Logger:
"""Initialize a default logger for tests."""
log = logging.getLogger("test-logger")
log.setLevel(logging.CRITICAL)
return log | 5e9f16998ec674eac19d25fc3bc45e68b7f14670 | 528,792 |
def unhex(s):
"""unhex(s) -> str
Hex-decodes a string.
Example:
>>> unhex("74657374")
'test'
"""
return s.decode('hex') | dcf2d6cd9c317b5eafd77e969272fcf753556403 | 694,014 |
def _column_number_to_letters(number):
"""
Converts given column number into a column letters.
Right shifts the column index by 26 to find column letters in reverse
order. These numbers are 1-based, and can be converted to ASCII
ordinals by adding 64.
Parameters
----------
number : int... | c9a68bcd32c8f254af322bc61e447cfae61cb6d2 | 705,080 |
def wern_after_distillation(wA, wB):
"""Calculates the Werner parameter and success probabililty of distillation.
Parameters
----------
wA : float
Werner parameter of one of the two links.
wB : float
Werner parameter of the other link.
Returns
-------
Tuple (wern, prob)... | 5ec9a84f08e823160b1365fef1de8b1811d053c3 | 468,546 |
def matrix_dot(mat1, mat2):
"""Inner product for matrices
Compute the inner product between matrices as:
.. math:: \\mathrm{Trace}(M_1^T M_2)
Parameters
----------
mat1: 2d array
First matrix
mat2: 2d matrix
Second matrix
Returns
-------
dot: float
The matrix inner product.
"""
return (mat1 *... | 85581405b51c1c13efb57da80a22e88322a38cea | 533,051 |
import socket
def bindsocket(port, host=''):
"""
Creates a socket assigned to the IP address (host, port).
Parameters
----------
port : int
port assigned to the socket.
host : str, optional
host assigned to the socket. The default is ''.
Returns
-------
tcpsock : ... | 48be29952a3d35af0ec0886e3ca332f9280384f1 | 13,175 |
def get_folders_from_params(advanced_args):
"""
Extracts and returns the list of file hash IDs from the input `advanced_args`. `folders` is an
expected property on `advanced_args`, if it does not exist, or it is empty, then an empty list
is returned instead.
"""
try:
if advanced_args['fo... | e74a57435c4e14c109f1c7905a65cb0315f7aa5f | 196,211 |
def file_system_arn(arn):
"""
Converts an ARN to a file-system friendly string, so that it can be used for directory &
file names
"""
for source, dest in {":": "#", "/": "_", " ": "_"}.items():
arn = arn.replace(source, dest)
return arn | 2c355a91e48a5ad87682e945d37f3b9c61311e46 | 44,528 |
def intensity( rgb ):
""" Returns the average value of the rgb pixel data.
Inputs:
-- rgb: rgb pixel array in the form [b,g,r]
Returns: average of the three values
"""
return int( (rgb[0] + rgb[1] + rgb[2])/3 ) | 31ee4138a9eca0d80e444bedd767c33e1911582f | 443,262 |
def get_area_rect(length, width):
"""Returns area of rectangle
>>> get_area_rect(5 , 5)
25
>>> get_area_rect(5 , 0)
Traceback (most recent call last):
...
ValueError
>>> get_area_rect(5 , -1)
Traceback (most recent call last):
...
V... | 6df6d1f075c4ff832800f88c0549555a29f65965 | 463,118 |
def reduceTuple(input_list):
""" Idea taken from https://www.geeksforgeeks.org/python-group-tuples-in-list-with-same-first-value/ """
out = {}
for elem in input_list:
try:
out[elem[0]].extend(elem[1:])
except KeyError:
out[elem[0]] = list(elem)
return [tu... | 099bee5a58ad70aa03123b28113c3c9d2170263a | 552,808 |
def team_created_payload(team_default_payload):
"""Provide a team payload for creating a team."""
created_payload = team_default_payload
created_payload["action"] = "created"
return created_payload | 105de6e28e2ff66f13289a5d67b406f3397f4fcf | 335,483 |
from typing import Union
def hex_colour(colour: Union[str, int]) -> str:
"""
Converts the given representation of a colour to its RGB hex string.
As we are using a Discord dark theme analogue, black colours are returned as white instead.
"""
if isinstance(colour, str):
colour = colour if ... | 07512010c2b4a44ead8761b89ee648de7286dcf9 | 419,178 |
import torch
def reserve_nn_scores(similarities, nn_num):
"""Reserver top-k nearest neighbors' similarity scores
Args:
similarities (Matrix): test_num * train_num
Returns:
nn_scores (Matrix): only keep the scores of the top-k nearest neighbors
"""
scores = torch.FloatTens... | b3da2563c0ac56c9428167f7f6bb992556d826ce | 60,195 |
def oneVoxelNoise(data, loc, scale=1.1):
"""applies 1-voxel scaling to the provided image matrix
The noise introduced is equivalent to a point magnification at the location
provided with scaled intensity equal to the value provided (default value is
an increase in intensity by 10%).
The location p... | eadf4383f5db6c7eb760f0acd6e487f5bb2fce5c | 91,475 |
def _bytes_bytearray_to_str(s):
"""If s is bytes or bytearray, convert to a unicode string (PRIVATE)."""
if isinstance(s, (bytes, bytearray)):
return s.decode()
return s | 675c9658b3512dbb9facbf865fe416a27c6dfd07 | 261,013 |
def unquote(s):
"""Strip single quotes from the string.
:param s: string to remove quotes from
:return: string with quotes removed
"""
return s.strip("'") | 15d29698e6a3db53243fc4d1f277184958092bc6 | 7,561 |
def get_daily_thread(subreddit):
"""return submission containing 'daily' in the title"""
for submission in subreddit.hot(limit=5):
if "daily" in submission.title.lower():
return submission | 6935290237f1d6e414182c5592beecb455a410b2 | 342,208 |
def parse_host(host):
"""
Parse *host* in format ``"[hostname:]port"`` and return :class:`tuple`
``(address, port)``.
>>> parse_host('localhost:4444')
('localhost', 4444)
>>> parse_host(':4444')
('', 4444)
>>> parse_host('4444')
('', 4444)
>>> parse_h... | 7afa0ae098ba8161cc561ea9c75b057f93878806 | 342,925 |
import math
def radial_collide(item1, item2):
""" item1 and item2 are 3-tuples in the format of
(x, y, radius) for each object to test
"""
x_diff = item1[0] - item2[0]
y_diff = item1[1] - item2[1]
hit_radius = item1[2] + item2[2]
return math.hypot(x_diff, y_diff) < hit_radius | 0e58976d9eae2565a8af46159b33d8538682e400 | 154,755 |
def boolean_color(mask, true_color='black', false_color='white',
name="face_color"):
"""Return a Series with colors replacing True and False."""
_mask = mask.copy()
result = _mask.apply(lambda x: true_color if x == True else false_color)
result.name = name
return result | 58c9b08e14d74cb244a42a39aa7513b26a706a66 | 317,205 |
def _compute_subprefix(attr):
"""
Get the part before the first '_' or the end of attr including
the potential '_'
"""
return "".join((attr.split("_")[0], "_" if len(attr.split("_")) > 1 else "")) | 9f91987a780d1d3c5d78745fd661608d22f247cf | 247,502 |
import unicodedata
def phonenumber_from_raw_contact(raw_phone_string):
"""Parses a phone number from a raw contact string, which could include
unicode whitespaces.
e.g. " / 555-555-1959"
Arguments:
raw_phone_string {str} -- Raw unicode string that includes a phon... | 6ec7a67178f85062d001f4907b404331906d700a | 424,846 |
import re
def only_numbers(string):
"""Return a string w only the numbers from the given string"""
return re.sub("\D", "", string) | 99bf3aeae8a462c5f6b2f217445d8d2fc616984e | 646,158 |
import torch
def rgb2yuv(rgb, device):
"""
Convert RGB image into YUV https://en.wikipedia.org/wiki/YUV
"""
rgb = ((rgb + 1) / 2) * 255.0
rgb_ = rgb.transpose(1, 3) # input is 3*n*n default
A = torch.tensor([[0.299, -0.14714119, 0.61497538],
[0.587, -0.28886916, -0.514... | 689990a31bc6d02348c6427c1478e09d26da7f1d | 99,111 |
import math
def lon2x(a):
""" Converts longitudinal co-ordinate to its web mercator equivalent"""
radius = 6378137.0 # in meters on the equator
return math.radians(a) * radius | 923e8f92ec34c722b1bfb7355b0282d4019c2901 | 318,605 |
def join_plus(xs, check_non_empty=False):
"""
Concatenate strings with '+' to form legend label.
Parameters
----------
xs : list
List of strings
check_non_empty : bool
If True, assert that len(xs) > 0
Returns
-------
str
Concatenation of xs (e.g., "CPU + GPU")
... | 9fc9a086f24bc95c6b3a921810c4e1a8ec1f2bba | 187,351 |
def unique_paths_with_obstacles(obstacle_grid: list[list[int]]) -> int:
"""
>>> print(unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]]))
2
>>> print(unique_paths_with_obstacles([[0,1],[0,0]]))
1
>>> print(unique_paths_with_obstacles([[0,1,0],[0,0,0],[0,0,1]]))
0
"""
# If the ob... | de854da00b5c7e8608dbc7f8a4d352fc61956f28 | 687,536 |
def id2num(s):
""" spreadsheet column name to number
http://stackoverflow.com/questions/7261936
:param s: str -- spreadsheet column alpha ID (i.e. A, B, ... AA, AB,...)
:returns: int -- spreadsheet column number (zero-based index)
>>> id2num('A')
0
>>> id2num('B')
1
>>> id2num('XFD')... | a1966821557324a0e95568bf0f63207d8cd3f350 | 16,886 |
import math
def length(k):
"""Finds length of k in bits
Arguments:
k {int} -- Integer number
"""
return int(math.log2(k) + 1) | 801863f985d48881a687e339fe96b3725a59f3f6 | 530,582 |
import requests
import json
def create_network(platform, key, cli_id, desired_name, desired_type):
"""
Sends a post request containing the information required to create that new network.
:param platform: URL for RiskSense Platform to be posted to
:type platform: str
:param key: ... | c97adaf150cc798a7b8771c0b96338a9d611967b | 540,635 |
def _get_reaction_key(functional_groups):
"""
Return a key for :data:`._reactions`
Parameters
----------
functional_groups : :class:`iterable`
An :class:`iterable` of :class:`.GenericFunctionalGroup`.
The correct reaction must be selected for these functional
groups.
Re... | 0dd855b6067830554332b5653410ed9940c0cd72 | 258,824 |
def delta(n_1, n_2) -> int:
"""Kronicka-delta function, yields 1 if indexing is the same, else zero."""
if n_1 == n_2:
return 1
else:
return 0 | 7ef01ef20ba0aff7f360eddb6d64873556116788 | 620,479 |
def second_smallest(numbers):
"""Find second smallest element of numbers."""
m1, m2 = float('inf'), float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2 | 0ca7b297da68651e4a8b56377e08f09d4d82cfb7 | 706,279 |
from typing import Set
def slate_teams(slate: dict) -> Set[str]:
"""Gets teams on given slate
Args:
slate (dict): the slate document
Returns:
Set[str]
"""
return set([sp['team'] for sp in slate['slatePlayers']]) | 96efae352a7094a1c0e7d339386b53adfe135ca4 | 110,453 |
def compute_M1_nl(formula, abundance):
"""Compute intensity of the second isotopologue M1.
Handle element X with specific abundance.
Parameters
----------
formula : pyteomics.mass.Composition
Chemical formula, as a dict of the number of atoms for each element:
{element_name: number... | 8c1ec0f2bcdf5c097a500d57ab20ef03a6443a89 | 232,023 |
def vorf_str_to_set(vorf):
"""
Convert a Vorf string into a Python set with the Vorf values in it,
appropriately quoted.
"""
bits = [x.strip() for x in vorf.split(',')]
bits_str = ["'{}'".format(x) for x in bits]
return "{%s}" % ', '.join(bits_str) | c3406422d0f214cd2298651e7cd324aeb8f4bb43 | 563,665 |
def describe_result(result):
""" Describe the result from "import-results" """
status = result['status']
suite_name = result['suite-name']
return '%s %s' % (status, suite_name) | 1c7daa6df6bc5ce2267dc602002da4ab741f407f | 310,761 |
def getOrCreateNew(couchServer, dbName):
""" Get a couch Database object given dbName. If dbName is not existed,
create a new database.
"""
try:
db = couchServer[dbName]
except: # couchdb.http.ResourceNotFound
db = couchServer.create(dbName)
return db | 54741eb436761dd1caccb320a6059584f31a5ad1 | 387,875 |
def get_primary_key_column_names(model):
"""
Returns the constituent column names for the primary key of the given
model.
Args:
model (class or object): The given model class or model instance.
Return:
list: Primary key column names as a list of strings.
"""
return [column.... | 369bf25022458b9f861f0e1af695e2ce05dede1e | 314,843 |
def unmap_address(library, session):
"""Unmap memory space previously mapped by map_address().
Corresponds to viUnmapAddress function of the VISA library.
Parameters
----------
library : ctypes.WinDLL or ctypes.CDLL
ctypes wrapped library.
session : VISASession
Unique logical i... | 6420df343a3704f9747a91289f3ebeb69866a310 | 469,238 |
import re
def clean(s):
"""
Cleans given string from non-relevant information: links, punctuation, etc.
:param s: raw string
:return: cleaned string
"""
s = re.sub(r"https\S+", " ", s)
s = re.sub(r"^\s+|\n|\r|\t|\s+$", " ", s)
s = re.sub(r"[^\w\s\d]", " ", s)
s = re.sub(r"\s{2,}", ... | 4d5d0ab6119456d131e2cba58dfed77dc9c9bdaa | 486,079 |
def count_distinct(collection, key, exclude=None):
"""Get the number of distinct values for key in the specified database collection"""
values = collection.distinct(key)
if exclude is not None and exclude in values:
values.remove(exclude)
return len(values) | 894428df0a3d913963c33ce2940c01305a5b700e | 625,073 |
def make_simple_preprocessor(obj):
"""Factory that makes a function that accepts (step, context) and returns the given obj as *args and no kwargs.
:param obj: Any object.
:return: A function that accepts (step, context) paramteres and returns a tuple (*args, **kwargs) in the
following fo... | 3b7ff8b9a92102480e2b0fb12b251863ec19d7ec | 390,289 |
def left_part_of(txt, sub_txt, n=1):
"""
Return the left part before the nth of sub_txt appeared in txt.
:param txt: text
:param sub_txt: separate text
:param n: the nth of sub_txt(default:1)
"""
parts = txt.split(sub_txt)
return sub_txt.join(parts[:n]) | af99d668038d62581792612ec189d15104b31cbf | 620,309 |
def is_second_run(command):
"""It's second run of `fudge`?"""
return command.script.startswith('fudge') | d89335c3390bef8dc9b295f6e982bb7295cd80c8 | 362,029 |
import random
import string
def random_string(size=60):
"""Generates a random alphanumeric string for a given size"""
return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(size)) | 0deae6d46bd09808df105e63a0e30323167fcc1f | 239,744 |
from typing import Dict
from typing import List
def _continuous_columns(feature_types: Dict) -> List[str]:
"""
Parameters
----------
feature_types : Dict
Column name mapping to list of feature types ordered by most to least relevant.
Returns
-------
List[str]
List of colum... | d21b02f949a5c658defeaaa67a0abec916373f0d | 689,242 |
def is_targeting_windows(pkg_vars):
"""Returns true if 'platform' in pkg_vars indicates Windows."""
return pkg_vars['platform'].startswith('windows-') | 83ee031170327348c57b50c86739c876e9f9f8f4 | 617,551 |
import torch
def check_GPU_availability(cuda_n=0):
"""
Checks if GPU is available
:return: avilable device name
"""
if torch.cuda.is_available(): # Check we're using GPU
torch.backends.cudnn.deterministic = True
device = 'cuda:%s' %(cuda_n)
else:
device = 'cpu'
re... | 0b8edaa5dce24c1cfeba58e96e6923a883b24b84 | 238,645 |
def recursive_array_addition(l:list):
"""Sum an array of integers using recursion."""
if len(l) == 0:
return 0
else:
i = l.pop()
return i + recursive_array_addition(l) | 05b88afc8a2deadb9fafb4170aecc31128743cc3 | 584,139 |
def _process_imp(imp_df, imp_name):
"""
Preprocessing on the input feature importance dataframe
:param imp_df: feature importance pandas dataframe
:param imp_name: column name of the importance value
:return:
dataframe with relative_imp and feat_rank
"""
imp_df = imp_df.sort_values... | 81a0253bee9c1aed746bf374ddf771ed691101a2 | 450,346 |
def _unary_apply(op, value):
"""
Constructs a Weld string to apply a unary function to a scalar.
Examples
--------
>>> _unary_apply("sqrt", "e")
'sqrt(e)'
"""
return "{op}({value})".format(op=op, value=value) | b5c69fc278e5b0453140e23ff21c1d1c8860ee2e | 131,679 |
def calc_max_min_marks(marks):
""" Function which returns the minimum(excluding 0) and maximum score of the class in the form of a list. """
result = []
marks.sort()
min_max = []
min_max[:] = (value for value in marks if value != 0)
least_score = min_max[0]
highest_score = min_max[-1]
r... | 92c6581ea2d967772cda043adee5c5d5ce893335 | 53,528 |
def elementwise_residual(true_val, pred_val):
"""The residual between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
residual : float
The residual, true minus predicted
... | e1eb2434b1d24032f3b7abc1233c165d7146ffff | 71,487 |
import re
def _SanitizeRepositoryName(name):
"""Sanitizes the given name to make it valid as an image repository.
As explained in
https://docs.docker.com/engine/reference/commandline/tag/#extended-description,
Valid name may contain only lowercase letters, digits and separators.
A separator is defined as a... | d6785746a85143a9aff97acbacf76347501c0f9d | 169,052 |
def _CreateActionsText(text, igm_field, action_types):
"""Creates text presented at each wait operation for given IGM field.
Args:
text: the text associated with the field.
igm_field: reference to a field in the Instance Group Manager.
action_types: array with field values to be counted.
Returns:
... | 2eb42dd58efccbc18dc827bb6582204eb7808144 | 609,513 |
def pick_latest_version(versions):
"""Returns the higher version available in the given list of versions.
versions:
Array of strings with the availalbe versions.
"""
def from_string(version):
return tuple(int(part) for part in version.split('.'))
def to_string(version):
return '.'.join(str(part)... | 550baba8d9d33dcff91f1572b046edfcb48deed5 | 245,006 |
import yaml
def write_watchlist(watchlist):
""" Writes the current watchlist to yaml file """
with open('data.yaml', 'w') as file:
return yaml.dump(watchlist, file) | 29e4bf0150220bf22a937666f1a4839b9997cda9 | 211,669 |
def calc_accu(a, b):
"""
Returns the accuracy (in %) between arrays <a> and <b>. The two arrays must
be column/row vectors.
"""
a = a.flatten()
b = b.flatten()
accu = 100.0 * (a == b).sum() / len(a)
return accu | 3f91e0805b3fc950da0ae02b34c8c0fb383e78c6 | 668,067 |
def fix_bases_mask(bases_mask,barcode_sequence):
"""Adjust input bases mask to match actual barcode sequence lengths
Updates the bases mask string extracted from RunInfo.xml so that the
index read masks correspond to the index barcode sequence lengths
given e.g. in the SampleSheet.csv file.
For ex... | ef3d7dd18ae338b6e4f92412085a2eb56c3e5514 | 486,999 |
def anagram(word_1: str,
word_2: str) -> bool:
"""Anagram check example
:param word_1: {str}
:param word_2: {str}
:return: {bool}
"""
word_1 = word_1.lower()
word_2 = word_2.lower()
return sorted(word_1) == sorted(word_2) | 6e99ebb0659fb4f81414f2dd552f854d52d61a0d | 669,562 |
import requests
def _download_index(category, index_url):
"""
Download the index.
:param category: suffixed category, e.g. 'filters', 'templates'
:param index_url: url to the index. Default: 'https://raw.githubusercontent.com/pandoc-extras/packages/master/<category>.yaml'
:return: the content of ... | 190a4b39f962cae43d281fa91d1614cbebaa681a | 50,209 |
def temba_compare_contacts(first, second):
"""
Compares two Temba contacts to determine if there are differences.
These two contacts are presumably referencing the same contact,
but we need to see if there are any differences between them.
Returns name of first difference found, one of 'name' or 'u... | 929460f61103ffda542f2e09c3d7dc0ff1e0d83a | 451,787 |
def get_application_instance_name(application):
"""
Return the name of the application instance.
"""
return "{}-{}".format(application.image.project.name, application.name) | e877677b831740f7bd156dc840593e69e185e411 | 649,778 |
import string
def first_int(s):
"""Return the first integer in a string, or None"""
# This technique appears to be faster than the re-based method
# by almost an order of magnitude. Prefer it
ret = ''
for c in s:
if c in string.digits:
ret += c
else:
break... | 63499dfd382836571690dc34c80d7a9b319ecb49 | 594,193 |
def hashable(x):
"""Check if an object is hashable. Hashable objects will usually be
immutable though this is not guaranteed.
Parameters
----------
x: object
The item to check for hashability.
Returns
-------
bool: True if `x` is hashable (suggesting immutability), False otherw... | 81abc4ba519cf39c8447c17716bd723b81475b57 | 374,532 |
from io import StringIO
import csv
def data_to_string(data):
"""Write a list of dicts as a CSV string
Args:
data (list): A list of dicts, one per CSV row
Returns:
str: The stringified csv data, with a header row
"""
with StringIO() as fout:
fieldnames = data[0].keys()
... | 416e285379244fd01463270899560fe3b11c9277 | 320,286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.