content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_n_regions(grid_enc):
""" Get the number of regions encoded by compress_background_smartgrid().
Parameters
----------
grid_enc: dict
Output from compress_background_smartgrid()
Returns
-------
int
Number of regions encoded
"""
regions = 0
for row in g... | f64e466752dc4c702423627113e9704c728a0d65 | 641,742 |
def remove_chars(line, chars=' \t', quotes='\'\"', comments=None):
"""
Removes all specified characters but leaves quotes intact. Removes comments if comment character is specified.
"""
new_line = ''
quote_stack = ''
remove_comments = (type(comments) is list) or (type(comments) is str)
for ... | 5cb7ef977192d361f5d5fc4a3a3b3a9329439fba | 641,744 |
def notify_owner(func):
""" A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``_... | 89f2ca3cdc870b60abef78226a14a4a982c58e24 | 641,745 |
import socket
import time
def check_connection(
ipv4_addr: str,
port: int,
timeout_secs: float = 3.0,
retries: int = 1,
retry_delay: float = 1.0,
raise_error: bool = False) -> bool:
""" Check if remote TCP connection is possible
:param ipv4_addr: remote ipv4 add... | 42ee0574611faf553eb1a0dad95b3731deb764b8 | 641,747 |
def close_time(km,brevet_distance):
"""
input:
km
brevet_distance is one of the standered distances
200,300,400,600,1000 km
output:
Closing time in minutes
"""
## brevet_dict[brevet_distance]=[max_time,min_speed]
brevet_max = { 200:810, 300:1200,400:1620,600:... | b357c8b003df71dda1808af0458cebac8e9cd6c9 | 641,748 |
def mapped_columns(*column_maps):
"""
Given any number of column_maps
return a list of unique column names
"""
result = set()
for column_map in column_maps:
result |= set(column_map.values())
return list(result) | e354cedd60daa6a22b8d52256c916bf0ef46d4df | 641,751 |
def transform_map(kfun=lambda x: x, vfun=lambda x: x):
"""
Function that takes two functions as arguments and returns
a function that applies those functions over all of the
keys and values in a map and returns the transformed version
of the map.
kfun: function applied to all keys (default iden... | 5302a1ddd70bdc94014700f663ebd91d85b8a567 | 641,752 |
def _compute_offset(page: int, items_per_page: int) -> int:
"""Compute the offset value for pagination.
Args:
page (int): The current page to compute the offset from.
items_per_page (int): Number of items per page.
Returns:
int: The offset value.
"""
return int(int(int(page)... | 6510936de2eb45ede1ac1b68735e68450d84262e | 641,754 |
def _positions(field):
"""Given an index into the puzzle (i.e. a single field, calculate and return
a 3-tuple (row, column, box) of the units the field belongs to.
"""
row = field // 9
column = field % 9
box = (field // 3) % 3 + 3 * ((field // 9) // 3)
return row, column, box | 1ff7da9c5adc95035351af31a8fa9e7f4edace3b | 641,760 |
def get_object_instances(predictions, target, confidence):
"""
Return the number of instances of a target class.
"""
targets_identified = [
pred for pred in predictions if pred['label'] == target and float(pred['confidence']) >= confidence]
return len(targets_identified) | a181500085ce2cd496e661f78cc2d54a965ae9bc | 641,765 |
def get_gid_ignore_list(inputfile):
"""Input a file with a list of geneids to ignore when normalizing across taxa
Each line should have 1 geneid on it.
Use '#' at the start of the line for comments
Output a list of geneids to ignore.
"""
# Don't convert GIDs to ints,
# GIDs are not ints for ... | eeb5130bf60e29ce6509adfdf33db0869112b931 | 641,766 |
def listify(x):
""" Coerce iterable object into a list or turn a scalar into single element list
>>> listify(1.2)
[1.2]
>>> listify(range(3))
[0, 1, 2]
"""
try:
return list(x)
except:
if x is None:
return []
return [x] | 656074864ae3795f3755a3d16964ea9779486fc3 | 641,768 |
from bs4 import BeautifulSoup
import re
def parse_course_detail(html):
"""
Use beautifulsoup to get detailed information of one course, then put them
in a dictionary.
"""
soup = BeautifulSoup(html, 'lxml')
table = soup.find_all('span', attrs = {'id': re.compile("^u2(45|54|63|72|81|90)_line\d.?... | c8ad8f6db72133bf8f9bd1dde1d60d094481f45c | 641,772 |
def get_admission_rules(data, scope):
"""Get admission control rules."""
args = {}
if scope == 'fed' or scope == 'local':
args["scope"] = scope
rules = data.client.show("admission/rules", "rules", None, **args) # show(self, path, obj, obj_id, **kwargs)
return rules | b9c0fd2fbc7550c560a9c75af1573d4317c99b72 | 641,779 |
def acquire(filename):
"""Return a grid of integers by parsing a file."""
grid = []
with open(filename) as f:
for line in f:
grid.append([int(x) for x in line.split()])
return grid | e8d13595e5f134f8312840a87331aa9f7da8f45b | 641,781 |
def determine_well_width_tolerance(mean_width):
"""
Determine the tolerance by which well widths are determined to be nearly equal.
Fitted to a polynomial trend line for the following data of (mean, tolerance) pairs::
(100, 0.11), (60, 0.13), (50, 0.15), (25, 0.25), (5, 0.50), (1, 0.59)
Args:... | f1202993fc09ad2d923e3efedbd51cc2ae39bfcb | 641,782 |
def to_unsigned_byte(num):
"""
Convert given signed byte number to byte number.
:param num: Signed number in range from -128 to 127.
:return: Unsigned byte number in range from 0 to 255.
"""
assert -128 <= num <= 127, 'Value out of range (-128 - 127)!'
ret = num if num >= 0 else (256 + num... | 35e52293399326fa1ef124da4d50e2a5363fcd81 | 641,784 |
import string
import random
def generate_random_string(
string_length=88,
chars=string.ascii_lowercase + string.ascii_uppercase + string.digits,
remove_confusing_digits=False):
"""
Generate a random string.
:param string_length:
:param chars:
:param remove_confusing_digits:... | d2ba6bfa407cbe71a8fc65d3350956b1ab51b35a | 641,786 |
def get_engagement_rate_min(selectpicker_id: str) -> int:
"""
Min-Delegate-target of get_engagement_rates_min_max (dac-pattern)
:param selectpicker_id:
:return: int -> min-value of engagement-rate
"""
min_values = {
"1": 0,
"2": 1,
"3": 2,
"4": 3,
"5": 4,... | d9cab14aa84b82cbe6b00d7470185f0353d4c84a | 641,787 |
def total_job_cost(labor, paint_cost):
""" Function that will return the total cost of a job """
return labor + paint_cost | c8bbf29fafcf7f0a4205c9020585e141927c6b97 | 641,788 |
def encode(batch, tokenizer, max_len):
"""
This function takes in a batch and a tokenizer and outputs encoded batch
"""
return tokenizer.encode_plus(
batch, None, add_special_tokens=True, max_length=max_len, pad_to_max_length=True
) | 395d9af6bbdbe0cf8c8bd90887f43c03b460e636 | 641,792 |
def retrieve_fields(arg: str) -> str:
"""Strip and filter out the empty elements from the string.
:type arg: ``str``
:param arg: The string from which we want to filter out the empty elements.
:return: Filtered out result.
:rtype: ``str``
"""
return ",".join([x.strip() for x in arg.split... | 2cb27d992180003c8c75ac0f5621544c8da8c020 | 641,793 |
def get_cz(mag):
"""
Returns the amount of magnetization along z.
Parameters
----------
mag : ndarray
Magnetization vector.
Returns
-------
magz_a, magz_b : float
Amount of magnetization in state a and b along z.
"""
magz_a = mag[2, 0]
magz_b = mag[5, 0]
... | e1a8625fa02845b4bf6ad7c5bc6b7dcddd823b4f | 641,794 |
import string
def make_file_name(song):
"""Returns a valid file name for a song object."""
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
fname = '{} - {}.mp3'.format(song.name.encode('utf8', 'replace'),
song.artist.name.encode('utf8', 'replace'))
f... | b29f1002a8547a7bce9aa20fc77561828bac766d | 641,798 |
def planetary_temp(S, A, L=1.0):
"""Calculate the planetary temperature.
SL(1-A) = sT**4
Arguments
---------
S : float
Incident solar energy.
A : float
Planetary albedo.
Keyword Arguments
-----------------
L = 1.0 : float
Normalised stellar luminosity.
"... | 3ba2c791c0dfa0e284bc2a6deff5d2cd6ef859a8 | 641,804 |
import torch
def batch_index_select(x, idx):
"""
:param x: *, n, Dim
:param idx: *, k
:return: *, k , Dim
"""
idx_ = idx.unsqueeze(-1).expand(idx.shape + (x.shape[-1],))
return torch.gather(x, -2, idx_) | ee0c68e683366bc2a887748d289c6ef52223a297 | 641,805 |
def draw_frame(surface, rect, color_fill, color_border, border=1):
"""
Creates and draws a rect with a frame. Returns the inside rect object.
returns a pygame.Rect() object, which is the filled area inside the frame
- surface: the pygame surface to draw this on
- rect: pygame.Rect() object for the o... | 2b37a96beb6d1c4d0aa184e677f6c8528b90193e | 641,806 |
def _eval_expr(expr, ctxt, vars=None):
"""Evaluate the given `Expression` object.
:param expr: the expression to evaluate
:param ctxt: the `Context`
:param vars: additional variables that should be available to the
expression
:return: the result of the evaluation
"""
if... | 20c3fc9d2a8a4f61ea72d6df3474e034c6369d7e | 641,808 |
def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field) | 7cd3d19024050f1a2e0d6912ef0824c632e0feb4 | 641,811 |
def allMatches(source, regex):
"""Return a list of matches for regex in source
"""
pos = 0
end = len(source)
rv = []
match = regex.search(source, pos)
while match:
rv.append(match)
match = regex.search(source, match.end() )
return rv | a7d20a2ea65ce28c0d3dd2cb08bc46b4f94d7030 | 641,817 |
import io
def readReviews(path):
"""
Function to store reviews in a list buffer.
Arguments
---------
path: location of reviews
Return
---------
list of reviews
"""
# Create an empty buffer to hold all the reviews
reviewBuf = []
# Open the file
with io.open(path,'r') as raw:
for line in raw:
revi... | e349cd18c63d5215e79f68cdfbc89a6a48371bd9 | 641,821 |
def get_fitzpatrick_type(ita):
"""
This function will take a ita value and return the Fitzpatrick skin tone scale
https://arxiv.org/pdf/2104.14685.pdf
:param ita:
:return:
"""
if ita < -50:
return "6"
elif -50 <= ita < -25:
return "5"
elif -25 <= ita < 0:
retu... | d4a205a760c28870911a7b9ed7e3aeafe61158e1 | 641,827 |
import requests
def twitter_get_friends_json(nickname: str, token: str) -> dict:
"""
Get json with friends by username from twitter.
"""
reqest_url = "https://api.twitter.com/1.1/friends/list.json"
headers = {
'Authorization': 'Bearer {}'.format(token)
}
params = {
'scree... | 2853a80a4707f19014c368ae15e7386838f96c5f | 641,830 |
def get_cam_name(i, min_chars=7):
"""Create formatted camera name from index."""
format_str = '{:0' + str(min_chars) + 'd}'
return 'cam_' + format_str.format(i) | 953446c3cf1b2ab9525931ac02a749e9645d8e47 | 641,831 |
def linear(x, slope=1.0, intercept=0.0):
"""Return a linear function.
x -> slope * x + intercept
"""
return slope * x + intercept | 174269c7e9d970cad60a1f15bc2231f317e7e8fe | 641,833 |
import random
def different_account(account, test_case=None):
"""Randomly choose a non-existant account or keep account."""
if test_case:
if test_case.get("account"):
return "FFFFFFFFF"
else:
return account
else:
return "FFFFFFFFF" if random.random() < 0.1 e... | 19c25746bdc17da845588f3e845e39b4a039181f | 641,834 |
import hashlib
def sha512_encode(t):
"""Encoder using SHA512.
>>> sha512_encode("Hola mundo")
'34ddb0edac59e441459e07cf33bd628f53fbbf752141125f069f32081b169f933666c71b2f1b83031da66bc905a1e72af7c6cfd779fc197513639a098f94c641'
"""
s = hashlib.sha512(t)
return s.hexdigest() | 2a005d9bfce688694e582c00434ba7e228ddc185 | 641,841 |
def geth_to_cmd(node, datadir, verbosity):
"""
Transform a node configuration into a cmd-args list for `subprocess.Popen`.
Args:
node (dict): a node configuration
datadir (str): the node's datadir
Return:
List[str]: cmd-args list
"""
node_config = [
'nodekeyhex'... | 17b8c8edd8895ef6d8bedd862ed214df16e28159 | 641,844 |
import re
def get_words_from_txt_file(txt_path: str) -> list:
""" Return list of words from txt file at specified path """
words = []
with open(txt_path, encoding='utf-8') as file:
for line in file:
try:
for word in line.split():
words.append(word... | 3c1957684d8bfe0e20711b9e63844d64c5806a23 | 641,846 |
def extract_terminal_pathname(url):
"""Extract the last path segment from a URL
"""
return list(filter(None, url.split("/"))).pop() | b3c4e7dddf3d903df54d38f2f9fc6593f2654bb2 | 641,847 |
import pickle
def load_pickle(path):
""" Loads a .pickle file
Parameters
----------
path : str
Absolute path to the file
Returns
-------
Object contained in the .pickle file
"""
with open(path, 'rb') as f:
return pickle.load(f) | b840696d71bd7b14749a68c4761ff4ae7aef0a4e | 641,855 |
import gzip
def parse (f):
"""Decompress an epgdb file.
:arg typing.BinaryIO f: epgdb file contents
:return: Uncompressed epgdb file contents
:rtype: typing.BinaryIO
"""
# skip epgdb-specific header
f.read(12)
return gzip.GzipFile(fileobj=f) | b5f1d67189896618a7cfa8fd68eb46419ab5ac5b | 641,856 |
def build_vocab(posts):
"""
Given the training set of posts, constructs the vocabulary dictionary, `tok_to_ix`, that
maps unique tokens to their index in the vocabulary.
"""
tok_to_ix = {}
for post in posts:
tokens = post.split(' ')
for token in tokens:
tok_to_ix.setd... | a3f06c4d8f9427672291b71f7f6d87e870cb7ad1 | 641,857 |
def get_feature_importance_data(data_income, column='Close_x', include_targets=False):
"""
:param data_income:
:param column:
:param include_targets: targets are 'Open_x', 'High_x', 'Low_x' and 'Close_x'
:return: train and test of X and y
"""
data = data_income.copy()
y = data[column]
... | 00b96f8ce08355a0d085c93d62200ac6f024f86e | 641,860 |
def naive(data, **kwargs):
"""The naive forecast for the next point is the value of the previous point.
In most forecasting situations, the naive model is a good baseline due to it's simplicity
and low computational overhead.
Args:
data (np.array): Observed data, presumed to be ordered in t... | 5410fb5d79c02ae8a0c2e035f677bc996889d87f | 641,861 |
def str_responder(*args, **kwargs):
"""Responds with an empty string"""
return '' | 159199ccb5bc2223e9add22e181e494ab2143d57 | 641,862 |
import hashlib
def get_hash(filepath):
"""
Generates unique ID based on hash of the file
Args: filepath (str) path to file to read
Returns hash of file
"""
filehash = hashlib.md5()
with open(filepath, 'rb') as fobj:
for chunk in iter(lambda: fobj.read(2097152), b""):
filehash.update... | b66b793bc2152de4042cf3b0567e8d24e00f5cba | 641,865 |
def biggest(a, b):
"""
This function returns the biggest of the numbers (but it does checks for None).
Input:
a: int, first number;
b: int, second number.
Output:
biggest: int, the biggest number of the passed numbers (the non-None number, if one of the ... | 8d43f3bb488dd3afe749873a32f091ca399da6ae | 641,873 |
def unflatten(tensor, batch_size, num_rounds):
"""Unflatten a tensor based on batch_size(B) and num_rounds(N).
Args:
tensor: Size [B*N, D1, D2, D3, ...]
batch_size: B
num_rounds = N
Returns:
unflat_tensor: Size [B, N, D1, D2, ...]
"""
old_size = tensor.shape
expected_fi... | bb09d5dc027798bb87aad4b254d93564d76ac251 | 641,874 |
def lstrip_keep(text):
"""
Like lstrip, but also returns the whitespace that was stripped off
"""
text_length = len(text)
new_text = text.lstrip()
prefix = text[0 : (text_length - len(new_text))]
return new_text, prefix | cb1667eb0f5189fbae0d00dcaf0e1f761e1cf3f2 | 641,879 |
import re
def get_track_quirk(quirks, cro_track_id):
"""Return Spotify track id for given CRo track id from quirks."""
q = quirks["tracks"].get(cro_track_id)
if q:
m = re.search(r"(?:track.)?([0-9a-zA-Z]{22})", q)
if m:
return m.group(1) | c5a37d3eb84a467ea37efd1c1f7cd7a532cae7b4 | 641,886 |
def generate_sns_event(message, topic, subject):
"""
Generates a SNS Event
:param str message: Message sent to the topic
:param str topic: Name of the Topic
:param str subject: Subject of the Topic
:return dict: Dictionary representing the SNS Event
"""
return {
"Records": [{
... | 53e3a4b97032539236d091535e7f746e2e239eed | 641,887 |
import time
def FunctionTimer(on_done=None):
"""
To check execution time of a function
borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
>>> def logger(details, args, kwargs): #some function that uses the time output
... print(d... | 3066beb22b589d1a25175a8fa423399cf33d3209 | 641,889 |
from typing import Tuple
def split_namespace(s: str) -> Tuple[str, str]:
""" Splits a namespace and name into their parts
Parameters
----------
s: str
string to be split
Returns
-------
(tuple)
namespace: str
name: str
"""
split = s.spl... | 118f48dfa3ef560c766efa81bf042762245a6218 | 641,890 |
from operator import mul
def compute_mul(tree):
"""
Compute the Variable that is the output of a multiplication tree.
This is the inverse of the operation performed by `parse_mul_tree`, i.e.
compute_mul(parse_mul_tree(tree)) == tree.
Parameters
----------
tree
A multiplication tr... | ad479d3dd44fc9db3eabea9a9dd7d9c38beffcd0 | 641,892 |
def doc_string(docstring: str = "default doc"):
"""Set a documentation string for `function`. Helpful if several functions have the same doc"""
def wrapper(function):
function.__doc__ += docstring
return function
return wrapper | 5b9957f22b588fb5868a03a2f4e852f19889a84d | 641,893 |
def local_temp(A, albedo, T, q=30):
"""Calculate local temperature experienced by a particular daisy type or
ground cover. This is a simplified version of the original.
q*(A-albedo)+T
Arguments
---------
A : float
Planetary albedo
alpha : float
Albedo of daisy type
T : f... | a0e92e2ae3fbf1226eebed2b19c8d221cf5a267a | 641,897 |
def to_bool(boolean: bool):
"""
Checks if an argument is of type bool:
- If argument is type bool, simply returns argument
- If argunent is type str, attempts to convert to type bool
- Raises TypeError otherwise
:param boolean: bool, str
argument to be converted to type bool... | da0848703887ae403934e2d16ddd7634d8348d57 | 641,901 |
import re
def _strip_blanks(table):
"""
Remove blank lines from table (included for "human readability" but
useless to us...
returns a single string joined by \n newlines
Parameters
----------
table : str
table to strip as a string
Returns
-------
single string joined ... | 28cbe4e8ef2c94fc43db3928a194a5724b39187b | 641,915 |
def is_parans_exp(istr):
"""
Determines if an expression is a valid function "call"
"""
fxn = istr.split('(')[0]
if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')':
return False
plevel = 1
for c in '('.join(istr[:-1].split('(')[1:]):
if c == '(':
plevel += 1... | 3b161e92e43afe5035a96595ad2c94a437b4d972 | 641,919 |
import inspect
def inherit_docstring(c, meth):
"""Since Python 3.5, inspect.getdoc is supposed to return the docstring from a parent class
if a class has none. However this doesn't seem to work for Cython classes.
"""
doc = None
for ancestor in inspect.getmro(c):
try:
ancest... | 657934baaabfb72888a1e8301ec8809103ee23d9 | 641,920 |
from typing import Callable
import importlib
def get_method(pkg_path: str) -> Callable:
"""
Returns a method given the full package path of the method, e.g.
given the string ``oedtools.schema.get_schema`` it will return the
actual method ``get_schema`` from the ``oedtools.schema`` module.
:param ... | 324baedaed4cb7f5d217afb7645891a6f6eef16a | 641,921 |
def epsg_from_utm_zone(zone):
"""
Returns the WGS-84 EPSG for a given UTM zone
Input:
zone(int): Zone, positive values for North
Output:
epsg code(int).
"""
if zone > 0:
epsg = 32600 + zone
else:
epsg = 32700 - zone
return epsg | 85dd9eb4548124591768ed1f316337c3fdabfa05 | 641,922 |
def liveobj_valid(obj):
"""
Check whether obj represents a valid Live API obj.
This will return False both if obj represents a lost weakref or is None.
It's important that Live API objects are not checked using "is None", since this
would treat lost weakrefs as valid.
"""
return obj != None | ba241abeac835711a1dfc2984c5128e11ae865bf | 641,925 |
from functools import reduce
import operator
def prod(factors):
"""
The product of the given factors (iterable)
:param factors:
:return:
"""
return reduce(operator.mul, factors, 1.0) | bb9e1659edb684c0ddda6dab0aa07ccc2ed3cd8d | 641,927 |
import re
def paragraphs(corpus):
"""
>>> text = 'P1\n\nP2\nP2\n \t \n\n\n \t\nP3'
>>> paragraphs(text)
'<p>P1</p>\n<p>P2\nP2</p>\n<p>P3</p>'
"""
inner_paras_added = re.sub(r'\n\s*\n', '</p>\n<p>', corpus)
all_paras_added = f'<p>{inner_paras_added}</p>'
return all_paras_added | da365a0a129b9090f98bb1874f309b42acc1e725 | 641,928 |
import random
import logging
def get_random_route(rs_api) -> int:
"""Gets a random route id used for testing"""
routes = rs_api.get_routes()
index = random.randint(1, len(routes) - 1)
route_id = routes[index]['RouteID']
logging.getLogger().info("Selecting RouteID %s", route_id)
return route_id | 0319dc99fe1357752ef5a5c215a2859b9a94b252 | 641,930 |
def prepareDFgeneral(dfAllCancerData):
"""
Given that the entire PSP cancer data is passed as a dataframe, it
i) separates the genes (features) from the target variables,
that is: CancerStatus, Project, TumorStage, Race, and Gender
ii) asks the user to chose one of them as the class variable
i... | b007bd63f44157fd5f941e64eb54d5fc0892e55b | 641,931 |
def _NameToIndex(name, L):
"""Return index of name in list, appending if necessary
This routine uses a list instead of a dictionary, because a
dictionary can't store two different keys if the keys have the
same value but different types, e.g. 2 and 2L. The compiler
must treat these two separately,... | 10b0a501f199c0a12ec303b8b087ce45c7de1574 | 641,933 |
def rhist(ax, data, **keywords):
"""Creates a histogram with default style parameters to look like ggplot2
Is equivalent to calling ax.hist and accepts the same keyword parameters.
If style parameters are explicitly defined, they will not be overwritten
"""
defaults = {
'facecol... | 59cf798b0787cfba9f8cb807b622d491f4b3add3 | 641,936 |
def flatten_arguments(arg_dict):
"""Flattens a dict of options into an argument list.
Parameters
----------
arg_dict : Dict[Str, Any]
Dictionary of arguments. Keys should be strings, values may be
lists or tuples (for multiple values), booleans (for flags)
or any other value tha... | 7088ac7d5d4ac7906b9baf526a7d14f90efed832 | 641,938 |
import stat
def file_groupreadable(path):
"""Check whether a given path has bad permissons."""
if not bool(stat.S_IRGRP & path.stat().mode):
return 'PROB_FILE_NOT_GRPRD' | 66138dea25e80344f70f1eec6d72662e0ad453ff | 641,939 |
def GetPortStatus(chameleond, port_id):
"""Gets port status with port_id through chameleond proxy."""
if not chameleond.IsPhysicalPlugged(port_id):
return 'Not connected\n'
if chameleond.IsPlugged(port_id):
return 'Connected\nPlugged\n'
return 'Connected\nNot plugged\n' | 2d2225c556ce3de4bad6269fa4f73b5a0da4ce13 | 641,941 |
def get_low_high_cells(methylation_df, patient, percentage):
"""
For the given patient calculate the percentage high and low cells, excluding normal cells.
:param methylation_df: df containing the average methylation levels for each cell.
:param patient: The patient to calculate cells for.
:param pe... | d884790e0bf3713ac04748547e3095b917b73cfd | 641,942 |
def _ch(x: int, y: int, z: int):
"""As defined in the specification."""
return (x & y) ^ (~x & z) | 6f63ce6a4ee484581d10809593ca4ed6cafc3118 | 641,943 |
def TransformSplit(r, sep='/', undefined=''):
"""Splits a string by the value of sep.
Args:
r: A string.
sep: The separator value to use when splitting.
undefined: Returns this value if the result after splitting is empty.
Returns:
A new array containing the split components of the resource.
... | c9288fe011f0f1a45992cfca5e9b4f409d8fe45d | 641,950 |
import torch
def MIoU(pred, gt):
"""
Description:
Mean Intersection over Union
Params:
pred -- the predicted label, tensor of shape (N,H,W,C)
gt -- the ground_truth label, tensor of shape (N,H,W,C)
Tips:
gt needs to be transformed to one_hot form
"""
intersectio... | c4da0cb179d200ed342e061abea8e06e3d38ba0a | 641,953 |
import torch
def default_orientation(num: int, device: str) -> torch.Tensor:
"""Returns identity rotation transform."""
quat = torch.zeros((num, 4,), dtype=torch.float, device=device)
quat[..., -1] = 1.0
return quat | 5eddc23ece4e98a264ce8592e95af8c36f2bf9bd | 641,955 |
def th_flatten(x):
"""Flatten tensor"""
return x.contiguous().view(-1) | 615e726cb5322cae1ca2faa3a1442667a66e2da4 | 641,956 |
import functools
import string
import unicodedata
def unaccent(text):
"""Translate accented characters to their non-accented equivalents"""
@functools.cache
def unaccent_c(char):
if char in string.printable:
return char
elif unicodedata.combining(char):
return None
else:
return unicodedata.normalize... | 1d49eb2089335692d3fb6c28b4a9a8575341945a | 641,959 |
import torch
def sample_batch(data, length, batch_size):
"""
Takes the data (a single sequence of tokens) and slices out a batch of subsequences to provide as input to the model.
For each input instance, it also slices out the sequence that is shofted one position to the right, to provide as a
target... | d35643d6e3be8a3fc37c010d0de3ff9ec00ec9f4 | 641,961 |
def italic(text: str) -> str:
"""
Return the *text* surrounded by italic HTML tags.
>>> italic("foo")
'<i>foo</i>'
"""
return f"<i>{text}</i>" | 5439c9d7d3c82c63d9f3ca5980a3d3c360b607d4 | 641,962 |
def carddir(deg):
"""Returns the cardinal direction string from degrees (0° = N, 90° = E, ...)
"""
return ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'][int(((deg+11.25)%360)/22.5)] | 77367c74f9593d173271a6f33e5f84f0bb8ee17a | 641,964 |
def chunk_array(array, num_chunks, len_array):
"""
Chunk a given list into a given number of smaller lists.
:param array:
:param num_chunks:
:return:
"""
# return [array[i:i + num_chunks] for i in range(0, len(array), num_chunks)]
if len_array > num_chunks:
if len_array % num_chu... | 8cc4451fd5c6a8360024cbeeebe79448d1d5ed0c | 641,974 |
import torch
def bboxes2tblr(priors, gts, normalizer=4.0, normalize_by_wh=False):
"""Encode ground truth boxes to tblr coordinate.
It first convert the gt coordinate to tblr format,
(top, bottom, left, right), relative to prior box centers.
The tblr coordinate may be normalized by the side length of... | 942ddf4baafb76141607485e388117816d69f908 | 641,977 |
from typing import Any
def cls_is_annotated(cls: Any) -> bool:
"""
Inspect if a class has annotations
Args:
cls (Any): Class to inspect
Returns:
bool: True if cls is annotated else False
"""
return (
hasattr(cls, "__dict__")
and "__annotations__" in cls.__dict... | 6d26d77310248917a8568516637cb3dcc27c21db | 641,982 |
def calc_relative_density_boulanger_et_al_2014_cpt_values(q_c1n, c_dq=0.9):
"""
Table 4.1 in PM4Sand v3.1 manual
Parameters
----------
q_c1n: array_like
Normalised cone penetration resistance
c_dq: float, default=0.9 (from :cite:`Idriss:2008ua`)
Correlation factor, (range 0.64-1... | 56042ae414e415843ed9a911383e2d0506c6b7b4 | 641,983 |
def get_row_col_matrix(row_index_set, col_index_set):
"""
Returns the resulting matrix when using a row and column of indices (list of tuples)
row_index_set: the index set that would be taken from wells A-H (or equivalent) on that plate. Should be dim 8 or 16.
col_index_set: the index set that would be... | f074fedfb681d40d8fafb3c2de8aa99d2601b907 | 641,987 |
def _UsingGtestJson(options):
"""Returns True if we're using GTest JSON summary."""
return (options.annotate == 'gtest' and
not options.run_python_script and
not options.run_shell_script) | 400d454fb00639395f44e1c5f99be1a0a53e6b4c | 641,988 |
def CSourceForArrayData(values, formatter, margin=4, width=80):
"""Turn an array of values into a C source array data definition.
Args:
values: Array of input values.
formatter: Formatting function, applied to each input value to get a
C-source description of the value.
margin: Left-side margin /... | 602c0cc6fab36647db2b6cddd5e51af920672f2f | 641,992 |
def get_binary_mask_from_raw_address(raw_address: str) -> str:
"""
Return binary mask from raw address.
>>> get_binary_mask_from_raw_address("192.168.1.15/24")
'11111111.11111111.11111111.00000000'
>>> get_binary_mask_from_raw_address("91.124.230.205/30")
'11111111.11111111.11111111.11111100'
... | a29567d0cebf2b4442f1f242f547c766726cd9f2 | 641,994 |
def cyclic(graph):
"""
Return True if the directed graph has a cycle.
The graph must be represented as a dictionary mapping vertices to
iterables of neighbouring vertices. For example:
>>> cyclic({1: (2,), 2: (3,), 3: (1,)})
True
>>> cyclic({1: (2,), 2: (3,), 3: (4,)})
False
"""
... | de8a768af9705b5c8a7b8a8c3f2d9a651e089ba4 | 641,995 |
def high_income_amount(responses, derived):
""" Return the guidelines table amount for a high income earner """
try:
under = float(responses.get('child_support_amount_under_high_income', 0))
except ValueError:
under = 0
try:
over = float(responses.get('amount_income_over_high_i... | 588ce06fd276be6695b0cab852ab6020a404338f | 642,000 |
def get_col(df, key):
"""
Return a DataFrame column by either name or numeric index.
:param df: A pandas.DataFrame
:param key: A string or int
:return: The indicated column from the dataframe, either by name or order.
"""
try:
if isinstance(key, int) and (key not in df.columns):
... | f91155c9200a1e3f2132d4c5601f771a4f06d2c2 | 642,002 |
import torch
def generate_noise(max_norm, parameter, noise_multiplier, noise_type, device):
"""
A noise generation function that can utilize different distributions for noise generation.
@param max_norm
The maximum norm of the per-sample gradients. Any gradient with norm
higher than this ... | fdd2689baf1b21e76aaf0655d887c1d4976237dc | 642,005 |
import pathlib
def get_testdata_file_path(rel_path: str) -> pathlib.Path:
"""Gets the full path to a file in the testdata directory.
Arguments:
rel_path -- path relative to testdata/
Returns:
pathlib.Path -- the full path to the file.
"""
return pathlib.Path(__file__).parent / "t... | 48431abacceb289a8349bd10b911001525caf954 | 642,006 |
def usage_hint(command, shell):
"""
Returns the usage hint and comment, for the given shell.
"""
if shell == "fish":
return ("eval ({command})".format(command=command), "#")
elif shell == "powershell":
return (
"{command} | ForEach-Object {{If (-Not[string]::IsNullOrEmpty... | e82469240fbf8f37daa0cebf7b40a500e27298ae | 642,008 |
import random
import string
def latin(minimum=3, maximum=8, separator=' '):
"""
Simple function to generate fake (two parts) Latin species names.
:param minimum: int, minimum number of letters in each part of the Latin name.
:param maximum: int, maximum number of letters in each part of the Latin... | ed5f0c7625af90e783015cd6304a2e2dd77d1762 | 642,010 |
def report(sufficient_items, insufficient_items, condition, output = ".", prefix = None, **kwargs):
"""
Report the symbols which did not pass the condition.
Parameters:
sufficient_items: List of (name, object)-tuples that passed the condition
insufficient_items: List of (n... | 359ba53b7ad68747a311606bc311306c8d1c1a07 | 642,014 |
def squeeze_batch_dim(tt):
"""Converts batch size 1 TensorTrainBatch into TensorTrain.
Args:
tt: TensorTrain or TensorTrainBatch.
Returns:
TensorTrain if the input is a TensorTrainBatch with batch_size == 1 (known
at compilation stage) or a TensorTrain.
TensorTrainBatch otherwise.
"""
tr... | eea54ca8b6c4582751b3bc76a519f911c6ecddf7 | 642,016 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.