content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_class_name(obj, instance=True):
"""
Given a class or instance of a class, returns a string representing the
fully specified path of the class.
Parameters
----------
obj : object
An instance of any object
instance: bool
Indicates whether given object is an instance o... | 3a7ebd1fb2682ec5dff6d42cd2cccf918d67f9a0 | 709,938 |
def _is_link_up(statedict):
"""Evaluate current operstate, carrier and link from dict."""
if statedict['link'] == 'yes' and statedict['carrier'] == 'running' and statedict['operstate'] == 'up':
return True
return False | 3215a79448e9d7b9f29b8455a56a336779862a95 | 246,116 |
def _n_grams(n, s):
"""Convert a string into an iterator of n_gram strings."""
return map(''.join, zip(*[s.lower()[i:] for i in range(n)])) | a93ccfcba60ddcf02342ba514e63ed263c060a38 | 545,144 |
def wgtd_avg(lines):
"""
Returns the weighted average of a set of line coefficients
"""
avg_coeffs = [0,0,0]
i = 0
n = len(lines)
# Weighted average of line coefficients to get smoothed lane lines
for line in lines:
i += 1
avg_coeffs = avg_coeffs + (i * line.coeffs / ((n*... | e51d44e7f03142dbea6bfe04721552a73ca64b30 | 391,846 |
from typing import Tuple
def floating_IoU(
r1: Tuple[float, float, float, float],
r2: Tuple[float, float, float, float]
) -> float:
"""IoU for non-grid based boxes
>>> floating_IoU((0, 0, 1, 1), (0, 0, 1, 2))
0.5
Params
======
r1 - (x, y, w, h,...)
r2 - (x, y, w, ... | 37a40d16c2728782ba65ceb93daa4095960ddcdd | 496,545 |
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None | ffadd9e06a20acdcda4b2d085e086e31ad53c694 | 593,296 |
def get_range(padding, *args):
"""Get a [min, max] for all of the data passed as *args."""
if not isinstance(padding, tuple):
padding = (padding, padding)
all_data = [item for lst in args for item in lst]
return [min(all_data) - padding[0], max(all_data) + padding[1]] | 3fd5c11a6986c55fef1a27ccdb7ca04106c107f2 | 102,323 |
import torch
def stft(y, n_fft, hop_length, win_length):
"""
Args:
y: [B, F, T]
n_fft:
hop_length:
win_length:
device:
Returns:
[B, F, T], **complex-valued** STFT coefficients
"""
assert y.dim() == 2
return torch.stft(
y,
n_fft,... | 9c48f99b072f766ec63b1ec68b95cd424652b700 | 260,656 |
def _parse_zeopp(filecontent: str) -> dict:
"""Parse the results line of a network call to zeopp
Args:
filecontent (str): results file
Returns:
dict: largest included sphere, largest free sphere,
largest included sphera along free sphere path
"""
first_line = fileconten... | 436e7579883a8c6700d3725756dd03dc7de3cf51 | 58,476 |
def handle_same_string(str1, alist):
""" if a string already exist in a list, add a number to it """
if str1 in alist:
for i in range(1, 1000):
str1_ = str1 + ' (%i)' % i
if str1_ not in alist:
return str1_
else:
return str1 | ea3ae39166ed81bd046d0ae095d0436c5f88c801 | 460,890 |
import pickle
def load_basic_model(model_file, vectorizer_file):
"""Load the either the Logistic Regression or SVM model and vectorizer"""
load_model = pickle.load(open(model_file, 'rb'))
load_vectorizer = pickle.load(open(vectorizer_file, 'rb'))
print(" ### Loading model complete ### ")
return lo... | b252cadd4067c67b8833dc2c2094fe14d007f504 | 325,576 |
def str2int(val):
"""
Converts a decimal or hex string into an int.
Also accepts an int and returns it unchanged.
"""
if type(val) is int:
return int(val)
if len(val) < 3:
return int(val, 10)
if val[:2] == '0x':
return int(val, 16)
return int(val, 10) | dadddb6a82b3243735c1b0136a6ccc266820bd5b | 634,638 |
def get_entity_name(s):
"""
Detect entity name from the raw entity string.
:param s: Entity string
:return: entity name
"""
tokens = s.split("/")
name = tokens[3]
return name | 90e35aec44801c560cbb8727213fea9a1056ed62 | 301,400 |
def translation_changed(verbose, obj_id, key, translation, target_string):
""" Checks if the translation for a given key changed """
if target_string == translation:
if verbose:
print(f"Translation for {obj_id} string '{key}' has not changed -- skipping")
return False
return True | 6fbfc83aa40050919fa62b37dd8dacf85949366e | 562,949 |
def _read_params_from_file(filepath, seperator=None):
"""Extract key=value pairs from a file.
:param filepath: path to a file containing key=value pairs separated by
whitespace or newlines.
:returns: a dictionary representing the content of the file
"""
with open(filepath) as f... | 97818e80342039c33c79f1ce6dc7250d06165877 | 378,950 |
def _has_not_created_operation(result, retryer_state):
"""Takes TransferJob Apitools object and returns if it lacks an operation."""
del retryer_state # Unused.
return not result.latestOperationName | f85422d9ddb37efdf0adde8dfc50601c825766c5 | 283,964 |
def is_valid(board, guess, row, col) -> bool:
"""
Check if potential digit is valid in a square
:param board: Sudoku board
:param guess: guessed digit
:param row: row number
:param col: column number
:return: bool if move is valid
"""
# Rule 1: No duplicates in same row
if guess ... | b72d8daba26c97c0a8aa7b111d02f83228801c75 | 187,546 |
def update_routing_segmentation_segment_by_id(
self,
segment_id: int,
new_segment_name: str,
) -> bool:
"""Update routing segment name in Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - vrf
- PUT
... | 01e58f34897ffc636048a384706a6be7e1f3ae2e | 476,239 |
from typing import Dict
from typing import Any
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping.
"""
return {v: k for k, v in d.items()} | 2ec76e23d76b82baf7716ed27298f8ae64033cb3 | 248,953 |
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float:
"""Return an linearly annealed epsilon
Epsilon will decrease over time until it reaches `target_episode`
(epsilon)
|
max_e ---|\
| \
| \
| \
mi... | fab650085f271f1271025e23f260eb18e645a9ba | 402 |
import base64
def base32_to_base64(base32_string):
"""Converts base32 string to base64 string"""
b64_string = base64.b64encode(base64.b32decode(base32_string)).decode('ascii')
return b64_string | 4c75717522016b57e19711ed34c0944072831a37 | 226,491 |
def request_help_privacy(twhandler):
"""Return the handler for GET help/privacy."""
return twhandler.help.privacy | aafb7e1ed7328fe5eff31933249205867a239657 | 595,204 |
def identity(X, y):
"""Identity operation.
Parameters
----------
X : torch.Tensor
EEG input example or batch.
y : torch.Tensor
EEG labels for the example or batch.
Returns
-------
torch.Tensor
Transformed inputs.
torch.Tensor
Transformed labels.
... | c0441302d7c85979fd73475d2d24f993a25490d3 | 621,779 |
def link_generator(start: int, end: int, page: int) -> str:
"""
Generates links with appropriate query parameters.
---
Args:
start (int): start year of the query
end (int): end year of the query
page (int): page number
Returns:
link (str): final link for scrape reque... | 23953bd273ccc11e103e1fc9ff134711c742ba34 | 477,945 |
def build_complement(c):
"""
The function convert alphabets in input c into certain alphabets.
:param c: str, can be 'A','T','G','C','a','t','g','c'
:return: The string of converted alphabets.
"""
c = c.upper() # The Str Class method changes input c into capital.
total = ''
for i in ran... | 6fece325432ac061d5f7577c85cb59c19918ed83 | 26,992 |
from pathlib import Path
def GetBadgeClassFileName(readPath: Path) -> Path:
"""
BadgeClass.csv へのパスとファイル名を返す。
unittest.mock でテストしやすいように分割した。
"""
return (readPath / "BadgeClass.csv") | 2893df1f8495a3dc00733190cfb513843a5b5d55 | 454,373 |
def c_to_k(tempe):
"""Receives a temperature in Celsius and returns in Kelvin"""
return tempe + 273.15 | d88f1daf532b8b592ce0feb6019669ee9b183a20 | 557,273 |
def count_orders(values : list[int], max_diff : int) -> int:
"""Count the valid progressions through the values with a maximum jump size."""
ordered = [0] + sorted(values) + [max(values) + 3]
options = [0] * len(ordered)
options[0] = 1
# Each element of options should be the sum of all prior elemen... | 864a7a15c0ae6300f39396d9bddc9d60ed073427 | 454,091 |
def hamming_distance(list1, list2):
""" Calculate the Hamming distance between two lists """
# Make sure we're working with lists
# Sorry, no other iterables are permitted
assert isinstance(list1, list)
assert isinstance(list2, list)
dist = 0
# 'zip' is a Python builtin, documented at
... | 81fe2293cd42684b88ab19cb8341a0f55e5323a8 | 241,069 |
def dice(u, v):
"""Return the dice coefficient between two vectors."""
u = u > 0
v = v > 0
return (2.0 * (u * v).sum()) / (u.sum() + v.sum()) | ae91be262af779885e805a7f6f0fe49b9efdef57 | 531,799 |
import random
def clueless(state):
"""A strategy that ignores the state and chooses at random from possible moves."""
possible_moves = ['roll', 'hold']
return random.choice(possible_moves) | 7ba97a5263dcf3bc65c0c37b4313b6c9b603bdbd | 160,934 |
def fake_user(**kwargs):
"""Fixture to return a dictionary representing a user with default values set."""
kwargs.setdefault("id", 43)
kwargs.setdefault("name", "bob the test man")
kwargs.setdefault("discriminator", 1337)
kwargs.setdefault("avatar_hash", None)
kwargs.setdefault("roles", (666,))
... | de688eca8b90b94fd90b7f7a1c8fb8ebbc545283 | 88,835 |
def _find_path(start, end, path=tuple()):
"""Return the path from start to end.
If no path exists, return None.
"""
path = path + (start, )
if start is end:
return path
else:
ret = None
if start.low is not None:
ret = _find_path(start.low, end, path)
... | 0679377669f10094852910d18a47399c33673355 | 370,332 |
def append(field, item):
"""
Appends item to a list at value `field`
"""
def transform(element):
if field not in element:
element[field] = [item]
else:
element[field].append(item)
return transform | 9dae1273b45314e6522c60b3aa784ec8e90dd0fa | 396,063 |
import torch
def CartesianHarmonics(xyz, kx, ky, kz, derivative=0, jacobian=True):
"""Computes the Real cartesian harmonics
x^kx, y^ky z^kz
Arguments:
xyz {torch.tensor} -- coordinate of each electrons from each BAS center (Nbatch, Nelec, Nbas, Ndim)
kx {torch.tensor} -- x exponent
... | 1bda66b04637ae9ada6794d5bd696a72e4270574 | 458,053 |
def get_residuals_update_tile(st, padded_tile):
"""
Translates a tile in the padded image to the unpadded image.
Given a state and a tile that corresponds to the padded image, returns
a tile that corresponds to the the corresponding pixels of the difference
image
Parameters
----------
... | 306f436f6fe59a04542a99a33c07156cb4a14537 | 365,133 |
def api_card(text: str, color: str) -> str:
"""Create a HTML Card for API display"""
html = f"""
<div class='demo_card' style='background-color:{color}'>
<span>{text}</span>
</div>
"""
return html | 8758078c92bfe7fafb87537501ba1c8a5490e47e | 279,844 |
def urlize(val):
"""
Ensures a would-be URL actually starts with "http://" or "https://".
:param val: the URL
:returns: the cleaned URL
>>> urlize('gnu.org')
'http://gnu.org'
>>> urlize(None) is None
True
>>> urlize(u'https://gnu.org')
'https://gnu.org'
"""
if val and n... | 44fa7ddac48a860fa332bfb2dbb2d18de766c284 | 393,942 |
def sum_even_fibonacci(n):
"""sum of the even-valued terms of the fibonacci sequence not exceeding n"""
result = 0
if n >= 2:
x, y = 1, 1
for _ in range(n):
x, y = y, x + y
if x > n:
break
if x % 2 == 0:
# print(x, y)
... | 0cfc53863115aa462f6d0558cc3a5018507c737f | 35,298 |
def block_device_has_mounts(device):
"""
Determines if a block device has filesystems mounted on any of its
partitions.
Parameters
----------
device: str
The block device.
Returns
-------
bool:
True if at least one partitions is mounted;
False under any othe... | 75a3ad14962334ec17f336f7abdd0b31d752acae | 523,988 |
def make_params(**kwargs):
"""
Helper to create a params dict, skipping undefined entries.
:returns: (dict) A params dict to pass to `request`.
"""
return {k: v for k, v in kwargs.items() if v is not None} | a2405b8c5ca2173320f28ab5b668ca1b577360ae | 543,199 |
def strict_dict(pairs):
"""Creates a dict from a sequence of key-value pairs, verifying uniqueness of each key."""
d = {}
for k,v in pairs:
if k in d:
raise ValueError("duplicate tupkey '%s'" % k)
d[k] = v
return d | 11690b8cde2fb2163f9c07001dc5864f21e0339f | 44,293 |
def convert(nested_dict):
"""
Convert nested dict with bytes to str.
This is needed because bytes are not JSON serializable.
:param nested_dict: nested dict with bytes
"""
if isinstance(nested_dict, dict):
return {convert(k): convert(v) for k, v in nested_dict.items()}
elif isinstan... | d267259c6113411d0db757d59248db18beb29e31 | 165,349 |
def x_in_process(coord2d: list, x_coord: int, lx: int, processes_in_x: int) -> bool:
"""
Checks whether a global x coordinate is in a given process or not.
Args:
coord2d: process coordinates given the cartesian topology
x_coord: global x coordinate
lx: size of the lattice grid in x ... | 8dbd5c7a2bba3dc93ededb04452dc67163232af6 | 430,762 |
def escape_pg_identifier(engine, name):
"""
Escape identifiers (tables, fields, roles, etc) for inclusion in SQL statements.
psycopg2 can safely merge query arguments, but cannot do the same for dynamically
generating queries.
See http://initd.org/psycopg/docs/sql.html for more information.
""... | ef572754bda07fd174b0ba7d940c1fcfaa665599 | 322,400 |
def jamf_records(cls, name="", exclude=()):
"""
Get Jamf Records
:param cls <str>: name of class
:param name <str>: name in record['name']
:param exclude <iter>: record['name'] not in exclude
:returns: list of dicts: [{'id': jamf_id, 'name': name}, ...]
"""
# exclude sp... | 12531de9682ab6864d760d7bfa3969e79835b6ca | 506,923 |
import re
def clean_variable_name(variable_name):
""" Convert the variable name to a name that can be used as a template variable. """
return re.sub(r"[^a-zA-Z0-9_]", '', variable_name.replace(' ', '_')) | ec89b05b299a479584620d82c44b009d3ce3a333 | 259,175 |
import shlex
def stringToArgList(string):
"""Converts a single argument string into a list of arguments"""
return shlex.split(string) | 4ad5613978b082bf95945442128006f5ce8819d7 | 150,889 |
def update_search_service(instance, partition_count=0, replica_count=0):
"""
Update partition and replica of the given search service.
:param partition_count: Number of partitions in the search service.
:param replica_count: Number of replicas in the search service.
"""
replica_count = int(repl... | c52219347758b5dea03812342019c0a1c23a74b1 | 362,835 |
from typing import Union
from typing import Dict
def form_store(
payload: Union[Dict, str],
metadata: Union[Dict, str, None],
):
"""
Processes the payload and the metadata (if any exists) into a JSON-like format.
:param payload: A string object or dictionary containing the message data.
... | 00b55e1f86eeea934d2ffc53de8237f72c3e99af | 233,074 |
from pathlib import Path
def _path_to_module(path: Path) -> str:
"""Returns the module name corresponding to a file path."""
parts = path.parts
if parts[-1] == "__init__.pyi":
parts = parts[:-1]
if parts[-1].endswith(".pyi"):
parts = parts[:-1] + (parts[-1][: -len(".pyi")],)
return... | f4caa79601793773e746f5f009d8239b0efbb8ee | 430,303 |
def get_new_dim(imgw, imgh, max_dim=400):
"""Get new image dimension with maximum constraint.
Args:
imgw: image width.
imgh: image height.
max_dim: maximum image dimension after.
Returns:
new img width and height.
"""
max_val = max(imgw, imgh)
ratio = max_val / max_dim
new_imgw = int(imgw... | dd25018f993b688c4e6767f8f196c3bcbf77fd7e | 76,545 |
def read_file_comment(file_path):
"""Reads info comment in a coin CSV file.
Args:
file_path (str): given coin file path
Raises:
ValueError: occurs if no comment exist at the top
of coin file
Returns:
comment (str): info comment in the coin file
"""
... | cdc7ae40d942a39811746024819a785b7d917168 | 556,442 |
def create_labels(team, name, calender, client, sprints):
"""
Helper function to create labels for a project.
:param Dict team: Team dict
:param Dict calender: Calender dict
:param jira.client.JIRA client: JIRA client
:param String name: Team name
:param List sprints: List of sprints
:r... | 86623adfbc648a940abf6d49cce2872c65f98e30 | 546,271 |
def ExpectsMultiple(options):
"""Decorator for questions that indicates expected values from a list
This decorator indicates to the renderer that the question will be answered
by a series of check boxes.
Args:
options: An OrderedDict of Options where the key is the text to be
presented to t... | 70e1be1712269a43998f4073323a3b8e851e1b27 | 301,134 |
def levelFromHtmid(htmid):
"""
Find the level of a trixel from its htmid. The level
indicates how refined the triangular mesh is.
There are 8*4**(d-1) triangles in a mesh of level=d
(equation 2.5 of
Szalay A. et al. (2007)
"Indexing the Sphere with the Hierarchical Triangular Mesh"
ar... | 86a2ca1c7176b06c38ff1acd028349690fb34aee | 675,177 |
def id_count(df, id_column: str):
"""
Count the amount of ids from the data frame for future accountability.
Returns an int.
"""
return len(list(set(df[id_column]))) | e4d87b8424e12d14a5e3d42a2de52c07ba4d3fd7 | 381,370 |
import math
def get_indices(width, height, xpartition, ypartition, xinput, yinput):
"""
Function to get the indices for grid.
Args:
width (float): width of the pitch.
height (float): height of the pitch.
xpartition (int): number of rows in a grid
ypartition (int): number o... | a93aefb4f04106341b498844751e2bc61b1754d4 | 83,100 |
def check_position(grid, num, row, col):
"""
Based on rules, checks if the given 'num' is in a valid position.
"""
def box_pos(val):
# Determine coordinates of 3x3 box corresponding to val(row or col of the current square)
if val < 3:
pos = 0
elif 3 <= val < 6:
... | 7e0c612c44d9e743084c295753f73ea9c69b4f36 | 280,110 |
def is_patch_inside_FOV(x,y,fov_img,patch_h,patch_w,mode='center'):
"""
check if the patch is contained in the FOV,
The center mode checks whether the center pixel of the patch is within fov,
the all mode checks whether all pixels of the patch are within fov.
"""
if mode == 'center':
ret... | 45c6be6f8647ae2bd93390fdd0ed4868eea19258 | 597,403 |
def add_format_field(record, fieldname):
"""Return record with fieldname added to the FORMAT field if it doesn't
already exist.
"""
format = record.FORMAT.split(':')
if fieldname not in format:
record.FORMAT = record.FORMAT + ":" + fieldname
return record | bcc3ff87a80bb561462b11428eeba8561bcc100f | 42,120 |
def extract_symbols(lst):
"""Takes a row or column of idents or alphanumeric symbols and just
extracts the symbols (letters).
Args:
lst (list): list of strings representing the cells in a row or col
e.g. ['1a', '1b', '1c', 2, 2]
Returns:
(list): just the letters from the in... | 0cbbc621aa4b0f7c6bc837bdb1f76e7317057ccb | 396,461 |
def get_bytes_from_gb(size_in_gb):
""" Convert size from GB into bytes """
return size_in_gb*(1024*1024*1024) | 9bfd7a0791a08a88ad83b388e25030ef8cc2df6b | 650,150 |
def binary_integer_format(integer: int,
number_of_bits: int) -> str:
"""
Return binary representation of an integer
:param integer:
:param number_of_bits:
NOTE: number of bits can be greater than minimal needed to represent integer
:return:
"""
return "{0:b}".fo... | 4ad126eb37cf781b01552ed2498683a75f8f3f22 | 340,873 |
def get_length_of_list_of_iterables(list_of_tuples):
"""Get the total length of a list of tuples."""
length = 0
for tuple_item in list_of_tuples:
length += len(tuple_item)
return length | eef9813c2e1e3e27dd94989bdf87cecbc3885b94 | 521,399 |
def total_fluorescence_from_intensity(I_par, I_per):
"""
Calculate total fluorescence from crossed intensities.
"""
return I_par + 2 * I_per | 9e46bc6f2088a0d489f3c94de4cb5248267173cb | 306,661 |
import re
def normalize_version(version):
"""
Normalize a version string by removing extra zeroes and periods.
"""
return [int(x) for x in re.sub(r'(\.0+)*$', '', version).split('.')] | 24f9db935e67495f6583b17627222c68ad5423ee | 622,368 |
def cpu_usage_for_process(results, process):
"""
Calculate the CPU percentage for a process running in a particular
scenario.
:param results: Results to extract values from.
:param process: Process name to calculate CPU usage for.
"""
process_results = [
r for r in results if r['met... | 8fc962cf9f7d1fcab1b8a223b4c15dd2eb0e51f4 | 57,146 |
def GetPatchDeploymentUriPath(project, patch_deployment):
"""Returns the URI path of an osconfig patch deployment."""
return '/'.join(['projects', project, 'patchDeployments', patch_deployment]) | 96298cc379e94fd6acb97f620b6f8dee35959b98 | 143,364 |
from typing import Callable
def filter_values(d: dict, predicate: Callable) -> dict:
"""
Returns new subset dict of d where values pass predicate fn
>>> d = {'Homer': 39, 'Marge': 36, 'Bart': 10}
>>> filter_values(d, lambda x: x < 20)
{'Bart': 10}
"""
return {k: v for k, v in d.items() if... | 551b00222361cdb684820d8ce2c22e407d65d362 | 615,270 |
from typing import List
def loadMatrix(file_name: str) -> List[List[float]]:
"""
Import matrix from file.
Matrix is stored in row oriented list.
Such that each row is a nested list.
"""
with open(file_name, 'r') as file:
row_count = int(file.readline())
column_count = int(file... | 860fca72aeb56ce2f30310a0db63c7b212ee2a3b | 89,474 |
def is_word_capitalized(word):
"""
Check if word is capitalized.
Args:
word (str): Word.
Returns:
(boole): True f word is capitalized. False otherwise.
"""
if not word:
return False
first_letter = word[0]
return first_letter == first_letter.upper() | 1e5e2ecc08330774bf5e25e72d1af97d2a73d0af | 388,308 |
def data_sort(gdf,str):
"""
sort the geodataframe by special string
Parameters
----------
gdf : geodataframe
geodataframe of gnss data
str: sort based on this string
Returns
-------
geodataframe:
geodataframe of gnss data after sorting
"""
gdf = gdf.sort_valu... | 8010c66872ec9c2954659bdcd34bfa313963ffc7 | 679,960 |
from typing import Generator
def is_gen(x):
"""Checks if argument is a generator."""
return isinstance(x, Generator) | af91e61f1638c3601c3b8db0bb7f2310ca967fdd | 244,422 |
import difflib
import heapq
def get_close_matches_and_similarity_ratios(word, possibilities, n=3, cutoff=0.6, junk_str=''):
"""Use SequenceMatcher to return list of the best "good enough" matches, along with the similarity ratios.
Code inspired from:
https://docs.python.org/3/library/difflib.html#dif... | 831949bd5ef427b01c47af6b4cca081074aef9ae | 142,118 |
def compute_pct_by_group(df, group_col='group', value_col='count'):
"""
Determine what percent each element contributes to its group's total.
- Sum value by group to get group totals
- Divide each group element by its group's total to get fraction of group
- Multiply by 100 to get percent of g... | 3a6f774806329c9fac02bc04eda3d95f97694361 | 189,183 |
import torch
def sample_reparameterize(mean, std):
"""
Perform the reparameterization trick to sample from a distribution with the given mean and std
Inputs:
mean - Tensor of arbitrary shape and range, denoting the mean of the distributions
std - Tensor of arbitrary shape with strictly pos... | 33e44a3ed3d3a12774250b2f9c3a6d019abd0ca2 | 113,629 |
def rgbToStrhex(r, g, b):
"""r (int), g (int), b (int): rgb values to be converted
Returned value (str): hex value of the color (ex: #7f866a"""
return '#%02x%02x%02x' % (r, g, b) | 9bcdb657c3ec3662b80f5fc83a09644b98292896 | 102,342 |
def get_element_from_list(attribute, search_string, element_list):
"""
Get element by attribute and string.
:param attribute: string of attribute type
:param search_string: identifying string to look for
:param element_list: element tree to look in
:return: found element
"""
for element ... | 834f78dfeae0a1406e1de98925e9052e08d7f6a4 | 381,023 |
def construct_wiki_header(wiki_meta):
"""
Return wiki page Jekyll front matter header for compomics.github.io pages.
"""
header = """---
title: "{title}"
layout: default
permalink: "{permalink}"
tags: {tags}
project: "{project}"
github_project: "{github_project}"
---
""".format(**wiki_meta)
return ... | dbc000d7cfa3b91edf243363f1af0d9956c42494 | 118,020 |
def _repr_tuple(dumper, data):
"""Fix yaml tuple representation (use list).
"""
return dumper.represent_list(list(data)) | 0365b33bfb039dea11729da88e186082ebdf7e53 | 377,942 |
def prefs_line_to_string(line):
""" Converts a prefs line to a string.
Prefs line is in the format tb(..);tc(..);..;..;.
tb(x, y) are "no preference" intervals (i.e., white) that last for
y 15-minute intervals (x has no meaning):
e.g., tb(0, 4) is an hour of white; tb(2, 8) is two hours.
... | 3497018ebf6306fdd23c8a12b9ad67a09811200c | 630,496 |
def get_region_period_spec_val_subtable(df, region=None, period=None, col='typemaatwerkarrangement', spec_value=None):
"""
Method to subset the dataframe based on a certain region, period and specific value of a column.
Parameters
----------
df : pd.DataFrame
DataFrame with the WMO data fro... | c5e8c9771417afa532b90973a08808860d9700de | 195,067 |
def trimmer(
scores: list,
counts: list,
direction: int = 0,
threshold: int = 3,
frac_retain: float = 0.9,
) -> int:
"""
Trimmer takes scores and direction as input and returns the position where
the sequence has to be trimmed in that direction
Parameters
---------
scores : ... | ba4a346d53e87bbd4227dfbdfd4a6fef2f9902ed | 491,186 |
from typing import Tuple
import math
def color_difference_redmean(
rgb1: Tuple[float, float, float], rgb2: Tuple[float, float, float]
) -> float:
"""Distance between colors in RGB space (redmean metric).
The maximal distance between (255, 255, 255) and (0, 0, 0) ≈ 765.
Sources:
- https://en.wiki... | 47837f4069c37902ba430ca1f52a67590a8a06ad | 176,643 |
def Identity(X):
"""
Identity fuction is the basic activation function
It return the same input value as output.
Parameters:
- X: int ,-Inf to +Inf
Returns:
X , -Inf to +Inf
"""
return X | 1b7d1f912e04fed5b503960a0ecd9bf9811ab19b | 606,243 |
def not_all_new(old_elements: list, new_elements: list):
"""
This function check whether at least one element from new_elements are in old_elements.
"""
return any([element in old_elements for element in new_elements]) | 2c9912479561f5a0a62234f4e14138e70abb71d9 | 203,272 |
from typing import Tuple
def _RGB_to_TkID(RGB: Tuple[int, int, int]) -> str:
"""
This function converts an RGB tuple (R, G, B) into a colour code
which can be used by tkinter.
:param RGB: Tuple[int, int, int]
:return: str
"""
r, g, b = RGB
return f'#{r:02x}{g:02x}{b:02x}' | cb3a0e7fd57a79351107c06ca5de56eaa7e3667a | 334,293 |
import click
def cccv_options(f):
"""CCCV-specific CLI options."""
f = click.option('--out', type=click.Path(), required=True,
help='Output file path for CCCV results.')(f)
f = click.option('--conta_steps', type=int, default=20,
help='Number of equidistant contami... | 3d3852846bf96ba38b91291faca181c26f3a9ab0 | 144,277 |
def get_formatted_duration(seconds: float, format: str="hms") -> str:
"""Format a time in seconds.
:param format: "hms" for hours mins secs or "ms" for min secs.
"""
mins, secs = divmod(seconds, 60)
if format == "ms":
t = "{:d}m:{:02d}s".format(int(mins), int(secs))
elif format == "hms":... | 9a968fba1f5cf9882875544a0de6d7e8e814eff0 | 507,096 |
def remove_place(net, place):
"""
Remove a place from a Petri net
Parameters
-------------
net
Petri net
place
Place to remove
Returns
-------------
net
Petri net
"""
if place in net.places:
in_arcs = place.in_arcs
for arc in in_arcs:... | b4bc3edabff29e0837c895f82ef9599eb59c811c | 74,308 |
def get_hms_from_seconds(seconds):
"""
function: get_hms_from_seconds
coverts the given number of seconds to hours, minutes, and seconds
input:
int seconds: the number of seconds to convert
output:
int hours: the number of hours that fit evenly into the given number of seconds
... | fe3804640c508bf7aadf1a7165158e89745e5d70 | 270,336 |
def get_cell_count(grid):
"""Return number alive cells on the grid."""
return len(grid.cell_sprite) | 849aaed0d579b1518e51172d6117e58195a98ab7 | 131,839 |
def components_in(containers):
""" given a list of containers, return the components within """
components = []
for container in containers:
instances = container.components()
components.extend(instances)
subcontainers = container.containers()
components.extend(components_in(... | 316bb95b1fed6183597a3cb6564ce217e3a35ba6 | 167,916 |
def c_to_k(image):
"""Convert temperature from C to K"""
return image.add(273.15).copyProperties(image, ['system:time_start']) | 97ba24243f2a42fb10a5303e011b4d71e1564f9c | 255,981 |
from datetime import datetime
def timestamp_datetime(timestamp):
"""
Converts a timestamp from the device to a python datetime value
"""
return datetime.fromtimestamp(timestamp / 1000000000.0) | ff20ae37a5775339e9566942224cc54f22acb6d0 | 487,958 |
def convert_version(version):
"""Convert version into a pin-compatible format according to PEP440."""
version_parts = version.split('.')
suffixes = ('post', 'pre')
if any(suffix in version_parts[-1] for suffix in suffixes):
version_parts.pop()
# the max pin length is n-1, but in terms of ind... | b62a40768f1f0f5790cb2d1b16b7e7007bffcef3 | 256,501 |
def set_date(cdate, is_first_loop, is_force_read_cache, arg_date):
"""set date given context
(read cache, get today date or set date argument)
Parameters
----------
is_first_loop : bool
true on first calendar call
is_force_read_cache : bool
force date from cache
arg_date : ... | 8ec3e542657497b71471bc9755d99191438aa530 | 594,801 |
import re
def get_values(text):
"""
Accept a string such as BACKGROUNDCOLOR [r] [g] [b]
and return ['r', 'g', 'b']
"""
res = re.findall("\[(.*?)\]", text)
values = []
for r in res:
if "|" in r:
params = r.split("|")
for p in params:
values.... | 8b315abb66fa7b8b1b35e789deb047026d534c8c | 436,448 |
import math
def distance(a, b):
"""The distance between two (x, y) points."""
return math.hypot((a[0] - b[0]), (a[1] - b[1])) | f1df262eaedac3a0ff21c78c8daafdef4e21dfcc | 229,034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.