content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def MostIterationsDone(): """(read-only) Max number of iterations required to converge at any control iteration of the most recent solution.""" return lib.Solution_Get_MostIterationsDone()
babffb8af7e1cf7025cbc9a3e2c3d417e4dd0ec7
3,605,000
import random def generate_color(i): """Generate hex color corresponding to integer. Colors should have well defined ordering. First N colors are hardcoded, then colors are random (must seed random number generator with deterministic value before getting colors). """ if i < len(COLORS):...
5f421579e0eb049acf5825999f1804eef331fd0d
3,605,001
import os import sys def systemd_workaround_requested(): """Check if execution of the systemd workaround has been requested.""" try: return os.path.basename(sys.argv[0]) == os.path.basename(CRYPTSETUP_GENERATOR) except Exception: return False
a11d052e2fd0930115d60388e0de691db9ead26b
3,605,002
import scipy def COM(z, M, **cosmo): """ Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict ...
4d14892da576af131b39f3c5bef29dc7053976f5
3,605,003
import functools import asyncio def _class_wrapper(f, _class): """Executes the coroutine f and wraps its result in a class. See WrapAsync. """ @functools.wraps(f) @asyncio.coroutine def _wrapper(self, *args, **kwargs): result = yield from f(self, *args, **kwargs) # Don't call...
b7c89a21873161fadcaea212f3da46d16d1a1775
3,605,004
from pathlib import Path def dashboard(): """ we send the www/dashboard-dev file made with generate_static. """ full_path = Path(current_app.config['WWW']) full_path_str = str(full_path.absolute()) return send_from_directory(full_path_str, 'dashboard-dev', ...
edd226b4884d8d62b997c3705b5155bf5bfee778
3,605,005
def grayscale_surface(surf) : """ converts a pygame surface to gray scale values """ width , height = surf.get_size() for x in range(width): for y in range(height): red , green , blue, alpha = surf.get_at((x,y)) L = 0.3 * red + 0.59 * green + 0.11 * blue gs_colo...
139e625ed448de84111e933dd3155fcef930ac19
3,605,006
def output(): """ Return the frequency characteristic filter tuple. 1st - output used for further excercises 2nd - output used for plotting """ maskon_frames, maskoff_frames = ex3.output() # Get the maskon and maskoff DFTs maskon_dfts = np.fft.fft(maskon_frames, n=N) maskoff_dfts =...
9dfec4f6dd8e4e4c082afe67ada48571551ad0bd
3,605,007
import os def _IsPlatformSupported(): """Checks that this platform and build system are supported. Args: opts: The options parsed from the command line. Returns: True if the platform and build system are supported. """ # Haven't tested the script out on any other platforms yet. supported = ['pos...
9b4c5696d4c49298d688ddd0b893e24332b2bd0a
3,605,008
import matplotlib.pyplot as plt from matplotlib import ticker def heat_map(df, ax_fs=13, **kwargs): """ kwargs param explain figsize (tuple): default (11,4) rows_len (int) : default DataFrame Index Length cols_len (int) : default DataFrame Columns Length colorbar (bool) : show up colo...
1f03448b3f755ee6185ad8de756e68f078007236
3,605,009
import scipy def get_corr_val_cubic(lambda_val, wave_ref, ref_ext, ref_xy, slit_x, slit_y, first_interp_method): """Perofrm an alternative interpolation in order to compare interpolation methods.""" index = np.where(wave_ref[:, 0, 0] == lambda_val) plcor_slice = ref_ext[index[0][0]].reshape(ref_ext[index[...
0392aea244dac4cd57e001b4c3ea6e7e72fb2e5f
3,605,010
import socket def find_port(): """ Return an unbound port """ s=socket.socket() s.bind(("127.0.0.1",0)) port=s.getsockname()[1] s.close() return port
a3a535e1bed9b079654a0ac8b3c329d8e575537c
3,605,011
def index(): """The index page which provide information about other API end points""" return """ <div> <h1> Inception REST API </h1> <h3> The following API end points are valid </h3> <ul> <h4> Inception V4 </h4> <li> <code>/inception/v4/ping </code> - <br/> ...
7037c89f27342724960097db6518f30003c27f17
3,605,012
def avg_length(tree, freq_dict): """ Return the number of bits per symbol required to compress text made of the symbols and frequencies in freq_dict, using the Huffman tree. @param HuffmanNode tree: a Huffman tree rooted at node 'tree' @param dict(int,int) freq_dict: frequency dictionary @rtype: fl...
32f4f509e156c4aef2fd77d0587559d68a081a1d
3,605,013
def traj_planner(grasp_position, grasp_step, way_points_number, movement, grasp_cartesian_pose, ori, d, actual_position): """Quintic Trajectory Planner Publish a trajectory to UR5 using quintic splines. Arguments: grasp_position {[float]} -- Grasp position [x, y, z] grasp_step {str} -- Set UR5 movement type...
9ccdb5b6dbec98329c27a3fb0f0222247616579f
3,605,014
import random def choose_move(data: dict) -> str: """ data: Dictionary of all Game Board data as received from the Battlesnake Engine. For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request return: A String, the single move to make. One of "up", "down", "left...
19bd90b3ae89159eac627db6d175486b280ad4fd
3,605,015
import tvm import torch import os def convert(topology, backend, test_input, device, extra_config={}): """ This function is used to convert a `Topology` object into a *backend* model. Args: topology: The `Topology` object that will be converted into a backend model backend: Which backend ...
c28d02b7d27fdbd2d2bafd9747eee53c47ff65fe
3,605,016
import types from typing import Optional from typing import Tuple def construct_nerf( rng: jax3d.RandomState, num_scenes: int, placeholder_batch: types.Batch, args: NerfParams, ) -> types.InitializedModel: """Construct a Neural Radiance Field. Args: rng: the random state. num_scenes: unus...
bc3fc871fd149f36d0c9bed70a360cbb6d5f3486
3,605,017
def index(): """Show portfolio of stocks""" # Store the username of the user logged username = db.execute("SELECT username FROM users WHERE id = :uid", uid=int(session['user_id']))[0]["username"] # Put information from 'portfolio' into a list # got help from https://cs50.stackexchange.com/question...
3c1b9e5c9c033715dda135da066fe14435680434
3,605,018
import email def message_with_one_attachment(): """ Pytest fixture """ with open("./test_data/pdf_one_email.eml", "rb") as f: message = email.message_from_binary_file(f) return message
180657eba6f7b90ad738a306750852716871dc91
3,605,019
import os def create_session(db=None, debug=False): """Create a session for the specified database file. If debug=True, the session will output raw SQL whenever it is executed on the database. """ if db is None: db = os.getenv("COSIMA_COOKBOOK_DB", __DEFAULT_DB__) engine = create_engine...
dcf568eab7199d6947ed2aad82aa1845396db37a
3,605,020
def create_layout(text, style, context, max_width, justification_spacing): """Return an opaque Pango layout with default Pango line-breaks. :param text: Unicode :param style: a :class:`StyleDict` of computed values :param hinting: whether to enable text hinting or not :param max_width: The ...
900cc3f47881721bf103926c11fa879d80d1781a
3,605,021
from typing import AnyStr def nodes_metric_rating(metric: AnyStr, tenant: AnyStr) -> Response: """ Get the rating for a given metric. :metric (AnyStr) A string representing the namespace. :tenant (AnyStr) A string representing the tenant. Return a response or nothing. """ config = reques...
6ec1eac948cdaed42a418ef97f6b312a730c9071
3,605,022
def list_to_python(value, convert_decimal=True, convert_number=True): """ convert a list of json values to python list """ return [value_to_python(item, convert_decimal=convert_decimal, \ convert_number=convert_number) for item in value]
7e859cd62643b46c710de804a89b2f0ca6a0c58a
3,605,023
import random def random_sized_rect_crop(item, cfg): """ :param item: :param cfg: :return: Return random sized rectangle crop item['im'] and item['ps_label'] """ (im_height, im_width) = cfg.dataset.im.h_w (ps_label_height, ps_label_width) = cfg.dataset.ps_label.h_w for attempt in ...
d3f01966318c40e6ccc821e1e035ea0101b55f4d
3,605,024
import random def flip(img, label, flip_mode='all', **kwargs): """ This function returns a tuple of tuples each of which includes flipped (img, label). """ # A Random Probability 0.5 is not applied to this function. result = [] choose = list(product([False, True], [False, True], [Fa...
77566b0f83487dece32acff08cf255b21ecbe0d0
3,605,025
def relu_backward(dout, cache): """ Computes the backward pass for a layer of rectified linear units (ReLUs). Input: - dout: Upstream derivatives, of any shape - cache: Input x, of same shape as dout Returns: - dx: Gradient with respect to x """ dx, x = None, cache ############...
51765bfe9b3db9fc195603c108053d5ad4637ebf
3,605,026
import re def clean_sentence(sentence): """Removes numbers, emails, URLs, unicode characters, hex characters, and punctuation from a sentence separated by whitespaces. Returns a tokenized, cleaned list of words from the sentence. Args: Sentence, i.e. string that possibly includes spaces and...
cc37abfb0334fdbc5b1f559c8ad9da14a7db31e8
3,605,027
def process_image(image, filters, ROI=None, return_predictions=False, combine_results=False, sort_filters=True): """Processes one image with process-function and returns the resulting value. """ return qualipy.process(image, filters, ROI, return_predictions, comb...
f6ae6e6aaed74b9c58d475b2c9f3a65c68867c44
3,605,028
def add_app_location(project_type, pkg_type, pkg_name, app_name, path, arch, build_host): """Add the location of a given application""" # Ensure the environment parameter is boolean project = PackageLocation( project_type=project_type, pkg_type=pkg_type, pkg_na...
9c5e8b0f7e665df62e39dbedd8808490b5d8af2c
3,605,029
import requests def get_json_from_url(url): """Retrieve JSON from a URL, raising on failure.""" response = requests.get(url) response.raise_for_status() return response.json()
c88b36ff6d4911aaa6d4115b5c054fbab2f3051f
3,605,030
def replace_merged(orig, merge): """Return sorted array of 'merge' and members of 'orig' that do not touch any of merge :param orig: Array of interval-like objects (e.g. peaks) :param merge: Array of interval-like objects (e.g. peaks) """ if not len(merge): return orig skip_windows ...
ca88a144bfba10e3175552c9c4d4475ece5e7fa3
3,605,031
def pop_transform(image: Image = None): """ Pop the last saved transform from the transform stack, and use it as the current transform. """ image = _get_target_image(image) return image.pop_transform()
fce58de75052123846c9b4e49b8a2158827f4405
3,605,032
def create_dynamic_lr(training_steps, k, warmup_steps, hidden_size): """ Generate dynamic learning rate. """ lr = [] for current_step in range(1, training_steps+1): cur_lr = rsqrt_hidden(hidden_size) * k * min(current_step ** (-0.5), current_step * (warmup_steps ** (-1.5))) lr.append...
2b73a30e1e112d567f808b9d5db405dc5c2301f2
3,605,033
def is_param(arg): """Returns whether the passed argument is a list or dictionary of params.""" return isinstance(arg, tuple) and arg[0] == "params"
bedb4745f8fc7095e235be588ad53c28db9fb4d8
3,605,034
import collections def bottleneck(x, depth, stride=1, params=None, moments=None, maml_arch=False, use_project=False, backprop_through_moments=True): """ResNet18 residual block.""" params_keys, params_vars = []...
5433363adab2c8485e69210dafb0017026ab176a
3,605,035
def evaluate_numeric_condition(target, reveal_response): """ Tests whether the reveal_response contains a numeric condition. If so, it will evaluate the numeric condition and return the results of that comparison. :param target: the questions value being tested against :param reveal_response: the ...
1eeb170635e5fb0ac5fd379af885a7a0222fb722
3,605,036
def _to_ice_data(data, column, x_s): """ Create the DataFrame necessary for ICE calculations """ ice_data = pd.DataFrame(np.repeat(data.values, x_s.size, axis=0), columns=data.columns) data_column = ice_data[column].copy() ice_data[column] = np.tile(x_s, data.shape[0]) return ice_data, data...
5397009ed0a1638fbf15bb938affdb1e38295677
3,605,037
import base64 def grab_screen(_driver): """ Grabs the screen """ image_b64 = _driver.execute_script(getbase64Script) screen = np.array(Image.open(BytesIO(base64.b64decode(image_b64)))) image = process_image(screen) # Processing image is required return image
44309724cb690887f73133abdd5a52115d627bc4
3,605,038
def render_parse_tag(): """Render a load more data button (only render the button).""" return {}
71f2f8ffe7fc961b99acdc49ee4ab5d9d7cd1f91
3,605,039
def player_exists(player): """See if a player exists in the database or not. If yes, return 1, if not return 0.""" array = (player,) cursor.execute('SELECT * from players where dwname=?', array) if cursor.fetchone(): return 1 else: return 0
f2ee3765191764f0d3273406c6bfe671bb9ff252
3,605,040
def diff(f, x, times = 1, evaluate=True): """Differentiate f with respect to x It's just a wrapper to unify .diff() and the Derivative class, it's interface is similar to that of integrate() see http://documents.wolfram.com/v5/Built-inFunctions/AlgebraicComputation/Calculus/D.html """ return ...
5c98c1b82f9d1d301e70afd5eaa738a4d0555971
3,605,041
def get_summary_tree(training_metrics_grabber): """Extracts desired training statistics from the grabber state. Currently this function will compute the scalar aggregate gradient variance for every weight matrix of the model. Future iterations of this function may depend on the metrics_grabber config. Args:...
132507a08a99e580dcd83fcb8e489ea4cd830e83
3,605,042
def strip_string(string): """ :param string: :return: """ return string.strip()
d57cae7b255d08505f05a7b97016e25f7a570995
3,605,043
def gm(dic,data,g1=0.0,g2=0.0,g3=0.0, c=1.0,start=1,size='default',inv=False,one=False,hdr=False): """ Lorentz-to-Gauss apodization Parameters: * dic Dictionary of NMRPipe parameters. * data array of spectral data. * g1 Inverse exponential width in Hz * g2 Gaussian broaden wi...
a405f44084aa57048b2e32f23f0cc9b7f92e4e76
3,605,044
async def get_account(name=None, resource_group_name=None): """ Use this data source to access information about an existing CosmosDB (formally DocumentDB) Account. """ __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name __ret__ = await pulumi.runti...
b63806175fe008aa5c87fa920e07f7cd04c1a1c2
3,605,045
import hashlib def checksum(filepath, hcnstrctr=hashlib.md5, enc="utf-8"): """Compute the checksum of given file, `filepath` :raises: OSError, IOError """ return hcnstrctr(open(filepath).read().encode(enc)).hexdigest()
a0a6c576ef9f22de106834088f69cbbc2b3c4bd0
3,605,046
def talkerIndication(): """TALKER INDICATION Section 9.1.44""" a = TpPd(pd=0x6) b = MessageType(mesType=0x11) # 00010001 c = MobileStationClassmark2() d = MobileId() packet = a / b / c / d return packet
63ef0951f32e4216292f7f5f502b9df6283d13f1
3,605,047
import json def status(dag_id: str) -> Response: """ Validate that the DAG is registered by Airflow. If exists, check the DagRun :param dag_id: DAG to find :return: API Response """ with settings.Session() as session: dag_model = session.query(DagModel).filter(DagModel.dag_id == ...
5a88aeb3595bdcec104ec6cd03a3d14974aa5d35
3,605,048
from datetime import datetime from typing import Tuple import select from operator import and_ def get_release_id(datestamp: datetime, process_name: str) -> Tuple[int, datetime]: """ Generates or retrieves the `release_id` for the process. Parameters ---------- datestamp : datetime Datest...
d76996eb03c77dc176e2f8c048b70d7585b67b39
3,605,049
def convert_down_sample_weight_to_torch(jax_down_sample_params, torch_down_params): """Converts down sample jax weights to torch.""" conv0_weight = np.transpose( jax_down_sample_params['ConvBlockFactory_0']['Conv_0']['kernel'], [4, 3, 0, 1, 2]) torch_down_params...
274046898252be8f5a811d76f785c3e7a5959cdf
3,605,050
import requests def handle_exceptions(resource): """Decorator to provide common error handling""" def exception_handler_wrapper(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except requests.exceptions.Timeout: logger.err...
0ddd8d0516eba50d9fb701c558f8ee31d7de6cd5
3,605,051
def find_gpa(): """find dynamically imported functions (Windows) example function to be passed to hr_toolbox.ic_t() """ func_name = 'GetProcAddress' query = lambda cfunc, e: (e.op is cot_call and e.x.op is cot_obj and get_name(e.x.obj_ea) == func_name and len(e.a) == 2 and ...
0bc418fff0bfd2569386a012979730888508a2e1
3,605,052
def extract_plane_triangulation(plane_data, verbose=False): """Extract the triangulation of the plane""" # Get Paraview's own triangulation cells = plane_data.GetPolys() triangles = cells.GetData() nb_triangles = triangles.GetNumberOfTuples()/4 tri = np.zeros((nb_triangles, 3)) for i in x...
1ad988ac03dd10f026339a4f1c1ed01661a834dd
3,605,053
def special_page(request, **kwargs): """Render a basic template of special pages.""" return render(request, 'special_page.html', kwargs)
b9875ed03693505d22bf92041b8eb3e61dc00f48
3,605,054
async def cache(request): """Invalidate cached Beacons.""" LOG.debug("DELETE /beacons received.") # Send request for processing await invalidate_cache() # Return confirmation return web.Response(text="Cache has been deleted.")
38cb5cf301dbe8d9aaf9e866784022276103dd9a
3,605,055
def play_torrent(params): """ Play torrent :param params: :return: """ file_index = params.get('file_index') if file_index is not None and file_index != 'dialog': file_index = int(file_index) return _play(buffer_torrent(params['torrent'], file_index))
08779fcb19792c764247c0f8a0a780429947b0a1
3,605,056
import importlib def import_module(path): """ 基于指定的模块导入 点分割模块的导入路径。 """ module_path, module = str(path).rsplit('.', maxsplit=1) return getattr(importlib.import_module(module_path), module)
c79bbad91058b07f8b7ffd791e3db4d9988f6f46
3,605,057
from typing import List def simulate_forecast_regr(feature_series: List[TimeSeries], target_series: TimeSeries, model: RegressiveModel, start: pd.Timestamp, fcast_horizon_n: int, trim...
a2782722cde829ea24a6662e2a25af0851d0655f
3,605,058
def get_temp(): """ Get the temperature :return: The system temperature """ c = ProcessManagement() # Try to get the time from multiple thermal zones cmd = "cat /sys/class/thermal/thermal_zone*/temp" command_output = c.system_call(cmd, True)[0].decode('ascii') try: temperat...
cb41ae883195cd15123763854ec3e8297cace78e
3,605,059
def distinct_color( exclude_colors, pastel_factor=0, n_attempts=1000, colorblind_type=None, rng=None ): """ Generate a colour as distinct as possible from the colours defined in exclude_colors Inspired by: https://gist.github.com/adewes/5884820 :param exclude_colors: a list of (r,g,b) tuples. r,g,b...
5b02ebfabc8ed7d609bd8dd2f62dd018a9d1af04
3,605,060
import requests import yaml def load_legislators_current(): """ Loads the legislators-current.yaml :return: dict of the data """ response = requests.get('https://theunitedstates.io/congress-legislators/legislators-current.yaml') return yaml.load(response.content)
06dafd51aa60110e081fdb845f5a2670dcd590f2
3,605,061
def tf_generate_random_color_map( img, shuffle_exclude_first: int, bin_size: int ): """ Get colors and random color index in image. Parameters ---------- img : `Tensor` Tensor to generate color map. shuffle_exclude_first : int Random index calculate after this value. ...
81fa7bbfd4ec3e9f7b554c450898e5c1d475dd93
3,605,062
import torch import os import tempfile def b0_transversal_5_5(**kwargs): """ # This docstring shows up in hub.help() Initial model trained on 138 transversal images via transfer learning on the base model chfc-cmi/cmr-seg-tl : cmr_seg_base """ # Call the model, load pretrained weights url = "https...
6974f0de605ffb9614a8eaee202d730e20aebb60
3,605,063
def _add_to_visited(values, visited, aut): """Return BDD `visited` updated with assignment `values`.""" c = list() for var, value in values.items(): t = aut.vars[var]['type'] if t == 'bool': assert value in (True, False), value if bool(value): c.append...
9cfc6a3d89ebca9bb0352a3a0d561e19a26790a4
3,605,064
def active_signal(depth=0): """Get the `Signal` object at the given `depth` of the active signals stack.""" return _active_signals[-1-depth]
c89d01c43f4d0e4a3df91d0f942221c874dd7667
3,605,065
from typing import Optional def routes(start, end) -> tuple[str, Optional[list]]: """Generate routes message and keyboard""" def map_type(vehicle: vvo.Vehicle): if vehicle.type == vvo.TransportationType.FOOTPATH: return "➡️", "Fußweg", "" elif vehicle.type == vvo.TransportationTyp...
0807b1a656cf73eca3788e6b7e254c899ec39f88
3,605,066
def meta_patient(Market, match=arbitraryMatch, a=np.inf, verbose=False, **kwargs): """ Patient(a) algorithm from Akbarpour et al. (2014) a is default set to infinity, so patient() algorithm by default Attempts match if agent is critical or if his sojourn==a """ if verbose: ...
71f2f7d9003c09bd443d6c1ed35d2e9e284533ef
3,605,067
def gen_grid(fov, min_, max_, overlap, snake, half_fov_offset=True, center=True): """ generate a grid of coordinates at which to do a tiled acquisition Parameters ---------- fov: array-like field-of-view in units min_: array-like minimum of bbox to scan max_: array-like ...
4ff0e02610b8a7ca258cace04a5b272821888a06
3,605,068
def increment(x): """increments input by one""" return x+1
416451d93765ee148de9b69bd3e1af0e846d6fb5
3,605,069
def prepare_df(df, reduce_mem=False): """ This function converts the df header into string format for the gui to be able to plot Args: df --> pandas dataframe: df needs to be cleaned Return: df --> pandas dataframe: cleaned df """ if reduce_mem: df = reduce_mem_usag...
6fe6c235234b59734a69994c49626670283650a8
3,605,070
from typing import Sequence from typing import Mapping from typing import Any import functools def event_predictions_to_ns( predictions: Sequence[Mapping[str, Any]], codec: event_codec.Codec, encoding_spec: note_sequences.NoteEncodingSpecType ) -> Mapping[str, Any]: """Convert a sequence of predictions to a...
20196f73055175c2082c2494ad5e41e93c5a9630
3,605,071
def dict_to_rule(rule, clf_feature_dict): """ Function to accept rule dict and convert to Rule object Parameters: rule: list of dict of schema [ { 'feature': int, 'operator': str, 'value': float }, ] """ output = '' for condition...
0f3cc79a86e62a6154d6d83ff4fb695cd181f0b8
3,605,072
async def friends( response: Response, db=Depends(get_db), current_user=Depends(get_current_active_user), ): """ Get current user's friends. """ return get_friends(db, current_user.id)
9b96f3e03f9d5102bf23fd80f804efc1936bd466
3,605,073
def set_publish_time_series_args(args): """Set args to publish time-series """ public_time_series = {} if args.public_time_series: public_time_series = {"private": False} if args.model_price: public_time_series.update(price=args.model_price) if args.cpp: ...
90e3d362ba236752a18dd117b3bd9d23d2cefba1
3,605,074
def generate_auth_token(uid, scope=None, expiration=7200): """生成令牌""" s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({ 'uid': uid, 'scope': scope })
b3be7f0efc87a8b3168d8710595b8a8def2b0808
3,605,075
def qute_log(url: QUrl) -> _HandlerRet: """Handler for qute://log. There are three query parameters: - level: The minimum log level to print. For example, qute://log?level=warning prints warnings and errors. Level can be one of: vdebug, debug, info, warning, error, critical. - plain: If given...
a2de87fe7f0b9c784ba81c7fb3ae7a1a8e275bdc
3,605,076
def lag_features(df, n_lags=1): """Calculate lagged features of input series.""" df_lagged = df.copy() for lag in range(1, n_lags + 1): shifted = df.shift(lag) shifted.columns = [x + "_lag" + str(lag) for x in df.columns] df_lagged = pd.concat((df_lagged, shifted), axis=1) ret...
29eee91ba50e0677119abf3153536d44ce083508
3,605,077
from unittest.mock import patch async def init_integration(hass, mock_config_entry): """Create a fake SMA Config Entry.""" mock_config_entry.add_to_hass(hass) with patch("pysma.SMA.read"): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() ...
b4a99d12143be7e6b114fa06d1b32aa1de57489e
3,605,078
async def system_private_info(): """ This end-point show private system info. """ try: return { 'branch': V.BRANCH_NAME, 'source_hash': V.SOURCE_HASH, 'directory': V.DB_HOME_DIR, 'unconfirmed': [txhash.hex() for txhash in obj.tx_builder.memory_pool...
18f240a68e1fbd1a28b1c342a2be8e33c83dbdf3
3,605,079
def dependency_trigger_has_expected_keys(job_dict: dict) -> bool: """ Dependency trigger must have expected keys. """ dependency_options = ["depends_on"] if not all(key in job_dict.keys() for key in dependency_options): raise InvalidSchemaError( "Dependency triggered job must hav...
fe4827d44924ec548449277a67517d12fb1f81a4
3,605,080
def flatten(list_like, recursive=True): """ Flattens a list-like datastructure (returning a new list). """ retval = [] for element in list_like: if isinstance(element, list): if recursive: retval += flatten(element, recursive=True) else: retval...
ad343decfa9e8ae949af303fc3f1a52179464009
3,605,081
def align(ref_seq, query_seq, window=100, aln_opts={}): """ Align two sequences then perform realignment around indels in order to obtain consistent gap positions. 1. Coarse alignment 2. Identify the location of indels 3. Create intervals of 'window' size around the indel locations 4. M...
c0c3adfd39d7dc0cdc20090e180f677608c0bf11
3,605,082
def console(prize_card, hand, max_card): """ Console strategy gets input from the user. """ result = None done = False while not done: print("") print("prize: " + str(prize_card) + " hand: " + str(hand.cards)) print("enter your pick:") answer = parse_input(input()) ...
476e45f7dceccdf69b4c8537664adbdaf23f45ae
3,605,083
import unicodedata def strip_accents(obj): """ Return ``obj`` as a string (or unicode in Python2) with its accents removed. """ string = force_text(obj) accentless_chars = [c for c in unicodedata.normalize('NFD', string) if unicodedata.category(c) != 'Mn'] return ''...
1b2ef44ccff0f9caa300e35351674095aaa0fbae
3,605,084
def compute_dice_score(y_pred, y_true, to_onehot_y=True, use_argmax=True, layout="NDHWC", include_background=False, compute_mean_score=True): """CPU compute dice score.""" dice_s...
5bb9729b83c14493a08e160dca7a7b8d155de770
3,605,085
import subprocess import re import time def parse_gpu_info(runs=20, wait=0.25): """Performs several runs of parsing the GPU info from nvidia-smi. Args: runs (int, optional): Number of runs wait (float, optional): Seconds to wait between the runs. Returns: Dict: Compiled GPU info ...
e0b5cfa850f8d53e283d333116cb3ba3b93a1f3b
3,605,086
def weighted_color(n_classes, probs, n_bins=100): """ Compute a weighted sum probability given a list of probabilities, a number of classes and a number of bins Returns: Weighted probability value """ n_classes = float(len(n_classes) - 1) l = 1.0 / n_bins h = 1 - l p = 0....
3dcb31c27f345a02c879e6286d2ace201ec46973
3,605,087
def proj_persp( xyz, C, a, fov, dims, normals=None): """ Project 3d point xyz based on a pinhole camera model. *Arguments*: - xyz = a nx3 numpy array with a position vector (x,y,z) in each column. - C = the position of the camera. - a = the three camera rotatation euler angles (appled around...
e734fce55fb56965080749e8378d30d899f73c65
3,605,088
def update(trend: PriceTrend, value: float) -> Price: """Adds new Price object to the price trend list""" new_price = Price.from_value(value) trend.append(new_price) return new_price
9071995cc10f0c9b5b94efb74a4319093461cd94
3,605,089
def modelLogsdetail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Log_Ansible_Model.objects.get(id=id) except Log_Ansible_Model.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': ...
b9e2b289696d9df2829406dd3fffba57a37d9d85
3,605,090
def hash_image_from_path(image_path, algorithm='aHash', raw=False): """ Hashes the given image from his path with the chosen algorithm (average hash by default) (> str or ImageHash if raw)\n © Anime no Sekai - 2020 Project Erina """ image = Image.open(image_path) return(hash_image(image=imag...
779a25ef054dfeaad97da1965bef10afae7933ae
3,605,091
def theta(fo, l): """ equation 16 electrical length: ... should probably use guide wavelength here """ wavelength = 3e8 / fo # free space wavelength return 2.0*_np.pi*l/wavelength
982f8ae0c349fa6fb37edccea815ffe34665ac5d
3,605,092
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import argparse def get_parser(): """Parse command line arguments""" parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--num-items', ...
9584e7d2ff34a4167500f99aeb351f5b14d4513b
3,605,093
def _read_annotated_models(version): """Read the contents of the annotated models file from github.""" repo = github.repo_from_path(github.WB_PIPELINE_REPO) annot_file_content = github.read_released_file(repo, version, ...
14f945d2c601bc55f45c1969b851cb77ac6e8f2b
3,605,094
def wfg(P): """ Speed of sound; [m / s] saturation rise of""" return wg(P) - wf(P)
340b6fa880bf8ce6dd7990db1180c1a942260a12
3,605,095
import re def _parse_openssl_req(csr_filename): """ Parses openssl command line output, this is a workaround for M2Crypto's inability to get them from CSR objects. """ if not salt.utils.path.which("openssl"): raise salt.exceptions.SaltInvocationError("openssl binary not found in path") ...
e20563eb97f05dc0ec05c953ed01093ecb959cc8
3,605,096
from pathlib import Path import os import subprocess def bedtoolscoverage(gfile, outdir, sortedbam): """computes the coverage for each mapped region parameters ---------- bedtoolspath path to the bedtools installation gfile genome file build by preparebedtools() outdir ...
3225526419f19e337f4e5ee41f851b96a0aede28
3,605,097
def load_images(left_name, right_name, parameters): """ read and blur stereo image pair. :param left_name: name of the left image. :param right_name: name of the right image. :param parameters: structure containing parameters of the algorithm. :return: blurred left and right images. """ ...
51bd56979ef17080e6a098d5ec2580cd1455bc57
3,605,098
def encode_apache( data, convert_bools=False, convert_nums=False, indent=" ", level=0, quote_all_nums=False, quote_all_strings=False, block_type='sections'): """Convert Python data structure to Apache format.""" # Return value rv = "" if block_type == 'sections': for c in data...
ca44198ca5112d96e04f4b17e0ba340eb62a2a9d
3,605,099