content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def translate_boarding_cards(boarding_cards):
"""Translate list of BoardingCards to readable travel instructions.
This function sorts list of random BoardingCard objects connecting starts
with ends of every stage of the trip then returns readable instructions
that include seat numbers, location names a... | 28,100 |
def detect_side(start: dict, point: dict, degrees):
"""detect to which side robot should rotate"""
if start['lat'] < point['lat'] and start['lng'] < point['lng']:
return f'{degrees} degrees right'
elif start['lat'] < point['lat'] and start['lng'] > point['lng']:
return f'{degrees} de... | 28,101 |
def ScanSlnFile(filename):
"""Scan a Visual Studio .sln and extract the project dependencies."""
try:
sln = open(filename, "r")
except IOError:
sys.stderr.write("Unable to open " + filename + " for reading.\n")
return 1
projects = {}
project = None
while 1:
line = sln.readline().strip()
... | 28,102 |
def iterate_log_lines(file_path:pathlib.Path, n:int = 0, **kwargs):
"""Reads the file in line by line
dev note: One of the best featuers of this functions is we can use efficient
unix style operations. Because we know we are inside of a unix container
there should be no problem relying on G... | 28,103 |
def moving_sum(x, start_idx: int, end_idx: int):
"""
From MONOTONIC CHUNKWISE ATTENTION
https://arxiv.org/pdf/1712.05382.pdf
Equation (18)
x = [x_1, x_2, ..., x_N]
MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m
for n in {1, 2, 3, ..., N}
x : src_len, b... | 28,104 |
def _wait_for_event(event_name, redis_address, extra_buffer=0):
"""Block until an event has been broadcast.
This is used to synchronize drivers for the multi-node tests.
Args:
event_name: The name of the event to wait for.
redis_address: The address of the Redis server to use for
... | 28,105 |
def _stack_exists(stack_name):
""" Checks if the stack exists.
Returns True if it exists and False if not.
"""
cf = boto3.client('cloudformation')
exists = False
try:
cf.describe_stacks(StackName=stack_name)
exists = True
except botocore.exceptions.ClientError as ex:
... | 28,106 |
def mode():
"""Compute mode.
Formatting multiple modes is a little ambiguous in the context of pcalc,
so this condition triggers an error."""
count = Counter(_values())
# If the two most common elements have the same count then there are at
# least 2 modes.
if len(count) > 1 and len({c[-... | 28,107 |
def make_sequence_output(detections, classes):
"""
Create the output object for an entire sequence
:param detections: A list of lists of detections. Must contain an entry for each image in the sequence
:param classes: The list of classes in the order they appear in the label probabilities
:return:
... | 28,108 |
def json_to_dataframe(json, subset=0):
"""Load data from path. The file needs to be a .csv
Returns:\n
Dataframe
"""
# This is to make sure it has the right format when passed to pandas
if type(json) != list:
json = [json]
try:
df = pd.DataFrame(json, [i for i in range(0, len... | 28,109 |
def pow(a, b, num_threads=None, direction='left'):
"""Raise to power multithreaded
Args
a (np.ndarray or scalar): Numpy array or scalar
b (np.ndarray or scalar): Numpy array or scalar
num_threads : Number of threads to be used, overrides threads as set by
... | 28,110 |
def dms_to_angle(dms):
"""
Get the angle from a tuple of numbers or strings giving its sexagesimal
representation in degrees
@param dms: (degrees, minutes, seconds)
"""
sign = 1
angle_string = dms[0]
if angle_string.startswith('-'):
sign = -1
angle_string = angle_string[1... | 28,111 |
def fix(text):
"""Repairs encoding problems."""
# NOTE(Jonas): This seems to be fixed on the PHP side for now.
# import ftfy
# return ftfy.fix_text(text)
return text | 28,112 |
def generate_labeled_regions(shape, n_regions, rand_gen=None, labels=None,
affine=np.eye(4), dtype=np.int):
"""Generate a 3D volume with labeled regions.
Parameters
----------
shape: tuple
shape of returned array
n_regions: int
number of regions to gene... | 28,113 |
def get_source_item_ids(portal, q=None):
"""
Get ids of hosted feature services that have an associated scene service.
Can pass in portal search function query (q).
Returns ids only for valid source items.
"""
source_item_ids = []
scene_item_ids = get_scene_service_item_ids(portal)
... | 28,114 |
def rasterize_poly(poly_xy, shape):
"""
Args:
poly_xy: [(x1, y1), (x2, y2), ...]
Returns a bool array containing True for pixels inside the polygon
"""
_poly = poly_xy[:-1]
# PIL wants *EXACTLY* a list of tuple (NOT a numpy array)
_poly = [tuple(p) for p in _poly]
img = Image.ne... | 28,115 |
def from_url_representation(url_rep: str) -> str:
"""Reconvert url representation of path to actual path"""
return url_rep.replace("__", "/").replace("-_-", "_") | 28,116 |
async def test_async_start_from_history_and_switch_to_watching_state_changes_multiple(
hass,
recorder_mock,
):
"""Test we startup from history and switch to watching state changes."""
hass.config.set_time_zone("UTC")
utcnow = dt_util.utcnow()
start_time = utcnow.replace(hour=0, minute=0, second=... | 28,117 |
def runningmean(data, nav):
"""
Compute the running mean of a 1-dimenional array.
Args:
data: Input data of shape (N, )
nav: Number of points over which the data will be averaged
Returns:
Array of shape (N-(nav-1), )
"""
return np.convolve(data, np.ones((nav,)) / nav, m... | 28,118 |
def retreive_dataset(filename, url):
"""
Download datasets, like the EADL or EPDL on the IAEA website, by blatantly
spoofing the User-Agent. Spoofing based on this reference:
http://stackoverflow.com/a/802246/2465202
Downloading based on this one:
http://stackoverflow.com/a/22721/2465202... | 28,119 |
def test_space(gym_space, expected_size, expected_min, expected_max):
"""Test that an action or observation space is the correct size and bounds.
Parameters
----------
gym_space : gym.spaces.Box
gym space object to be tested
expected_size : int
expected size
expected_min : float... | 28,120 |
def multiindex_strategy(
pandera_dtype: Optional[DataType] = None,
strategy: Optional[SearchStrategy] = None,
*,
indexes: Optional[List] = None,
size: Optional[int] = None,
):
"""Strategy to generate a pandas MultiIndex object.
:param pandera_dtype: :class:`pandera.dtypes.DataType` instance... | 28,121 |
def pitch_from_centers(X, Y):
"""Spot pitch in X and Y direction estimated from spot centers (X, Y).
"""
assert X.shape == Y.shape
assert X.size > 1
nspots_y, nspots_x = X.shape
if nspots_x > 1 and nspots_y == 1:
pitch_x = pitch_y = np.mean(np.diff(X, axis=1))
elif nspots_y > 1 and n... | 28,122 |
def cleanup(signal_received, frame):
"""Cleanup method, clears all pins.
"""
clear_all_pins()
sys.exit(0) | 28,123 |
def upload(files, to, config, delete_on_success, print_file_id, force_file, forward, directories, large_files, caption,
no_thumbnail):
"""Upload one or more files to Telegram using your personal account.
The maximum file size is 1.5 GiB and by default they will be saved in
your saved messages.
... | 28,124 |
def scilab_console():
"""
This requires that the optional Scilab program be installed and in
your PATH, but no optional Sage packages need to be installed.
EXAMPLES:
sage: from sage.interfaces.scilab import scilab_console # optional - scilab
sage: scilab_console() ... | 28,125 |
def _create_lists(config, results, current, stack, inside_cartesian=None):
"""
An ugly recursive method to transform config dict
into a tree of AbstractNestedList.
"""
# Have we done it already?
try:
return results[current]
except KeyError:
pass
# Check recursion depth an... | 28,126 |
def encode(value):
"""
Encode strings in UTF-8.
:param value: value to be encoded in UTF-8
:return: encoded value
"""
return str(u''.join(value).encode('utf-8')) | 28,127 |
def get_season(months, str_='{}'):
"""
Creates a season string.
Parameters:
- months (list of int)
- str_ (str, optional): Formatter string, should contain exactly one {}
at the position where the season substring is included.
Returns:
str
"""
if months is None:
retur... | 28,128 |
def data_availability(tags):
"""
get availability based on the validation tags
Args:
tags (pandas.DataFrame): errors tagged as true (see function data_validation)
Returns:
pandas.Series: availability
"""
return ~tags.any(axis=1) | 28,129 |
def name(ctx: EndpointContext) -> None:
"""Handles changing the name of the client.
If the name is longer than 31 characters it will be cut off after
the 31st character.
Informs the client of the success of the operation.
Args:
ctx: The request's context.
"""
name_param = ctx.param... | 28,130 |
async def fetch_image_by_id(
image_uid: str
):
"""
API request to return a single image by uid
"""
image_uid = int(image_uid)
image = utils_com.get_com_image_by_uid(image_uid)
return image | 28,131 |
def last(user, channel, text):
"""Show the last lines from the log"""
max_lines = lala.config.get_int("max_lines")
s_text = text.split()
try:
lines = min(max_lines, int(s_text[1]))
except IndexError:
lines = max_lines
logfile = lala.config.get("log_file")
with codecs.open(log... | 28,132 |
def get_spring_break(soup_lst, year):
"""
Purpose:
* returns a list of the weekdays during spring break
* only relevant for spring semesters
"""
spring_break_week = set()
# search for the "Spring Break begins after last class." text
for i in range(len(soup_lst)):
if soup... | 28,133 |
def GetProQ3Option(query_para):#{{{
"""Return the proq3opt in list
"""
yes_or_no_opt = {}
for item in ['isDeepLearning', 'isRepack', 'isKeepFiles']:
if query_para[item]:
yes_or_no_opt[item] = "yes"
else:
yes_or_no_opt[item] = "no"
proq3opt = [
"-r... | 28,134 |
def test_migration_slug_generator(unit, resource):
"""
Test that the migration which adds slug fields also generates values for
those.
"""
# set initial fake values for slugs
Unit.objects.filter(id=unit.id).update(slug="xxxfakeunit")
Resource.objects.filter(id=resource.id).update(slug="xxxf... | 28,135 |
def is_empty_config(host):
"""
Check if any services should to be configured to run on the given host.
"""
return host.AS is None | 28,136 |
def total_value(metric):
"""Given a time series of values, sum the values"""
total = 0
for i in metric:
total += i
return total | 28,137 |
def unpackJSON(target_naming_scheme, chemdf_dict):
"""
most granular data for each row of the final CSV is the well information.
Each well will need all associated information of chemicals, run, etc.
Unpack those values first and then copy the generated array to each of the invidual wells
developed ... | 28,138 |
def mtrace(m):
"""Takes module name, adds imported modules recursively to mtable."""
if mtable.has_key(m):
return
mtable[m] = []
mf = get_module_file(m)
if mf == None:
return
f = open(mf)
l = f.readline()
while l:
# Skipping doc strings at beginning of file
... | 28,139 |
def set_thread_exception_handler():
"""
taken from http://bugs.python.org/issue1230540
Workaround for sys.excepthook thread bug
From
http://spyced.blogspot.com/2007/06/workaround-for-sysexcepthook-bug.html
(https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1230540&group... | 28,140 |
def create_vpn_int_feature_template(types, name, if_name, description, ip_addr_name, color):
""" Usage: sdwancli template feature create banner -t '["vedge-cloud",
"vedge-1000"]' -n VE-banner-2
"""
headers = authentication(vmanage)
base_url = "https://" + f'{vmanage["host"]}:{vmanage["port"]}/datase... | 28,141 |
def generate_fixture_tests(metafunc: Any,
base_fixture_path: str,
filter_fn: Callable[..., Any] = identity,
preprocess_fn: Callable[..., Any] = identity) -> None:
"""
Helper function for use with `pytest_generate_tests` which will ... | 28,142 |
def validate_email_add(email_str):
"""Validates the email string"""
email = extract_email_id(email_str)
import re
return re.match("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", email.lower()) | 28,143 |
def get_seed_nodes_json(json_node: dict, seed_nodes_control: dict or list) -> dict:
""" We need to seed some json sections for extract_fields.
This seeds those nodes as needed. """
seed_json_output = {}
if isinstance(seed_nodes_control, dict) or isinstance(seed_nodes_control, list):
for node... | 28,144 |
def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
... | 28,145 |
def _inufft(kspace,
trajectory,
sensitivities=None,
image_shape=None,
tol=1e-5,
max_iter=10,
return_cg_state=False,
multicoil=None,
combine_coils=True):
"""MR image reconstruction using iterative inverse NUFFT.
For the ... | 28,146 |
def adjust_cart(request, item_id):
"""Adjust the quantity of the specified product to the specified amount"""
album = get_object_or_404(Album, pk=item_id)
# Returns 404 if an invalid quantity is entered
try:
quantity = int(request.POST.get("quantity"))
except Exception as e:
return... | 28,147 |
def calculate_delta_v(scouseobject, momone, momnine):
"""
Calculate the difference between the moment one and the velocity of the
channel containing the peak flux
Parameters
----------
scouseobject : instance of the scousepy class
momone : ndarray
moment one (intensity-weighted aver... | 28,148 |
def _validate_image(values):
"""
Validates the incoming data and raises a Invalid exception
if anything is out of order.
:param values: Mapping of image metadata to check
"""
status = values.get('status', None)
if not status:
msg = "Image status is required."
raise exceptio... | 28,149 |
def revcmp(x, y):
"""Does the reverse of cmp():
Return negative if y<x, zero if y==x, positive if y>x"""
return cmp(y, x) | 28,150 |
def linear_regression(data: pd.DataFrame):
"""
https://www.statsmodels.org/
:param data: 数据集中要包含收盘价Close
:return: 拟合的y,k,b以及k转化的角度
"""
y_arr = data.Close.values
x_arr = np.arange(0, len(y_arr))
b_arr = sm.add_constant(x_arr)
model = regression.linear_model.OLS(y_arr, b_arr).fit()
... | 28,151 |
def get_expiry():
"""
Returns the membership IDs of memberships expiring within 'time_frame' amount of MONTHS
"""
time_frame = request.args.get('time_frame')
try:
time_frame = int(time_frame)
except ValueError as e:
print(e)
return jsonify({
'code': 400,
... | 28,152 |
def get_functions(input_file):
"""Alias for load_data bellow."""
return load_data(input_file) | 28,153 |
def is_elem_ref(elem_ref):
"""
Returns true if the elem_ref is an element reference
:param elem_ref:
:return:
"""
return (
elem_ref
and isinstance(elem_ref, tuple)
and len(elem_ref) == 3
and (elem_ref[0] == ElemRefObj or elem_ref[0] == ElemRefArr)
) | 28,154 |
def read_csv(filepath_or_buffer: Literal["test.csv"], encoding: Literal["utf8"]):
"""
usage.modin: 1
"""
... | 28,155 |
def listen(target, identifier, fn, *args, **kw):
"""Register a listener function for the given target.
e.g.::
from sqlalchemy import event
from sqlalchemy.schema import UniqueConstraint
def unique_constraint_name(const, table):
const.name = "uq_%s_%s" % (
t... | 28,156 |
def analyse_subcommand(
analyser: Analyser,
param: Subcommand
) -> Tuple[str, SubcommandResult]:
"""
分析 Subcommand 部分
Args:
analyser: 使用的分析器
param: 目标Subcommand
"""
if param.requires:
if analyser.sentences != param.requires:
raise ParamsUnmatched(... | 28,157 |
def fetch_pg_types(columns_info, trans_obj):
"""
This method is used to fetch the pg types, which is required
to map the data type comes as a result of the query.
Args:
columns_info:
"""
# get the default connection as current connection attached to trans id
# holds the cursor whic... | 28,158 |
def open_popup(text) -> bool:
""" Opens popup when it's text is updated """
if text is not None:
return True
return False | 28,159 |
def se_beta_formatter(value: str) -> str:
"""
SE Beta formatter.
This formats SE beta values. A valid SE beta values
is a positive float.
@param value:
@return:
"""
try:
se_beta = float(value)
if se_beta >= 0:
result = str(se_beta)
else:
... | 28,160 |
def replace_missing_data(
data: pd.DataFrame,
target_col: str,
source_col: str,
dropna: Optional[bool] = False,
inplace: Optional[bool] = False,
) -> Optional[pd.DataFrame]:
"""Replace missing data in one column by data from another column.
Parameters
----------
data : :class:`~pand... | 28,161 |
def jsonpath_parse(data, jsonpath, match_all=False):
"""Parse value in the data for the given ``jsonpath``.
Retrieve the nested entry corresponding to ``data[jsonpath]``. For
example, a ``jsonpath`` of ".foo.bar.baz" means that the data section
should conform to:
.. code-block:: yaml
---
... | 28,162 |
def test_bug_size():
"""Two series of length 1500 should not trigger a size error.
The warping paths matrix is of size 1501**2 = 2_253_001.
If using 64bit values: 1501**2*64/(8*1024*1024) = 17.2MiB.
"""
with util_numpy.test_uses_numpy() as np:
s1 = np.random.rand(1500)
s2 = np.rando... | 28,163 |
def extract_urlparam(name, urlparam):
"""
Attempts to extract a url parameter embedded in another URL
parameter.
"""
if urlparam is None:
return None
query = name+'='
if query in urlparam:
split_args = urlparam[urlparam.index(query):].replace(query, '').split('&')
ret... | 28,164 |
def get_nlb_data(elb_data, region, load_balancer_name, ssl_hc_path):
"""
Render a dictionary which contains Network Load Balancer attributes
"""
if debug:
logger.debug("Building the Network Load Balancer data structure")
# this is used for building the load balancer spec
nlb_data = {'Vpc... | 28,165 |
def get_objects_for_group(group, perms, klass=None, any_perm=False, accept_global_perms=True):
"""
Returns a queryset of objects for which there can be calculated a path....
"""
raise NotImplementedError | 28,166 |
def _get_required_var(key: str, data: Dict[str, Any]) -> str:
"""Get a value from a dict coerced to str.
raise RequiredVariableNotPresentException if it does not exist"""
value = data.get(key)
if value is None:
raise RequiredVariableNotPresentException(f"Missing required var {key}")
return s... | 28,167 |
def phones():
"""Return a list of phones used in the main dict."""
cmu_phones = []
for line in phones_stream():
parts = line.decode("utf-8").strip().split()
cmu_phones.append((parts[0], parts[1:]))
return cmu_phones | 28,168 |
def the_state_and_the_temperature_of_the_tpm_hw_can_be_monitored(devices):
"""the state and the temperature of the TPM_HW can be monitored.."""
if devices.mccs_tile_0001.simulationMode == 1:
logger.info('MCCS tile 0001 is in simulation mode')
devices.print_device_states()
device = devices.mccs_... | 28,169 |
def load_specific_forecast(city, provider, date, forecasts):
"""reads in the city, provider, date and forecast_path and returns the data queried from the forecast path
:param city: city for which the weather forecast is for
:type string
:param provider: provider for which the weather forecast is for
... | 28,170 |
def eeg_to_montage(eeg):
"""Returns an instance of montage from an eeg file"""
from numpy import array, isnan
from mne.channels import Montage
pos = array([eeg.info['chs'][i]['loc'][:3]
for i in range(eeg.info['nchan'])])
if not isnan(pos).all():
selection = [i for i in ran... | 28,171 |
def test_ass_style_list_modifying_style_emits_modification_event_in_parent() -> None:
"""Test that modifying an style emits a modification event in the context
of its parent list.
"""
subscriber = Mock()
style = AssStyle(name="dummy style")
styles = AssStyleList()
styles.append(style)
st... | 28,172 |
def mul_inv2(x:int, k:int) -> int:
""" Computes x*2^{-1} in (Z/3^kZ)*."""
return (inv2(k)*x)%(3**k) | 28,173 |
def Be(Subject = P.CA(), Contract=FALSE):
"""Synonym for Agree("be")."""
return Agree("be", Subject, Contract) | 28,174 |
def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=0.99):
"""
Armijo linesearch function that works with matrices
find an approximate minimum of f(xk+alpha*pk) that satifies the
armijo conditions.
Parameters
----------
f : function
loss function
xk : np.nda... | 28,175 |
def lprob2sigma(lprob):
""" translates a log_e(probability) to units of Gaussian sigmas """
if (lprob>-36.):
sigma = norm.ppf(1.-0.5*exp(1.*lprob))
else:
sigma = sqrt( log(2./pi) - 2.*log(8.2) - 2.*lprob )
return float(sigma) | 28,176 |
def convert_from_fortran_bool(stringbool):
"""
Converts a string in this case ('T', 'F', or 't', 'f') to True or False
:param stringbool: a string ('t', 'f', 'F', 'T')
:return: boolean (either True or False)
"""
true_items = ['True', 't', 'T']
false_items = ['False', 'f', 'F']
if isi... | 28,177 |
def generate(host, port, user, password, dbname, prompt, verbose):
"""
Generate a YAML spec that represents the role attributes, memberships, object ownerships,
and privileges for all roles in a database.
Note that roles and memberships are database cluster-wide settings, i.e. they are the same
acr... | 28,178 |
def gaussian_device(n_subsystems):
"""Number of qubits or modes."""
return DummyDevice(wires=n_subsystems) | 28,179 |
def create_playlist(current_user, user_id):
"""
Creates a playlist.
:param user_id: the ID of the user.
:return: 200, playlist created successfully.
"""
x = user_id
user = session.query(User).filter_by(id=user_id).one()
data = request.get_json()
new_playlist = Playlist(name=data['nam... | 28,180 |
def gram_matrix(y):
"""
Input shape: b,c,h,w
Output shape: b,c,c
"""
(b, ch, h, w) = y.size()
features = y.view(b, ch, w * h)
features_t = features.transpose(1, 2)
gram = features.bmm(features_t) / (ch * h * w)
return gram | 28,181 |
def process_pair_v2(data, global_labels):
"""
:param path: graph pair data.
:return data: Dictionary with data, also containing processed DGL graphs.
"""
# print('Using v2 process_pair')
edges_1 = data["graph_1"] #diff from v1
edges_2 = data["graph_2"] #diff from v1
edges_1 = np.array(e... | 28,182 |
def calculate_line_changes(diff: Diff) -> Tuple[int, int]:
"""Return a two-tuple (additions, deletions) of a diff."""
additions = 0
deletions = 0
raw_diff = "\n".join(diff.raw_unified_diff())
for line in raw_diff.splitlines():
if line.startswith("+ "):
additions += 1
elif... | 28,183 |
def get_synonyms(token):
""" get synonyms of word using wordnet
args:
token: string
returns:
synonyms: list containing synonyms as strings
"""
synonyms = []
if len(wordnet.synsets(token)) == 0:
return None
for synset in wordnet.synsets(token):
for lemma in syn... | 28,184 |
def concat_experiments_on_channel(experiments, channel_name):
"""Combines channel values from experiments into one dataframe.
This function helps to compare channel values from a list of experiments
by combining them in a dataframe. E.g: Say we want to extract the `log_loss`
channel values for a list o... | 28,185 |
def sghmc_naive_mh_noresample_uni(u_hat_func, du_hat_func, epsilon, nt, m, M, V, theta_init, r_init, formula):
"""
This is a function to realize Naive Stochastic Gradient Hamiltonian Monte Carlo
with Metropolis-Hastings correction in unidimensional cases without resampling
procedure.
"""
B = 1... | 28,186 |
def detect_voices(aud, sr=44100):
"""
Detect the presence and absence of voices in an array of audio
Args:
Returns:
"""
pcm_16 = np.round(
(np.iinfo(np.int16).max * aud)).astype(np.int16).tobytes()
voices = [
VAD.is_speech(pcm_16[2 * ix:2 * (ix + SMOOTHING_WSIZE)],
... | 28,187 |
def turn_on(hass, entity_id=None):
"""Turn on specified automation or all."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.services.call(DOMAIN, SERVICE_TURN_ON, data) | 28,188 |
def process_to_binary_otsu_image(img_path, inverse=False, max_threshold=255):
"""
Purpose:
Process an image to binary colours using binary otsu thresholding.
Args:
img_path - path to the image to process
inverse - if true an inverted binary thresholding will be applied (optional).
... | 28,189 |
def _fold_in_str(rng, data):
"""Folds a string into a jax.random.PRNGKey using its SHA-1 hash."""
m = hashlib.sha1()
m.update(data.encode('utf-8'))
d = m.digest()
hash_int = int.from_bytes(d[:4], byteorder='big', signed=True)
return random.fold_in(rng, hash_int) | 28,190 |
def create_task_dialog(request):
"""called when creating tasks
"""
return data_dialog(request, mode='create', entity_type='Task') | 28,191 |
def deroulementRandom(b):
"""Play the Tic-Tac-Toe game randomly."""
print("----------")
print(b)
if b.is_game_over():
res = getresult(b)
if res == 1:
print("Victory of X")
elif res == -1:
print("Victory of O")
else:
print("Draw")
... | 28,192 |
def raw_rearrange(da, pattern, **kwargs):
"""Crudely wrap `einops.rearrange <https://einops.rocks/api/rearrange/>`_.
Wrapper around einops.rearrange with a very similar syntax.
Spaces, parenthesis ``()`` and `->` are not allowed in dimension names.
Parameters
----------
da : xarray.DataArray
... | 28,193 |
def get_users() -> Tuple[int, ...]:
"""Count user ids in db."""
db = get_database_connection()
user_searches = db.keys(pattern=f'{DB_SEARCH_PREFIX}*')
user_ids = [
int(user_search.decode('utf-8').lstrip(DB_SEARCH_PREFIX))
for user_search in user_searches
]
return tuple(user_ids) | 28,194 |
def rotate_files(fname, cnt=0, max_cnt=5):
"""Function: rotate_files
Description: Move a set of files up a sequence of backup files
(e.g. file.0, file.1, file.2, etc). It is a recursive function as it
will find the largest sequence file or opening in the sequence and then
rename the... | 28,195 |
async def login(
email: str,
password: str,
session: Optional[ClientSession] = None,
*,
conf_update_interval: Optional[timedelta] = None,
device_set_debounce: Optional[timedelta] = None,
):
"""Login using email and password."""
if session:
response = await _do_login(session, emai... | 28,196 |
def test_field_mapper_operate_on_values(sdc_builder, sdc_executor):
"""
Test the Field Mapper processor, by value. Rounds double fields up to the nearest integer (ceiling).
The pipeline that will be constructed is:
dev_raw_data_source (JSON data) >> field_mapper (ceiling) >> trash
"""
raw... | 28,197 |
def rcomp_prediction(system, rcomp, predargs, init_cond):
""" Make a prediction with the given system
Parameters:
system (str): Name of the system to predict
rcomp (ResComp): Trained reservoir computer
predargs (variable length arguments): Passed directly into rcomp.predict
init_... | 28,198 |
def signal_handler(signal, frame):
"""Handles explicit interruptions."""
logging.exception('Received Ctrl-C, terminating...')
if sock:
kill_socket()
sys.exit(1) | 28,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.